diff --git a/.phpcs.xml.dist b/.phpcs.xml.dist new file mode 100644 index 00000000000..a98cf177eca --- /dev/null +++ b/.phpcs.xml.dist @@ -0,0 +1,13 @@ + + + + + + + + + + diff --git a/COPYRIGHT b/COPYRIGHT index fb2d6159e06..fc50ab2093e 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -28,7 +28,7 @@ Escpos-php 3.0 MIT License Yes GeoIP2 0.2.0 Apache License 2.0 Yes Lib to make geoip convert MathPHP 2.8.1 MIT License Yes Modern math library for PHP (only few files) Mobiledetect 2.8.41 MIT License Yes Detect mobile devices browsers -NuSoap 0.9.5 LGPL 2.1+ Yes Library to develop SOAP Web services (not into rpm and deb package) +NuSoap 0.9.16 LGPL 2.1+ Yes Library to develop SOAP Web services. From https://github.com/f00b4r/nusoap/tree/v0.9.16 PEAR Mail_MIME 1.8.9 BSD Yes NuSoap dependency ParseDown 1.7.4 MIT License Yes Markdown parser PCLZip 2.8.4 LGPL-3+ Yes Library to zip/unzip files @@ -38,6 +38,7 @@ PHP-Iban 4.1.1 LGPL-3+ Yes PHP-Imap 2.7.2 MIT License Yes Library to use IMAP with OAuth PHPoAuthLib 0.8.2 MIT License Yes Library to provide oauth1 and oauth2 to different service PHPPrintIPP 1.3 GPL-2+ Yes Library to send print IPP requests +PrestaShop-WS-Lib 94feb5f OSL-3.0 No Library providing API client for Prestashop. PSR/Logs 1.0 MIT License Yes Library for logs (used by DebugBar) PSR/simple-cache ? MIT License Yes Library for cache (used by PHPSpreadSheet) Restler 3.1.1 LGPL-3+ Yes Library to develop REST Web services (+ swagger-ui js lib into dir explorer) diff --git a/ChangeLog b/ChangeLog index a5d8b7c967e..0458780eeab 100644 --- a/ChangeLog +++ b/ChangeLog @@ -254,6 +254,44 @@ The following changes may create regressions for some external modules, but were * A very high number of class properties (with old name in french) are now deprecated in favor of the property name in english. +***** ChangeLog for 18.0.4 compared to 18.0.3 ***** +FIX: $this->newref already exists and could have been modified by trigger but we still use a local variable for the filesystem-based renaming +FIX: 16.0 only, backport fix for SQL error on global search product +FIX: #25399 (#26694) +FIX: #25458 intervention localizations (backport v17) (#26757) +FIX: #26518 +FIX: #26536 Accountancy - Balance - Not divided lines by label & account, only by account (#26547) +FIX: #26553 Supplier invoice - Do not display the delete button for reconciled payment (#26554) +FIX: #26735 +FIX: #26994 +FIX: Accountancy - Possibility to write in bookkeeping expense report operation with some line not bound (#26545) +FIX: add display of an error when attempting to delete a committed transaction (#26573) +FIX: avoid warning : Cannot use a scalar value as an array (#26437) +FIX: backport SQL error on global search product +FIX: # Bug Estimated Stock at date value in V14 (#26479) +FIX: commande context (#26497) +FIX: delivery note disappear after generation +FIX: double hook and paging search param in product list (#26767) +FIX: Email reminder template must not be visible when option is off +FIX: escape HTML tags in return value of getFullName() (#26735) +FIX: Fix set private note (#26610) +FIX: Fix when options FAC_FORCE_DATE_VALIDATION and INVOICE_CHECK_POSTERIOR_DATE enabled. The date is forced after the test and not before +FIX: menu auguria +FIX: pagination parameters on save and cancel buttons (#26605) +FIX: pdf cornas page head multicell width (backport v17) +FIX: php8 fatal on edit supplier order when multicurrency is activated (#26758) +FIX: possible inconsistency between llx_ecm_files and file system when BILL_SUPPLIER_VALIDATES changes ref +FIX: regression on planned bank entries (#26556) +FIX: Social contribution - Payment list - Wrong information in type column (#26561) +FIX: special_code update line keep old value. (#26819) +FIX: substitute project variables in invoice documents (#26445) +FIX: Test on permission for holiday tooltips +FIX: v17: Param $notrigger in $societe->create() causes method to return true regardless of actual result of database functions (#26499) +FIX: v18 SQL error in llx_c_forme_juridique.sql when installing +FIX: Warehouse Global Amounts not displayed (#26478) +FIX: warning param $lineID getSpecialCode is negatif (#26826) +FIX: warning php8.2 undefined_array_key (#26830) + ***** ChangeLog for 18.0.3 compared to 18.0.2 ***** FIX: #25793 Cannot add time spent (#26405) FIX: #26100 Ticket - On edit, list of closed project must be excluded (#26223) diff --git a/build/exe/doliwamp/UsedPort.cpp b/build/exe/doliwamp/UsedPort.cpp index e2724b831a1..a63938c5038 100644 --- a/build/exe/doliwamp/UsedPort.cpp +++ b/build/exe/doliwamp/UsedPort.cpp @@ -253,6 +253,7 @@ int main(int argc, char **argv) //---------------- int noarg,curseurarg,help=0,invalide=0; char option; +char *endptr; for (noarg=1;noarg INT_MAX) { + // Handle error: Port number out of range + printf("Port number out of range\n"); + exit(-1); +} + help=!(Port > 0); // Show usage diff --git a/dev/dolibarr_changes.txt b/dev/dolibarr_changes.txt index 8305dbefbd9..a2a99bdfd5a 100644 --- a/dev/dolibarr_changes.txt +++ b/dev/dolibarr_changes.txt @@ -44,37 +44,34 @@ With NUSOAP: ------- -* In file nusoap.php, to avoid a warning, -Replace - if (isset($this->methodreturn) && ((get_class($this->methodreturn) == 'soap_fault') || (get_class($this->methodreturn) == 'nusoap_fault'))) { -By - if (! is_array($this->methodreturn) && isset($this->methodreturn) && ((get_class($this->methodreturn) == 'soap_fault') || (get_class($this->methodreturn) == 'nusoap_fault'))) { +* Line 1257 of file nusoap.php. Add: -* In file nusoap.php, to avoid a warning, -Replace call to serialize_val with no bugged value + libxml_disable_entity_loader(true); // Avoid load of external entities (security problem). Required only for libxml < 2. + + +* Line 4346 of file nusoap.php -* In all files, replace constructor names into __construct. Replace also parent::constructor_name with parent::__construct + $rev = array(); + preg_match('/\$Revision: ([^ ]+)/', $this->revision, $rev); + $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".(isset($rev[1]) ? $rev[1] : '').")"; -* Line 4222 of file nusoap.php - - $rev = array(); - preg_match('/\$Revision: ([^ ]+)/', $this->revision, $rev); - $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".(isset($rev[1]) ? $rev[1] : '').")"; +* Line 6566 of file nusoap.php, replace + if (count($attrs) > 0) { + with + if (is_array($attrs) && count($attrs) > 0) { TCPDF: ------ * Replace in tcpdf.php: - if (isset($this->imagekeys)) { foreach($this->imagekeys as $file) { unlink($file); } } with - if (isset($this->imagekeys)) { foreach($this->imagekeys as $file) { // DOL CHANGE If we keep this, source image files are physically destroyed @@ -82,8 +79,7 @@ with } } -* Replace in tcpdf.php - +* Replace in tcpdf.php: $preserve = array( 'file_id', 'internal_encoding', @@ -91,9 +87,7 @@ with 'bufferlen', 'buffer', 'cached_files', - with - $preserve = array( 'file_id', 'internal_encoding', @@ -104,14 +98,11 @@ with // @CHANGE DOL 'imagekeys', -* Replace in tcpdf.php - +* Replace in tcpdf.php: if (!@TCPDF_STATIC::file_exists($file)) { - return false; + return false; } - with - if (!@TCPDF_STATIC::file_exists($file)) { // DOL CHANGE If we keep this, the image is not visible on pages after the first one. //var_dump($file.' '.(!@TCPDF_STATIC::file_exists($file))); @@ -122,12 +113,9 @@ with } } -* Replace in tcpdf.php - +* Replace in tcpdf.php: if (($imgsrc[0] === '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) { - with - // @CHANGE LDR Add support for src="file://..." links if (strpos($imgsrc, 'file://') === 0) { $imgsrc = str_replace('file://', '/', $imgsrc); @@ -144,12 +132,9 @@ with elseif (($imgsrc[0] === '/') AND !empty($_SERVER['DOCUMENT_ROOT']) AND ($_SERVER['DOCUMENT_ROOT'] != '/')) { -* In tecnickcom/tcpdf/include/tcpdf_static.php, in function fopenLocal, replace - +* In tecnickcom/tcpdf/include/tcpdf_static.php, in function fopenLocal, replace: if (strpos($filename, '://') === false) { - with - if (strpos($filename, '//') === 0) { // Share folder on a (windows) server // e.g.: "//[MyServerName]/[MySharedFolder]/" @@ -158,17 +143,22 @@ with } elseif (strpos($filename, '://') === false) -* To avoid to have QRcode changed because generated with a random mask, replace -define('QR_FIND_FROM_RANDOM', 2); +* To avoid to have QRcode changed because generated with a random mask, replace: + define('QR_FIND_FROM_RANDOM', 2); with -define('QR_FIND_FROM_RANDOM', false); + define('QR_FIND_FROM_RANDOM', false); +* Change line: + imagesetpixel($imgalpha, $xpx, $ypx, $alpha); +into + imagesetpixel($imgalpha, $xpx, $ypx, (int) $alpha); + * Removed useless directories ("examples", "tools") -* Optionnaly, removed all fonts except - dejavusans* (used by greek, arab, persan, romanian, turkish), - freemono* (russian), - cid*+msungstdlight+stsongstdlight+uni2cid* (chinese), +* Optionnaly, removed all fonts except + dejavusans* (used by greek, arab, persan, romanian, turkish), + freemono* (russian), + cid*+msungstdlight+stsongstdlight+uni2cid* (chinese), helvetica* (all other languages), zapfdingbats.php (for special chars like form checkboxes) @@ -180,15 +170,15 @@ In htdocs/includes/tecnickcom/tcpdf/tcpdf.php * In tecnickcom/tcpdf/include/tcpdf_static, in function intToRoman, right at the beginning of the function, replace: - $roman = ''; + $roman = ''; -with: + with: - $roman = ''; - if ($number >= 4000) { - // do not represent numbers above 4000 in Roman numerals - return strval($number); - } + $roman = ''; + if ($number >= 4000) { + // do not represent numbers above 4000 in Roman numerals + return strval($number); + } * Add this at begin of tcpdf_autoconfig.php @@ -223,7 +213,7 @@ with: * Fix syntax error by replacing } elseif (($key == '/Index') AND ($v[0] == PDF_TYPE_ARRAY AND count($v[1] >= 2))) { -with + with } elseif (($key == '/Index') AND ($v[0] == PDF_TYPE_ARRAY AND count($v[1]) >= 2)) { * Fix php fatal error on php 8.0 on tcpdi.php @@ -314,6 +304,24 @@ RESTLER: empty($value[0]) ? null : empty($value[1]) ? null : +* Add a test into AutoLoader.php to complete function loadThisLoader and test if property exists before calling it. For this replace code + + if (false !== $file = $b::$loader[1]($className) && $this->exists($className, $b::$loader[1])) { + return $file; + } + + with: + + //avoid PHP Fatal error: Uncaught Error: Access to undeclared static property: Composer\\Autoload\\ClassLoader::$loader + //in case of multiple autoloader systems + if(property_exists($b, $loader[1])) { + if (false !== $file = $b::$loader[1]($className) + && $this->exists($className, $b::$loader[1])) { + return $file; + } + } + + +With swagger 2 provided into /explorer: ---------------------------------------- @@ -327,16 +335,15 @@ PARSEDOWN * Add support of css by adding in Parsedown.php: // @CHANGE LDR - 'class' => $Link['element']['attributes']['class'] + 'class' => $Link['element']['attributes']['class'] ... - + // @CHANGE LDR - if (preg_match('/{([^}]+)}/', $remainder, $matches2)) - { - $Element['attributes']['class'] = $matches2[1]; - $remainder = preg_replace('/{'.preg_quote($matches2[1],'/').'}/', '', $remainder); - } + if (preg_match('/{([^}]+)}/', $remainder, $matches2)) { + $Element['attributes']['class'] = $matches2[1]; + $remainder = preg_replace('/{'.preg_quote($matches2[1],'/').'}/', '', $remainder); + } // @CHANGE LDR @@ -369,7 +376,7 @@ Add into Class Google of file OAuth2/Service/Google: } $this->approvalPrompt = $prompt; } - + JEDITABLE.JS diff --git a/dev/initdata/generate-proposal.php b/dev/initdata/generate-proposal.php index cf9a708de9e..3c357949e28 100755 --- a/dev/initdata/generate-proposal.php +++ b/dev/initdata/generate-proposal.php @@ -152,7 +152,7 @@ $user->rights->propal->creer=1; $user->rights->propal->propal_advance->validate=1; -if (!empty($conf->global->PROPALE_ADDON) && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/propale/" . getDolGlobalString('PROPALE_ADDON').".php")) { +if (getDolGlobalString('PROPALE_ADDON') && is_readable(DOL_DOCUMENT_ROOT ."/core/modules/propale/" . getDolGlobalString('PROPALE_ADDON').".php")) { require_once DOL_DOCUMENT_ROOT ."/core/modules/propale/" . getDolGlobalString('PROPALE_ADDON').".php"; } diff --git a/dev/initdata/import-thirdparties.php b/dev/initdata/import-thirdparties.php index 5a5bde31905..a0e40d7b883 100755 --- a/dev/initdata/import-thirdparties.php +++ b/dev/initdata/import-thirdparties.php @@ -129,7 +129,7 @@ while ($fields=fgetcsv($fhandle, $linelength, $delimiter, $enclosure, $escape)) $object->fournisseur = $fields[8]; $object->name = $fields[13] ? trim($fields[13]) : $fields[0]; - $object->name_alias = $fields[0]!=$fields[13] ? trim($fields[0]) : ''; + $object->name_alias = $fields[0] != $fields[13] ? trim($fields[0]) : ''; $object->address = trim($fields[14]); $object->zip = trim($fields[15]); diff --git a/dev/initdata/purge-data.php b/dev/initdata/purge-data.php index d75c9fae8b2..442d991a453 100755 --- a/dev/initdata/purge-data.php +++ b/dev/initdata/purge-data.php @@ -148,8 +148,8 @@ $sqls=array( "DELETE FROM ".MAIN_DB_PREFIX."product where datec < '__DATE__'", ), 'project'=>array( - // TODO set fk_project to null on object that refer to project - "DELETE FROM ".MAIN_DB_PREFIX."projet_task_time WHERE fk_task IN (select rowid FROM ".MAIN_DB_PREFIX."projet_task WHERE fk_projet IN (select rowid FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__'))", + // TODO set fk_project to null on all objects/tables that refer to project + "DELETE FROM ".MAIN_DB_PREFIX."element_time WHERE elementtype = 'task' AND fk_element IN (select rowid FROM ".MAIN_DB_PREFIX."projet_task WHERE fk_projet IN (select rowid FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__'))", "DELETE FROM ".MAIN_DB_PREFIX."projet_task WHERE fk_projet IN (select rowid FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__')", "DELETE FROM ".MAIN_DB_PREFIX."projet where datec < '__DATE__'", ), diff --git a/dev/tools/github_authors_and_commits_peryear.sh b/dev/tools/github_authors_and_commits_peryear.sh index bdba2a2a6ed..9b6d299601e 100755 --- a/dev/tools/github_authors_and_commits_peryear.sh +++ b/dev/tools/github_authors_and_commits_peryear.sh @@ -1,10 +1,11 @@ #!/bin/sh # # Count number of different contributors and number of commits for a given year. +# Can be used for statistics (for example to generate the inforgraphy of the year) # if [ "x$1" = "x" ]; then - echo "Usage: $0 YEAR" + echo "Usage: $0 YEARSTART [YEAREND]" exit fi @@ -12,10 +13,15 @@ fi FROM=$1-01-01 TO=$1-12-31 -echo "Number of contributors for the year" -echo "git log --since $FROM --before $TO | grep ^Author | sort -u -f -i -b | wc -l" -git log --since $FROM --before $TO | grep ^Author | sort -u -f -i -b | wc -l +if [ "x$2" != "x" ]; then + TO=$2-12-31 +fi + +echo "--- Number of contributors for the year" +echo "git log --since $FROM --before $TO | grep ^Author | awk -F'<' '{ print $1 }' | iconv -f UTF-8 -t ASCII//TRANSLIT | sort -u -f -i -b | wc -l" +git log --since $FROM --before $TO | grep '^Author' | awk -F"<" '{ print $1 }' | iconv -f UTF-8 -t ASCII//TRANSLIT | sort -u -f -i -b | wc -l -echo "Number of commit for the year" -git log --pretty='format:%cd' --date=format:'%Y' | uniq -c | awk '{print "Year: "$2", commits: "$1}' | grep "Year: $1" +echo "--- Number of commit for the year" +echo "git log --pretty='format:%cd' --date=format:'%Y' | sort | uniq -c | awk '{ if (\$2 >= '"$1"') { print \"Year: \"\$2\", commits: \"\$1 } }'" +git log --pretty='format:%cd' --date=format:'%Y' | sort | uniq -c | awk '{ if ($2 >= '$1') { print "Year: "$2", commits: "$1 } }' diff --git a/dev/tools/rector/rector.php b/dev/tools/rector/rector.php index 6b13c2fbf0b..5b07d1da6cc 100644 --- a/dev/tools/rector/rector.php +++ b/dev/tools/rector/rector.php @@ -5,6 +5,7 @@ declare(strict_types=1); use Rector\Config\RectorConfig; use Rector\Core\ValueObject\PhpVersion; use Rector\Set\ValueObject\LevelSetList; +use Rector\Set\ValueObject\SetList; return static function (RectorConfig $rectorConfig): void { $rectorConfig->phpVersion(PhpVersion::PHP_71); @@ -26,6 +27,8 @@ return static function (RectorConfig $rectorConfig): void { $rectorConfig->skip([ '**/includes/**', '**/custom/**', + '**/vendor/**', + '**/rector/**', // Disable this line to test the "test.php" file. __DIR__ . '/../../../htdocs/custom/', __DIR__ . '/../../../htdocs/install/doctemplates/*' ]); @@ -39,15 +42,33 @@ return static function (RectorConfig $rectorConfig): void { //$rectorConfig->rule(Rector\Php72\Rector\FuncCall\GetClassOnNullRector::class); //$rectorConfig->rule(Rector\Php72\Rector\Assign\ListEachRector::class); //$rectorConfig->rule(Rector\Php72\Rector\FuncCall\ParseStrWithResultArgumentRector::class); - //$rectorConfig->rule(ReplaceEachAssignmentWithKeyCurrentRector::class); //$rectorConfig->rule(Rector\Php72\Rector\FuncCall\StringifyDefineRector::class); + //$rectorConfig->rule(ReplaceEachAssignmentWithKeyCurrentRector::class); + + $rectorConfig->rule(Rector\CodeQuality\Rector\FuncCall\FloatvalToTypeCastRector::class); + $rectorConfig->rule(Rector\CodeQuality\Rector\FuncCall\BoolvalToTypeCastRector::class); + $rectorConfig->rule(Rector\CodeQuality\Rector\NotEqual\CommonNotEqualRector::class); + //$rectorconfig->rule(Rector\CodeQuality\Rector\If_\CompleteMissingIfElseBracketRector::class); + $rectorConfig->rule(Rector\CodeQuality\Rector\For_\ForRepeatedCountToOwnVariableRector::class); + $rectorConfig->rule(Dolibarr\Rector\Renaming\GlobalToFunction::class); $rectorConfig->rule(Dolibarr\Rector\Renaming\UserRightsToFunction::class); $rectorConfig->rule(Dolibarr\Rector\Renaming\EmptyGlobalToFunction::class); - // Add all predefined rules to migrate to up to php 71 - // $rectorConfig->sets([ - // LevelSetList::UP_TO_PHP_71 - // ]); + // Add all predefined rules to migrate to up to php 71. + // Warning this break tab spacing of arrays on several lines + /*$rectorConfig->sets([ + LevelSetList::UP_TO_PHP_70 + ]);*/ + // Add predefined rules for a given version only + //$rectorConfig->import(SetList::PHP_70); + //$rectorConfig->import(SetList::PHP_71); + //$rectorConfig->import(SetList::PHP_72); + //$rectorConfig->import(SetList::PHP_73); + //$rectorConfig->import(SetList::PHP_74); + //$rectorConfig->import(SetList::PHP_80); + //$rectorConfig->import(SetList::PHP_81); + //$rectorConfig->import(SetList::PHP_82); + //$rectorConfig->import(SetList::PHP_83); }; diff --git a/dev/tools/rector/src/Renaming/GlobalToFunction.php b/dev/tools/rector/src/Renaming/GlobalToFunction.php index 656a7d4ff59..ea5b2718f8c 100644 --- a/dev/tools/rector/src/Renaming/GlobalToFunction.php +++ b/dev/tools/rector/src/Renaming/GlobalToFunction.php @@ -4,6 +4,7 @@ namespace Dolibarr\Rector\Renaming; use PhpParser\Node; use PhpParser\Node\Arg; +use PhpParser\Node\Expr\ArrayItem; use PhpParser\Node\Expr\ArrayDimFetch; use PhpParser\Node\Expr\BinaryOp\BooleanAnd; use PhpParser\Node\Expr\BinaryOp\Concat; @@ -12,6 +13,7 @@ use PhpParser\Node\Expr\BooleanNot; use PhpParser\Node\Expr\Empty_; use PhpParser\Node\Expr\FuncCall; use PhpParser\Node\Expr\Isset_; +use PhpParser\Node\Expr\MethodCall; use PhpParser\Node\Expr\PropertyFetch; use PhpParser\Node\Name; use PhpParser\Node\Scalar\String_; @@ -72,7 +74,7 @@ class GlobalToFunction extends AbstractRector */ public function getNodeTypes(): array { - return [FuncCall::class, Equal::class, NotEqual::class, Greater::class, GreaterOrEqual::class, Smaller::class, SmallerOrEqual::class, NotIdentical::class, BooleanAnd::class, Concat::class, ArrayDimFetch::class]; + return [FuncCall::class, MethodCall::class, Equal::class, NotEqual::class, Greater::class, GreaterOrEqual::class, Smaller::class, SmallerOrEqual::class, NotIdentical::class, BooleanAnd::class, Concat::class, ArrayItem::class, ArrayDimFetch::class]; } /** @@ -84,6 +86,23 @@ class GlobalToFunction extends AbstractRector */ public function refactor(Node $node) { + if ($node instanceof Node\Expr\ArrayItem) { + if (!isset($node->key)) { + return; + } + if ($this->isGlobalVar($node->value)) { + $constName = $this->getConstName($node->value); + if (empty($constName)) { + return; + } + $node->value = new FuncCall( + new Name('getDolGlobalString'), + [new Arg($constName)] + ); + } + return $node; + } + if ($node instanceof Node\Expr\ArrayDimFetch) { if (!isset($node->dim)) { return; @@ -103,7 +122,9 @@ class GlobalToFunction extends AbstractRector if ($node instanceof FuncCall) { $tmpfunctionname = $this->getName($node); - if (in_array($tmpfunctionname, array('dol_escape_htmltag', 'make_substitutions', 'min', 'max', 'explode'))) { + // If function is ok. We must avoid a lot of cases like isset(), empty() + if (in_array($tmpfunctionname, array('dol_escape_htmltag', 'dol_hash', 'make_substitutions', 'min', 'max', 'explode'))) { + //print "tmpfunctionname=".$tmpfunctionname."\n"; $args = $node->getArgs(); $nbofparam = count($args); @@ -129,6 +150,37 @@ class GlobalToFunction extends AbstractRector return $node; } + if ($node instanceof MethodCall) { + $tmpmethodname = $this->getName($node->name); + // If function is ok. We must avoid a lot of cases + if (in_array($tmpmethodname, array('idate'))) { + //print "tmpmethodname=".$tmpmethodname."\n"; + $expr = $node->var; + $args = $node->getArgs(); + $nbofparam = count($args); + + if ($nbofparam >= 1) { + $tmpargs = $args; + foreach ($args as $key => $arg) { // only 1 element in this array + //var_dump($key); + //var_dump($arg->value);exit; + if ($this->isGlobalVar($arg->value)) { + $constName = $this->getConstName($arg->value); + if (empty($constName)) { + return; + } + $a = new FuncCall(new Name('getDolGlobalString'), [new Arg($constName)]); + $tmpargs[$key] = new Arg($a); + + $r = new MethodCall($expr, $tmpmethodname, $tmpargs); + return $r; + } + } + } + } + return $node; + } + if ($node instanceof Concat) { if ($this->isGlobalVar($node->left)) { $constName = $this->getConstName($node->left); diff --git a/dev/tools/spider.php b/dev/tools/spider.php deleted file mode 100644 index 28871122e2c..00000000000 --- a/dev/tools/spider.php +++ /dev/null @@ -1,156 +0,0 @@ -#!/usr/bin/env php -. - */ - -/** - * \file dev/tools/spider.php - * \brief Script to spider Dolibarr app. - * - * To use it: - * - Disable module "bookmark" - * - Exclude param optioncss, token, sortfield, sortorder - */ - -$crawledLinks = array(); -const MAX_DEPTH = 2; - - -/** - * @param string $url URL - * @param string $depth Depth - * @return string String - */ -function followLink($url, $depth = 0) -{ - global $crawledLinks; - $crawling = array(); - if ($depth > MAX_DEPTH) { - echo "
The Crawler is giving up!
"; - return; - } - $options = array( - 'http' => array( - 'method' => "GET", - 'user-agent' => "gfgBot/0.1\n" - ) - ); - $context = stream_context_create($options); - $doc = new DomDocument(); - @$doc->loadHTML(file_get_contents($url, false, $context)); - $links = $doc->getElementsByTagName('a'); - $pageTitle = getDocTitle($doc, $url); - $metaData = getDocMetaData($doc); - foreach ($links as $i) { - $link = $i->getAttribute('href'); - if (ignoreLink($link)) { - continue; - } - $link = convertLink($url, $link); - if (!in_array($link, $crawledLinks)) { - $crawledLinks[] = $link; - $crawling[] = $link; - insertIntoDatabase($link, $pageTitle, $metaData, $depth); - } - } - foreach ($crawling as $crawlURL) { - followLink($crawlURL, $depth + 1); - } -} - -/** - * @param string $site Site - * @param string $path Path - * @return string String - */ -function convertLink($site, $path) -{ - if (substr_compare($path, "//", 0, 2) == 0) { - return parse_url($site)['scheme'].$path; - } elseif (substr_compare($path, "http://", 0, 7) == 0 - or substr_compare($path, "https://", 0, 8) == 0 - or substr_compare($path, "www.", 0, 4) == 0 - ) { - return $path; - } else { - return $site.'/'.$path; - } -} - -/** - * @param string $url URL - * @return boolean - */ -function ignoreLink($url) -{ - return $url[0] == "#" or substr($url, 0, 11) == "javascript:"; -} - -/** - * @param string $link URL - * @param string $title Title - * @param string $metaData Array - * @param int $depth Depth - * @return void - */ -function insertIntoDatabase($link, $title, &$metaData, $depth) -{ - //global $crawledLinks; - - echo "Inserting new record {URL= ".$link.", Title = '$title', Description = '".$metaData['description']."', Keywords = ' ".$metaData['keywords']."'}


"; - - //²$crawledLinks[]=$link; -} - -/** - * @param string $doc Doc - * @param string $url URL - * @return string URL/Title - */ -function getDocTitle(&$doc, $url) -{ - $titleNodes = $doc->getElementsByTagName('title'); - if (count($titleNodes) == 0 or !isset($titleNodes[0]->nodeValue)) { - return $url; - } - $title = str_replace('', '\n', $titleNodes[0]->nodeValue); - return (strlen($title) < 1) ? $url : $title; -} - -/** - * @param string $doc Doc - * @return array Array - */ -function getDocMetaData(&$doc) -{ - $metaData = array(); - $metaNodes = $doc->getElementsByTagName('meta'); - foreach ($metaNodes as $node) { - $metaData[$node->getAttribute("name")] = $node->getAttribute("content"); - } - if (!isset($metaData['description'])) { - $metaData['description'] = 'No Description Available'; - } - if (!isset($metaData['keywords'])) { - $metaData['keywords'] = ''; - } - return array( - 'keywords' => str_replace('', '\n', $metaData['keywords']), - 'description' => str_replace('', '\n', $metaData['description']) - ); -} - - -followLink("http://localhost/dolibarr_dev/htdocs"); diff --git a/dev/translation/autotranslator.class.php b/dev/translation/autotranslator.class.php index d2ad8d60344..3d6117b3892 100644 --- a/dev/translation/autotranslator.class.php +++ b/dev/translation/autotranslator.class.php @@ -240,7 +240,7 @@ class autoTranslator if ($this->_outputpagecode == 'UTF-8') { $val=$this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2)); } else { - $val=utf8_decode($this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2))); + $val=mb_convert_encoding($this->translateTexts(array($value), substr($this->_refLang, 0, 2), substr($my_destlang, 0, 2)), 'ISO-8859-1'); } } diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 29cb1300f4c..456b1503ca7 100644 --- a/htdocs/accountancy/admin/accountmodel.php +++ b/htdocs/accountancy/admin/accountmodel.php @@ -125,18 +125,10 @@ $tabfieldinsert[31] = "pcg_version,label,fk_country"; $tabrowid = array(); $tabrowid[31] = ""; -// Condition to show dictionary in setup page -$tabcond = array(); -$tabcond[31] = isModEnabled('accounting'); - // List of help for fields $tabhelp = array(); $tabhelp[31] = array('pcg_version'=>$langs->trans("EnterAnyCode")); -// List of check for fields (NOT USED YET) -$tabfieldcheck = array(); -$tabfieldcheck[31] = array(); - // Define elementList and sourceList (used for dictionary type of contacts "llx_c_type_contact") $elementList = array(); @@ -173,9 +165,12 @@ if (GETPOST('actionadd', 'alpha') || GETPOST('actionmodify', 'alpha')) { if ($fieldnamekey == 'pcg_version') { $fieldnamekey = 'Pcg_version'; } - if ($fieldnamekey == 'libelle' || ($fieldnamekey == 'label')) { + if ($fieldnamekey == 'label') { $fieldnamekey = 'Label'; } + if ($fieldnamekey == 'country') { + $fieldnamekey = "Country"; + } setEventMessages($langs->transnoentities("ErrorFieldRequired", $langs->transnoentities($fieldnamekey)), null, 'errors'); } @@ -453,6 +448,7 @@ if ($id) { print ''; // Form to add a new line + if ($tabname[$id]) { $fieldlist = explode(',', $tabfield[$id]); @@ -467,8 +463,9 @@ if ($id) { if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); } - if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { + if ($fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Label"); + $class = 'minwidth300'; } if ($fieldlist[$field] == 'country') { if (in_array('region_id', $fieldlist)) { @@ -483,6 +480,7 @@ if ($id) { if ($fieldlist[$field] == 'pcg_version' || $fieldlist[$field] == 'fk_pcg_version') { $valuetoshow = $langs->trans("Pcg_version"); } + //var_dump($value); if ($valuetoshow != '') { print ''; + print ''; } else { $tmpaction = 'view'; $parameters = array('fieldlist'=>$fieldlist, 'tabname'=>$tabname[$id]); @@ -711,6 +711,8 @@ if ($id) { $i++; } + } else { + print ''; } } else { dol_print_error($db); @@ -738,11 +740,10 @@ $db->close(); * @param string $context 'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered * @return void */ -function fieldListAccountModel($fieldlist, $obj = '', $tabname = '', $context = '') +function fieldListAccountModel($fieldlist, $obj = null, $tabname = '', $context = '') { - global $conf, $langs, $db; + global $langs, $db; global $form; - global $region_id; global $elementList, $sourceList; $formadmin = new FormAdmin($db); @@ -784,21 +785,14 @@ function fieldListAccountModel($fieldlist, $obj = '', $tabname = '', $context = print ''; } else { print ''; } } diff --git a/htdocs/accountancy/admin/categories_list.php b/htdocs/accountancy/admin/categories_list.php index 95714b0ce87..66f411c8cca 100644 --- a/htdocs/accountancy/admin/categories_list.php +++ b/htdocs/accountancy/admin/categories_list.php @@ -507,6 +507,7 @@ if ($tabname[$id]) { } if ($fieldlist[$field] == 'code') { $valuetoshow = $langs->trans("Code"); + $class = 'width75'; } if ($fieldlist[$field] == 'libelle' || $fieldlist[$field] == 'label') { $valuetoshow = $langs->trans("Label"); @@ -869,9 +870,12 @@ if ($resql) { $key = $langs->trans("Country".strtoupper($obj->country_code)); $valuetoshow = ($key != "Country".strtoupper($obj->country_code) ? $obj->country_code." - ".$key : $obj->country); } - } elseif (in_array($fieldlist[$field], array('label', 'range_account', 'formula'))) { + } elseif (in_array($fieldlist[$field], array('label', 'formula'))) { $class = "tdoverflowmax250"; $title = $valuetoshow; + } elseif (in_array($fieldlist[$field], array('range_account'))) { + $class = "tdoverflowmax250 small"; + $title = $valuetoshow; } elseif ($fieldlist[$field] == 'region_id' || $fieldlist[$field] == 'country_id') { $showfield = 0; } @@ -954,7 +958,7 @@ $db->close(); * @param string $context 'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered * @return void */ -function fieldListAccountingCategories($fieldlist, $obj = '', $tabname = '', $context = '') +function fieldListAccountingCategories($fieldlist, $obj = null, $tabname = '', $context = '') { global $conf, $langs, $db; global $form, $mysoc; @@ -994,8 +998,11 @@ function fieldListAccountingCategories($fieldlist, $obj = '', $tabname = '', $co } else { print '\n"; if (!$i) { diff --git a/htdocs/accountancy/bookkeeping/listbyaccount.php b/htdocs/accountancy/bookkeeping/listbyaccount.php index a6999195470..51b37ce6651 100644 --- a/htdocs/accountancy/bookkeeping/listbyaccount.php +++ b/htdocs/accountancy/bookkeeping/listbyaccount.php @@ -104,7 +104,7 @@ if (GETPOST("button_delmvt_x") || GETPOST("button_delmvt.x") || GETPOST("button_ } // Load variable for pagination -$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : (!getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION') ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION', $conf->liste_limit); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $optioncss = GETPOST('optioncss', 'alpha'); @@ -1200,12 +1200,9 @@ while ($i < min($num, $limit)) { // Other type } - print '\n"; if (!$i) { @@ -1228,7 +1224,11 @@ while ($i < min($num, $limit)) { if (!empty($arrayfields['t.label_operation']['checked'])) { // Affiche un lien vers la facture client/fournisseur $doc_ref = preg_replace('/\(.*\)/', '', $line->doc_ref); - print strlen(length_accounta($line->subledger_account)) == 0 ? '' : ''; + if (strlen(length_accounta($line->subledger_account)) == 0) { + print ''; + } else { + print ''; + } if (!$i) { $totalarray['nbfield']++; } @@ -1236,7 +1236,7 @@ while ($i < min($num, $limit)) { // Lettering code if (!empty($arrayfields['t.lettering_code']['checked'])) { - print ''; + print ''; if (!$i) { $totalarray['nbfield']++; } @@ -1295,7 +1295,7 @@ while ($i < min($num, $limit)) { } if (!empty($arrayfields['t.import_key']['checked'])) { - print '\n"; + print '\n"; if (!$i) { $totalarray['nbfield']++; } diff --git a/htdocs/accountancy/class/accountancyexport.class.php b/htdocs/accountancy/class/accountancyexport.class.php index 737573ef21e..e372ab9c206 100644 --- a/htdocs/accountancy/class/accountancyexport.class.php +++ b/htdocs/accountancy/class/accountancyexport.class.php @@ -103,7 +103,7 @@ class AccountancyExport $this->db = $db; $this->separator = $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV; - $this->end_line = !getDolGlobalString('ACCOUNTING_EXPORT_ENDLINE') ? "\n" : (getDolGlobalInt('ACCOUNTING_EXPORT_ENDLINE') == 1 ? "\n" : "\r\n"); + $this->end_line = getDolGlobalString('ACCOUNTING_EXPORT_ENDLINE') ? (getDolGlobalInt('ACCOUNTING_EXPORT_ENDLINE') == 1 ? "\n" : "\r\n") : "\n"; $hookmanager->initHooks(array('accountancyexport')); } @@ -201,9 +201,9 @@ class AccountancyExport 'param' => array( self::$EXPORT_TYPE_CONFIGURABLE => array( 'label' => $langs->trans('Modelcsv_configurable'), - 'ACCOUNTING_EXPORT_FORMAT' => !getDolGlobalString('ACCOUNTING_EXPORT_FORMAT') ? 'txt' : $conf->global->ACCOUNTING_EXPORT_FORMAT, - 'ACCOUNTING_EXPORT_SEPARATORCSV' => !getDolGlobalString('ACCOUNTING_EXPORT_SEPARATORCSV') ? ',' : $conf->global->ACCOUNTING_EXPORT_SEPARATORCSV, - 'ACCOUNTING_EXPORT_ENDLINE' => !getDolGlobalString('ACCOUNTING_EXPORT_ENDLINE') ? 1 : $conf->global->ACCOUNTING_EXPORT_ENDLINE, + 'ACCOUNTING_EXPORT_FORMAT' => getDolGlobalString('ACCOUNTING_EXPORT_FORMAT', 'txt'), + 'ACCOUNTING_EXPORT_SEPARATORCSV' => getDolGlobalString('ACCOUNTING_EXPORT_SEPARATORCSV', ','), + 'ACCOUNTING_EXPORT_ENDLINE' => getDolGlobalString('ACCOUNTING_EXPORT_ENDLINE', 1), 'ACCOUNTING_EXPORT_DATE' => getDolGlobalString('ACCOUNTING_EXPORT_DATE', '%Y-%m-%d'), ), self::$EXPORT_TYPE_CEGID => array( @@ -829,7 +829,7 @@ class AccountancyExport * @param array $objectLines data * @param resource $exportFile [=null] File resource to export or print if null * @param array $archiveFileList [=array()] Archive file list : array of ['path', 'name'] - * @param bool $withAttachment [=0] Not add files or 1 to have attached in an archive + * @param int $withAttachment [=0] Not add files or 1 to have attached in an archive * @return array Archive file list : array of ['path', 'name'] */ public function exportQuadratus($objectLines, $exportFile = null, $archiveFileList = array(), $withAttachment = 0) @@ -839,8 +839,6 @@ class AccountancyExport $end_line = "\r\n"; // We should use dol_now function not time however this is wrong date to transfert in accounting - // $date_ecriture = dol_print_date(dol_now(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy - // $date_ecriture = dol_print_date(time(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy foreach ($objectLines as $line) { // Clean some data $line->doc_ref = dol_string_unaccent($line->doc_ref); @@ -938,7 +936,6 @@ class AccountancyExport // Force date format : %d%m%y if (!empty($line->date_lim_reglement)) { - //$tab['date_echeance'] = dol_print_date($line->date_lim_reglement, $conf->global->ACCOUNTING_EXPORT_DATE); $tab['date_echeance'] = dol_print_date($line->date_lim_reglement, '%d%m%y'); // Format must be ddmmyy } else { $tab['date_echeance'] = '000000'; @@ -1061,10 +1058,6 @@ class AccountancyExport $end_line = "\r\n"; $index = 1; - //We should use dol_now function not time however this is wrong date to transfert in accounting - //$date_ecriture = dol_print_date(dol_now(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy - //$date_ecriture = dol_print_date(time(), $conf->global->ACCOUNTING_EXPORT_DATE); // format must be ddmmyy - // Warning ! When truncation is necessary, no dot because 3 dots = three characters. The columns are shifted foreach ($objectLines as $line) { @@ -1109,7 +1102,6 @@ class AccountancyExport $tab['code_stat'] = str_repeat(' ', 4); if (!empty($line->date_lim_reglement)) { - //$tab['date_echeance'] = dol_print_date($line->date_lim_reglement, $conf->global->ACCOUNTING_EXPORT_DATE); $tab['date_echeance'] = dol_print_date($line->date_lim_reglement, '%d%m%Y'); } else { $tab['date_echeance'] = dol_print_date($line->doc_date, '%d%m%Y'); @@ -1276,7 +1268,7 @@ class AccountancyExport $separator = $this->separator; foreach ($objectLines as $line) { - $date_document = dol_print_date($line->doc_date, $conf->global->ACCOUNTING_EXPORT_DATE); + $date_document = dol_print_date($line->doc_date, getDolGlobalString('ACCOUNTING_EXPORT_DATE')); $tab = array(); // export configurable @@ -1309,7 +1301,7 @@ class AccountancyExport * @param array $objectLines data * @param resource $exportFile [=null] File resource to export or print if null * @param array $archiveFileList [=array()] Archive file list : array of ['path', 'name'] - * @param bool $withAttachment [=0] Not add files or 1 to have attached in an archive + * @param int $withAttachment [=0] Not add files or 1 to have attached in an archive * @return array Archive file list : array of ['path', 'name'] */ public function exportFEC($objectLines, $exportFile = null, $archiveFileList = array(), $withAttachment = 0) @@ -1520,7 +1512,7 @@ class AccountancyExport * @param array $objectLines data * @param resource $exportFile [=null] File resource to export or print if null * @param array $archiveFileList [=array()] Archive file list : array of ['path', 'name'] - * @param bool $withAttachment [=0] Not add files or 1 to have attached in an archive + * @param int $withAttachment [=0] Not add files or 1 to have attached in an archive * @return array Archive file list : array of ['path', 'name'] */ public function exportFEC2($objectLines, $exportFile = null, $archiveFileList = array(), $withAttachment = 0) diff --git a/htdocs/accountancy/class/accountancyimport.class.php b/htdocs/accountancy/class/accountancyimport.class.php index 5f4d76bc4c5..cc21b5ccf6e 100644 --- a/htdocs/accountancy/class/accountancyimport.class.php +++ b/htdocs/accountancy/class/accountancyimport.class.php @@ -66,7 +66,7 @@ class AccountancyImport public function cleanAmount(&$arrayrecord, $listfields, $record_key) { $value_trim = trim($arrayrecord[$record_key]['val']); - return floatval($value_trim); + return (float) $value_trim; } /** @@ -98,8 +98,8 @@ class AccountancyImport $debit_index = $field_index_list['debit']; $credit_index = $field_index_list['credit']; - $debit = floatval($arrayrecord[$debit_index]['val']); - $credit = floatval($arrayrecord[$credit_index]['val']); + $debit = (float) $arrayrecord[$debit_index]['val']; + $credit = (float) $arrayrecord[$credit_index]['val']; if (!empty($debit)) { $amount = $debit; } else { @@ -127,7 +127,7 @@ class AccountancyImport if (isset($field_index_list['debit'])) { $debit_index = $field_index_list['debit']; - $debit = floatval($arrayrecord[$debit_index]['val']); + $debit = (float) $arrayrecord[$debit_index]['val']; if (!empty($debit)) { $sens = 'D'; } else { diff --git a/htdocs/accountancy/class/accountingjournal.class.php b/htdocs/accountancy/class/accountingjournal.class.php index 8456732a2a1..dd8dd36e2c9 100644 --- a/htdocs/accountancy/class/accountingjournal.class.php +++ b/htdocs/accountancy/class/accountingjournal.class.php @@ -470,7 +470,7 @@ class AccountingJournal extends CommonObject } // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND ad.depreciation_date >= '" . $this->db->idate($conf->global->ACCOUNTING_DATE_START_BINDING) . "'"; + $sql .= " AND ad.depreciation_date >= '" . $this->db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) . "'"; } $sql .= " ORDER BY ad.depreciation_date"; @@ -533,8 +533,6 @@ class AccountingJournal extends CommonObject $element_link = $element_static->getNomUrl(1, 'with_label'); $element_name_formatted_0 = dol_trunc($element_static->label, 16); - $element_name_formatted_1 = utf8_decode(dol_trunc($element_static->label, 32)); - $element_name_formatted_2 = utf8_decode(dol_trunc($element_static->label, 16)); $label_operation = $element_static->getNomUrl(0, 'label', 16); $element = array( @@ -618,12 +616,12 @@ class AccountingJournal extends CommonObject $disposal_date = $pre_data_info['disposal']['date']; if ((!($date_start && $date_end) || ($date_start <= $disposal_date && $disposal_date <= $date_end)) && - (!getDolGlobalString('ACCOUNTING_DATE_START_BINDING') || $conf->global->ACCOUNTING_DATE_START_BINDING <= $disposal_date) + (!getDolGlobalString('ACCOUNTING_DATE_START_BINDING') || getDolGlobalInt('ACCOUNTING_DATE_START_BINDING') <= $disposal_date) ) { $disposal_amount = $pre_data_info['disposal']['amount']; $disposal_subject_to_vat = $pre_data_info['disposal']['subject_to_vat']; $disposal_date_formatted = dol_print_date($disposal_date, 'day'); - $disposal_vat = getDolGlobalInt('ASSET_DISPOSAL_VAT') > 0 ? $conf->global->ASSET_DISPOSAL_VAT : 20; + $disposal_vat = getDolGlobalInt('ASSET_DISPOSAL_VAT') > 0 ? getDolGlobalInt('ASSET_DISPOSAL_VAT') : 20; // Get accountancy codes //--------------------------- @@ -1017,7 +1015,7 @@ class AccountingJournal extends CommonObject 'found' => true, 'label' => $accountingaccount->label, 'code_formatted_1' => length_accounta(html_entity_decode($account)), - 'label_formatted_1' => utf8_decode(dol_trunc($accountingaccount->label, 32)), + 'label_formatted_1' => mb_convert_encoding(dol_trunc($accountingaccount->label, 32), 'ISO-8859-1'), 'label_formatted_2' => dol_trunc($accountingaccount->label, 32), ); } else { diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index ffda82c2174..9de46b09d39 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -2124,7 +2124,7 @@ class BookKeeping extends CommonObject * @param array $event Event options * @param int $select_in Value is a aa.rowid (0 default) or aa.account_number (1) * @param int $select_out Set value returned by select 0=rowid (default), 1=account_number - * @param int $aabase Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number + * @param string $aabase Set accounting_account base class to display empty=all or from 1 to 8 will display only account beginning by this number * @return string String with HTML select */ public function select_account($selectid, $htmlname = 'account', $showempty = 0, $event = array(), $select_in = 0, $select_out = 0, $aabase = '') diff --git a/htdocs/accountancy/customer/index.php b/htdocs/accountancy/customer/index.php index 0551a3fe95a..3a9eced377c 100644 --- a/htdocs/accountancy/customer/index.php +++ b/htdocs/accountancy/customer/index.php @@ -165,7 +165,7 @@ if ($action == 'validatehistory') { $sql .= " AND l.product_type <= 2"; $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND f.datef >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } if ($validatemonth && $validateyear) { $sql .= dolSqlDateFilter('f.datef', 0, $validatemonth, $validateyear); @@ -329,7 +329,7 @@ print '
'; @@ -625,8 +623,10 @@ if ($id) { fieldListAccountModel($fieldlist, $obj, $tabname[$id], 'edit'); } - print ' '; - print ' '; + print ' '; + print ' '; + print '
'.$langs->trans("NoRecordFound").'
'; - $size = ''; $class = ''; - if ($fieldlist[$field] == 'code') { - $size = 'size="8" '; + if ($fieldlist[$field] == 'pcg_version') { + $class = 'width150'; } - if ($fieldlist[$field] == 'position') { - $size = 'size="4" '; + if ($fieldlist[$field] == 'label') { + $class = 'width300'; } - if ($fieldlist[$field] == 'libelle') { - $size = 'centpercent'; - } - if ($fieldlist[$field] == 'sortorder' || $fieldlist[$field] == 'sens' || $fieldlist[$field] == 'category_type') { - $size = 'size="2" '; - } - print ''; + print ''; print ''; $class = ''; - if (in_array($fieldlist[$field], array('code', 'range_account', 'label', 'formula'))) { - $class = 'maxwidth100'; + if (in_array($fieldlist[$field], array('code', 'formula'))) { + $class = 'maxwidth75'; + } + if (in_array($fieldlist[$field], array('label', 'range_account'))) { + $class = 'maxwidth150'; } if ($fieldlist[$field] == 'position') { $class = 'maxwidth50'; diff --git a/htdocs/accountancy/admin/index.php b/htdocs/accountancy/admin/index.php index 363fd2ecbb5..acff0845286 100644 --- a/htdocs/accountancy/admin/index.php +++ b/htdocs/accountancy/admin/index.php @@ -267,6 +267,7 @@ if ($action == 'setenablevatreversecharge') { } } + /* * View */ @@ -274,12 +275,16 @@ if ($action == 'setenablevatreversecharge') { $form = new Form($db); $title = $langs->trans('ConfigAccountingExpert'); + llxHeader('', $title); + $linkback = ''; //$linkback = '' . $langs->trans("BackToModuleList") . ''; print load_fiche_titre($title, $linkback, 'accountancy'); +print '
'; + // Show message if accountancy hidden options are activated to help to resolve some problems if (!$user->admin) { if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) { @@ -304,6 +309,7 @@ print ''; print ''; // Params +print '
'; print ''; print ''; print ''; @@ -387,9 +393,12 @@ foreach ($list as $key) { print ''; } print '
'.$langs->trans('Options').'
'; +print '
'; + print '
'; // Binding params +print '
'; print ''; print ''; print ''; @@ -403,12 +412,12 @@ foreach ($list_binding as $key) { $label = $langs->trans($key); print ''; // Value - print ''; print '
'.$langs->trans('BindingOptions').''.$label.''; + print ''; if ($key == 'ACCOUNTING_DATE_START_BINDING') { print $form->selectDate((getDolGlobalInt($key) ? (int) getDolGlobalInt($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, getDolGlobalInt('ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER', 0), 0, 0, 0, '', 0, 0, 0, '', 'onrightofpage'); + print $form->selectarray($key, $array, getDolGlobalInt('ACCOUNTING_DEFAULT_PERIOD_ON_TRANSFER', 0), 0, 0, 0, '', 0, 0, 0, '', 'onrightofpage width200'); } else { print ''; } @@ -457,7 +466,8 @@ if (getDolGlobalString('ACCOUNTING_DISABLE_BINDING_ON_EXPENSEREPORTS')) { print '
'; -print '
'; +print '
'; + // Show advanced options @@ -465,6 +475,7 @@ print '
'; // Advanced params +print '
'; print ''; print ''; print ''; @@ -533,6 +544,7 @@ if (getDolGlobalString('ACCOUNTING_FORCE_ENABLE_VAT_REVERSE_CHARGE')) { print ''; print '
' . $langs->trans('OptionsAdvanced') . '
'; +print '
'; print '
'; diff --git a/htdocs/accountancy/admin/journals_list.php b/htdocs/accountancy/admin/journals_list.php index 02158f7536a..c1ad8bdb0c5 100644 --- a/htdocs/accountancy/admin/journals_list.php +++ b/htdocs/accountancy/admin/journals_list.php @@ -691,7 +691,7 @@ $db->close(); * @param string $context 'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered * @return void */ -function fieldListJournal($fieldlist, $obj = '', $tabname = '', $context = '') +function fieldListJournal($fieldlist, $obj = null, $tabname = '', $context = '') { global $conf, $langs, $db; global $form, $mysoc; diff --git a/htdocs/accountancy/bookkeeping/card.php b/htdocs/accountancy/bookkeeping/card.php index 657ab76baf5..6ebc4b218bd 100644 --- a/htdocs/accountancy/bookkeeping/card.php +++ b/htdocs/accountancy/bookkeeping/card.php @@ -103,7 +103,7 @@ if ($cancel) { if ($action == "confirm_update") { $error = 0; - if ((floatval($debit) != 0.0) && (floatval($credit) != 0.0)) { + if (((float) $debit != 0.0) && ((float) $credit != 0.0)) { $error++; setEventMessages($langs->trans('ErrorDebitCredit'), null, 'errors'); $action = 'update'; @@ -130,12 +130,12 @@ if ($action == "confirm_update") { $object->debit = $debit; $object->credit = $credit; - if (floatval($debit) != 0.0) { + if ((float) $debit != 0.0) { $object->montant = $debit; // deprecated $object->amount = $debit; $object->sens = 'D'; } - if (floatval($credit) != 0.0) { + if ((float) $credit != 0.0) { $object->montant = $credit; // deprecated $object->amount = $credit; $object->sens = 'C'; @@ -159,7 +159,7 @@ if ($action == "confirm_update") { } elseif ($action == "add") { $error = 0; - if ((floatval($debit) != 0.0) && (floatval($credit) != 0.0)) { + if (((float) $debit != 0.0) && ((float) $credit != 0.0)) { $error++; setEventMessages($langs->trans('ErrorDebitCredit'), null, 'errors'); $action = ''; @@ -189,13 +189,13 @@ if ($action == "confirm_update") { $object->fk_doc = GETPOSTINT('fk_doc'); $object->fk_docdet = GETPOSTINT('fk_docdet'); - if (floatval($debit) != 0.0) { + if ((float) $debit != 0.0) { $object->montant = $debit; // deprecated $object->amount = $debit; $object->sens = 'D'; } - if (floatval($credit) != 0.0) { + if ((float) $credit != 0.0) { $object->montant = $credit; // deprecated $object->amount = $credit; $object->sens = 'C'; diff --git a/htdocs/accountancy/bookkeeping/export.php b/htdocs/accountancy/bookkeeping/export.php index b6f21694a4f..0d4b02386e1 100644 --- a/htdocs/accountancy/bookkeeping/export.php +++ b/htdocs/accountancy/bookkeeping/export.php @@ -134,7 +134,7 @@ $search_lettering_code = GETPOST('search_lettering_code', 'alpha'); $search_not_reconciled = GETPOST('search_not_reconciled', 'alpha'); // Load variable for pagination -$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : (!getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION') ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION', $conf->liste_limit); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $optioncss = GETPOST('optioncss', 'alpha'); diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index 580ea4287d1..7a10c5d96d6 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -129,7 +129,7 @@ $search_lettering_code = GETPOST('search_lettering_code', 'alpha'); $search_not_reconciled = GETPOST('search_not_reconciled', 'alpha'); // Load variable for pagination -$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : (!getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION') ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION', $conf->liste_limit); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $optioncss = GETPOST('optioncss', 'alpha'); @@ -1198,7 +1198,7 @@ while ($i < min($num, $limit)) { $labeltoshowalt .= $line->doc_ref; } - print '
'; + print ''; print $labeltoshow; print "'; + print ''; - print ''; // Picto + Ref - print '
'; - if ($line->doc_type == 'customer_invoice' || $line->doc_type == 'supplier_invoice' || $line->doc_type == 'expense_report') { print $objectstatic->getNomUrl(1, '', 0, 0, '', 0, -1, 1); print $documentlink; @@ -1216,7 +1213,6 @@ while ($i < min($num, $limit)) { } else { print $line->doc_ref; } - print '
'; print "
'.$line->label_operation.''.$line->label_operation.'
('.length_accounta($line->subledger_account).')
'.dol_escape_htmltag($line->label_operation).'('.length_accounta($line->subledger_account).')').'">'.dol_escape_htmltag($line->label_operation).($line->label_operation?'
':'').'('.dol_escape_htmltag(length_accounta($line->subledger_account)).')
'.$line->lettering_code.''.dol_escape_htmltag($line->lettering_code).''.$line->import_key."'.dol_escape_htmltag($line->import_key)."
'; print ''; print ''; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -337,7 +337,7 @@ for ($i = 1; $i <= 12; $i++) { if ($cursormonth > 12) { $cursormonth -= 12; } - $cursoryear = ($cursormonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt'); print '' $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,"; $sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,"; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -371,7 +371,7 @@ $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'"; $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND f.datef >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } $sql .= " AND f.fk_statut > 0"; $sql .= " AND fd.product_type <= 2"; @@ -405,27 +405,27 @@ if ($resql) { print ''; print ''; for ($i = 2; $i <= 13; $i++) { - $cursormonth = (($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) + $i - 2); + $cursormonth = (getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + $i - 2); if ($cursormonth > 12) { $cursormonth -= 12; } - $cursoryear = ($cursormonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt'); print '
'.$langs->trans("Account").''.$langs->trans("Label").''; @@ -357,7 +357,7 @@ print ''.$langs->trans("Total").'
'; if ($row[0] == 'tobind') { - $startmonth = ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1); + $startmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); if ($startmonth > 12) { $startmonth -= 12; } - $startyear = ($startmonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; - $endmonth = ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) + 11; + $startyear = ($startmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; + $endmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + 11; if ($endmonth > 12) { $endmonth -= 12; } - $endyear = ($endmonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $endyear = ($endmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/customer/list.php?search_date_startday=1&search_date_startmonth='.((int) $startmonth).'&search_date_startyear='.((int) $startyear).'&search_date_endday=&search_date_endmonth='.((int) $endmonth).'&search_date_endyear='.((int) $endyear), $langs->transnoentitiesnoconv("ToBind")); } else { print $row[1]; } print ''; @@ -466,7 +466,7 @@ print ''; print ''; print ''; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -474,7 +474,7 @@ for ($i = 1; $i <= 12; $i++) { if ($cursormonth > 12) { $cursormonth -= 12; } - $cursoryear = ($cursormonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt'); print '' $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,"; $sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,"; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -508,7 +508,7 @@ $sql .= " WHERE f.datef >= '".$db->idate($search_date_start)."'"; $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND f.datef >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND f.fk_statut > 0"; @@ -551,11 +551,11 @@ if ($resql) { print ''; for ($i = 2; $i <= 13; $i++) { - $cursormonth = (($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) + $i - 2); + $cursormonth = (getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + $i - 2); if ($cursormonth > 12) { $cursormonth -= 12; } - $cursoryear = ($cursormonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt'); print '
'.$langs->trans("Account").''.$langs->trans("Label").''; @@ -494,7 +494,7 @@ print ''.$langs->trans("Total").'
'; @@ -590,7 +590,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa print ''; print ''; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -600,7 +600,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa $sql = "SELECT '".$db->escape($langs->trans("TotalVente"))."' AS total,"; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -613,7 +613,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND f.datef >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND f.fk_statut > 0"; @@ -650,7 +650,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa print '
'.$langs->trans("TotalVente").'
'; print ''; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -662,7 +662,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa // With old situation invoice setup $sql = "SELECT '".$db->escape($langs->trans("Vide"))."' AS marge,"; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -684,7 +684,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa } else { $sql = "SELECT '".$db->escape($langs->trans("Vide"))."' AS marge,"; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -710,7 +710,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa $sql .= " AND f.datef <= '".$db->idate($search_date_end)."'"; // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND f.datef >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } $sql .= " AND f.entity IN (".getEntity('invoice', 0).")"; // We don't share object for accountancy $sql .= " AND f.fk_statut > 0"; diff --git a/htdocs/accountancy/customer/lines.php b/htdocs/accountancy/customer/lines.php index aad7c00f46c..4929b45ac67 100644 --- a/htdocs/accountancy/customer/lines.php +++ b/htdocs/accountancy/customer/lines.php @@ -65,7 +65,7 @@ $search_country = GETPOST('search_country', 'alpha'); $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); // Load variable for pagination -$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : (!getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION') ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION', $conf->liste_limit); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); @@ -506,7 +506,7 @@ if ($result) { print ''; diff --git a/htdocs/accountancy/customer/list.php b/htdocs/accountancy/customer/list.php index 3e312a220ef..4976c285dc0 100644 --- a/htdocs/accountancy/customer/list.php +++ b/htdocs/accountancy/customer/list.php @@ -76,11 +76,11 @@ $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); // Define begin binding date if (empty($search_date_start) && getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $search_date_start = $db->idate($conf->global->ACCOUNTING_DATE_START_BINDING); + $search_date_start = $db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING')); } // Load variable for pagination -$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : (!getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION') ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION', $conf->liste_limit); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); @@ -660,7 +660,7 @@ if ($result) { // Description of line print ''; diff --git a/htdocs/accountancy/expensereport/index.php b/htdocs/accountancy/expensereport/index.php index 1382eaf5ac6..97741175372 100644 --- a/htdocs/accountancy/expensereport/index.php +++ b/htdocs/accountancy/expensereport/index.php @@ -204,7 +204,7 @@ print '
'.$langs->trans("TotalMarge").''; $text = dolGetFirstLineOfText(dol_string_nohtmltag($objp->description, 1)); - $trunclength = !getDolGlobalString('ACCOUNTING_LENGTH_DESCRIPTION') ? 32 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION; + $trunclength = getDolGlobalInt('ACCOUNTING_LENGTH_DESCRIPTION', 32); print $form->textwithtooltip(dol_trunc($text, $trunclength), $objp->description); print ''; $text = dolGetFirstLineOfText(dol_string_nohtmltag($facture_static_det->desc, 1)); - $trunclength = !getDolGlobalString('ACCOUNTING_LENGTH_DESCRIPTION') ? 32 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION; + $trunclength = getDolGlobalInt('ACCOUNTING_LENGTH_DESCRIPTION', 32); print $form->textwithtooltip(dol_trunc($text, $trunclength), $facture_static_det->desc); print '
'; print ''; print ''; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -212,7 +212,7 @@ for ($i = 1; $i <= 12; $i++) { if ($cursormonth > 12) { $cursormonth -= 12; } - $cursoryear = ($cursormonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt'); print '' $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,"; $sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,"; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -247,7 +247,7 @@ $sql .= " WHERE er.date_debut >= '".$db->idate($search_date_start)."'"; $sql .= " AND er.date_debut <= '".$db->idate($search_date_end)."'"; // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND er.date_debut >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND er.date_debut >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } $sql .= " AND er.fk_statut IN (".ExpenseReport::STATUS_APPROVED.", ".ExpenseReport::STATUS_CLOSED.")"; $sql .= " AND er.entity IN (".getEntity('expensereport', 0).")"; // We don't share object for accountancy @@ -271,27 +271,27 @@ if ($resql) { print ''; print ''; for ($i = 2; $i <= 13; $i++) { - $cursormonth = (($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) + $i - 2); + $cursormonth = (getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + $i - 2); if ($cursormonth > 12) { $cursormonth -= 12; } - $cursoryear = ($cursormonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt'); print '
'.$langs->trans("Account").''.$langs->trans("Label").''; @@ -233,7 +233,7 @@ print ''.$langs->trans("Total").'
'; if ($row[0] == 'tobind') { - $startmonth = ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1); + $startmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); if ($startmonth > 12) { $startmonth -= 12; } - $startyear = ($startmonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; - $endmonth = ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) + 11; + $startyear = ($startmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; + $endmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + 11; if ($endmonth > 12) { $endmonth -= 12; } - $endyear = ($endmonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $endyear = ($endmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/expensereport/list.php?search_date_startday=1&search_date_startmonth='.((int) $startmonth).'&search_date_startyear='.((int) $startyear).'&search_date_endday=&search_date_endmonth='.((int) $endmonth).'&search_date_endyear='.((int) $endyear), $langs->transnoentitiesnoconv("ToBind")); } else { print $row[1]; } print ''; @@ -333,7 +333,7 @@ print ''; print ''; print ''; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -344,7 +344,7 @@ print '' $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,"; $sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,"; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -358,7 +358,7 @@ $sql .= " WHERE er.date_debut >= '".$db->idate($search_date_start)."'"; $sql .= " AND er.date_debut <= '".$db->idate($search_date_end)."'"; // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND er.date_debut >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND er.date_debut >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } $sql .= " AND er.fk_statut IN (".ExpenseReport::STATUS_APPROVED.", ".ExpenseReport::STATUS_CLOSED.")"; $sql .= " AND er.entity IN (".getEntity('expensereport', 0).")"; // We don't share object for accountancy @@ -421,7 +421,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa print '
'.$langs->trans("Account").''.$langs->trans("Label").''.$langs->trans("Total").'
'; print ''; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -431,7 +431,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa $sql = "SELECT '".$db->escape($langs->trans("TotalExpenseReport"))."' AS label,"; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -444,7 +444,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa $sql .= " AND er.date_debut <= '".$db->idate($search_date_end)."'"; // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND er.date_debut >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND er.date_debut >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } $sql .= " AND er.fk_statut IN (".ExpenseReport::STATUS_APPROVED.", ".ExpenseReport::STATUS_CLOSED.")"; $sql .= " AND er.entity IN (".getEntity('expensereport', 0).")"; // We don't share object for accountancy diff --git a/htdocs/accountancy/expensereport/lines.php b/htdocs/accountancy/expensereport/lines.php index 2f9c4e70e8e..998992dc3cd 100644 --- a/htdocs/accountancy/expensereport/lines.php +++ b/htdocs/accountancy/expensereport/lines.php @@ -59,7 +59,7 @@ $search_date_start = dol_mktime(0, 0, 0, $search_date_startmonth, $search_date_s $search_date_end = dol_mktime(23, 59, 59, $search_date_endmonth, $search_date_endday, $search_date_endyear); // Load variable for pagination -$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : (!getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION') ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION', $conf->liste_limit); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); @@ -414,7 +414,7 @@ if ($result) { // Fees description -- Can be null print ''; diff --git a/htdocs/accountancy/expensereport/list.php b/htdocs/accountancy/expensereport/list.php index a1d405f5725..a5a67770361 100644 --- a/htdocs/accountancy/expensereport/list.php +++ b/htdocs/accountancy/expensereport/list.php @@ -69,11 +69,11 @@ $search_date_end = dol_mktime(23, 59, 59, $search_date_endmonth, $search_date_en // Define begin binding date if (empty($search_date_start) && getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $search_date_start = $db->idate($conf->global->ACCOUNTING_DATE_START_BINDING); + $search_date_start = $db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING')); } // Load variable for pagination -$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : (!getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION') ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION', $conf->liste_limit); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); @@ -489,7 +489,7 @@ if ($result) { // Fees description -- Can be null print ''; diff --git a/htdocs/accountancy/index.php b/htdocs/accountancy/index.php index d8c49b639f4..4dcc41d38f1 100644 --- a/htdocs/accountancy/index.php +++ b/htdocs/accountancy/index.php @@ -40,14 +40,6 @@ $hookmanager->initHooks(array('accountancyindex')); if ($user->socid > 0) { accessforbidden(); } -/* -if (!isModEnabled('accounting')) { - accessforbidden(); -} -if (!$user->hasRight('accounting', 'mouvements', 'lire')) { - accessforbidden(); -} -*/ if (!isModEnabled('comptabilite') && !isModEnabled('accounting') && !isModEnabled('asset') && !isModEnabled('intracommreport')) { accessforbidden(); } @@ -55,6 +47,8 @@ if (!$user->hasRight('compta', 'resultat', 'lire') && !$user->hasRight('accounti accessforbidden(); } +$pcgver = getDolGlobalInt('CHARTOFACCOUNTS'); + /* * Actions @@ -127,18 +121,38 @@ if (isModEnabled('accounting')) { // STEPS $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescJournalSetup", $step, '{s}'); - $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("AccountingJournals").'', $s); + $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("AccountingJournals").'', $s); print $s; print "
\n"; $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescChartModel", $step, '{s}'); - $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("Pcg_version").'', $s); + $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("Pcg_version").'', $s); print $s; print "
\n"; $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescChart", $step, '{s}'); - $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("Chartofaccounts").'', $s); + $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("Chartofaccounts").'', $s); print $s; + if ($pcgver > 0) { + $pcgversion = ''; + $pcglabel = ''; + + $sql = "SELECT a.rowid, a.pcg_version, a.label, a.active"; + $sql .= " FROM ".MAIN_DB_PREFIX."accounting_system as a"; + $sql .= " WHERE a.rowid = ".((int) $pcgver); + + $resqlchart = $db->query($sql); + if ($resqlchart) { + $obj = $db->fetch_object($resqlchart); + if ($obj) { + $pcgversion = $obj->pcg_version; + $pcglabel = $obj->label; + } + } else { + dol_print_error($db); + } + print ' ('.$langs->trans("CurrentChartOfAccount").': '.$pcgversion.')'; + } print "
\n"; print "
\n"; @@ -149,32 +163,32 @@ if (isModEnabled('accounting')) { if (getDolGlobalString('ACCOUNTANCY_FISCAL_PERIOD_MODE') != 'blockedonclosed') { $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescFiscalPeriod", $step, '{s}'); - $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("FiscalPeriod").'', $s); + $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("FiscalPeriod").'', $s); print $s; print "
\n"; } $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescDefault", $step, '{s}'); - $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuDefaultAccounts").'', $s); + $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuDefaultAccounts").'', $s); print $s; print "
\n"; $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBank", $step, '{s}')."\n"; - $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuBankAccounts").'', $s); + $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuBankAccounts").'', $s); print $s; print "
\n"; $step++; - $textlink = ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuVatAccounts").''; + $textlink = ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuVatAccounts").''; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescVat", $step, '{s}'); $s = str_replace('{s}', $textlink, $s); print $s; print "
\n"; if (isModEnabled('tax')) { - $textlink = ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuTaxAccounts").''; + $textlink = ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("MenuTaxAccounts").''; $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescContrib", $step, '{s}'); $s = str_replace('{s}', $textlink, $s); @@ -191,7 +205,7 @@ if (isModEnabled('accounting')) { $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescProd", $step, '{s}'); - $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("ProductsBinding").'', $s); + $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("Setup").' - '.$langs->transnoentitiesnoconv("ProductsBinding").'', $s); print $s; print "
\n"; @@ -210,20 +224,20 @@ if (isModEnabled('accounting')) { $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64 + $step), $langs->transnoentitiesnoconv("BillsCustomers"), '{s}')."\n"; - $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("CustomersVentilation").'', $s); + $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("CustomersVentilation").'', $s); print $s; print "
\n"; $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64 + $step), $langs->transnoentitiesnoconv("BillsSuppliers"), '{s}')."\n"; - $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("SuppliersVentilation").'', $s); + $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("SuppliersVentilation").'', $s); print $s; print "
\n"; if (isModEnabled('expensereport') || isModEnabled('deplacement')) { $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescBind", chr(64 + $step), $langs->transnoentitiesnoconv("ExpenseReports"), '{s}')."\n"; - $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("ExpenseReportsVentilation").'', $s); + $s = str_replace('{s}', ''.$langs->transnoentitiesnoconv("TransferInAccounting").' - '.$langs->transnoentitiesnoconv("ExpenseReportsVentilation").'', $s); print $s; print "
\n"; } @@ -236,8 +250,14 @@ if (isModEnabled('accounting')) { $step++; $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescAnalyze", chr(64 + $step))."
\n"; print $s; + + $step++; + $s = img_picto('', 'puce').' '.$langs->trans("AccountancyAreaDescClosePeriod", chr(64 + $step))."
\n"; + print $s; + print "
\n"; + print '
'; print ''; diff --git a/htdocs/accountancy/journal/bankjournal.php b/htdocs/accountancy/journal/bankjournal.php index 5d80232d51d..11c00917743 100644 --- a/htdocs/accountancy/journal/bankjournal.php +++ b/htdocs/accountancy/journal/bankjournal.php @@ -1305,7 +1305,7 @@ if (empty($action) || $action == 'view') { if (!getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE') || getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE') == '-1') { $accounttoshow = ''.$langs->trans('UnknownAccountForThirdpartyAndWaitingAccountNotDefinedBlocking').''; } else { - $accounttoshow = ''.$langs->trans('UnknownAccountForThirdparty', length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE)).''; // We will use a waiting account + $accounttoshow = ''.$langs->trans('UnknownAccountForThirdparty', length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_SUSPENSE'))).''; // We will use a waiting account } } else { // We will refuse writing @@ -1396,7 +1396,8 @@ if (empty($action) || $action == 'view') { { print ''.$langs->trans("WaitAccountNotDefined").''; } - else */ print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE); + else */ + print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE); print ""; // Subledger account print ""; - print ""; + print ""; print '"; print '"; print '"; diff --git a/htdocs/accountancy/journal/expensereportsjournal.php b/htdocs/accountancy/journal/expensereportsjournal.php index fb86cdc3505..a1bf3006328 100644 --- a/htdocs/accountancy/journal/expensereportsjournal.php +++ b/htdocs/accountancy/journal/expensereportsjournal.php @@ -133,7 +133,7 @@ if ($date_start && $date_end) { } // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND er.date_debut >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND er.date_debut >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } // Already in bookkeeping or not if ($in_bookkeeping == 'already') { @@ -162,8 +162,8 @@ if ($result) { $num = $db->num_rows($result); // Variables - $account_salary = (getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT')) ? $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT : 'NotDefined'; - $account_vat = (getDolGlobalString('ACCOUNTING_VAT_BUY_ACCOUNT')) ? $conf->global->ACCOUNTING_VAT_BUY_ACCOUNT : 'NotDefined'; + $account_salary = getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT', 'NotDefined'); + $account_vat = getDolGlobalString('ACCOUNTING_VAT_BUY_ACCOUNT', 'NotDefined'); $i = 0; while ($i < $num) { @@ -247,7 +247,7 @@ if ($action == 'writebookkeeping' && !$error) { $error = 0; $accountingaccountexpense = new AccountingAccount($db); - $accountingaccountexpense->fetch(null, $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT, true); + $accountingaccountexpense->fetch(null, getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT'), true); foreach ($taber as $key => $val) { // Loop on each expense report $errorforline = 0; @@ -279,7 +279,7 @@ if ($action == 'writebookkeeping' && !$error) { $bookkeeping->subledger_account = $tabuser[$key]['user_accountancy_code']; $bookkeeping->subledger_label = $tabuser[$key]['name']; - $bookkeeping->numero_compte = $conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT; + $bookkeeping->numero_compte = getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT'); $bookkeeping->label_compte = $accountingaccountexpense->label; $bookkeeping->label_operation = $tabuser[$key]['name']; @@ -726,7 +726,7 @@ if (empty($action) || $action == 'view') { print ""; // Account print "", 3); + $buffer .= '
'.$langs->trans("Total").''; $text = dolGetFirstLineOfText(dol_string_nohtmltag($objp->comments, 1)); - $trunclength = !getDolGlobalString('ACCOUNTING_LENGTH_DESCRIPTION') ? 32 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION; + $trunclength = getDolGlobalString('ACCOUNTING_LENGTH_DESCRIPTION', 32); print $form->textwithtooltip(dol_trunc($text, $trunclength), $objp->comments); print ''; $text = dolGetFirstLineOfText(dol_string_nohtmltag($objp->comments, 1)); - $trunclength = !getDolGlobalString('ACCOUNTING_LENGTH_DESCRIPTION') ? 32 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION; + $trunclength = getDolGlobalInt('ACCOUNTING_LENGTH_DESCRIPTION', 32); print $form->textwithtooltip(dol_trunc($text, $trunclength), $objp->comments); print '"; @@ -1407,7 +1408,7 @@ if (empty($action) || $action == 'view') { else print length_accountg($conf->global->ACCOUNTING_ACCOUNT_SUSPENSE); */ print "".$reflabel."".dol_escape_htmltag($reflabel)."'.$val["type_payment"]."'.($mt < 0 ? price(-$mt) : '')."'.($mt >= 0 ? price($mt) : '')."".$expensereportstatic->getNomUrl(1).""; - $accountoshow = length_accountg($conf->global->SALARIES_ACCOUNTING_ACCOUNT_PAYMENT); + $accountoshow = length_accountg(getDolGlobalString('SALARIES_ACCOUNTING_ACCOUNT_PAYMENT')); if (($accountoshow == "") || $accountoshow == 'NotDefined') { print ''.$langs->trans("MainAccountForUsersNotDefined").''; } else { diff --git a/htdocs/accountancy/journal/purchasesjournal.php b/htdocs/accountancy/journal/purchasesjournal.php index 8439ff5ec99..21a624194ca 100644 --- a/htdocs/accountancy/journal/purchasesjournal.php +++ b/htdocs/accountancy/journal/purchasesjournal.php @@ -808,12 +808,12 @@ if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 ! print '"'.$key.'"'.$sep; print '"'.$date.'"'.$sep; print '"'.$val["refsologest"].'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 32), 'ISO-8859-1').'"'.$sep; print '"'.length_accounta(html_entity_decode($k)).'"'.$sep; print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER')).'"'.$sep; print '"'.length_accounta(html_entity_decode($k)).'"'.$sep; print '"'.$langs->trans("Thirdparty").'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("Thirdparty").'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 16), 'ISO-8859-1').' - '.$val["refsuppliersologest"].' - '.$langs->trans("Thirdparty").'"'.$sep; print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep; print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep; print '"'.$journal.'"'; @@ -829,12 +829,12 @@ if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 ! print '"'.$key.'"'.$sep; print '"'.$date.'"'.$sep; print '"'.$val["refsologest"].'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 32), 'ISO-8859-1').'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '""'.$sep; - print '"'.utf8_decode(dol_trunc($accountingaccount->label, 32)).'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.dol_trunc($accountingaccount->label, 32).'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($accountingaccount->label, 32), 'ISO-8859-1').'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 16), 'ISO-8859-1').' - '.$val["refsuppliersologest"].' - '.dol_trunc($accountingaccount->label, 32).'"'.$sep; print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep; print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep; print '"'.$journal.'"'; @@ -881,12 +881,12 @@ if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 ! print '"'.$key.'"'.$sep; print '"'.$date.'"'.$sep; print '"'.$val["refsologest"].'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 32), 'ISO-8859-1').'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '""'.$sep; print '"'.$langs->trans("VAT").' - '.join(', ', $def_tva[$key][$k]).' %"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("VAT").join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '').'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 16), 'ISO-8859-1').' - '.$val["refsuppliersologest"].' - '.$langs->trans("VAT").join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '').'"'.$sep; print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep; print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep; print '"'.$journal.'"'; @@ -901,12 +901,12 @@ if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 ! print '"'.$key.'"'.$sep; print '"'.$date.'"'.$sep; print '"'.$val["refsologest"].'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 32), 'ISO-8859-1').'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '"'.$langs->trans("Thirdparty").'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$val["refsuppliersologest"].' - '.$langs->trans("VAT").' NPR"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 16), 'ISO-8859-1').' - '.$val["refsuppliersologest"].' - '.$langs->trans("VAT").' NPR"'.$sep; print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep; print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep; print '"'.$journal.'"'; diff --git a/htdocs/accountancy/journal/sellsjournal.php b/htdocs/accountancy/journal/sellsjournal.php index b91a7393572..d8097020289 100644 --- a/htdocs/accountancy/journal/sellsjournal.php +++ b/htdocs/accountancy/journal/sellsjournal.php @@ -869,12 +869,12 @@ if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 ! print '"'.$key.'"'.$sep; print '"'.$date.'"'.$sep; print '"'.$val["ref"].'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 32), 'ISO-8859-1').'"'.$sep; print '"'.length_accounta(html_entity_decode($k)).'"'.$sep; print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER_RETAINED_WARRANTY')).'"'.$sep; print '"'.length_accounta(html_entity_decode($k)).'"'.$sep; print '"'.$langs->trans("Thirdparty").'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("Retainedwarranty").'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 16), 'ISO-8859-1').' - '.$invoicestatic->ref.' - '.$langs->trans("Retainedwarranty").'"'.$sep; print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep; print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep; print '"'.$journal.'"'; @@ -888,12 +888,12 @@ if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 ! print '"'.$key.'"'.$sep; print '"'.$date.'"'.$sep; print '"'.$val["ref"].'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 32), 'ISO-8859-1').'"'.$sep; print '"'.length_accounta(html_entity_decode($k)).'"'.$sep; print '"'.length_accountg(getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER')).'"'.$sep; print '"'.length_accounta(html_entity_decode($k)).'"'.$sep; print '"'.$langs->trans("Thirdparty").'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("Thirdparty").'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 16), 'ISO-8859-1').' - '.$invoicestatic->ref.' - '.$langs->trans("Thirdparty").'"'.$sep; print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep; print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep; print '"'.$journal.'"'; @@ -909,12 +909,12 @@ if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 ! print '"'.$key.'"'.$sep; print '"'.$date.'"'.$sep; print '"'.$val["ref"].'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 32), 'ISO-8859-1').'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '""'.$sep; - print '"'.utf8_decode(dol_trunc($accountingaccount->label, 32)).'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.dol_trunc($accountingaccount->label, 32).'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($accountingaccount->label, 32), 'ISO-8859-1').'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 16), 'ISO-8859-1').' - '.dol_trunc($accountingaccount->label, 32).'"'.$sep; print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep; print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep; print '"'.$journal.'"'; @@ -938,12 +938,12 @@ if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 ! print '"'.$key.'"'.$sep; print '"'.$date.'"'.$sep; print '"'.$val["ref"].'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 32), 'ISO-8859-1').'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '""'.$sep; print '"'.$langs->trans("VAT").' - '.join(', ', $def_tva[$key][$k]).' %"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '').'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 16), 'ISO-8859-1').' - '.$invoicestatic->ref.' - '.$langs->trans("VAT").join(', ', $def_tva[$key][$k]).' %'.($numtax ? ' - Localtax '.$numtax : '').'"'.$sep; print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep; print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep; print '"'.$journal.'"'; @@ -958,12 +958,12 @@ if ($action == 'exportcsv' && !$error) { // ISO and not UTF8 ! print '"'.$key.'"'.$sep; print '"'.$date.'"'.$sep; print '"'.$val["ref"].'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 32)).'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 32), 'ISO-8859-1').'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '"'.length_accountg(html_entity_decode($k)).'"'.$sep; print '""'.$sep; print '"'.$langs->trans("RevenueStamp").'"'.$sep; - print '"'.utf8_decode(dol_trunc($companystatic->name, 16)).' - '.$invoicestatic->ref.' - '.$langs->trans("RevenueStamp").'"'.$sep; + print '"'.mb_convert_encoding(dol_trunc($companystatic->name, 16), 'ISO-8859-1').' - '.$invoicestatic->ref.' - '.$langs->trans("RevenueStamp").'"'.$sep; print '"'.($mt < 0 ? price(-$mt) : '').'"'.$sep; print '"'.($mt >= 0 ? price($mt) : '').'"'.$sep; print '"'.$journal.'"'; diff --git a/htdocs/accountancy/supplier/index.php b/htdocs/accountancy/supplier/index.php index a8181885c3a..562d4f73e9d 100644 --- a/htdocs/accountancy/supplier/index.php +++ b/htdocs/accountancy/supplier/index.php @@ -163,7 +163,7 @@ if ($action == 'validatehistory') { $sql .= " AND l.product_type <= 2"; $sql .= " AND f.entity IN (".getEntity('facture_fourn', 0).")"; // We don't share object for accountancy if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND f.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND f.datef >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } if ($validatemonth && $validateyear) { $sql .= dolSqlDateFilter('f.datef', 0, $validatemonth, $validateyear); @@ -322,7 +322,7 @@ print ''; print ''; print ''; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -330,7 +330,7 @@ for ($i = 1; $i <= 12; $i++) { if ($cursormonth > 12) { $cursormonth -= 12; } - $cursoryear = ($cursormonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt'); print '' $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,"; $sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,"; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -364,7 +364,7 @@ $sql .= " WHERE ff.datef >= '".$db->idate($search_date_start)."'"; $sql .= " AND ff.datef <= '".$db->idate($search_date_end)."'"; // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND ff.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND ff.datef >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } $sql .= " AND ff.fk_statut > 0"; $sql .= " AND ffd.product_type <= 2"; @@ -393,27 +393,27 @@ if ($resql) { print ''; print ''; for ($i = 2; $i <= 13; $i++) { - $cursormonth = (($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) + $i - 2); + $cursormonth = (getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + $i - 2); if ($cursormonth > 12) { $cursormonth -= 12; } - $cursoryear = ($cursormonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt'); print ''; print ''; } diff --git a/htdocs/admin/pdf_other.php b/htdocs/admin/pdf_other.php index 31c4013901a..2c76236310c 100644 --- a/htdocs/admin/pdf_other.php +++ b/htdocs/admin/pdf_other.php @@ -79,11 +79,15 @@ if ($action == 'update') { } if (GETPOSTISSET('INVOICE_ADD_ZATCA_QR_CODE')) { dolibarr_set_const($db, "INVOICE_ADD_ZATCA_QR_CODE", GETPOST("INVOICE_ADD_ZATCA_QR_CODE", 'int'), 'chaine', 0, '', $conf->entity); - dolibarr_del_const($db, "INVOICE_ADD_SWISS_QR_CODE", $conf->entity); + if (GETPOSTINT('INVOICE_ADD_ZATCA_QR_CODE') == 1) { + dolibarr_del_const($db, "INVOICE_ADD_SWISS_QR_CODE", $conf->entity); + } } if (GETPOSTISSET('INVOICE_ADD_SWISS_QR_CODE')) { dolibarr_set_const($db, "INVOICE_ADD_SWISS_QR_CODE", GETPOST("INVOICE_ADD_SWISS_QR_CODE", 'alpha'), 'chaine', 0, '', $conf->entity); - dolibarr_del_const($db, "INVOICE_ADD_ZATCA_QR_CODE", $conf->entity); + if (GETPOST('INVOICE_ADD_SWISS_QR_CODE', 'alpha') != '0') { + dolibarr_del_const($db, "INVOICE_ADD_ZATCA_QR_CODE", $conf->entity); + } } if (GETPOSTISSET('INVOICE_CATEGORY_OF_OPERATION')) { dolibarr_set_const($db, "INVOICE_CATEGORY_OF_OPERATION", GETPOST("INVOICE_CATEGORY_OF_OPERATION", 'int'), 'chaine', 0, '', $conf->entity); diff --git a/htdocs/admin/perms.php b/htdocs/admin/perms.php index 4a284a9bf6d..c89c7ad914c 100644 --- a/htdocs/admin/perms.php +++ b/htdocs/admin/perms.php @@ -193,7 +193,7 @@ if ($result) { } // Break found, it's a new module to catch - if (isset($obj->module) && ($oldmod <> $obj->module)) { + if (isset($obj->module) && ($oldmod != $obj->module)) { $oldmod = $obj->module; // Break detected, we get objMod @@ -248,7 +248,7 @@ if ($result) { } // Permission and tick - $permlabel = (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && ($langs->trans("PermissionAdvanced".$obj->id) != ("PermissionAdvanced".$obj->id)) ? $langs->trans("PermissionAdvanced".$obj->id) : (($langs->trans("Permission".$obj->id) != ("Permission".$obj->id)) ? $langs->trans("Permission".$obj->id) : $langs->trans($obj->label))); + $permlabel = (getDolGlobalString('MAIN_USE_ADVANCED_PERMS') && ($langs->trans("PermissionAdvanced".$obj->id) != "PermissionAdvanced".$obj->id) ? $langs->trans("PermissionAdvanced".$obj->id) : (($langs->trans("Permission".$obj->id) != "Permission".$obj->id) ? $langs->trans("Permission".$obj->id) : $langs->trans($obj->label))); print ''; - echo ''; + echo ''; echo ''; } diff --git a/htdocs/bookcal/admin/setup.php b/htdocs/bookcal/admin/setup.php index 5ddcffd25a7..7117deee8e1 100644 --- a/htdocs/bookcal/admin/setup.php +++ b/htdocs/bookcal/admin/setup.php @@ -188,7 +188,7 @@ if ($action == 'updateMask') { $tmpobjectkey = GETPOST('object'); if (!empty($tmpobjectkey)) { $constforval = 'BOOKCAL_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; - if ($conf->global->$constforval == "$value") { + if (getDolGlobalString($constforval) == "$value") { dolibarr_del_const($db, $constforval, $conf->entity); } } diff --git a/htdocs/bookcal/bookcalindex.php b/htdocs/bookcal/bookcalindex.php index c236815a040..d5ca67b5b39 100644 --- a/htdocs/bookcal/bookcalindex.php +++ b/htdocs/bookcal/bookcalindex.php @@ -19,7 +19,7 @@ */ /** - * \file bookcal/bookcalindex.php + * \file htdocs/bookcal/bookcalindex.php * \ingroup bookcal * \brief Home page of bookcal top menu */ @@ -138,7 +138,7 @@ print '
'; $NBMAX = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; -$max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; +$max = getDolGlobalInt('MAIN_SIZE_SHORTLIST_LIMIT'); /* BEGIN MODULEBUILDER LASTMODIFIED MYOBJECT // Last modified myobject diff --git a/htdocs/bookcal/booking_list.php b/htdocs/bookcal/booking_list.php index 5aef44ac048..20cecf07a51 100644 --- a/htdocs/bookcal/booking_list.php +++ b/htdocs/bookcal/booking_list.php @@ -22,8 +22,8 @@ */ /** - * \file htdocs/compta/facture/prelevement.php - * \ingroup facture + * \file htdocs/bookcal/booking_list.php + * \ingroup bookcal * \brief Management of direct debit order or credit tranfer of invoices */ diff --git a/htdocs/bookcal/calendar_agenda.php b/htdocs/bookcal/calendar_agenda.php index cb4c381ea33..a9792756553 100644 --- a/htdocs/bookcal/calendar_agenda.php +++ b/htdocs/bookcal/calendar_agenda.php @@ -17,7 +17,7 @@ */ /** - * \file calendar_agenda.php + * \file htdocs/bookcal/calendar_agenda.php * \ingroup bookcal * \brief Tab of events on Calendar */ diff --git a/htdocs/bookcal/calendar_card.php b/htdocs/bookcal/calendar_card.php index 6d83687c13d..4cd79c357f1 100644 --- a/htdocs/bookcal/calendar_card.php +++ b/htdocs/bookcal/calendar_card.php @@ -17,7 +17,7 @@ */ /** - * \file calendar_card.php + * \file htdocs/bookcal/calendar_card.php * \ingroup bookcal * \brief Page to create/edit/view calendar */ diff --git a/htdocs/bookcal/calendar_contact.php b/htdocs/bookcal/calendar_contact.php index 87fd2721489..a102542f5ca 100644 --- a/htdocs/bookcal/calendar_contact.php +++ b/htdocs/bookcal/calendar_contact.php @@ -17,7 +17,7 @@ */ /** - * \file calendar_contact.php + * \file htdocs/bookcal/calendar_contact.php * \ingroup bookcal * \brief Tab for contacts linked to Calendar */ diff --git a/htdocs/bookcal/calendar_document.php b/htdocs/bookcal/calendar_document.php index 61f9c8b9fd9..07df7276c3a 100644 --- a/htdocs/bookcal/calendar_document.php +++ b/htdocs/bookcal/calendar_document.php @@ -17,7 +17,7 @@ */ /** - * \file calendar_document.php + * \file htdocs/bookcal/calendar_document.php * \ingroup bookcal * \brief Tab for documents linked to Calendar */ diff --git a/htdocs/bookcal/calendar_list.php b/htdocs/bookcal/calendar_list.php index 44f0ea96e6f..04b14be5743 100644 --- a/htdocs/bookcal/calendar_list.php +++ b/htdocs/bookcal/calendar_list.php @@ -17,7 +17,7 @@ */ /** - * \file calendar_list.php + * \file htdocs/bookcal/calendar_list.php * \ingroup bookcal * \brief List page for calendar */ diff --git a/htdocs/bookcal/calendar_note.php b/htdocs/bookcal/calendar_note.php index ae509dbf019..69c30f892bb 100644 --- a/htdocs/bookcal/calendar_note.php +++ b/htdocs/bookcal/calendar_note.php @@ -17,7 +17,7 @@ */ /** - * \file calendar_note.php + * \file htdocs/bookcal/calendar_note.php * \ingroup bookcal * \brief Tab for notes on Calendar */ diff --git a/htdocs/bookcal/class/availabilities.class.php b/htdocs/bookcal/class/availabilities.class.php index e94eb3f0990..3e8a0c4dab2 100644 --- a/htdocs/bookcal/class/availabilities.class.php +++ b/htdocs/bookcal/class/availabilities.class.php @@ -855,7 +855,7 @@ class Availabilities extends CommonObject $return .= ''.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency).''; } if (method_exists($this, 'getLibStatut')) { - $return .= '
'.$this->getLibStatut(3).'
'; + $return .= '
'.$this->getLibStatut(3).'
'; } $return .= '
'; $return .= ''; diff --git a/htdocs/bookcal/class/calendar.class.php b/htdocs/bookcal/class/calendar.class.php index 2b1cf06d779..4490852b2a8 100644 --- a/htdocs/bookcal/class/calendar.class.php +++ b/htdocs/bookcal/class/calendar.class.php @@ -844,7 +844,7 @@ class Calendar extends CommonObject $return .= ''.price($this->amount, 0, $langs, 1, -1, -1, $conf->currency).''; } if (method_exists($this, 'getLibStatut')) { - $return .= '
'.$this->getLibStatut(3).'
'; + $return .= '
'.$this->getLibStatut(3).'
'; } $return .= ''; $return .= ''; diff --git a/htdocs/categories/class/api_categories.class.php b/htdocs/categories/class/api_categories.class.php index 5d2a9d0862a..b1d0ff392d6 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -182,9 +182,7 @@ class Categories extends DolibarrApi } else { throw new RestException(503, 'Error when retrieve category list : '.$this->db->lasterror()); } - if (!count($obj_ret)) { - throw new RestException(404, 'No category found'); - } + return $obj_ret; } @@ -342,9 +340,6 @@ class Categories extends DolibarrApi $categories = $this->category->getListForItem($id, $type, $sortfield, $sortorder, $limit, $page); if (!is_array($categories)) { - if ($categories == 0) { - throw new RestException(404, 'No category found for this object'); - } throw new RestException(600, 'Error when fetching object categories', array_merge(array($this->category->error), $this->category->errors)); } return $categories; diff --git a/htdocs/categories/class/categorie.class.php b/htdocs/categories/class/categorie.class.php index 3a57d245956..f7008dad5eb 100644 --- a/htdocs/categories/class/categorie.class.php +++ b/htdocs/categories/class/categorie.class.php @@ -1385,7 +1385,7 @@ class Categorie extends CommonObject * @param string $sep Separator * @param string $url Url ('', 'none' or 'urltouse') * @param int $nocolor 0 - * @param string $addpicto Add picto into link + * @param int $addpicto Add picto into link * @return array */ public function print_all_ways($sep = '>>', $url = '', $nocolor = 0, $addpicto = 0) diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index f586cbca79a..a36d7f73090 100644 --- a/htdocs/comm/action/card.php +++ b/htdocs/comm/action/card.php @@ -7,7 +7,7 @@ * Copyright (C) 2013 Florian Henry * Copyright (C) 2014 Cedric GROSS * Copyright (C) 2015 Alexandre Spangaro - * Copyright (C) 2018-2021 Frédéric France + * Copyright (C) 2018-2023 Frédéric France * Copyright (C) 2019 Ferran Marcet * * This program is free software; you can redistribute it and/or modify @@ -321,11 +321,11 @@ if (empty($reshook) && $action == 'add') { if ($fulldayevent) { $tzforfullday = getDolGlobalString('MAIN_STORE_FULL_EVENT_IN_GMT'); // For "full day" events, we must store date in GMT (It must be viewed as same moment everywhere) - $datep = dol_mktime($fulldayevent ? '00' : GETPOST("aphour", 'int'), $fulldayevent ? '00' : GETPOST("apmin", 'int'), $fulldayevent ? '00' : GETPOST("apsec", 'int'), GETPOST("apmonth", 'int'), GETPOST("apday", 'int'), GETPOST("apyear", 'int'), $tzforfullday ? $tzforfullday : 'tzuserrel'); - $datef = dol_mktime($fulldayevent ? '23' : GETPOST("p2hour", 'int'), $fulldayevent ? '59' : GETPOST("p2min", 'int'), $fulldayevent ? '59' : GETPOST("apsec", 'int'), GETPOST("p2month", 'int'), GETPOST("p2day", 'int'), GETPOST("p2year", 'int'), $tzforfullday ? $tzforfullday : 'tzuserrel'); + $datep = dol_mktime('00', '00', '00', GETPOST("apmonth", 'int'), GETPOST("apday", 'int'), GETPOST("apyear", 'int'), $tzforfullday ? $tzforfullday : 'tzuserrel'); + $datef = dol_mktime('23', '59', '59', GETPOST("p2month", 'int'), GETPOST("p2day", 'int'), GETPOST("p2year", 'int'), $tzforfullday ? $tzforfullday : 'tzuserrel'); } else { - $datep = dol_mktime($fulldayevent ? '00' : GETPOST("aphour", 'int'), $fulldayevent ? '00' : GETPOST("apmin", 'int'), $fulldayevent ? '00' : GETPOST("apsec", 'int'), GETPOST("apmonth", 'int'), GETPOST("apday", 'int'), GETPOST("apyear", 'int'), 'tzuserrel'); - $datef = dol_mktime($fulldayevent ? '23' : GETPOST("p2hour", 'int'), $fulldayevent ? '59' : GETPOST("p2min", 'int'), $fulldayevent ? '59' : GETPOST("apsec", 'int'), GETPOST("p2month", 'int'), GETPOST("p2day", 'int'), GETPOST("p2year", 'int'), 'tzuserrel'); + $datep = dol_mktime(GETPOST("aphour", 'int'), GETPOST("apmin", 'int'), GETPOST("apsec", 'int'), GETPOST("apmonth", 'int'), GETPOST("apday", 'int'), GETPOST("apyear", 'int'), 'tzuserrel'); + $datef = dol_mktime(GETPOST("p2hour", 'int'), GETPOST("p2min", 'int'), GETPOST("apsec", 'int'), GETPOST("p2month", 'int'), GETPOST("p2day", 'int'), GETPOST("p2year", 'int'), 'tzuserrel'); } // Check parameters @@ -475,7 +475,8 @@ if (empty($reshook) && $action == 'add') { // Fill array 'array_options' with data from add form $ret = $extrafields->setOptionalsFromPost(null, $object); if ($ret < 0) { - $error++; + $error++; $donotclearsession = 1; + $action = 'create'; } @@ -970,15 +971,19 @@ if (empty($reshook) && $action == 'update') { $object->setCategories($categories); $object->loadReminders($remindertype, 0, false); - if (!empty($object->reminders) && $object->datep > dol_now()) { + + // If there is reminders, we remove them + if (!empty($object->reminders)) { foreach ($object->reminders as $reminder) { - $reminder->delete($user); + if ($reminder->status < 1) { // If already sent, we never remove it + $reminder->delete($user); + } } $object->reminders = array(); } - // Create reminders - if ($addreminder == 'on' && $object->datep > dol_now()) { + // Create reminders for every assigned user if reminder is on + if ($addreminder == 'on') { $actionCommReminder = new ActionCommReminder($db); $dateremind = dol_time_plus_duree($datep, -1 * $offsetvalue, $offsetunit); @@ -2159,8 +2164,12 @@ if ($id > 0) { $actionCommReminder->offsetunit = 'i'; $actionCommReminder->typeremind = 'email'; } + $disabled = ''; + if ($object->datep < dol_now()) { + //$disabled = 'disabled title="'.dol_escape_htmltag($langs->trans("EventExpired")).'"'; + } - print '
'; + print '
'; print '
'; @@ -2553,6 +2562,7 @@ if ($id > 0) { print ' ('.$tmpuserstatic->getNomUrl(0, '', 0, 0, 16).')'; } print ' - '.$actioncommreminder->offsetvalue.' '.$TDurationTypes[$actioncommreminder->offsetunit]; + if ($actioncommreminder->status == $actioncommreminder::STATUS_TODO) { print ' - '; print $langs->trans("NotSent"); @@ -2561,6 +2571,10 @@ if ($id > 0) { print ' - '; print $langs->trans("Done"); print ' '; + } elseif ($actioncommreminder->status == $actioncommreminder::STATUS_ERROR) { + print ' - '; + print $form->textwithpicto($langs->trans("Error"), $actioncommreminder->lasterror); + print ' '; } print '
'; } diff --git a/htdocs/comm/action/class/actioncomm.class.php b/htdocs/comm/action/class/actioncomm.class.php index 8f13709a1e0..c128e3dbab6 100644 --- a/htdocs/comm/action/class/actioncomm.class.php +++ b/htdocs/comm/action/class/actioncomm.class.php @@ -784,7 +784,7 @@ class ActionComm extends CommonObject * @param string $ref Ref of action to get * @param string $ref_ext Ref ext to get * @param string $email_msgid Email msgid - * @param string $loadresources 1=Load also resources + * @param int $loadresources 1=Load also resources * @return int Return integer <0 if KO, >0 if OK */ public function fetch($id, $ref = '', $ref_ext = '', $email_msgid = '', $loadresources = 1) @@ -1328,7 +1328,7 @@ class ActionComm extends CommonObject * @param string $filter Other filter * @param string $sortfield Sort on this field * @param string $sortorder ASC or DESC - * @param string $limit Limit number of answers + * @param int $limit Limit number of answers * @return ActionComm[]|string Error string if KO, array with actions if OK */ public function getActions($socid = 0, $fk_element = 0, $elementtype = '', $filter = '', $sortfield = 'a.datep', $sortorder = 'DESC', $limit = 0) @@ -1542,7 +1542,7 @@ class ActionComm extends CommonObject * @param int $percent Percent * @param int $mode 0=Long label, 1=Short label, 2=Picto+Short label, 3=Picto, 4=Picto+Short label, 5=Short label+Picto, 6=Picto+Long label, 7=Very short label+Picto * @param int $hidenastatus 1=Show nothing if status is "Not applicable" - * @param int $datestart Date start of event + * @param int|string $datestart Date start of event * @return string Label */ public function LibStatut($percent, $mode, $hidenastatus = 0, $datestart = '') @@ -2443,23 +2443,23 @@ class ActionComm extends CommonObject $this->reminders = array(); //Select all action comm reminders for event - $sql = "SELECT rowid as id, typeremind, dateremind, status, offsetvalue, offsetunit, fk_user"; + $sql = "SELECT rowid as id, typeremind, dateremind, status, offsetvalue, offsetunit, fk_user, fk_email_template, lasterror"; $sql .= " FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; $sql .= " WHERE fk_actioncomm = ".((int) $this->id); if ($onlypast) { $sql .= " AND dateremind <= '".$this->db->idate(dol_now())."'"; } if ($type) { - $sql .= " AND typeremind ='".$this->db->escape($type)."'"; + $sql .= " AND typeremind = '".$this->db->escape($type)."'"; } if ($fk_user > 0) { $sql .= " AND fk_user = ".((int) $fk_user); } if (!getDolGlobalString('AGENDA_REMINDER_EMAIL')) { - $sql .= " AND typeremind != 'email'"; + $sql .= " AND typeremind <> 'email'"; } if (!getDolGlobalString('AGENDA_REMINDER_BROWSER')) { - $sql .= " AND typeremind != 'browser'"; + $sql .= " AND typeremind <> 'browser'"; } $sql .= $this->db->order("dateremind", "ASC"); @@ -2475,6 +2475,8 @@ class ActionComm extends CommonObject $tmpactioncommreminder->offsetunit = $obj->offsetunit; $tmpactioncommreminder->status = $obj->status; $tmpactioncommreminder->fk_user = $obj->fk_user; + $tmpactioncommreminder->fk_email_template = $obj->fk_email_template; + $tmpactioncommreminder->lasterror = $obj->lasterror; $this->reminders[$obj->id] = $tmpactioncommreminder; } @@ -2523,7 +2525,8 @@ class ActionComm extends CommonObject //Select all action comm reminders $sql = "SELECT rowid as id FROM ".MAIN_DB_PREFIX."actioncomm_reminder"; - $sql .= " WHERE typeremind = 'email' AND status = 0"; + $sql .= " WHERE typeremind = 'email'"; + $sql .= " AND status = 0"; // 0=No yet sent, -1=Error. TODO Include reminder in error once we can count number of error, so we can try 5 times and not more on errors. $sql .= " AND dateremind <= '".$this->db->idate($now)."'"; $sql .= " AND entity IN (".getEntity('actioncomm').")"; $sql .= $this->db->order("dateremind", "ASC"); @@ -2594,7 +2597,7 @@ class ActionComm extends CommonObject if ($cMailFile->sendfile()) { $nbMailSend++; } else { - $errormesg = $cMailFile->error.' : '.$to; + $errormesg = 'Failed to send email to: '.$to.' '.$cMailFile->error.join(',', $cMailFile->errors); $error++; } } diff --git a/htdocs/comm/action/class/api_agendaevents.class.php b/htdocs/comm/action/class/api_agendaevents.class.php index 5c86aa9f6b5..d1c013bc59c 100644 --- a/htdocs/comm/action/class/api_agendaevents.class.php +++ b/htdocs/comm/action/class/api_agendaevents.class.php @@ -103,7 +103,7 @@ class AgendaEvents extends DolibarrApi * @param string $properties Restrict the data returned to theses properties. Ignored if empty. Comma separated list of properties names * @return array Array of Agenda Events objects */ - public function index($sortfield = "t.id", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = 0, $sqlfilters = '', $properties = '') + public function index($sortfield = "t.id", $sortorder = 'ASC', $limit = 100, $page = 0, $user_ids = '', $sqlfilters = '', $properties = '') { global $db, $conf; @@ -192,9 +192,7 @@ class AgendaEvents extends DolibarrApi } else { throw new RestException(503, 'Error when retrieve Agenda Event list : '.$this->db->lasterror()); } - if (!count($obj_ret)) { - throw new RestException(404, 'No Agenda Event found'); - } + return $obj_ret; } diff --git a/htdocs/comm/action/class/ical.class.php b/htdocs/comm/action/class/ical.class.php index bace864360e..d7b60f5e5ef 100644 --- a/htdocs/comm/action/class/ical.class.php +++ b/htdocs/comm/action/class/ical.class.php @@ -109,7 +109,7 @@ class ICal * * @param string $uri Url * @param string $usecachefile Full path of a cache file to use a cache file - * @param string $delaycache Delay in seconds for cache (by default 3600 secondes) + * @param int $delaycache Delay in seconds for cache (by default 3600 secondes) * @return array|string */ public function parse($uri, $usecachefile = '', $delaycache = 3600) diff --git a/htdocs/comm/action/document.php b/htdocs/comm/action/document.php index 8493ba2abc9..1f46ee6df1b 100644 --- a/htdocs/comm/action/document.php +++ b/htdocs/comm/action/document.php @@ -148,31 +148,45 @@ if ($object->id > 0) { print dol_get_fiche_head($head, 'documents', $langs->trans("Action"), -1, 'action'); - $linkback = img_picto($langs->trans("BackToList"), 'object_calendarlist', 'class="hideonsmartphone pictoactionview"'); - $linkback .= ''.$langs->trans("BackToList").''; - // Link to other agenda views - $out = ''; - $out .= '
  • '.img_picto($langs->trans("ViewPerUser"), 'object_calendarperuser', 'class="hideonsmartphone pictoactionview"'); - $out .= ''.$langs->trans("ViewPerUser").''; - $out .= '
  • '.img_picto($langs->trans("ViewCal"), 'object_calendarmonth', 'class="hideonsmartphone pictoactionview"'); - $out .= ''.$langs->trans("ViewCal").''; - $out .= '
  • '.img_picto($langs->trans("ViewWeek"), 'object_calendarweek', 'class="hideonsmartphone pictoactionview"'); - $out .= ''.$langs->trans("ViewWeek").''; - $out .= '
  • '.img_picto($langs->trans("ViewDay"), 'object_calendarday', 'class="hideonsmartphone pictoactionview"'); - $out .= ''.$langs->trans("ViewDay").''; + $linkback .= ''; + $linkback .= img_picto($langs->trans("BackToList"), 'object_calendarlist', 'class="pictoactionview pictofixedwidth"'); + $linkback .= ''.$langs->trans("BackToList").''; + $linkback .= ''; + $linkback .= '
  • '; + $linkback .= '
  • '; + $linkback .= ''; + $linkback .= img_picto($langs->trans("ViewCal"), 'object_calendar', 'class="pictoactionview pictofixedwidth"'); + $linkback .= ''.$langs->trans("ViewCal").''; + $linkback .= ''; + $linkback .= '
  • '; + $linkback .= '
  • '; + $linkback .= ''; + $linkback .= img_picto($langs->trans("ViewWeek"), 'object_calendarweek', 'class="pictoactionview pictofixedwidth"'); + $linkback .= ''.$langs->trans("ViewWeek").''; + $linkback .= ''; + $linkback .= '
  • '; + $linkback .= '
  • '; + $linkback .= ''; + $linkback .= img_picto($langs->trans("ViewDay"), 'object_calendarday', 'class="pictoactionview pictofixedwidth"'); + $linkback .= ''.$langs->trans("ViewDay").''; + $linkback .= ''; + $linkback .= '
  • '; + $linkback .= '
  • '; + $linkback .= ''; + $linkback .= img_picto($langs->trans("ViewPerUser"), 'object_calendarperuser', 'class="pictoactionview pictofixedwidth"'); + $linkback .= ''.$langs->trans("ViewPerUser").''; + $linkback .= ''; // Add more views from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('addCalendarView', $parameters, $object, $action); if (empty($reshook)) { - $out .= $hookmanager->resPrint; + $linkback .= $hookmanager->resPrint; } elseif ($reshook > 1) { - $out = $hookmanager->resPrint; + $linkback = $hookmanager->resPrint; } - $linkback .= $out; - $morehtmlref = '
    '; // Thirdparty //$morehtmlref.='
    '.$langs->trans('ThirdParty') . ' : ' . $object->thirdparty->getNomUrl(1); diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index f008b84dfad..2187df8caf4 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -315,8 +315,8 @@ if (empty($mode) || $mode == 'show_month') { $next_year = $next['year']; $next_month = $next['month']; - $max_day_in_prev_month = date("t", dol_mktime(0, 0, 0, $prev_month, 1, $prev_year, 'gmt')); // Nb of days in previous month - $max_day_in_month = date("t", dol_mktime(0, 0, 0, $month, 1, $year)); // Nb of days in next month + $max_day_in_prev_month = date("t", dol_mktime(12, 0, 0, $prev_month, 1, $prev_year, 'gmt')); // Nb of days in previous month + $max_day_in_month = date("t", dol_mktime(12, 0, 0, $month, 1, $year, 'gmt')); // Nb of days in next month // tmpday is a negative or null cursor to know how many days before the 1st to show on month view (if tmpday=0, 1st is monday) $tmpday = -date("w", dol_mktime(12, 0, 0, $month, 1, $year, 'gmt')) + 2; // date('w') is 0 fo sunday $tmpday += ((isset($conf->global->MAIN_START_WEEK) ? $conf->global->MAIN_START_WEEK : 1) - 1); @@ -641,7 +641,7 @@ if (!empty($conf->use_javascript_ajax)) { // If javascript on $s .= ''."\n"; foreach ($showextcals as $val) { - $htmlname = md5($val['name']); + $htmlname = md5($val['name']); // not used for security purpose, only to get a string with no special char if (!empty($val['default']) || GETPOST('check_ext'.$htmlname, 'int')) { $default = "checked"; @@ -1743,8 +1743,8 @@ $db->close(); * @param string $newparam Parameters on current URL * @param int $showinfo Add extended information (used by day and week view) * @param int $minheight Minimum height for each event. 60px by default. - * @param string $nonew 0=Add "new entry button", 1=No "new entry button", -1=Only "new entry button" - * @param string $bookcalcalendarsarray Used for Bookcal module array of calendar of bookcal + * @param int $nonew 0=Add "new entry button", 1=No "new entry button", -1=Only "new entry button" + * @param array $bookcalcalendarsarray Used for Bookcal module array of calendar of bookcal * @return void */ function show_day_events($db, $day, $month, $year, $monthshown, $style, &$eventarray, $maxprint = 0, $maxnbofchar = 16, $newparam = '', $showinfo = 0, $minheight = 60, $nonew = 0, $bookcalcalendarsarray = array()) diff --git a/htdocs/comm/action/info.php b/htdocs/comm/action/info.php index 9d9baff3c3e..2301e3e329c 100644 --- a/htdocs/comm/action/info.php +++ b/htdocs/comm/action/info.php @@ -72,31 +72,45 @@ $object->info($object->id); $head = actions_prepare_head($object); print dol_get_fiche_head($head, 'info', $langs->trans("Action"), -1, 'action'); -$linkback = img_picto($langs->trans("BackToList"), 'object_calendarlist', 'class="hideonsmartphone pictoactionview"'); -$linkback .= ''.$langs->trans("BackToList").''; - // Link to other agenda views -$out = ''; -$out .= '
  • '.img_picto($langs->trans("ViewPerUser"), 'object_calendarperuser', 'class="hideonsmartphone pictoactionview"'); -$out .= ''.$langs->trans("ViewPerUser").''; -$out .= '
  • '.img_picto($langs->trans("ViewCal"), 'object_calendarmonth', 'class="hideonsmartphone pictoactionview"'); -$out .= ''.$langs->trans("ViewCal").''; -$out .= '
  • '.img_picto($langs->trans("ViewWeek"), 'object_calendarweek', 'class="hideonsmartphone pictoactionview"'); -$out .= ''.$langs->trans("ViewWeek").''; -$out .= '
  • '.img_picto($langs->trans("ViewDay"), 'object_calendarday', 'class="hideonsmartphone pictoactionview"'); -$out .= ''.$langs->trans("ViewDay").''; +$linkback .= ''; +$linkback .= img_picto($langs->trans("BackToList"), 'object_calendarlist', 'class="pictoactionview pictofixedwidth"'); +$linkback .= ''.$langs->trans("BackToList").''; +$linkback .= ''; +$linkback .= '
  • '; +$linkback .= '
  • '; +$linkback .= ''; +$linkback .= img_picto($langs->trans("ViewCal"), 'object_calendar', 'class="pictoactionview pictofixedwidth"'); +$linkback .= ''.$langs->trans("ViewCal").''; +$linkback .= ''; +$linkback .= '
  • '; +$linkback .= '
  • '; +$linkback .= ''; +$linkback .= img_picto($langs->trans("ViewWeek"), 'object_calendarweek', 'class="pictoactionview pictofixedwidth"'); +$linkback .= ''.$langs->trans("ViewWeek").''; +$linkback .= ''; +$linkback .= '
  • '; +$linkback .= '
  • '; +$linkback .= ''; +$linkback .= img_picto($langs->trans("ViewDay"), 'object_calendarday', 'class="pictoactionview pictofixedwidth"'); +$linkback .= ''.$langs->trans("ViewDay").''; +$linkback .= ''; +$linkback .= '
  • '; +$linkback .= '
  • '; +$linkback .= ''; +$linkback .= img_picto($langs->trans("ViewPerUser"), 'object_calendarperuser', 'class="pictoactionview pictofixedwidth"'); +$linkback .= ''.$langs->trans("ViewPerUser").''; +$linkback .= ''; // Add more views from hooks $parameters = array(); $reshook = $hookmanager->executeHooks('addCalendarView', $parameters, $object, $action); if (empty($reshook)) { - $out .= $hookmanager->resPrint; + $linkback .= $hookmanager->resPrint; } elseif ($reshook > 1) { - $out = $hookmanager->resPrint; + $linkback = $hookmanager->resPrint; } -$linkback .= $out; - $morehtmlref = '
    '; // Project if (isModEnabled('project')) { diff --git a/htdocs/comm/action/list.php b/htdocs/comm/action/list.php index 652f60552ff..5e403dff7a8 100644 --- a/htdocs/comm/action/list.php +++ b/htdocs/comm/action/list.php @@ -575,6 +575,7 @@ if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) { /* The fast and low memory method to get and count full list converts the sql into a sql count */ $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql); $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount); + $resql = $db->query($sqlforcount); if ($resql) { $objforcount = $db->fetch_object($resql); diff --git a/htdocs/comm/card.php b/htdocs/comm/card.php index 4737ff0d9d4..c3b53faccae 100644 --- a/htdocs/comm/card.php +++ b/htdocs/comm/card.php @@ -538,8 +538,8 @@ if ($object->id > 0) { print '
  • "; print ''; diff --git a/htdocs/comm/index.php b/htdocs/comm/index.php index 44a7565e9be..da07b9f9dd6 100644 --- a/htdocs/comm/index.php +++ b/htdocs/comm/index.php @@ -64,7 +64,7 @@ if (isset($user->socid) && $user->socid > 0) { } -$max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; +$max = getDolGlobalInt('MAIN_SIZE_SHORTLIST_LIMIT'); $maxofloop = (!getDolGlobalString('MAIN_MAXLIST_OVERLOAD') ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD); $now = dol_now(); diff --git a/htdocs/comm/mailing/card.php b/htdocs/comm/mailing/card.php index 40140b43167..1a9286c6091 100644 --- a/htdocs/comm/mailing/card.php +++ b/htdocs/comm/mailing/card.php @@ -285,13 +285,13 @@ if (empty($reshook)) { $substitutionarray['__ONLINEPAYMENTLINK_INVOICE__'] = getHtmlOnlinePaymentLink('invoice', $obj->source_id); $substitutionarray['__ONLINEPAYMENTLINK_CONTRACTLINE__'] = getHtmlOnlinePaymentLink('contractline', $obj->source_id); - $substitutionarray['__SECUREKEYPAYMENT__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), 2); if (!getDolGlobalString('PAYMENT_SECURITY_TOKEN_UNIQUE')) { - $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); - $substitutionarray['__SECUREKEYPAYMENT_DONATION__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); - $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); - $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); - $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = dol_hash($conf->global->PAYMENT_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), 2); + $substitutionarray['__SECUREKEYPAYMENT_DONATION__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), 2); + $substitutionarray['__SECUREKEYPAYMENT_ORDER__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), 2); + $substitutionarray['__SECUREKEYPAYMENT_INVOICE__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), 2); + $substitutionarray['__SECUREKEYPAYMENT_CONTRACTLINE__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN'), 2); } else { $substitutionarray['__SECUREKEYPAYMENT_MEMBER__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN') . 'member'.$obj->source_id, 2); $substitutionarray['__SECUREKEYPAYMENT_DONATION__'] = dol_hash(getDolGlobalString('PAYMENT_SECURITY_TOKEN') . 'donation'.$obj->source_id, 2); @@ -305,28 +305,28 @@ if (empty($reshook)) { } /* For backward compatibility, deprecated */ if (isModEnabled('paypal') && getDolGlobalString('PAYPAL_SECURITY_TOKEN')) { - $substitutionarray['__SECUREKEYPAYPAL__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYPAL__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN'), 2); if (!getDolGlobalString('PAYPAL_SECURITY_TOKEN_UNIQUE')) { - $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN'), 2); } else { $substitutionarray['__SECUREKEYPAYPAL_MEMBER__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN') . 'membersubscription'.$obj->source_id, 2); } if (!getDolGlobalString('PAYPAL_SECURITY_TOKEN_UNIQUE')) { - $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN'), 2); } else { $substitutionarray['__SECUREKEYPAYPAL_ORDER__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN') . 'order'.$obj->source_id, 2); } if (!getDolGlobalString('PAYPAL_SECURITY_TOKEN_UNIQUE')) { - $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN'), 2); } else { $substitutionarray['__SECUREKEYPAYPAL_INVOICE__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN') . 'invoice'.$obj->source_id, 2); } if (!getDolGlobalString('PAYPAL_SECURITY_TOKEN_UNIQUE')) { - $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash($conf->global->PAYPAL_SECURITY_TOKEN, 2); + $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN'), 2); } else { $substitutionarray['__SECUREKEYPAYPAL_CONTRACTLINE__'] = dol_hash(getDolGlobalString('PAYPAL_SECURITY_TOKEN') . 'contractline'.$obj->source_id, 2); } diff --git a/htdocs/comm/mailing/cibles.php b/htdocs/comm/mailing/cibles.php index 9139e41d189..5b708cb3995 100644 --- a/htdocs/comm/mailing/cibles.php +++ b/htdocs/comm/mailing/cibles.php @@ -430,7 +430,7 @@ if ($object->fetch($id) >= 0) { $handle = @opendir($dir); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) { - if (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') { + if (substr($file, 0, 1) != '.' && substr($file, 0, 3) != 'CVS') { $reg = array(); if (preg_match("/(.*)\.modules\.php$/i", $file, $reg)) { if ($reg[1] == 'example') { diff --git a/htdocs/comm/mailing/index.php b/htdocs/comm/mailing/index.php index cf3d18adbac..1f28a16a9d3 100644 --- a/htdocs/comm/mailing/index.php +++ b/htdocs/comm/mailing/index.php @@ -86,7 +86,7 @@ $handle = opendir($dir); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) { - if (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') { + if (substr($file, 0, 1) != '.' && substr($file, 0, 3) != 'CVS') { if (preg_match("/(.*)\.(.*)\.(.*)/i", $file, $reg)) { $modulename = $reg[1]; if ($modulename == 'example') { diff --git a/htdocs/comm/multiprix.php b/htdocs/comm/multiprix.php index fe6c733713b..d2729885b96 100644 --- a/htdocs/comm/multiprix.php +++ b/htdocs/comm/multiprix.php @@ -110,8 +110,8 @@ if ($_socid > 0) { } print '>'.$i; $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$i; - if (!empty($conf->global->$keyforlabel)) { - print ' - '.$langs->trans($conf->global->$keyforlabel); + if (getDolGlobalString($keyforlabel)) { + print ' - '.$langs->trans(getDolGlobalString($keyforlabel)); } print ''; } diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index 05cb33a17df..be45153fb10 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -245,9 +245,7 @@ class Proposals extends DolibarrApi } else { throw new RestException(503, 'Error when retrieve propal list : '.$this->db->lasterror()); } - if (!count($obj_ret)) { - throw new RestException(404, 'No proposal found'); - } + return $obj_ret; } diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index d470fc8bc52..c5e9175a2af 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -577,8 +577,8 @@ class Propal extends CommonObject * @param int $fk_fournprice Id supplier price * @param int $pa_ht Buying price without tax * @param string $label ??? - * @param int $date_start Start date of the line - * @param int $date_end End date of the line + * @param int|string $date_start Start date of the line + * @param int|string $date_end End date of the line * @param array $array_options extrafields array * @param string $fk_unit Code of the unit to use. Null to use the default one * @param string $origin Depend on global conf MAIN_CREATEFROM_KEEP_LINE_ORIGIN_INFORMATION can be 'orderdet', 'propaldet'..., else 'order','propal,'.... @@ -589,7 +589,7 @@ class Propal extends CommonObject * @return int >0 if OK, <0 if KO * @see add_product() */ - public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $fk_product = 0, $remise_percent = 0.0, $price_base_type = 'HT', $pu_ttc = 0.0, $info_bits = 0, $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $origin = '', $origin_id = 0, $pu_ht_devise = 0, $fk_remise_except = 0, $noupdateafterinsertline = 0) + public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $fk_product = 0, $remise_percent = 0.0, $price_base_type = 'HT', $pu_ttc = 0.0, $info_bits = 0, $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $date_start = '', $date_end = '', $array_options = array(), $fk_unit = null, $origin = '', $origin_id = 0, $pu_ht_devise = 0, $fk_remise_except = 0, $noupdateafterinsertline = 0) { global $mysoc, $conf, $langs; @@ -827,8 +827,8 @@ class Propal extends CommonObject * @param int $pa_ht Price (without tax) of product when it was bought * @param string $label ??? * @param int $type 0/1=Product/service - * @param int $date_start Start date of the line - * @param int $date_end End date of the line + * @param int|string $date_start Start date of the line + * @param int|string $date_end End date of the line * @param array $array_options extrafields array * @param string $fk_unit Code of the unit to use. Null to use the default one * @param double $pu_ht_devise Unit price in currency @@ -836,7 +836,7 @@ class Propal extends CommonObject * @param integer $rang line rank * @return int 0 if OK, <0 if KO */ - public function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $desc = '', $price_base_type = 'HT', $info_bits = 0, $special_code = 0, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $type = 0, $date_start = '', $date_end = '', $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $rang = 0) + public function updateline($rowid, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $desc = '', $price_base_type = 'HT', $info_bits = 0, $special_code = 0, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = 0, $pa_ht = 0, $label = '', $type = 0, $date_start = '', $date_end = '', $array_options = array(), $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $rang = 0) { global $mysoc, $langs; diff --git a/htdocs/comm/propal/contact.php b/htdocs/comm/propal/contact.php index 26bb7c5818e..e56d383550c 100644 --- a/htdocs/comm/propal/contact.php +++ b/htdocs/comm/propal/contact.php @@ -3,6 +3,7 @@ * Copyright (C) 2005-2016 Destailleur Laurent * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2011-2022 Philippe Grand + * Copyright (C) 2023 Christian Foellmann * * 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 @@ -67,50 +68,58 @@ $socid = ''; if (!empty($user->socid)) { $socid = $user->socid; } -restrictedArea($user, 'propal', $object->id); +$result = restrictedArea($user, 'propal', $object->id); +$hookmanager->initHooks(array('proposalcontactcard', 'globalcard')); $usercancreate = $user->hasRight("propal", "creer"); - /* - * Add a new contact + * Actions */ -if ($action == 'addcontact' && $user->hasRight('propal', 'creer')) { - if ($object->id > 0) { - $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); - $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); - $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); - } - - if ($result >= 0) { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $langs->load("errors"); - setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } -} elseif ($action == 'swapstatut' && $user->hasRight('propal', 'creer')) { - // Toggle the status of a contact - if ($object->id > 0) { - $result = $object->swapContactStatus(GETPOST('ligne', 'int')); - } -} elseif ($action == 'deletecontact' && $user->hasRight('propal', 'creer')) { - // Deletes a contact - $result = $object->delete_contact($lineid); - - if ($result >= 0) { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } else { - dol_print_error($db); - } +$parameters = array('id'=>$id); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); } +if (empty($reshook)) { + // Add new contact + if ($action == 'addcontact' && $user->hasRight('propal', 'creer')) { + if ($object->id > 0) { + $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); + $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); + $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); + } + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } elseif ($action == 'swapstatut' && $user->hasRight('propal', 'creer')) { + // Toggle the status of a contact + if ($object->id > 0) { + $result = $object->swapContactStatus(GETPOST('ligne', 'int')); + } + } elseif ($action == 'deletecontact' && $user->hasRight('propal', 'creer')) { + // Delete contact + $result = $object->delete_contact($lineid); + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + dol_print_error($db); + } + } +} /* * View diff --git a/htdocs/comm/propal/list.php b/htdocs/comm/propal/list.php index 97e2a1d4307..7f5e0a8ce26 100644 --- a/htdocs/comm/propal/list.php +++ b/htdocs/comm/propal/list.php @@ -75,13 +75,13 @@ $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'pr $mode = GETPOST('mode', 'alpha'); // Search Fields +$search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $search_user = GETPOST('search_user', 'int'); $search_sale = GETPOST('search_sale', 'int'); $search_ref = GETPOST('sf_ref') ? GETPOST('sf_ref', 'alpha') : GETPOST('search_ref', 'alpha'); $search_refcustomer = GETPOST('search_refcustomer', 'alpha'); $search_refproject = GETPOST('search_refproject', 'alpha'); $search_project = GETPOST('search_project', 'alpha'); - $search_societe = GETPOST('search_societe', 'alpha'); $search_societe_alias = GETPOST('search_societe_alias', 'alpha'); $search_montant_ht = GETPOST('search_montant_ht', 'alpha'); @@ -130,8 +130,6 @@ $search_fk_cond_reglement = GETPOST("search_fk_cond_reglement", 'int'); $search_fk_shipping_method = GETPOST("search_fk_shipping_method", 'int'); $search_fk_input_reason = GETPOST("search_fk_input_reason", 'int'); $search_fk_mode_reglement = GETPOST("search_fk_mode_reglement", 'int'); -$search_btn = GETPOST('button_search', 'alpha'); -$search_remove_btn = GETPOST('button_removefilter', 'alpha'); $search_date_signature_startday = GETPOST('search_date_signature_startday', 'int'); $search_date_signature_startmonth = GETPOST('search_date_signature_startmonth', 'int'); $search_date_signature_startyear = GETPOST('search_date_signature_startyear', 'int'); @@ -140,23 +138,20 @@ $search_date_signature_endmonth = GETPOST('search_date_signature_endmonth', 'int $search_date_signature_endyear = GETPOST('search_date_signature_endyear', 'int'); $search_date_signature_start = dol_mktime(0, 0, 0, $search_date_signature_startmonth, $search_date_signature_startday, $search_date_signature_startyear); $search_date_signature_end = dol_mktime(23, 59, 59, $search_date_signature_endmonth, $search_date_signature_endday, $search_date_signature_endyear); - $search_status = GETPOST('search_status', 'alpha'); $optioncss = GETPOST('optioncss', 'alpha'); $object_statut = GETPOST('search_statut', 'alpha'); -$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); -$mesg = (GETPOST("msg") ? GETPOST("msg") : GETPOST("mesg")); - // Pagination $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); -if (empty($page) || $page == -1 || !empty($search_btn) || !empty($search_remove_btn) || (empty($toselect) && $massaction === '0')) { +if (empty($page) || $page < 0 || GETPOST('button_search', 'alpha') || GETPOST('button_removefilter', 'alpha')) { + // If $page is not defined, or '' or -1 or if we click on clear filters $page = 0; -} // If $page is not defined, or '' or -1 +} $offset = $limit * $page; $pageprev = $page - 1; $pagenext = $page + 1; @@ -327,7 +322,6 @@ if (empty($reshook)) { // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers - $search_categ = ''; $search_user = ''; $search_sale = ''; $search_ref = ''; @@ -563,7 +557,7 @@ $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage); // This also change content of $arrayfields $sql = 'SELECT'; -if ($sall || $search_user > 0) { +if ($search_all || $search_user > 0) { $sql = 'SELECT DISTINCT'; } $sql .= ' s.rowid as socid, s.nom as name, s.name_alias as alias, s.email, s.phone, s.fax , s.address, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client,'; @@ -602,7 +596,7 @@ $sql .= ', '.MAIN_DB_PREFIX.'propal as p'; if (!empty($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX.$object->table_element."_extrafields as ef on (p.rowid = ef.fk_object)"; } -if ($sall) { +if ($search_all) { $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'propaldet as pd ON p.rowid = pd.fk_propal'; } $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'user as u ON p.fk_user_author = u.rowid'; @@ -690,8 +684,8 @@ if ($search_multicurrency_montant_vat != '') { if ($search_multicurrency_montant_ttc != '') { $sql .= natural_search('p.multicurrency_total_ttc', $search_multicurrency_montant_ttc, 1); } -if ($sall) { - $sql .= natural_search(array_keys($fieldstosearchall), $sall); +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } if ($search_fk_cond_reglement > 0) { $sql .= " AND p.fk_cond_reglement = ".((int) $search_fk_cond_reglement); @@ -872,7 +866,7 @@ if ($socid > 0) { $arrayofselected = is_array($toselect) ? $toselect : array(); -if ($num == 1 && getDolGlobalString('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $sall) { +if ($num == 1 && getDolGlobalString('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; @@ -894,8 +888,8 @@ if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { if ($limit > 0 && $limit != $conf->liste_limit) { $param .= '&limit='.((int) $limit); } -if ($sall) { - $param .= '&sall='.urlencode($sall); +if ($search_all) { + $param .= '&search_all='.urlencode($search_all); } if ($search_date_startday) { $param .= '&search_date_startday='.urlencode($search_date_startday); @@ -1135,11 +1129,11 @@ if ($search_date_signature_endyear) { print $form->formconfirm($_SERVER["PHP_SELF"], $langs->trans("ConfirmMassNoSignature"), $langs->trans("ConfirmMassNoSignatureQuestion"), "nosign", null, '', 0, 200, 500, 1); } - if ($sall) { + if ($search_all) { foreach ($fieldstosearchall as $key => $val) { $fieldstosearchall[$key] = $langs->trans($val); } - print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; } $i = 0; diff --git a/htdocs/comm/remx.php b/htdocs/comm/remx.php index 39bd6bb44a5..a3da222a216 100644 --- a/htdocs/comm/remx.php +++ b/htdocs/comm/remx.php @@ -206,7 +206,7 @@ if (GETPOST('action', 'aZ09') == 'confirm_remove' && GETPOST("confirm") == 'yes' $db->begin(); $discount = new DiscountAbsolute($db); - $result = $discount->fetch(GETPOST("remid")); + $result = $discount->fetch(GETPOSTINT("remid")); $result = $discount->delete($user); if ($result > 0) { $db->commit(); diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 791f67fcd56..6d1821472c0 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -166,6 +166,8 @@ if (empty($reshook)) { } } + $selectedLines = GETPOST('toselect', 'array'); + if ($cancel) { if (!empty($backtopageforcancel)) { header("Location: ".$backtopageforcancel); @@ -206,11 +208,18 @@ if (empty($reshook)) { } elseif ($action == 'reopen' && $usercancreate) { // Reopen a closed order if ($object->statut == Commande::STATUS_CANCELED || $object->statut == Commande::STATUS_CLOSED) { - $result = $object->set_reopen($user); - if ($result > 0) { - setEventMessages($langs->trans('OrderReopened', $object->ref), null); + if (getDolGlobalInt('ORDER_REOPEN_TO_DRAFT')) { + $result = $object->setDraft($user, $idwarehouse); + if ($result < 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } } else { - setEventMessages($object->error, $object->errors, 'errors'); + $result = $object->set_reopen($user); + if ($result > 0) { + setEventMessages($langs->trans('OrderReopened', $object->ref), null); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } } } } elseif ($action == 'confirm_delete' && $confirm == 'yes' && $usercandelete) { @@ -258,7 +267,6 @@ if (empty($reshook)) { // Add order $datecommande = dol_mktime(12, 0, 0, GETPOST('remonth'), GETPOST('reday'), GETPOST('reyear')); $date_delivery = dol_mktime(GETPOST('liv_hour', 'int'), GETPOST('liv_min', 'int'), 0, GETPOST('liv_month', 'int'), GETPOST('liv_day', 'int'), GETPOST('liv_year', 'int')); - $selectedLines = GETPOST('toselect', 'array'); if ($datecommande == '') { setEventMessages($langs->trans('ErrorFieldRequired', $langs->transnoentities('Date')), null, 'errors'); @@ -3037,7 +3045,7 @@ if ($action == 'create' && $usercancreate) { // Cancel order if ($object->statut == Commande::STATUS_VALIDATED && !empty($usercancancel)) { - print ''.$langs->trans("Cancel").''; + print ''.$langs->trans("CancelOrder").''; } // Delete order diff --git a/htdocs/commande/class/api_orders.class.php b/htdocs/commande/class/api_orders.class.php index c5119a51f6e..31daad85e9b 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -259,9 +259,7 @@ class Orders extends DolibarrApi } else { throw new RestException(503, 'Error when retrieve commande list : '.$this->db->lasterror()); } - if (!count($obj_ret)) { - throw new RestException(404, 'No order found'); - } + return $obj_ret; } diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 5ec0a3374d1..8daed0d9242 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -1483,8 +1483,8 @@ class Commande extends CommonOrder * @param int $fk_remise_except Id remise * @param string $price_base_type HT or TTC * @param float $pu_ttc Prix unitaire TTC - * @param int $date_start Start date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html) - * @param int $date_end End date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html) + * @param int|string $date_start Start date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html) + * @param int|string $date_end End date of the line - Added by Matelli (See http://matelli.fr/showcases/patchs-dolibarr/add-dates-in-order-lines.html) * @param int $type Type of line (0=product, 1=service). Not used if fk_product is defined, the type of product is used. * @param int $rang Position of line * @param int $special_code Special code (also used by externals modules!) @@ -1508,7 +1508,7 @@ class Commande extends CommonOrder * par l'appelant par la methode get_default_tva(societe_vendeuse,societe_acheteuse,produit) * et le desc doit deja avoir la bonne valeur (a l'appelant de gerer le multilangue) */ - public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $info_bits = 0, $fk_remise_except = 0, $price_base_type = 'HT', $pu_ttc = 0, $date_start = '', $date_end = '', $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $array_options = 0, $fk_unit = null, $origin = '', $origin_id = 0, $pu_ht_devise = 0, $ref_ext = '', $noupdateafterinsertline = 0) + public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $info_bits = 0, $fk_remise_except = 0, $price_base_type = 'HT', $pu_ttc = 0, $date_start = '', $date_end = '', $type = 0, $rang = -1, $special_code = 0, $fk_parent_line = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $array_options = array(), $fk_unit = null, $origin = '', $origin_id = 0, $pu_ht_devise = 0, $ref_ext = '', $noupdateafterinsertline = 0) { global $mysoc, $conf, $langs, $user; @@ -1755,8 +1755,8 @@ class Commande extends CommonOrder * @param int $idproduct Product Id * @param float $qty Quantity * @param float $remise_percent Product discount relative - * @param int $date_start Start date of the line - * @param int $date_end End date of the line + * @param int|string $date_start Start date of the line + * @param int|string $date_end End date of the line * @return void * * TODO Remplacer les appels a cette fonction par generation objet Ligne @@ -2728,7 +2728,7 @@ class Commande extends CommonOrder * @param string $sortorder Sort order * @return int|array -1 if KO, array with result if OK */ - public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'c.date_commande', $sortorder = 'DESC') + public function liste_array($shortlist = 0, $draft = 0, $excluser = null, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'c.date_commande', $sortorder = 'DESC') { // phpcs:enable global $user; @@ -3092,8 +3092,8 @@ class Commande extends CommonOrder * @param float $txlocaltax2 Local tax 2 rate * @param string $price_base_type HT or TTC * @param int $info_bits Miscellaneous informations on line - * @param int $date_start Start date of the line - * @param int $date_end End date of the line + * @param int|string $date_start Start date of the line + * @param int|string $date_end End date of the line * @param int $type Type of line (0=product, 1=service) * @param int $fk_parent_line Id of parent line (0 in most cases, used by modules adding sublevels into lines). * @param int $skip_update_total Keep fields total_xxx to 0 (used for special lines by some modules) @@ -3109,7 +3109,7 @@ class Commande extends CommonOrder * @param integer $rang line rank * @return int Return integer < 0 if KO, > 0 if OK */ - public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $price_base_type = 'HT', $info_bits = 0, $date_start = '', $date_end = '', $type = 0, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '', $rang = 0) + public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $txtva, $txlocaltax1 = 0.0, $txlocaltax2 = 0.0, $price_base_type = 'HT', $info_bits = 0, $date_start = '', $date_end = '', $type = 0, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = array(), $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '', $rang = 0) { global $conf, $mysoc, $langs, $user; diff --git a/htdocs/commande/contact.php b/htdocs/commande/contact.php index a5fc715eb38..1d800e1eaca 100644 --- a/htdocs/commande/contact.php +++ b/htdocs/commande/contact.php @@ -46,57 +46,65 @@ if ($user->socid) { $socid = $user->socid; } $result = restrictedArea($user, 'commande', $id, ''); +$hookmanager->initHooks(array('ordercontactcard', 'globalcard')); $usercancreate = $user->hasRight("commande", "creer"); $object = new Commande($db); - /* - * Ajout d'un nouveau contact + * Actions */ -if ($action == 'addcontact' && $user->hasRight('commande', 'creer')) { - $result = $object->fetch($id); +$parameters = array('id'=>$id); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} - if ($result > 0 && $id > 0) { - $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); - $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); - $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); - } +if (empty($reshook)) { + // Add new contact + if ($action == 'addcontact' && $user->hasRight('commande', 'creer')) { + $result = $object->fetch($id); - if ($result >= 0) { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $langs->load("errors"); - setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); + if ($result > 0 && $id > 0) { + $contactid = (GETPOST('userid', 'int') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); + $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); + $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); + } + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } elseif ($action == 'swapstatut' && $user->hasRight('commande', 'creer')) { + // Toggle the status of a contact + if ($object->fetch($id)) { + $result = $object->swapContactStatus(GETPOST('ligne', 'int')); + } else { + dol_print_error($db); + } + } elseif ($action == 'deletecontact' && $user->hasRight('commande', 'creer')) { + // Delete contact + $object->fetch($id); + $result = $object->delete_contact(GETPOST("lineid", 'int')); + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; } else { setEventMessages($object->error, $object->errors, 'errors'); } } -} elseif ($action == 'swapstatut' && $user->hasRight('commande', 'creer')) { - // bascule du statut d'un contact - if ($object->fetch($id)) { - $result = $object->swapContactStatus(GETPOST('ligne', 'int')); - } else { - dol_print_error($db); - } -} elseif ($action == 'deletecontact' && $user->hasRight('commande', 'creer')) { - // Efface un contact - $object->fetch($id); - $result = $object->delete_contact(GETPOST("lineid", 'int')); - - if ($result >= 0) { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } } - /* * View */ diff --git a/htdocs/commande/document.php b/htdocs/commande/document.php index 66964b2636a..c354e9f34ec 100644 --- a/htdocs/commande/document.php +++ b/htdocs/commande/document.php @@ -177,7 +177,7 @@ if ($id > 0 || !empty($ref)) { $modulepart = 'commande'; $permissiontoadd = $user->rights->commande->creer; $permtoedit = $user->rights->commande->creer; - $param = '&id='.$object->id.'&entity='.(!empty($object->entity) ? $object->entity : $conf->entity); + $param = '&id='.$object->id.'&entity='.(empty($object->entity) ? $conf->entity : $object->entity); include DOL_DOCUMENT_ROOT.'/core/tpl/document_actions_post_headers.tpl.php'; } else { dol_print_error($db); diff --git a/htdocs/commande/index.php b/htdocs/commande/index.php index 7958762e720..cf30a608387 100644 --- a/htdocs/commande/index.php +++ b/htdocs/commande/index.php @@ -56,7 +56,7 @@ if ($user->socid > 0) { $socid = $user->socid; } -$max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; +$max = getDolGlobalInt('MAIN_SIZE_SHORTLIST_LIMIT'); // Maximum elements of the tables $maxDraftCount = !getDolGlobalString('MAIN_MAXLIST_OVERLOAD') ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD; diff --git a/htdocs/commande/list.php b/htdocs/commande/list.php index 8c8f661fac8..962fbf318b5 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -76,6 +76,8 @@ $search_dateorder_end = dol_mktime(23, 59, 59, GETPOST('search_dateorder_end_mon $search_datedelivery_start = dol_mktime(0, 0, 0, GETPOST('search_datedelivery_start_month', 'int'), GETPOST('search_datedelivery_start_day', 'int'), GETPOST('search_datedelivery_start_year', 'int')); $search_datedelivery_end = dol_mktime(23, 59, 59, GETPOST('search_datedelivery_end_month', 'int'), GETPOST('search_datedelivery_end_day', 'int'), GETPOST('search_datedelivery_end_year', 'int')); +$socid = GETPOST('socid', 'int'); +$search_all = trim((GETPOST('search_all', 'alphanohtml') != '') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); $search_product_category = GETPOST('search_product_category', 'int'); $search_ref = GETPOST('search_ref', 'alpha') != '' ? GETPOST('search_ref', 'alpha') : GETPOST('sref', 'alpha'); $search_ref_customer = GETPOST('search_ref_customer', 'alpha'); @@ -87,8 +89,6 @@ $search_zip = GETPOST('search_zip', 'alpha'); $search_state = GETPOST('search_state', 'alpha'); $search_country = GETPOST('search_country', 'int'); $search_type_thirdparty = GETPOST('search_type_thirdparty', 'int'); -$sall = trim((GETPOST('search_all', 'alphanohtml') != '') ? GETPOST('search_all', 'alphanohtml') : GETPOST('sall', 'alphanohtml')); -$socid = GETPOST('socid', 'int'); $search_user = GETPOST('search_user', 'int'); $search_sale = GETPOST('search_sale', 'int'); $search_total_ht = GETPOST('search_total_ht', 'alpha'); @@ -107,8 +107,6 @@ $search_categ_cus = GETPOST("search_categ_cus", 'int'); $optioncss = GETPOST('optioncss', 'alpha'); $search_billed = GETPOST('search_billed', 'int'); $search_status = GETPOST('search_status', 'int'); -$search_btn = GETPOST('button_search', 'alpha'); -$search_remove_btn = GETPOST('button_removefilter', 'alpha'); $search_project_ref = GETPOST('search_project_ref', 'alpha'); $search_project = GETPOST('search_project', 'alpha'); $search_shippable = GETPOST('search_shippable', 'aZ09'); @@ -167,15 +165,15 @@ if (empty($user->socid)) { $checkedtypetiers = 0; $arrayfields = array( - 'c.ref'=>array('label'=>"Ref", 'checked'=>1, 'position'=>5), - 'c.ref_client'=>array('label'=>"RefCustomerOrder", 'checked'=>-1, 'position'=>10), + 'c.ref'=>array('label'=>"Ref", 'checked'=>1, 'position'=>5, 'searchall'=>1), + 'c.ref_client'=>array('label'=>"RefCustomerOrder", 'checked'=>-1, 'position'=>10, 'searchall'=>1), 'p.ref'=>array('label'=>"ProjectRef", 'checked'=>-1, 'enabled'=>(!isModEnabled('project') ? 0 : 1), 'position'=>20), 'p.title'=>array('label'=>"ProjectLabel", 'checked'=>0, 'enabled'=>(!isModEnabled('project') ? 0 : 1), 'position'=>25), - 's.nom'=>array('label'=>"ThirdParty", 'checked'=>1, 'position'=>30), - 's.name_alias'=>array('label'=>"AliasNameShort", 'checked'=>-1, 'position'=>31), + 's.nom'=>array('label'=>"ThirdParty", 'checked'=>1, 'position'=>30, 'searchall'=>1), + 's.name_alias'=>array('label'=>"AliasNameShort", 'checked'=>-1, 'position'=>31, 'searchall'=>1), 's2.nom'=>array('label'=>'ParentCompany', 'position'=>32, 'checked'=>0), - 's.town'=>array('label'=>"Town", 'checked'=>-1, 'position'=>35), - 's.zip'=>array('label'=>"Zip", 'checked'=>-1, 'position'=>40), + 's.town'=>array('label'=>"Town", 'checked'=>-1, 'position'=>35, 'searchall'=>1), + 's.zip'=>array('label'=>"Zip", 'checked'=>-1, 'position'=>40, 'searchall'=>1), 'state.nom'=>array('label'=>"StateShort", 'checked'=>0, 'position'=>45), 'country.code_iso'=>array('label'=>"Country", 'checked'=>0, 'position'=>50), 'typent.code'=>array('label'=>"ThirdPartyType", 'checked'=>$checkedtypetiers, 'position'=>55), @@ -202,7 +200,7 @@ $arrayfields = array( 'c.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>120), 'c.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>125), 'c.date_cloture'=>array('label'=>"DateClosing", 'checked'=>0, 'position'=>130), - 'c.note_public'=>array('label'=>'NotePublic', 'checked'=>0, 'enabled'=>(!getDolGlobalInt('MAIN_LIST_HIDE_PUBLIC_NOTES')), 'position'=>135), + 'c.note_public'=>array('label'=>'NotePublic', 'checked'=>0, 'enabled'=>(!getDolGlobalInt('MAIN_LIST_HIDE_PUBLIC_NOTES')), 'position'=>135, 'searchall'=>1), 'c.note_private'=>array('label'=>'NotePrivate', 'checked'=>0, 'enabled'=>(!getDolGlobalInt('MAIN_LIST_HIDE_PRIVATE_NOTES')), 'position'=>140), 'shippable'=>array('label'=>"Shippable", 'checked'=>1,'enabled'=>(isModEnabled("expedition")), 'position'=>990), 'c.facture'=>array('label'=>"Billed", 'checked'=>1, 'enabled'=>(!getDolGlobalString('WORKFLOW_BILL_ON_SHIPMENT')), 'position'=>995), @@ -210,6 +208,14 @@ $arrayfields = array( 'c.fk_statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000) ); +$parameters = array('fieldstosearchall'=>$fieldstosearchall); +$reshook = $hookmanager->executeHooks('completeFieldsToSearchAll', $parameters, $object, $action); // Note that $action and $object may have been modified by some hooks +if ($reshook > 0) { + $fieldstosearchall = empty($hookmanager->resArray['fieldstosearchall']) ? array() : $hookmanager->resArray['fieldstosearchall']; +} elseif ($reshook == 0) { + $fieldstosearchall = array_merge($fieldstosearchall, empty($hookmanager->resArray['fieldstosearchall']) ? array() : $hookmanager->resArray['fieldstosearchall']); +} + // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; @@ -255,7 +261,6 @@ if (empty($reshook)) { // Purge search criteria if (GETPOST('button_removefilter_x', 'alpha') || GETPOST('button_removefilter.x', 'alpha') || GETPOST('button_removefilter', 'alpha')) { // All tests are required to be compatible with all browsers - $search_categ = ''; $search_user = ''; $search_sale = ''; $search_product_category = ''; @@ -599,8 +604,14 @@ if (empty($reshook)) { if ($limit > 0 && $limit != $conf->liste_limit) { $param .= '&limit='.((int) $limit); } - if ($sall) { - $param .= '&sall='.urlencode($sall); + if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); + } + if ($search_all) { + $param .= '&search_all='.urlencode($search_all); + } + if ($show_files) { + $param .= '&show_files='.urlencode($show_files); } if ($socid > 0) { $param .= '&socid='.urlencode($socid); @@ -653,14 +664,8 @@ if (empty($reshook)) { if ($search_project_ref >= 0) { $param .= "&search_project_ref=".urlencode($search_project_ref); } - if ($show_files) { - $param .= '&show_files='.urlencode($show_files); - } - if ($optioncss != '') { - $param .= '&optioncss='.urlencode($optioncss); - } - if ($billed != '') { - $param .= '&billed='.urlencode($billed); + if ($search_billed != '') { + $param .= '&search_billed='.urlencode($search_billed); } header("Location: ".$_SERVER['PHP_SELF'].'?'.$param); @@ -789,7 +794,6 @@ if (!$error && $massaction === 'setbilled' && $permissiontoclose) { * View */ - $form = new Form($db); $formother = new FormOther($db); $formfile = new FormFile($db); @@ -813,7 +817,7 @@ $help_url = "EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_P // Build and execute select // -------------------------------------------------------------------- $sql = 'SELECT'; -if ($sall || $search_user > 0) { +if ($search_all || $search_user > 0) { $sql = 'SELECT DISTINCT'; } $sql .= ' s.rowid as socid, s.nom as name, s.name_alias as alias, s.email, s.phone, s.fax, s.address, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client,'; @@ -830,9 +834,6 @@ $sql .= ' p.rowid as project_id, p.ref as project_ref, p.title as project_label, $sql .= ' u.login, u.lastname, u.firstname, u.email as user_email, u.statut as user_statut, u.entity, u.photo, u.office_phone, u.office_fax, u.user_mobile, u.job, u.gender,'; $sql .= ' c.fk_cond_reglement,c.deposit_percent,c.fk_mode_reglement,c.fk_shipping_method,'; $sql .= ' c.fk_input_reason, c.import_key'; -if (($search_categ_cus > 0) || ($search_categ_cus == -2)) { - $sql .= ", cc.fk_categorie, cc.fk_soc"; -} // Add fields from extrafields if (!empty($extrafields->attributes[$object->table_element]['label'])) { @@ -854,14 +855,11 @@ $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."societe as s2 ON s2.rowid = s.parent"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as country on (country.rowid = s.fk_pays)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_typent as typent on (typent.id = s.fk_typent)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_departements as state on (state.rowid = s.fk_departement)"; -if (($search_categ_cus > 0) || ($search_categ_cus == -2)) { - $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX."categorie_societe as cc ON s.rowid = cc.fk_soc"; // We'll need this table joined to the select in order to filter by categ -} $sql .= ', '.MAIN_DB_PREFIX.'commande as c'; if (!empty($extrafields->attributes[$object->table_element]['label']) && is_array($extrafields->attributes[$object->table_element]['label']) && count($extrafields->attributes[$object->table_element]['label'])) { $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."commande_extrafields as ef on (c.rowid = ef.fk_object)"; } -if ($sall) { +if ($search_all) { $sql .= ' LEFT JOIN '.MAIN_DB_PREFIX.'commandedet as pd ON c.rowid=pd.fk_commande'; } $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."projet as p ON p.rowid = c.fk_projet"; @@ -887,13 +885,13 @@ if ($search_ref) { if ($search_ref_customer) { $sql .= natural_search('c.ref_client', $search_ref_customer); } -if ($sall) { - $sql .= natural_search(array_keys($fieldstosearchall), $sall); +if ($search_all) { + $sql .= natural_search(array_keys($fieldstosearchall), $search_all); } if ($search_billed != '' && $search_billed >= 0) { $sql .= ' AND c.facture = '.((int) $search_billed); } -if ($search_status <> '') { +if ($search_status != '') { if ($search_status <= 3 && $search_status >= -1) { // status from -1 to 3 are real status (other are virtual combination) if ($search_status == 1 && !isModEnabled('expedition')) { $sql .= ' AND c.fk_statut IN (1,2)'; // If module expedition disabled, we include order with status 'sending in process' into 'validated' @@ -997,12 +995,6 @@ if ($search_project_ref != '') { if ($search_project != '') { $sql .= natural_search("p.title", $search_project); } -if ($search_categ_cus > 0) { - $sql .= " AND cc.fk_categorie = ".((int) $search_categ_cus); -} -if ($search_categ_cus == -2) { - $sql .= " AND cc.fk_categorie IS NULL"; -} if ($search_fk_cond_reglement > 0) { $sql .= " AND c.fk_cond_reglement = ".((int) $search_fk_cond_reglement); } @@ -1023,6 +1015,36 @@ if ($search_sale && $search_sale != '-1') { $sql .= " AND EXISTS (SELECT sc.fk_soc FROM ".MAIN_DB_PREFIX."societe_commerciaux as sc WHERE sc.fk_soc = c.fk_soc AND sc.fk_user = ".((int) $search_sale).")"; } } +// Search for tag/category ($searchCategoryCustomerList is an array of ID) +$searchCategoryCustomerOperator = -1; +$searchCategoryCustomerList = array($search_categ_cus); +if (!empty($searchCategoryCustomerList)) { + $searchCategoryCustomerSqlList = array(); + $listofcategoryid = ''; + foreach ($searchCategoryCustomerList as $searchCategoryCustomer) { + if (intval($searchCategoryCustomer) == -2) { + $searchCategoryCustomerSqlList[] = "NOT EXISTS (SELECT cs.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as cs WHERE s.rowid = cs.fk_soc)"; + } elseif (intval($searchCategoryCustomer) > 0) { + if ($searchCategoryCustomerOperator == 0) { + $searchCategoryCustomerSqlList[] = " EXISTS (SELECT cs.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as cs WHERE s.rowid = cs.fk_soc AND cs.fk_categorie = ".((int) $searchCategoryCustomer).")"; + } else { + $listofcategoryid .= ($listofcategoryid ? ', ' : '') .((int) $searchCategoryCustomer); + } + } + } + if ($listofcategoryid) { + $searchCategoryCustomerSqlList[] = " EXISTS (SELECT cs.fk_soc FROM ".MAIN_DB_PREFIX."categorie_societe as cs WHERE s.rowid = cs.fk_soc AND cs.fk_categorie IN (".$db->sanitize($listofcategoryid)."))"; + } + if ($searchCategoryCustomerOperator == 1) { + if (!empty($searchCategoryCustomerSqlList)) { + $sql .= " AND (".implode(' OR ', $searchCategoryCustomerSqlList).")"; + } + } else { + if (!empty($searchCategoryCustomerSqlList)) { + $sql .= " AND (".implode(' AND ', $searchCategoryCustomerSqlList).")"; + } + } +} // Search for tag/category ($searchCategoryProductList is an array of ID) $searchCategoryProductOperator = -1; $searchCategoryProductList = array($search_product_category); @@ -1138,7 +1160,7 @@ $num = $db->num_rows($resql); $arrayofselected = is_array($toselect) ? $toselect : array(); -if ($num == 1 && getDolGlobalString('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $sall) { +if ($num == 1 && getDolGlobalString('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && $search_all) { $obj = $db->fetch_object($resql); $id = $obj->rowid; header("Location: ".DOL_URL_ROOT.'/commande/card.php?id='.$id); @@ -1162,8 +1184,8 @@ if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { if ($limit > 0 && $limit != $conf->liste_limit) { $param .= '&limit='.((int) $limit); } -if ($sall) { - $param .= '&sall='.urlencode($sall); +if ($search_all) { + $param .= '&search_all='.urlencode($search_all); } if ($socid > 0) { $param .= '&socid='.((int) $socid); @@ -1312,7 +1334,7 @@ if ($permissiontoclose) { $arrayofmassactions['setbilled'] = img_picto('', 'bill', 'class="pictofixedwidth"').$langs->trans("ClassifyBilled"); } if ($permissiontocancel) { - $arrayofmassactions['cancelorders'] = img_picto('', 'close_title', 'class="pictofixedwidth"').$langs->trans("Cancel"); + $arrayofmassactions['cancelorders'] = img_picto('', 'close_title', 'class="pictofixedwidth"').$langs->trans("CancelOrder"); } if (!empty($permissiontodelete)) { $arrayofmassactions['predelete'] = img_picto('', 'delete', 'class="pictofixedwidth"').$langs->trans("Delete"); @@ -1415,14 +1437,14 @@ if ($massaction == 'createbills') { print '

    '; } -if ($sall) { +if ($search_all) { $setupstring = ''; foreach ($fieldstosearchall as $key => $val) { $fieldstosearchall[$key] = $langs->trans($val); $setupstring .= $key."=".$val.";"; } print ''."\n"; - print '
    '.$langs->trans("FilterOnInto", $sall).join(', ', $fieldstosearchall).'
    '; + print '
    '.$langs->trans("FilterOnInto", $search_all).join(', ', $fieldstosearchall).'
    '; } $moreforfilter = ''; diff --git a/htdocs/commande/list_det.php b/htdocs/commande/list_det.php index 255dd76614e..61a363ae3fa 100644 --- a/htdocs/commande/list_det.php +++ b/htdocs/commande/list_det.php @@ -10,7 +10,7 @@ * Copyright (C) 2015 Marcos García * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2016-2021 Ferran Marcet - * Copyright (C) 2018 Charlene Benke + * Copyright (C) 2018-2023 Charlene Benke * Copyright (C) 2021-2023 Anthony Berton * * This program is free software; you can redistribute it and/or modify @@ -373,7 +373,7 @@ $help_url = "EN:Module_Customers_Orders|FR:Module_Commandes_Clients|ES:Módulo_P // llxHeader('',$title,$help_url); $sql = 'SELECT'; -if ($sall || $search_product_category > 0 || $search_user > 0) { +if ($sall || $search_product_category_array > 0 || $search_user > 0) { $sql = 'SELECT DISTINCT'; } $sql .= ' s.rowid as socid, s.nom as name, s.name_alias as alias, s.email, s.phone, s.fax, s.address, s.town, s.zip, s.fk_pays, s.client, s.code_client,'; @@ -470,7 +470,7 @@ if ($sall) { if ($search_billed != '' && $search_billed >= 0) { $sql .= ' AND c.facture = '.((int) $search_billed); } -if ($search_status <> '') { +if ($search_status != '') { if ($search_status <= 3 && $search_status >= -1) { // status from -1 to 3 are real status (other are virtual combination) if ($search_status == 1 && !isModEnabled('expedition')) { $sql .= ' AND c.fk_statut IN (1,2)'; // If module expedition disabled, we include order with status 'sending in process' into 'validated' @@ -1486,6 +1486,7 @@ if ($resql) { $totalarray = array(); $totalarray['nbfield'] = 0; + $subtotalarray['nbfield'] = 0; $totalarray['val']['cdet.total_tva'] = 0; $totalarray['val']['cdet.total_ttc'] = 0; $imaxinloop = ($limit ? min($num, $limit) : $num); diff --git a/htdocs/compta/accounting-files.php b/htdocs/compta/accounting-files.php index d9467795953..edfe20bce00 100644 --- a/htdocs/compta/accounting-files.php +++ b/htdocs/compta/accounting-files.php @@ -480,7 +480,7 @@ if (($action == 'searchfiles' || $action == 'dl')) { *ZIP creation */ -$dirfortmpfile = ($conf->accounting->dir_temp ? $conf->accounting->dir_temp : $conf->comptabilite->dir_temp); +$dirfortmpfile = (!empty($conf->accounting->dir_temp) ? $conf->accounting->dir_temp : $conf->comptabilite->dir_temp); if (empty($dirfortmpfile)) { setEventMessages($langs->trans("ErrorNoAccountingModuleEnabled"), null, 'errors'); $error++; diff --git a/htdocs/compta/bank/annuel.php b/htdocs/compta/bank/annuel.php index ef64c1746f1..c6513038854 100644 --- a/htdocs/compta/bank/annuel.php +++ b/htdocs/compta/bank/annuel.php @@ -2,7 +2,7 @@ /* Copyright (C) 2005 Rodolphe Quiedeville * Copyright (C) 2004-2017 Laurent Destailleur * Copyright (C) 2005-2012 Regis Houssin - * Copyright (C) 2013 Charles-Fr BENKE + * Copyright (C) 2013-2023 Charlene BENKE * * 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 @@ -51,7 +51,8 @@ if ($user->socid) { $result = restrictedArea($user, 'banque', $fieldvalue, 'bank_account&bank_account', '', '', $fieldtype); $year_start = GETPOST('year_start'); -$year_current = strftime("%Y", time()); +//$year_current = strftime("%Y", time()); +$year_current = dol_print_date(time(), "%Y"); if (!$year_start) { $year_start = $year_current - 2; $year_end = $year_current; diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index 84131a90fc3..038663e4dc5 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -1290,6 +1290,9 @@ if ($resql) { $savnbfield = $totalarray['nbfield']; $totalarray = array(); $totalarray['nbfield'] = 0; + $totalarray['totaldeb'] = 0; + $totalarray['totalcred'] = 0; + $imaxinloop = ($limit ? min($num, $limit) : $num); while ($i < $imaxinloop) { $objp = $db->fetch_object($resql); diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index 5b10b742d87..bdeed68f0b0 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -491,7 +491,7 @@ class Account extends CommonObject * @param string $type To search using type * @return array|int Array of links array('url'=>, 'url_id'=>, 'label'=>, 'type'=> 'fk_bank'=> ) or -1 on error */ - public function get_url($fk_bank = '', $url_id = '', $type = '') + public function get_url($fk_bank = 0, $url_id = 0, $type = '') { // phpcs:enable $lines = array(); @@ -701,6 +701,15 @@ class Account extends CommonObject } // Load librairies to check BAN + $balance = $this->balance; + if (empty($balance) && !empty($this->solde)) { + $balance = $this->solde; + } + if (empty($balance)) { + $balance = 0; + } + + // Load the library to validate/check a BAN account require_once DOL_DOCUMENT_ROOT.'/core/lib/bank.lib.php'; $now = dol_now(); @@ -779,7 +788,7 @@ class Account extends CommonObject $accline = new AccountLine($this->db); $accline->datec = $now; $accline->label = '('.$langs->trans("InitialBankBalance").')'; - $accline->amount = price2num($this->solde); + $accline->amount = price2num($balance); $accline->fk_user_author = $user->id; $accline->fk_account = $this->id; $accline->datev = $this->date_solde; @@ -1249,7 +1258,7 @@ class Account extends CommonObject * Return current sold * * @param int $option 1=Exclude future operation date (this is to exclude input made in advance and have real account sold) - * @param int $date_end Date until we want to get bank account sold + * @param int|string $date_end Date until we want to get bank account sold * @param string $field dateo or datev * @return int current sold (value date <= today) */ @@ -1880,7 +1889,7 @@ class Account extends CommonObject $return .= ''.$langs->trans("Balance").' : '.price(price2num($this->solde(1), 'MT'), 0, $langs, 1, -1, -1, $this->currency_code).''; } if (method_exists($this, 'getLibStatut')) { - $return .= '
    '.$this->getLibStatut(3).'
    '; + $return .= '
    '.$this->getLibStatut(3).'
    '; } $return .= ''; $return .= ''; diff --git a/htdocs/compta/bank/graph.php b/htdocs/compta/bank/graph.php index 490107e4893..c7be41eed61 100644 --- a/htdocs/compta/bank/graph.php +++ b/htdocs/compta/bank/graph.php @@ -188,7 +188,8 @@ if ($result < 0) { $subtotal = 0; $day = dol_mktime(12, 0, 0, $month, 1, $year); - $textdate = strftime("%Y%m%d", $day); + //$textdate = strftime("%Y%m%d", $day); + $textdate = dol_print_date($day, "%Y%m%d"); $xyear = substr($textdate, 0, 4); $xday = substr($textdate, 6, 2); $xmonth = substr($textdate, 4, 2); @@ -207,7 +208,8 @@ if ($result < 0) { $labels[$i] = $xday; $day += 86400; - $textdate = strftime("%Y%m%d", $day); + //$textdate = strftime("%Y%m%d", $day); + $textdate = dol_print_date($day, "%Y%m%d"); $xyear = substr($textdate, 0, 4); $xday = substr($textdate, 6, 2); $xmonth = substr($textdate, 4, 2); @@ -332,7 +334,8 @@ if ($result < 0) { $subtotal = 0; $now = time(); $day = dol_mktime(12, 0, 0, 1, 1, $year); - $textdate = strftime("%Y%m%d", $day); + //$textdate = strftime("%Y%m%d", $day); + $textdate = dol_print_date($day, "%Y%m%d"); $xyear = substr($textdate, 0, 4); $xday = substr($textdate, 6, 2); @@ -352,7 +355,8 @@ if ($result < 0) { }*/ $labels[$i] = dol_print_date($day, "%Y%m"); $day += 86400; - $textdate = strftime("%Y%m%d", $day); + //$textdate = strftime("%Y%m%d", $day); + $textdate = dol_print_date($day, "%Y%m%d"); $xyear = substr($textdate, 0, 4); $xday = substr($textdate, 6, 2); $i++; @@ -449,7 +453,8 @@ if ($result < 0) { $subtotal = 0; $day = $min; - $textdate = strftime("%Y%m%d", $day); + //$textdate = strftime("%Y%m%d", $day); + $textdate = dol_print_date($day, "%Y%m%d"); //print "x".$textdate; $i = 0; while ($day <= ($max + 86400)) { // On va au dela du dernier jour @@ -469,7 +474,8 @@ if ($result < 0) { $labels[$i] = substr($textdate, 0, 6); $day += 86400; - $textdate = strftime("%Y%m%d", $day); + //$textdate = strftime("%Y%m%d", $day); + $textdate = dol_print_date($day, "%Y%m%d"); $i++; } diff --git a/htdocs/compta/cashcontrol/class/cashcontrol.class.php b/htdocs/compta/cashcontrol/class/cashcontrol.class.php index 6a2233cee9e..1481678a06c 100644 --- a/htdocs/compta/cashcontrol/class/cashcontrol.class.php +++ b/htdocs/compta/cashcontrol/class/cashcontrol.class.php @@ -507,7 +507,7 @@ class CashControl extends CommonObject $return .= '
    '.$langs->trans("Year").' : '.$this->year_close.''; } if (method_exists($this, 'getLibStatut')) { - $return .= '
    '.$this->getLibStatut(3).'
    '; + $return .= '
    '.$this->getLibStatut(3).'
    '; } $return .= ''; $return .= ''; diff --git a/htdocs/compta/cashcontrol/report.php b/htdocs/compta/cashcontrol/report.php index e702e05ea2c..b8a062c0111 100644 --- a/htdocs/compta/cashcontrol/report.php +++ b/htdocs/compta/cashcontrol/report.php @@ -281,10 +281,10 @@ if ($resql) { } $transactionspertype[$objp->code] += 1; } else { - if ($conf->global->$var1 == $bankaccount->id) { + if (getDolGlobalString($var1) == $bankaccount->id) { $cash += $objp->amount; - // } elseif ($conf->global->$var2 == $bankaccount->id) $bank+=$objp->amount; - //elseif ($conf->global->$var3 == $bankaccount->id) $cheque+=$objp->amount; + // } elseif (getDolGlobalString($var2) == $bankaccount->id) $bank+=$objp->amount; + //elseif (getDolGlobalString($var3) == $bankaccount->id) $cheque+=$objp->amount; if (empty($transactionspertype['CASH'])) { $transactionspertype['CASH'] = 0; } diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index a3df224a900..9e5b10ce402 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -2757,7 +2757,7 @@ if (empty($reshook)) { $all_progress = GETPOST('all_progress', 'int'); foreach ($object->lines as $line) { $percent = $line->get_prev_progress($object->id); - if (floatval($all_progress) < floatval($percent)) { + if ((float) $all_progress < (float) $percent) { $mesg = $langs->trans("Line").' '.$i.' : '.$langs->trans("CantBeLessThanMinPercent"); setEventMessages($mesg, null, 'warnings'); $result = -1; @@ -3847,7 +3847,7 @@ if ($action == 'create') { if($( this ).prop("checked") && $.inArray($( this ).val(), '.json_encode($retainedWarrantyInvoiceAvailableType).' ) !== -1) { $(".retained-warranty-line").show(); - $("#new-situation-invoice-retained-warranty").val("'.floatval($retained_warranty_js_default).'"); + $("#new-situation-invoice-retained-warranty").val("'.(float) $retained_warranty_js_default.'"); } else{ $(".retained-warranty-line").hide(); @@ -3925,9 +3925,9 @@ if ($action == 'create') { if (getDolGlobalString('INVOICE_USE_DEFAULT_DOCUMENT')) { // Hidden conf $paramkey = 'FACTURE_ADDON_PDF_'.$object->type; - $preselected = !empty($conf->global->$paramkey) ? $conf->global->$paramkey : $conf->global->FACTURE_ADDON_PDF; + $preselected = getDolGlobalString($paramkey, getDolGlobalString('FACTURE_ADDON_PDF')); } else { - $preselected = $conf->global->FACTURE_ADDON_PDF; + $preselected = getDolGlobalString('FACTURE_ADDON_PDF'); } print $form->selectarray('model', $liste, $preselected, 0, 0, 0, '', 0, 0, 0, '', 'maxwidth200 widthcentpercentminusx', 1); print ""; @@ -5264,7 +5264,7 @@ if ($action == 'create') { } print ''; - $label = ($langs->trans("PaymentType".$objp->payment_code) != ("PaymentType".$objp->payment_code)) ? $langs->trans("PaymentType".$objp->payment_code) : $objp->payment_label; + $label = ($langs->trans("PaymentType".$objp->payment_code) != "PaymentType".$objp->payment_code) ? $langs->trans("PaymentType".$objp->payment_code) : $objp->payment_label; print '
    '; if (isModEnabled("banque")) { $bankaccountstatic->id = $objp->baid; diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index 94de562a3c2..35e81b82f82 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -281,9 +281,7 @@ class Invoices extends DolibarrApi } else { throw new RestException(503, 'Error when retrieve invoice list : '.$this->db->lasterror()); } - if (!count($obj_ret)) { - throw new RestException(404, 'No invoice found'); - } + return $obj_ret; } diff --git a/htdocs/compta/facture/class/facture-rec.class.php b/htdocs/compta/facture/class/facture-rec.class.php index 1410c86b0dd..9a0127134fa 100644 --- a/htdocs/compta/facture/class/facture-rec.class.php +++ b/htdocs/compta/facture/class/facture-rec.class.php @@ -873,7 +873,7 @@ class FactureRec extends CommonInvoice * @param int $fk_parent_line Id of parent line * @return int Return integer <0 if KO, Id of line if OK */ - public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = '', $pu_ttc = 0, $type = 0, $rang = -1, $special_code = 0, $label = '', $fk_unit = null, $pu_ht_devise = 0, $date_start_fill = 0, $date_end_fill = 0, $fk_fournprice = null, $pa_ht = 0, $fk_parent_line = 0) + public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = 0, $pu_ttc = 0, $type = 0, $rang = -1, $special_code = 0, $label = '', $fk_unit = null, $pu_ht_devise = 0, $date_start_fill = 0, $date_end_fill = 0, $fk_fournprice = null, $pa_ht = 0, $fk_parent_line = 0) { global $mysoc; @@ -1080,7 +1080,7 @@ class FactureRec extends CommonInvoice * @param int $fk_parent_line Id of parent line * @return int Return integer <0 if KO, Id of line if OK */ - public function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = '', $pu_ttc = 0, $type = 0, $rang = -1, $special_code = 0, $label = '', $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $date_start_fill = 0, $date_end_fill = 0, $fk_fournprice = null, $pa_ht = 0, $fk_parent_line = 0) + public function updateline($rowid, $desc, $pu_ht, $qty, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $fk_product = 0, $remise_percent = 0, $price_base_type = 'HT', $info_bits = 0, $fk_remise_except = 0, $pu_ttc = 0, $type = 0, $rang = -1, $special_code = 0, $label = '', $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $date_start_fill = 0, $date_end_fill = 0, $fk_fournprice = null, $pa_ht = 0, $fk_parent_line = 0) { global $mysoc; @@ -1447,7 +1447,7 @@ class FactureRec extends CommonInvoice * @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, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = '', $save_lastsearch_value = -1) + public function getNomUrl($withpicto = 0, $option = '', $max = 0, $short = 0, $moretitle = '', $notooltip = 0, $save_lastsearch_value = -1) { global $langs, $hookmanager; @@ -2172,7 +2172,7 @@ class FactureLigneRec extends CommonInvoiceLine * @param int $notrigger Disable triggers * @return int Return integer <0 if KO, >0 if OK */ - public function delete(User $user, $notrigger = false) + public function delete(User $user, $notrigger = 0) { $error = 0; diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index b277db0da53..ac8bf5b43f3 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -685,7 +685,7 @@ class Facture extends CommonInvoice $sql .= ", ".(empty($this->date_pointoftax) ? "null" : "'".$this->db->idate($this->date_pointoftax)."'"); $sql .= ", ".($this->note_private ? "'".$this->db->escape($this->note_private)."'" : "null"); $sql .= ", ".($this->note_public ? "'".$this->db->escape($this->note_public)."'" : "null"); - $sql .= ", ".($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null"); + $sql .= ", ".($this->ref_customer ? "'".$this->db->escape($this->ref_customer)."'" : ($this->ref_client ? "'".$this->db->escape($this->ref_client)."'" : "null")); $sql .= ", ".($this->fk_account > 0 ? $this->fk_account : 'NULL'); $sql .= ", ".($this->module_source ? "'".$this->db->escape($this->module_source)."'" : "null"); $sql .= ", ".($this->pos_source != '' ? "'".$this->db->escape($this->pos_source)."'" : "null"); @@ -1689,10 +1689,10 @@ class Facture extends CommonInvoice $modelByTypeConfName = 'FACTURE_ADDON_PDF_' . $deposit->type; - if (!empty($conf->global->$modelByTypeConfName)) { - $deposit->model_pdf = $conf->global->$modelByTypeConfName; + if (getDolGlobalString($modelByTypeConfName)) { + $deposit->model_pdf = getDolGlobalString($modelByTypeConfName); } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) { - $deposit->model_pdf = $conf->global->FACTURE_ADDON_PDF; + $deposit->model_pdf = getDolGlobalString('FACTURE_ADDON_PDF'); } if (!getDolGlobalString('MAIN_DISABLE_PROPAGATE_NOTES_FROM_ORIGIN')) { @@ -2113,7 +2113,7 @@ class Facture extends CommonInvoice * @param bool $fetch_situation Load also the previous and next situation invoice into $tab_previous_situation_invoice and $tab_next_situation_invoice * @return int >0 if OK, <0 if KO, 0 if not found */ - public function fetch($rowid, $ref = '', $ref_ext = '', $notused = '', $fetch_situation = false) + public function fetch($rowid, $ref = '', $ref_ext = '', $notused = 0, $fetch_situation = false) { if (empty($rowid) && empty($ref) && empty($ref_ext)) { return -1; @@ -2488,7 +2488,7 @@ class Facture extends CommonInvoice $this->import_key = trim($this->import_key); } if (isset($this->retained_warranty)) { - $this->retained_warranty = floatval($this->retained_warranty); + $this->retained_warranty = (float) $this->retained_warranty; } @@ -3270,7 +3270,7 @@ class Facture extends CommonInvoice // Check for mandatory $keymandatory = 'INVOICE_'.$key.'_MANDATORY_FOR_VALIDATION'; - if (!$vallabel && !empty($conf->global->$keymandatory)) { + if (!$vallabel && getDolGlobalString($keymandatory)) { $langs->load("errors"); $error++; setEventMessages($langs->trans("ErrorFieldRequired", $langs->transnoentitiesnoconv($val)), null, 'errors'); @@ -3747,8 +3747,8 @@ class Facture extends CommonInvoice * @param double $txlocaltax2 Local tax 2 rate (deprecated, use instead txtva with code inside) * @param int $fk_product Id of predefined product/service * @param double $remise_percent Percent of discount on line - * @param int $date_start Date start of service - * @param int $date_end Date end of service + * @param int|string $date_start Date start of service + * @param int|string $date_end Date end of service * @param int $ventil Code of dispatching into accountancy * @param int $info_bits Bits of type of lines * @param int $fk_remise_except Id discount used @@ -3785,7 +3785,7 @@ class Facture extends CommonInvoice $date_end = '', $ventil = 0, $info_bits = 0, - $fk_remise_except = '', + $fk_remise_except = 0, $price_base_type = 'HT', $pu_ttc = 0, $type = 0, @@ -3797,7 +3797,7 @@ class Facture extends CommonInvoice $fk_fournprice = null, $pa_ht = 0, $label = '', - $array_options = 0, + $array_options = array(), $situation_percent = 100, $fk_prev_id = 0, $fk_unit = null, @@ -4068,7 +4068,7 @@ class Facture extends CommonInvoice * @param integer $rang rank of line * @return int Return integer < 0 if KO, > 0 if OK */ - public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = 0, $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '', $rang = 0) + public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $txtva, $txlocaltax1 = 0, $txlocaltax2 = 0, $price_base_type = 'HT', $info_bits = 0, $type = self::TYPE_STANDARD, $fk_parent_line = 0, $skip_update_total = 0, $fk_fournprice = null, $pa_ht = 0, $label = '', $special_code = 0, $array_options = array(), $situation_percent = 100, $fk_unit = null, $pu_ht_devise = 0, $notrigger = 0, $ref_ext = '', $rang = 0) { global $conf, $user; // Deprecation warning @@ -4709,7 +4709,7 @@ class Facture extends CommonInvoice * @param string $sortorder Sort order * @return array|int -1 if KO, array with result if OK */ - public function liste_array($shortlist = 0, $draft = 0, $excluser = '', $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC') + public function liste_array($shortlist = 0, $draft = 0, $excluser = null, $socid = 0, $limit = 0, $offset = 0, $sortfield = 'f.datef,f.rowid', $sortorder = 'DESC') { // phpcs:enable global $conf, $user; @@ -5219,8 +5219,8 @@ class Facture extends CommonInvoice if (!empty($this->model_pdf)) { $modele = $this->model_pdf; - } elseif (!empty($conf->global->$thisTypeConfName)) { - $modele = $conf->global->$thisTypeConfName; + } elseif (getDolGlobalString($thisTypeConfName)) { + $modele = getDolGlobalString($thisTypeConfName); } elseif (getDolGlobalString('FACTURE_ADDON_PDF')) { $modele = $conf->global->FACTURE_ADDON_PDF; } @@ -5432,7 +5432,7 @@ class Facture extends CommonInvoice $hasDelay = $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay); if ($hasDelay && !empty($this->retained_warranty) && !empty($this->retained_warranty_date_limit)) { $totalpaid = $this->getSommePaiement(); - $totalpaid = floatval($totalpaid); + $totalpaid = (float) $totalpaid; $RetainedWarrantyAmount = $this->getRetainedWarrantyAmount(); if ($totalpaid >= 0 && $RetainedWarrantyAmount >= 0) { if (($totalpaid < $this->total_ttc - $RetainedWarrantyAmount) && $this->date_lim_reglement < ($now - $conf->facture->client->warning_delay)) { @@ -5532,7 +5532,7 @@ class Facture extends CommonInvoice } if ($rounding < 0) { - $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), $conf->global->MAIN_MAX_DECIMALS_TOT); + $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), getDolGlobalString('MAIN_MAX_DECIMALS_TOT')); } if ($rounding > 0) { @@ -5559,7 +5559,7 @@ class Facture extends CommonInvoice $sql .= ' WHERE rowid='.((int) $this->id); if ($this->db->query($sql)) { - $this->retained_warranty = floatval($value); + $this->retained_warranty = (float) $value; return 1; } else { dol_syslog(get_class($this).'::setRetainedWarranty Erreur '.$sql.' - '.$this->db->error()); @@ -5581,7 +5581,7 @@ class Facture extends CommonInvoice * @param string $dateYmd date limit of retained warranty in Y m d format * @return int >0 if OK, <0 if KO */ - public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = false) + public function setRetainedWarrantyDateLimit($timestamp, $dateYmd = '') { if (!$timestamp && $dateYmd) { $timestamp = $this->db->jdate($dateYmd); @@ -6449,7 +6449,7 @@ class FactureLigne extends CommonInvoiceLine * @param int $notrigger Disable triggers * @return int Return integer <0 if KO, >0 if OK */ - public function update($user = '', $notrigger = 0) + public function update($user = null, $notrigger = 0) { global $user, $conf; @@ -6755,7 +6755,7 @@ class FactureLigne extends CommonInvoiceLine if ($resql && $this->db->num_rows($resql) > 0) { $res = $this->db->fetch_array($resql); - $returnPercent = floatval($res['situation_percent']); + $returnPercent = (float) $res['situation_percent']; if ($include_credit_note) { $sql = 'SELECT fd.situation_percent FROM '.MAIN_DB_PREFIX.'facturedet fd'; @@ -6767,7 +6767,7 @@ class FactureLigne extends CommonInvoiceLine $res = $this->db->query($sql); if ($res) { while ($obj = $this->db->fetch_object($res)) { - $returnPercent = $returnPercent + floatval($obj->situation_percent); + $returnPercent = $returnPercent + (float) $obj->situation_percent; } } else { dol_print_error($this->db); diff --git a/htdocs/compta/facture/contact.php b/htdocs/compta/facture/contact.php index dee8c7b5b09..616a365e879 100644 --- a/htdocs/compta/facture/contact.php +++ b/htdocs/compta/facture/contact.php @@ -4,6 +4,7 @@ * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2011-2015 Philippe Grand * Copyright (C) 2017 Ferran Marcet + * Copyright (C) 2023 Christian Foellmann * * 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 @@ -57,47 +58,56 @@ if ($id > 0 || !empty($ref)) { } $result = restrictedArea($user, 'facture', $object->id); +$hookmanager->initHooks(array('invoicecontactcard', 'globalcard')); $usercancreate = $user->hasRight("facture", "creer"); /* - * Add a new contact + * Actions */ -if ($action == 'addcontact' && $user->hasRight('facture', 'creer')) { - if ($result > 0 && $id > 0) { - $contactid = (GETPOST('userid') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); - $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); - $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); - } - - if ($result >= 0) { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $langs->load("errors"); - setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); - } else { - setEventMessages($object->error, $object->errors, 'errors'); - } - } -} elseif ($action == 'swapstatut' && $user->hasRight('facture', 'creer')) { - // Toggle the status of a contact - $result = $object->swapContactStatus(GETPOST('ligne', 'int')); -} elseif ($action == 'deletecontact' && $user->hasRight('facture', 'creer')) { - // Deletes a contact - $result = $object->delete_contact($lineid); - - if ($result >= 0) { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } else { - dol_print_error($db); - } +$parameters = array('id'=>$id); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); } +if (empty($reshook)) { + // Add new contact + if ($action == 'addcontact' && $user->hasRight('facture', 'creer')) { + if ($result > 0 && $id > 0) { + $contactid = (GETPOST('userid') ? GETPOST('userid', 'int') : GETPOST('contactid', 'int')); + $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); + $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); + } + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $langs->load("errors"); + setEventMessages($langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"), null, 'errors'); + } else { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + } elseif ($action == 'swapstatut' && $user->hasRight('facture', 'creer')) { + // Toggle the status of a contact + $result = $object->swapContactStatus(GETPOST('ligne', 'int')); + } elseif ($action == 'deletecontact' && $user->hasRight('facture', 'creer')) { + // Delete contact + $result = $object->delete_contact($lineid); + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + dol_print_error($db); + } + } +} /* * View diff --git a/htdocs/compta/facture/index.php b/htdocs/compta/facture/index.php index 36d118672e1..fe614a7d2dc 100644 --- a/htdocs/compta/facture/index.php +++ b/htdocs/compta/facture/index.php @@ -41,7 +41,7 @@ if (isset($user->socid) && $user->socid > 0) { $socid = $user->socid; } -$max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; +$max = getDolGlobalInt('MAIN_SIZE_SHORTLIST_LIMIT'); // Maximum elements of the tables $maxDraftCount = !getDolGlobalString('MAIN_MAXLIST_OVERLOAD') ? $max : $conf->global->MAIN_MAXLIST_OVERLOAD; diff --git a/htdocs/compta/facture/list.php b/htdocs/compta/facture/list.php index d58a1cf15d4..f66b13dca46 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -925,6 +925,7 @@ if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) { /* The fast and low memory method to get and count full list converts the sql into a sql count */ $sqlforcount = preg_replace('/^'.preg_quote($sqlfields, '/').'/', 'SELECT COUNT(*) as nbtotalofrecords', $sql); $sqlforcount = preg_replace('/GROUP BY .*$/', '', $sqlforcount); + $resql = $db->query($sqlforcount); if ($resql) { $objforcount = $db->fetch_object($resql); diff --git a/htdocs/compta/index.php b/htdocs/compta/index.php index ec46ef0af3c..14aa6143769 100644 --- a/htdocs/compta/index.php +++ b/htdocs/compta/index.php @@ -67,7 +67,7 @@ if ($user->socid > 0) { $socid = $user->socid; } -$max = $conf->global->MAIN_SIZE_SHORTLIST_LIMIT; +$max = getDolGlobalInt('MAIN_SIZE_SHORTLIST_LIMIT'); // Maximum elements of the tables $maxDraftCount = !getDolGlobalString('MAIN_MAXLIST_OVERLOAD') ? 500 : $conf->global->MAIN_MAXLIST_OVERLOAD; diff --git a/htdocs/compta/journal/purchasesjournal.php b/htdocs/compta/journal/purchasesjournal.php index 49925556725..09e52081228 100644 --- a/htdocs/compta/journal/purchasesjournal.php +++ b/htdocs/compta/journal/purchasesjournal.php @@ -75,7 +75,8 @@ llxHeader('', $langs->trans("PurchasesJournal"), '', '', 0, 0, '', '', $morequer $form = new Form($db); $year_current = dol_print_date(dol_now('gmt'), "%Y", 'gmt'); -$pastmonth = strftime("%m", dol_now()) - 1; +//$pastmonth = strftime("%m", dol_now()) - 1; +$pastmonth = dol_print_date(dol_now(), "%m") - 1; $pastmonthyear = $year_current; if ($pastmonth == 0) { $pastmonth = 12; diff --git a/htdocs/compta/journal/sellsjournal.php b/htdocs/compta/journal/sellsjournal.php index 6f76ebfcedb..0ecdf3b2f0c 100644 --- a/htdocs/compta/journal/sellsjournal.php +++ b/htdocs/compta/journal/sellsjournal.php @@ -79,7 +79,8 @@ llxHeader('', $langs->trans("SellsJournal"), '', '', 0, 0, '', '', $morequery); $year_current = dol_print_date(dol_now('gmt'), "%Y", 'gmt'); -$pastmonth = strftime("%m", dol_now()) - 1; +//$pastmonth = strftime("%m", dol_now()) - 1; +$pastmonth = dol_print_date(dol_now(), "%m") - 1; $pastmonthyear = $year_current; if ($pastmonth == 0) { $pastmonth = 12; diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index 32e05251fde..ae2a97958b7 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -141,7 +141,7 @@ if (empty($reshook)) { } elseif (substr($key, 0, 21) == 'multicurrency_amount_') { $cursorfacid = substr($key, 21); $multicurrency_amounts[$cursorfacid] = price2num(GETPOST($key)); - $multicurrency_totalpayment += floatval($multicurrency_amounts[$cursorfacid]); + $multicurrency_totalpayment += (float) $multicurrency_amounts[$cursorfacid]; if (!empty($multicurrency_amounts[$cursorfacid])) { $atleastonepaymentnotnull++; } @@ -301,7 +301,7 @@ if (empty($reshook)) { $invoiceid = 0; foreach ($paiement->amounts as $key => $amount) { $facid = $key; - if (is_numeric($amount) && $amount <> 0) { + if (is_numeric($amount) && $amount != 0) { if ($invoiceid != 0) { $invoiceid = -1; // There is more than one invoice payed by this payment } else { diff --git a/htdocs/compta/paiement/card.php b/htdocs/compta/paiement/card.php index adb1e38af89..63a47618cd7 100644 --- a/htdocs/compta/paiement/card.php +++ b/htdocs/compta/paiement/card.php @@ -308,7 +308,7 @@ print $form->editfieldval("Date", 'datep', $object->date, $object, $user->hasRig print ''; // Payment type (VIR, LIQ, ...) -$labeltype = $langs->trans("PaymentType".$object->type_code) != ("PaymentType".$object->type_code) ? $langs->trans("PaymentType".$object->type_code) : $object->type_label; +$labeltype = $langs->trans("PaymentType".$object->type_code) != "PaymentType".$object->type_code ? $langs->trans("PaymentType".$object->type_code) : $object->type_label; print ''; diff --git a/htdocs/compta/paiement/cheque/class/remisecheque.class.php b/htdocs/compta/paiement/cheque/class/remisecheque.class.php index 562d9da587f..e9ea56f19ed 100644 --- a/htdocs/compta/paiement/cheque/class/remisecheque.class.php +++ b/htdocs/compta/paiement/cheque/class/remisecheque.class.php @@ -258,7 +258,7 @@ class RemiseCheque extends CommonObject } if ($this->id > 0 && $this->errno == 0) { - if ($this->updateAmount() <> 0) { + if ($this->updateAmount() != 0) { $this->errno = -1027; dol_syslog("RemiseCheque::Create Error update amount ".$this->errno, LOG_ERR); } @@ -291,7 +291,7 @@ class RemiseCheque extends CommonObject * @param User $user User that delete * @return int */ - public function delete($user = '') + public function delete($user = null) { global $conf; @@ -307,7 +307,7 @@ class RemiseCheque extends CommonObject if ($resql) { $num = $this->db->affected_rows($resql); - if ($num <> 1) { + if ($num != 1) { $this->errno = -2; dol_syslog("Remisecheque::Delete Erreur Lecture ID ($this->errno)"); } diff --git a/htdocs/compta/paiement/class/paiement.class.php b/htdocs/compta/paiement/class/paiement.class.php index ffb3f5083b8..b35b091f315 100644 --- a/htdocs/compta/paiement/class/paiement.class.php +++ b/htdocs/compta/paiement/class/paiement.class.php @@ -178,7 +178,7 @@ class Paiement extends CommonObject * @param int $fk_bank Id of bank line associated to payment * @return int Return integer <0 if KO, 0 if not found, >0 if OK */ - public function fetch($id, $ref = '', $fk_bank = '') + public function fetch($id, $ref = '', $fk_bank = 0) { $sql = 'SELECT p.rowid, p.ref, p.ref_ext, p.datep as dp, p.amount, p.statut, p.ext_payment_id, p.ext_payment_site, p.fk_bank, p.multicurrency_amount,'; $sql .= ' c.code as type_code, c.libelle as type_label,'; @@ -362,7 +362,7 @@ class Paiement extends CommonObject // Insert links amount / invoices foreach ($this->amounts as $key => $amount) { $facid = $key; - if (is_numeric($amount) && $amount <> 0) { + if (is_numeric($amount) && $amount != 0) { $amount = price2num($amount); $sql = "INSERT INTO ".MAIN_DB_PREFIX."paiement_facture (fk_facture, fk_paiement, amount, multicurrency_amount, multicurrency_code, multicurrency_tx)"; $sql .= " VALUES (".((int) $facid).", ".((int) $this->id).", ".((float) $amount).", ".((float) $this->multicurrency_amounts[$key]).", ".($currencyofpayment ? "'".$this->db->escape($currencyofpayment)."'" : 'NULL').", ".(!empty($this->multicurrency_tx) ? (float) $currencytxofpayment : 1).")"; diff --git a/htdocs/compta/paiement_vat.php b/htdocs/compta/paiement_vat.php index dfb25dd6c69..5984c9f2f04 100644 --- a/htdocs/compta/paiement_vat.php +++ b/htdocs/compta/paiement_vat.php @@ -273,7 +273,7 @@ if ($action == 'create') { print ''; print ''; print ''; diff --git a/htdocs/compta/resultat/index.php b/htdocs/compta/resultat/index.php index 059084dec0e..5f70269512d 100644 --- a/htdocs/compta/resultat/index.php +++ b/htdocs/compta/resultat/index.php @@ -1044,8 +1044,8 @@ for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++) { if ($mois > 12) { $annee_decalage = $annee + 1; } - $case = strftime("%Y-%m", dol_mktime(12, 0, 0, $mois_modulo, 1, $annee_decalage)); - + //$case = strftime("%Y-%m", dol_mktime(12, 0, 0, $mois_modulo, 1, $annee_decalage)); + $case = dol_print_date(dol_mktime(12, 0, 0, $mois_modulo, 1, $annee_decalage), "%Y-%m"); print ''; print '\n"; - $labeltype = $langs->trans("PaymentType".$objp->type_code) != ("PaymentType".$objp->type_code) ? $langs->trans("PaymentType".$objp->type_code) : $objp->paiement_type; + $labeltype = $langs->trans("PaymentType".$objp->type_code) != "PaymentType".$objp->type_code ? $langs->trans("PaymentType".$objp->type_code) : $objp->paiement_type; print "\n"; if (isModEnabled("banque")) { $bankaccountstatic->id = $objp->baid; diff --git a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php index 5b0782a6598..645f1d0c25f 100644 --- a/htdocs/compta/sociales/class/paymentsocialcontribution.class.php +++ b/htdocs/compta/sociales/class/paymentsocialcontribution.class.php @@ -229,7 +229,7 @@ class PaymentSocialContribution extends CommonObject // Insere tableau des montants / factures foreach ($this->amounts as $key => $amount) { $contribid = $key; - if (is_numeric($amount) && $amount <> 0) { + if (is_numeric($amount) && $amount != 0) { $amount = price2num($amount); // If we want to closed paid invoices diff --git a/htdocs/compta/stats/byratecountry.php b/htdocs/compta/stats/byratecountry.php index a8c5f88e435..dced36d44a6 100644 --- a/htdocs/compta/stats/byratecountry.php +++ b/htdocs/compta/stats/byratecountry.php @@ -374,9 +374,9 @@ if ($modecompta == 'CREANCES-DETTES') { $j -= 12; } $monthj = 'month'.str_pad($j, 2, '0', STR_PAD_LEFT); - print ''; + print ''; } - print ''; + print ''; print ''; } else { print $db->lasterror(); // Show last sql error diff --git a/htdocs/compta/stats/index.php b/htdocs/compta/stats/index.php index 9cafa6d2da0..835d8a999fe 100644 --- a/htdocs/compta/stats/index.php +++ b/htdocs/compta/stats/index.php @@ -377,7 +377,8 @@ $now_show_delta = 0; $minyear = substr($minyearmonth, 0, 4); $maxyear = substr($maxyearmonth, 0, 4); $nowyear = dol_print_date(dol_now('gmt'), "%Y", 'gmt'); -$nowyearmonth = strftime("%Y-%m", dol_now()); +$nowyearmonth = dol_print_date(dol_now(), "%Y%m"); +//$nowyearmonth = strftime("%Y-%m", dol_now()); $maxyearmonth = max($maxyearmonth, $nowyearmonth); $now = dol_now(); $casenow = dol_print_date($now, "%Y-%m"); @@ -419,7 +420,7 @@ for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++) { // Value turnover of month w/o VAT print ''; print '\n"; - $labeltype = $langs->trans("PaymentType".$objp->type_code) != ("PaymentType".$objp->type_code) ? $langs->trans("PaymentType".$objp->type_code) : $objp->paiement_type; + $labeltype = $langs->trans("PaymentType".$objp->type_code) != "PaymentType".$objp->type_code ? $langs->trans("PaymentType".$objp->type_code) : $objp->paiement_type; print "\n"; if (isModEnabled("banque")) { $bankaccountstatic->id = $objp->baid; diff --git a/htdocs/compta/tva/class/paymentvat.class.php b/htdocs/compta/tva/class/paymentvat.class.php index 3d0d51bebf8..713cc9a6ed0 100644 --- a/htdocs/compta/tva/class/paymentvat.class.php +++ b/htdocs/compta/tva/class/paymentvat.class.php @@ -233,7 +233,7 @@ class PaymentVAT extends CommonObject // Insert table of amounts / invoices foreach ($this->amounts as $key => $amount) { $contribid = $key; - if (is_numeric($amount) && $amount <> 0) { + if (is_numeric($amount) && $amount != 0) { $amount = price2num($amount); // If we want to closed paid invoices diff --git a/htdocs/compta/tva/class/tva.class.php b/htdocs/compta/tva/class/tva.class.php index e160abfc3b8..8eac0e00140 100644 --- a/htdocs/compta/tva/class/tva.class.php +++ b/htdocs/compta/tva/class/tva.class.php @@ -891,18 +891,18 @@ class Tva extends CommonObject //$langs->load("mymodule"); $this->labelStatus[self::STATUS_UNPAID] = $langs->transnoentitiesnoconv('BillStatusNotPaid'); $this->labelStatus[self::STATUS_PAID] = $langs->transnoentitiesnoconv('BillStatusPaid'); - if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) { + if ($status == self::STATUS_UNPAID && $alreadypaid != 0) { $this->labelStatus[self::STATUS_UNPAID] = $langs->transnoentitiesnoconv("BillStatusStarted"); } $this->labelStatusShort[self::STATUS_UNPAID] = $langs->transnoentitiesnoconv('BillStatusNotPaid'); $this->labelStatusShort[self::STATUS_PAID] = $langs->transnoentitiesnoconv('BillStatusPaid'); - if ($status == self::STATUS_UNPAID && $alreadypaid <> 0) { + if ($status == self::STATUS_UNPAID && $alreadypaid != 0) { $this->labelStatusShort[self::STATUS_UNPAID] = $langs->transnoentitiesnoconv("BillStatusStarted"); } } $statusType = 'status1'; - if ($status == 0 && $alreadypaid <> 0) { + if ($status == 0 && $alreadypaid != 0) { $statusType = 'status3'; } if ($status == 1) { diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 0a1877d49b6..028ad27c755 100644 --- a/htdocs/contact/class/contact.class.php +++ b/htdocs/contact/class/contact.class.php @@ -99,7 +99,7 @@ class Contact extends CommonObject * @var array Array with all fields and their property. Do not use it as a static var. It may be modified by constructor. */ public $fields = array( - 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-1, 'notnull'=>1, 'position'=>10), + 'rowid' =>array('type'=>'integer', 'label'=>'TechnicalID', 'enabled'=>1, 'visible'=>-2, 'noteditable'=>1, 'notnull'=> 1, 'index'=>1, 'position'=>1, 'comment'=>'Id', 'css'=>'left'), 'entity' =>array('type'=>'integer', 'label'=>'Entity', 'default'=>1, 'enabled'=>1, 'visible'=>3, 'notnull'=>1, 'position'=>30, 'index'=>1), 'ref_ext' =>array('type'=>'varchar(255)', 'label'=>'Ref ext', 'enabled'=>1, 'visible'=>3, 'position'=>35), 'civility' =>array('type'=>'varchar(6)', 'label'=>'Civility', 'enabled'=>1, 'visible'=>3, 'position'=>40), @@ -356,14 +356,9 @@ class Contact extends CommonObject */ public function __construct($db) { - global $conf, $langs; - $this->db = $db; $this->statut = 1; // By default, status is enabled - if (!getDolGlobalString('MAIN_SHOW_TECHNICAL_ID')) { - $this->fields['rowid']['visible'] = 0; - } if (!isModEnabled('mailing')) { $this->fields['no_email']['enabled'] = 0; } @@ -573,7 +568,7 @@ class Contact extends CommonObject */ public function update($id, $user = null, $notrigger = 0, $action = 'update', $nosyncuser = 0) { - global $conf, $langs, $hookmanager; + global $conf; $error = 0; @@ -601,6 +596,7 @@ class Contact extends CommonObject $this->civility_code = $this->civility_id; // For backward compatibility } $this->setUpperOrLowerCase(); + $this->db->begin(); $sql = "UPDATE ".MAIN_DB_PREFIX."socpeople SET"; @@ -1032,7 +1028,7 @@ class Contact extends CommonObject $this->ref_ext = $obj->ref_ext; $this->civility_code = $obj->civility_code; - $this->civility = $obj->civility_code ? ($langs->trans("Civility".$obj->civility_code) != ("Civility".$obj->civility_code) ? $langs->trans("Civility".$obj->civility_code) : $obj->civility_code) : ''; + $this->civility = $obj->civility_code ? ($langs->trans("Civility".$obj->civility_code) != "Civility".$obj->civility_code ? $langs->trans("Civility".$obj->civility_code) : $obj->civility_code) : ''; $this->lastname = $obj->lastname; $this->firstname = $obj->firstname; @@ -2169,7 +2165,7 @@ class Contact extends CommonObject } $return .= ''; $return .= '
    '; - $return .= '
    '.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'
    '; + $return .= '
    '.(method_exists($this, 'getNomUrl') ? $this->getNomUrl(1) : $this->ref).'
    '; if ($selected >= 0) { $return .= ''; } @@ -2185,7 +2181,7 @@ class Contact extends CommonObject $return .= ' : '.$this->LibPubPriv($this->priv).''; }*/ if (method_exists($this, 'getLibStatut')) { - $return .= '
    '.$this->getLibStatut(3).'
    '; + $return .= '
    '.$this->getLibStatut(3).'
    '; } $return .= '
    '; $return .= ''; diff --git a/htdocs/contact/consumption.php b/htdocs/contact/consumption.php index b4cde56687f..23b30813bb7 100644 --- a/htdocs/contact/consumption.php +++ b/htdocs/contact/consumption.php @@ -206,7 +206,7 @@ if ($type_element == 'fichinter') { // Customer : show products from invoices $tables_from .= ' LEFT JOIN '.MAIN_DB_PREFIX.'fichinter as f ON d.fk_fichinter=f.rowid'; $tables_from .= ' INNER JOIN '.MAIN_DB_PREFIX.'element_contact ec ON ec.element_id=f.rowid AND ec.fk_socpeople = '.((int) $object->id); $tables_from .= ' INNER JOIN '.MAIN_DB_PREFIX."c_type_contact tc ON (ec.fk_c_type_contact=tc.rowid and tc.element='fichinter' and tc.source='external' and tc.active=1)"; - $where = ' WHERE f.entity IN ('.getEntity('ficheinter').')'; + $where = ' WHERE f.entity IN ('.getEntity('intervention').')'; $dateprint = 'f.datec'; $doc_number = 'f.ref'; } elseif ($type_element == 'invoice') { // Customer : show products from invoices diff --git a/htdocs/contact/list.php b/htdocs/contact/list.php index 8330a43f424..126b475a665 100644 --- a/htdocs/contact/list.php +++ b/htdocs/contact/list.php @@ -298,7 +298,7 @@ if ($action == "change" && $user->hasRight('takepos', 'run')) { // Change custom require_once DOL_DOCUMENT_ROOT.'/compta/facture/class/facture.class.php'; $invoice = new Facture($db); $constforthirdpartyid = 'CASHDESK_ID_THIRDPARTY'.$_SESSION["takeposterminal"]; - $invoice->socid = $conf->global->$constforthirdpartyid; + $invoice->socid = getDolGlobalInt($constforthirdpartyid); $invoice->date = dol_now(); $invoice->module_source = 'takepos'; $invoice->pos_source = $_SESSION["takeposterminal"]; @@ -594,7 +594,7 @@ if (!empty($searchCategoryCustomerList)) { } } - // Search Supplier Categories +// Search Supplier Categories $searchCategorySupplierList = $search_categ_supplier ? array($search_categ_supplier) : array(); $searchCategorySupplierOperator = 0; // Search for tag/category ($searchCategorySupplierList is an array of ID) @@ -748,6 +748,11 @@ $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $objec $sql .= $hookmanager->resPrint; //print $sql; +// Add GroupBy from hooks +$parameters = array('fieldstosearchall' => $fieldstosearchall); +$reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters, $object, $action); // Note that $action and $object may have been modified by hook +$sql .= $hookmanager->resPrint; + // Count total nb of records $nbtotalofrecords = ''; if (!getDolGlobalInt('MAIN_DISABLE_FULL_SCANLIST')) { @@ -798,7 +803,7 @@ if ($num == 1 && getDolGlobalString('MAIN_SEARCH_DIRECT_OPEN_IF_ONLY_ONE') && ($ // Output page // -------------------------------------------------------------------- -// Page Header + llxHeader('', $title, $help_url, '', 0, 0, $morejs, $morecss, '', 'bodyforlist'); $arrayofselected = is_array($toselect) ? $toselect : array(); @@ -813,6 +818,9 @@ if (!empty($contextpage) && $contextpage != $_SERVER["PHP_SELF"]) { if ($limit > 0 && $limit != $conf->liste_limit) { $param .= '&limit='.((int) $limit); } +if ($optioncss != '') { + $param .= '&optioncss='.urlencode($optioncss); +} $param .= '&begin='.urlencode($begin).'&userid='.urlencode($userid).'&contactname='.urlencode($search_all); $param .= '&type='.urlencode($type).'&view='.urlencode($view); if (!empty($search_categ) && $search_categ != '-1') { @@ -892,9 +900,6 @@ if (is_array($search_level) && count($search_level)) { if ($search_import_key != '') { $param .= '&search_import_key='.urlencode($search_import_key); } -if ($optioncss != '') { - $param .= '&optioncss='.urlencode($optioncss); -} if (count($search_roles) > 0) { $param .= implode('&search_roles[]=', $search_roles); } @@ -953,6 +958,7 @@ if ($contextpage != 'poslist') { $label = 'MenuNewCustomer'; $newcardbutton .= dolGetButtonTitle($langs->trans($label), '', 'fa fa-plus-circle', $url); } + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, 'address', 0, $newcardbutton, '', $limit, 0, 0, 1); $topicmail = "Information"; @@ -1020,7 +1026,7 @@ print ''; $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; $selectedfields = $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN', '')); // This also change content of $arrayfields -$selectedfields .= count($arrayofmassactions) && $contextpage != 'poslist' ? $form->showCheckAddButtons('checkforselect', 1) : ''; +$selectedfields .= ((count($arrayofmassactions) && $contextpage != 'poslist') ? $form->showCheckAddButtons('checkforselect', 1) : ''); print '
    '; print '
    '.$langs->trans("Account").''.$langs->trans("Label").''; @@ -350,7 +350,7 @@ print ''.$langs->trans("Total").'
    '; if ($row[0] == 'tobind') { - $startmonth = ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1); + $startmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); if ($startmonth > 12) { $startmonth -= 12; } - $startyear = ($startmonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; - $endmonth = ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) + 11; + $startyear = ($startmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; + $endmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) + 11; if ($endmonth > 12) { $endmonth -= 12; } - $endyear = ($endmonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $endyear = ($endmonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; print $langs->trans("UseMenuToSetBindindManualy", DOL_URL_ROOT.'/accountancy/supplier/list.php?search_date_startday=1&search_date_startmonth='.((int) $startmonth).'&search_date_startyear='.((int) $startyear).'&search_date_endday=&search_date_endmonth='.((int) $endmonth).'&search_date_endyear='.((int) $endyear), $langs->transnoentitiesnoconv("ToBind")); } else { print $row[1]; } print ''; @@ -454,7 +454,7 @@ print ''; print ''; print ''; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -462,7 +462,7 @@ for ($i = 1; $i <= 12; $i++) { if ($cursormonth > 12) { $cursormonth -= 12; } - $cursoryear = ($cursormonth < ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1)) ? $y + 1 : $y; + $cursoryear = ($cursormonth < getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1)) ? $y + 1 : $y; $tmp = dol_getdate(dol_get_last_day($cursoryear, $cursormonth, 'gmt'), false, 'gmt'); print '' $sql = "SELECT ".$db->ifsql('aa.account_number IS NULL', "'tobind'", 'aa.account_number')." AS codecomptable,"; $sql .= " ".$db->ifsql('aa.label IS NULL', "'tobind'", 'aa.label')." AS intitule,"; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -496,7 +496,7 @@ $sql .= " WHERE ff.datef >= '".$db->idate($search_date_start)."'"; $sql .= " AND ff.datef <= '".$db->idate($search_date_end)."'"; // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND ff.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND ff.datef >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } $sql .= " AND ff.entity IN (".getEntity('facture_fourn', 0).")"; // We don't share object for accountancy $sql .= " AND ff.fk_statut > 0"; @@ -566,7 +566,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa print '
    '.$langs->trans("Account").''.$langs->trans("Label").''; @@ -482,7 +482,7 @@ print ''.$langs->trans("Total").'
    '; print ''; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -576,7 +576,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa $sql = "SELECT '".$db->escape($langs->trans("CAHTF"))."' AS label,"; for ($i = 1; $i <= 12; $i++) { - $j = $i + ($conf->global->SOCIETE_FISCAL_MONTH_START ? $conf->global->SOCIETE_FISCAL_MONTH_START : 1) - 1; + $j = $i + getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1) - 1; if ($j > 12) { $j -= 12; } @@ -589,7 +589,7 @@ if (getDolGlobalString('SHOW_TOTAL_OF_PREVIOUS_LISTS_IN_LIN_PAGE')) { // This pa $sql .= " AND ff.datef <= '".$db->idate($search_date_end)."'"; // Define begin binding date if (getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $sql .= " AND ff.datef >= '".$db->idate($conf->global->ACCOUNTING_DATE_START_BINDING)."'"; + $sql .= " AND ff.datef >= '".$db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING'))."'"; } $sql .= " AND ff.entity IN (".getEntity('facture_fourn', 0).")"; // We don't share object for accountancy $sql .= " AND ff.fk_statut > 0"; diff --git a/htdocs/accountancy/supplier/lines.php b/htdocs/accountancy/supplier/lines.php index ac35e048744..480c18f1c25 100644 --- a/htdocs/accountancy/supplier/lines.php +++ b/htdocs/accountancy/supplier/lines.php @@ -67,7 +67,7 @@ $search_country = GETPOST('search_country', 'alpha'); $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); // Load variable for pagination -$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : (!getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION') ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION', $conf->liste_limit); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); @@ -536,7 +536,7 @@ if ($result) { print ''; diff --git a/htdocs/accountancy/supplier/list.php b/htdocs/accountancy/supplier/list.php index 6573f18503f..17f87eec351 100644 --- a/htdocs/accountancy/supplier/list.php +++ b/htdocs/accountancy/supplier/list.php @@ -77,7 +77,7 @@ $search_country = GETPOST('search_country', 'alpha'); $search_tvaintra = GETPOST('search_tvaintra', 'alpha'); // Load variable for pagination -$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : (!getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION') ? $conf->liste_limit : $conf->global->ACCOUNTING_LIMIT_LIST_VENTILATION); +$limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : getDolGlobalString('ACCOUNTING_LIMIT_LIST_VENTILATION', $conf->liste_limit); $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); $page = GETPOSTISSET('pageplusone') ? (GETPOST('pageplusone') - 1) : GETPOST("page", 'int'); @@ -119,7 +119,7 @@ if (!$user->hasRight('accounting', 'mouvements', 'lire')) { // Define begin binding date if (empty($search_date_start) && getDolGlobalString('ACCOUNTING_DATE_START_BINDING')) { - $search_date_start = $db->idate($conf->global->ACCOUNTING_DATE_START_BINDING); + $search_date_start = $db->idate(getDolGlobalString('ACCOUNTING_DATE_START_BINDING')); } @@ -687,7 +687,7 @@ if ($result) { // Description of line print ''; diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index 51af75d9591..a3bc6ce2ade 100644 --- a/htdocs/adherents/class/adherent.class.php +++ b/htdocs/adherents/class/adherent.class.php @@ -280,35 +280,35 @@ class Adherent extends CommonObject */ public $fields = array( 'rowid' => array('type' => 'integer', 'label' => 'TechnicalID', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 10), - 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'default' => 1, 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 12, 'index' => 1), + 'ref' => array('type' => 'varchar(30)', 'label' => 'Ref', 'default' => 1, 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 12, 'index' => 1), 'entity' => array('type' => 'integer', 'label' => 'Entity', 'default' => 1, 'enabled' => 1, 'visible' => -2, 'notnull' => 1, 'position' => 15, 'index' => 1), 'ref_ext' => array('type' => 'varchar(128)', 'label' => 'Ref ext', 'enabled' => 1, 'visible' => 0, 'position' => 20), 'civility' => array('type' => 'varchar(6)', 'label' => 'Civility', 'enabled' => 1, 'visible' => -1, 'position' => 25), - 'lastname' => array('type' => 'varchar(50)', 'label' => 'Lastname', 'enabled' => 1, 'visible' => -1, 'position' => 30, 'showoncombobox'=>1), - 'firstname' => array('type' => 'varchar(50)', 'label' => 'Firstname', 'enabled' => 1, 'visible' => -1, 'position' => 35, 'showoncombobox'=>1), - 'login' => array('type' => 'varchar(50)', 'label' => 'Login', 'enabled' => 1, 'visible' => -1, 'position' => 40), - 'gender' => array('type' => 'varchar(10)', 'label' => 'Gender', 'enabled' => 1, 'visible' => -1, 'position' => 250), + 'lastname' => array('type' => 'varchar(50)', 'label' => 'Lastname', 'enabled' => 1, 'visible' => 1, 'position' => 30, 'showoncombobox'=>1), + 'firstname' => array('type' => 'varchar(50)', 'label' => 'Firstname', 'enabled' => 1, 'visible' => 1, 'position' => 35, 'showoncombobox'=>1), + 'login' => array('type' => 'varchar(50)', 'label' => 'Login', 'enabled' => 1, 'visible' => 1, 'position' => 40), 'pass' => array('type' => 'varchar(50)', 'label' => 'Pass', 'enabled' => 1, 'visible' => -1, 'position' => 45), 'pass_crypted' => array('type' => 'varchar(128)', 'label' => 'Pass crypted', 'enabled' => 1, 'visible' => -1, 'position' => 50), - 'fk_adherent_type' => array('type' => 'integer', 'label' => 'Fk adherent type', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 55), - 'morphy' => array('type' => 'varchar(3)', 'label' => 'MorPhy', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 60), - 'societe' => array('type' => 'varchar(128)', 'label' => 'Societe', 'enabled' => 1, 'visible' => -1, 'position' => 65, 'showoncombobox'=>2), - 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 1, 'visible' => -1, 'position' => 70), + 'morphy' => array('type' => 'varchar(3)', 'label' => 'MemberNature', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 55), + 'fk_adherent_type' => array('type' => 'integer', 'label' => 'Fk adherent type', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 60), + 'societe' => array('type' => 'varchar(128)', 'label' => 'Societe', 'enabled' => 1, 'visible' => 1, 'position' => 65, 'showoncombobox'=>2), + 'fk_soc' => array('type' => 'integer:Societe:societe/class/societe.class.php', 'label' => 'ThirdParty', 'enabled' => 1, 'visible' => 1, 'position' => 70), 'address' => array('type' => 'text', 'label' => 'Address', 'enabled' => 1, 'visible' => -1, 'position' => 75), 'zip' => array('type' => 'varchar(10)', 'label' => 'Zip', 'enabled' => 1, 'visible' => -1, 'position' => 80), 'town' => array('type' => 'varchar(50)', 'label' => 'Town', 'enabled' => 1, 'visible' => -1, 'position' => 85), 'state_id' => array('type' => 'integer', 'label' => 'State id', 'enabled' => 1, 'visible' => -1, 'position' => 90), - 'country' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => -1, 'position' => 95), - 'email' => array('type' => 'varchar(255)', 'label' => 'Email', 'enabled' => 1, 'visible' => -1, 'position' => 100), - 'url' =>array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>110), - 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 105), + 'country' => array('type' => 'integer:Ccountry:core/class/ccountry.class.php', 'label' => 'Country', 'enabled' => 1, 'visible' => 1, 'position' => 95), 'phone' => array('type' => 'varchar(30)', 'label' => 'Phone', 'enabled' => 1, 'visible' => -1, 'position' => 115), 'phone_perso' => array('type' => 'varchar(30)', 'label' => 'Phone perso', 'enabled' => 1, 'visible' => -1, 'position' => 120), 'phone_mobile' => array('type' => 'varchar(30)', 'label' => 'Phone mobile', 'enabled' => 1, 'visible' => -1, 'position' => 125), + 'email' => array('type' => 'varchar(255)', 'label' => 'Email', 'enabled' => 1, 'visible' => 1, 'position' => 126), + 'url' =>array('type'=>'varchar(255)', 'label'=>'Url', 'enabled'=>1, 'visible'=>-1, 'position'=>127), + 'socialnetworks' => array('type' => 'text', 'label' => 'Socialnetworks', 'enabled' => 1, 'visible' => -1, 'position' => 128), 'birth' => array('type' => 'date', 'label' => 'DateOfBirth', 'enabled' => 1, 'visible' => -1, 'position' => 130), + 'gender' => array('type' => 'varchar(10)', 'label' => 'Gender', 'enabled' => 1, 'visible' => -1, 'position' => 132), 'photo' => array('type' => 'varchar(255)', 'label' => 'Photo', 'enabled' => 1, 'visible' => -1, 'position' => 135), 'public' => array('type' => 'smallint(6)', 'label' => 'Public', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 145), - 'datefin' => array('type' => 'datetime', 'label' => 'DateEnd', 'enabled' => 1, 'visible' => -1, 'position' => 150), + 'datefin' => array('type' => 'datetime', 'label' => 'DateEnd', 'enabled' => 1, 'visible' => 1, 'position' => 150), 'default_lang' =>array('type'=>'varchar(6)', 'label'=>'Default lang', 'enabled'=>1, 'visible'=>-1, 'position'=> 153), 'note_public' => array('type' => 'text', 'label' => 'NotePublic', 'enabled' => 1, 'visible' => 0, 'position' => 155), 'note_private' => array('type' => 'text', 'label' => 'NotePrivate', 'enabled' => 1, 'visible' => 0, 'position' => 160), @@ -319,8 +319,7 @@ class Adherent extends CommonObject 'fk_user_mod' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'Fk user mod', 'enabled' => 1, 'visible' => -1, 'position' => 185), 'fk_user_valid' => array('type' => 'integer:User:user/class/user.class.php', 'label' => 'UserValidation', 'enabled' => 1, 'visible' => -1, 'position' => 190), 'canvas' => array('type' => 'varchar(32)', 'label' => 'Canvas', 'enabled' => 1, 'visible' => -1, 'position' => 195), - 'statut' => array('type' => 'smallint(6)', 'label' => 'Statut', 'enabled' => 1, 'visible' => -1, 'notnull' => 1, 'position' => 500, - 'arrayofkeyval' => array(-1 => 'Draft', 1 => 'Validated', 0 => 'MemberStatusResiliatedShort', -2 => 'MemberStatusExcludedShort')), + 'statut' => array('type' => 'smallint(6)', 'label' => 'Statut', 'enabled' => 1, 'visible' => 1, 'notnull' => 1, 'position' => 500, 'arrayofkeyval' => array(-1 => 'Draft', 1 => 'Validated', 0 => 'MemberStatusResiliatedShort', -2 => 'MemberStatusExcludedShort')), 'model_pdf' => array('type' => 'varchar(255)', 'label' => 'Model pdf', 'enabled' => 1, 'visible' => 0, 'position' => 800), 'import_key' => array('type' => 'varchar(14)', 'label' => 'ImportId', 'enabled' => 1, 'visible' => -2, 'position' => 805) ); @@ -352,7 +351,7 @@ class Adherent extends CommonObject { $this->db = $db; $this->statut = self::STATUS_DRAFT; - $this->status = $this->statut; + $this->status = self::STATUS_DRAFT; // l'adherent n'est pas public par defaut $this->public = 0; // les champs optionnels sont vides @@ -416,7 +415,7 @@ class Adherent extends CommonObject } } - dol_syslog('send_an_email msgishtml='.$msgishtml); + dol_syslog('sendEmail msgishtml='.$msgishtml); $texttosend = $this->makeSubstitution($text); $subjecttosend = $this->makeSubstitution($subject); @@ -708,7 +707,7 @@ class Adherent extends CommonObject */ public function update($user, $notrigger = 0, $nosyncuser = 0, $nosyncuserpass = 0, $nosyncthirdparty = 0, $action = 'update') { - global $conf, $langs, $hookmanager; + global $langs, $hookmanager; require_once DOL_DOCUMENT_ROOT.'/core/lib/functions2.lib.php'; @@ -1361,7 +1360,7 @@ class Adherent extends CommonObject * @param bool $fetch_subscriptions To load member subscriptions * @return int >0 if OK, 0 if not found, <0 if KO */ - public function fetch($rowid, $ref = '', $fk_soc = '', $ref_ext = '', $fetch_optionals = true, $fetch_subscriptions = true) + public function fetch($rowid, $ref = '', $fk_soc = 0, $ref_ext = '', $fetch_optionals = true, $fetch_subscriptions = true) { global $langs; @@ -1413,7 +1412,7 @@ class Adherent extends CommonObject $this->civility_id = $obj->civility_code; // Bad. Kept for backard compatibility $this->civility_code = $obj->civility_code; - $this->civility = $obj->civility_code ? ($langs->trans("Civility".$obj->civility_code) != ("Civility".$obj->civility_code) ? $langs->trans("Civility".$obj->civility_code) : $obj->civility_code) : ''; + $this->civility = $obj->civility_code ? ($langs->trans("Civility".$obj->civility_code) != "Civility".$obj->civility_code ? $langs->trans("Civility".$obj->civility_code) : $obj->civility_code) : ''; $this->firstname = $obj->firstname; $this->lastname = $obj->lastname; @@ -1679,7 +1678,7 @@ class Adherent extends CommonObject * @param string $num_chq Numero cheque (if Id bank account provided) * @param string $emetteur_nom Name of cheque writer * @param string $emetteur_banque Name of bank of cheque - * @param string $autocreatethirdparty Auto create new thirdparty if member not yet linked to a thirdparty and we request an option that generate invoice. + * @param int $autocreatethirdparty Auto create new thirdparty if member not yet linked to a thirdparty and we request an option that generate invoice. * @param string $ext_payment_id External id of payment (for example Stripe charge id) * @param string $ext_payment_site Name of external paymentmode (for example 'stripe') * @return int Return integer <0 if KO, >0 if OK @@ -2045,8 +2044,6 @@ class Adherent extends CommonObject */ public function exclude($user) { - global $langs, $conf; - $error = 0; // Check parameters @@ -2093,7 +2090,7 @@ class Adherent extends CommonObject public function add_to_abo() { // phpcs:enable - global $conf, $langs; + global $langs; include_once DOL_DOCUMENT_ROOT.'/mailmanspip/class/mailmanspip.class.php'; $mailmanspip = new MailmanSpip($this->db); @@ -3260,7 +3257,7 @@ class Adherent extends CommonObject $return .= '
    '.$this->getmorphylib('', 2).''; } if (method_exists($this, 'getLibStatut')) { - $return .= '
    '.$this->getLibStatut(3).'
    '; + $return .= '
    '.$this->getLibStatut(3).'
    '; } $return .= ''; $return .= ''; diff --git a/htdocs/adherents/class/adherent_type.class.php b/htdocs/adherents/class/adherent_type.class.php index 4832a4242e7..19fdae122eb 100644 --- a/htdocs/adherents/class/adherent_type.class.php +++ b/htdocs/adherents/class/adherent_type.class.php @@ -1025,7 +1025,7 @@ class AdherentType extends CommonObject } } if (method_exists($this, 'getLibStatut')) { - $return .= '
    '.$this->getLibStatut(3).'
    '; + $return .= '
    '.$this->getLibStatut(3).'
    '; } $return .= ''; $return .= ''; diff --git a/htdocs/adherents/class/adherentstats.class.php b/htdocs/adherents/class/adherentstats.class.php index 8ae8c77146c..b2644ec7c19 100644 --- a/htdocs/adherents/class/adherentstats.class.php +++ b/htdocs/adherents/class/adherentstats.class.php @@ -231,7 +231,7 @@ class AdherentStats extends Stats ); $totalrow = 0; foreach ($MembersCountArray[$objp->fk_adherent_type] as $key=>$nb) { - if ($key!='label') { + if ($key != 'label') { $totalrow += $nb; $totalstatus[$key] += $nb; } @@ -311,7 +311,7 @@ class AdherentStats extends Stats ); $totalrow = 0; foreach ($MembersCountArray[$objp->fk_categorie] as $key=>$nb) { - if ($key!='label') { + if ($key != 'label') { $totalrow += $nb; $totalstatus[$key] += $nb; } diff --git a/htdocs/adherents/class/api_members.class.php b/htdocs/adherents/class/api_members.class.php index 4de525281b1..435f6a7e24e 100644 --- a/htdocs/adherents/class/api_members.class.php +++ b/htdocs/adherents/class/api_members.class.php @@ -271,9 +271,6 @@ class Members extends DolibarrApi } else { throw new RestException(503, 'Error when retrieve member list : '.$this->db->lasterror()); } - if (!count($obj_ret)) { - throw new RestException(404, 'No member found'); - } return $obj_ret; } @@ -543,10 +540,6 @@ class Members extends DolibarrApi $result = $categories->getListForItem($id, 'member', $sortfield, $sortorder, $limit, $page); - if (empty($result)) { - throw new RestException(404, 'No category found'); - } - if ($result < 0) { throw new RestException(503, 'Error when retrieve category list : '.$categories->error); } diff --git a/htdocs/adherents/class/api_memberstypes.class.php b/htdocs/adherents/class/api_memberstypes.class.php index 5f1a1aec7b6..302270d5c5f 100644 --- a/htdocs/adherents/class/api_memberstypes.class.php +++ b/htdocs/adherents/class/api_memberstypes.class.php @@ -136,9 +136,6 @@ class MembersTypes extends DolibarrApi } else { throw new RestException(503, 'Error when retrieve member type list : '.$this->db->lasterror()); } - if (!count($obj_ret)) { - throw new RestException(404, 'No member type found'); - } return $obj_ret; } diff --git a/htdocs/adherents/class/api_subscriptions.class.php b/htdocs/adherents/class/api_subscriptions.class.php index 9c051ac6a41..77c7a8b933a 100644 --- a/htdocs/adherents/class/api_subscriptions.class.php +++ b/htdocs/adherents/class/api_subscriptions.class.php @@ -133,9 +133,6 @@ class Subscriptions extends DolibarrApi } else { throw new RestException(503, 'Error when retrieve subscription list : '.$this->db->lasterror()); } - if (!count($obj_ret)) { - throw new RestException(404, 'No Subscription found'); - } return $obj_ret; } diff --git a/htdocs/adherents/list.php b/htdocs/adherents/list.php index db1b89a49ab..018b023a837 100644 --- a/htdocs/adherents/list.php +++ b/htdocs/adherents/list.php @@ -150,32 +150,57 @@ $arrayfields = array( 'd.lastname'=>array('label'=>"Lastname", 'checked'=>1), 'd.firstname'=>array('label'=>"Firstname", 'checked'=>1), 'd.gender'=>array('label'=>"Gender", 'checked'=>0), - 'd.company'=>array('label'=>"Company", 'checked'=>1), + 'd.company'=>array('label'=>"Company", 'checked'=>1, 'position'=>70), 'd.login'=>array('label'=>"Login", 'checked'=>1), 'd.morphy'=>array('label'=>"MemberNature", 'checked'=>1), - 't.libelle'=>array('label'=>"Type", 'checked'=>1), - 'd.email'=>array('label'=>"Email", 'checked'=>1), + 't.libelle'=>array('label'=>"Type", 'checked'=>1, 'position'=>55), 'd.address'=>array('label'=>"Address", 'checked'=>0), 'd.zip'=>array('label'=>"Zip", 'checked'=>0), 'd.town'=>array('label'=>"Town", 'checked'=>0), 'd.phone'=>array('label'=>"Phone", 'checked'=>0), 'd.phone_perso'=>array('label'=>"PhonePerso", 'checked'=>0), 'd.phone_mobile'=>array('label'=>"PhoneMobile", 'checked'=>0), - 'state.nom'=>array('label'=>"State", 'checked'=>0), - 'country.code_iso'=>array('label'=>"Country", 'checked'=>0), + 'd.email'=>array('label'=>"Email", 'checked'=>1), + 'state.nom'=>array('label'=>"State", 'checked'=>0, 'position'=>90), + 'country.code_iso'=>array('label'=>"Country", 'checked'=>0, 'position'=>95), /*'d.note_public'=>array('label'=>"NotePublic", 'checked'=>0), 'd.note_private'=>array('label'=>"NotePrivate", 'checked'=>0),*/ - 'd.datefin'=>array('label'=>"EndSubscription", 'checked'=>1, 'position'=>500), - 'd.datec'=>array('label'=>"DateCreation", 'checked'=>0, 'position'=>500), - 'd.birth'=>array('label'=>"Birthday", 'checked'=>0, 'position'=>500), - 'd.tms'=>array('label'=>"DateModificationShort", 'checked'=>0, 'position'=>500), - 'd.statut'=>array('label'=>"Status", 'checked'=>1, 'position'=>1000), - 'd.import_key'=>array('label'=>"ImportId", 'checked'=>0, 'position'=>1100), + 'd.datefin'=>array('label'=>"EndSubscription"), + 'd.datec'=>array('label'=>"DateCreation"), + 'd.birth'=>array('label'=>"Birthday"), + 'd.tms'=>array('label'=>"DateModificationShort"), + 'd.statut'=>array('label'=>"Status"), + 'd.import_key'=>array('label'=>"ImportId"), ); // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_array_fields.tpl.php'; +$object->fields = dol_sort_array($object->fields, 'position'); +//$arrayfields['anotherfield'] = array('type'=>'integer', 'label'=>'AnotherField', 'checked'=>1, 'enabled'=>1, 'position'=>90, 'csslist'=>'right'); + +// Complete array of fields for columns +$tableprefix = 'd'; +foreach ($object->fields as $key => $val) { + if (!array_key_exists($tableprefix.'.'.$key, $arrayfields)) { // Discard record not into $arrayfields + continue; + } + // If $val['visible']==0, then we never show the field + + if (!empty($val['visible'])) { + $visible = (int) dol_eval($val['visible'], 1); + $arrayfields[$tableprefix.'.'.$key] = array( + 'label'=>$val['label'], + 'checked'=>(($visible < 0) ? 0 : 1), + 'enabled'=>dol_eval($val['enabled'], 1), + 'position'=>$val['position'], + 'help'=> isset($val['help']) ? $val['help'] : '' + ); + } +} +$arrayfields = dol_sort_array($arrayfields, 'position'); +//var_dump($arrayfields);exit; + // Security check $result = restrictedArea($user, 'adherent'); diff --git a/htdocs/admin/barcode.php b/htdocs/admin/barcode.php index 2c1cf0bef0b..9a476798c20 100644 --- a/htdocs/admin/barcode.php +++ b/htdocs/admin/barcode.php @@ -162,7 +162,7 @@ foreach ($dirbarcode as $reldir) { $handle = @opendir($newdir); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) { - if (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS') { + if (substr($file, 0, 1) != '.' && substr($file, 0, 3) != 'CVS') { if (is_readable($newdir.$file)) { if (preg_match('/(.*)\.modules\.php$/i', $file, $reg)) { $filebis = $reg[1]; diff --git a/htdocs/admin/chequereceipts.php b/htdocs/admin/chequereceipts.php index 01dd7dcd2db..ec4bb7cf47d 100644 --- a/htdocs/admin/chequereceipts.php +++ b/htdocs/admin/chequereceipts.php @@ -130,7 +130,7 @@ foreach ($dirmodels as $reldir) { $handle = opendir($dir); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) { - if (!is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) { + if (!is_dir($dir.$file) || (substr($file, 0, 1) != '.' && substr($file, 0, 3) != 'CVS')) { $filebis = $file; $name = substr($file, 4, dol_strlen($file) - 16); $classname = preg_replace('/\.php$/', '', $file); diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index c92d0032176..87639008243 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -75,8 +75,13 @@ if ($reshook < 0) { if (($action == 'update' && !GETPOST("cancel", 'alpha')) || ($action == 'updateedit')) { - $tmparray = getCountry(GETPOST('country_id', 'int'), 'all', $db, $langs, 0); + $tmparray = getCountry(GETPOSTINT('country_id'), 'all', $db, $langs, 0); if (!empty($tmparray['id'])) { + if ($tmparray['code'] == 'FR' && $tmparray['id'] != $mysoc->country_id) { + // For FR, default value of option to show profid SIREN is on by default + $res = dolibarr_set_const($db, "MAIN_PROFID1_IN_ADDRESS", 1, 'chaine', 0, '', $conf->entity); + } + $mysoc->country_id = $tmparray['id']; $mysoc->country_code = $tmparray['code']; $mysoc->country_label = $tmparray['label']; diff --git a/htdocs/admin/dict.php b/htdocs/admin/dict.php index d1fbb458549..6a6ee16dbcb 100644 --- a/htdocs/admin/dict.php +++ b/htdocs/admin/dict.php @@ -2540,7 +2540,7 @@ $db->close(); * @param string $context 'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered * @return string '' or value of entity into table */ -function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') +function fieldList($fieldlist, $obj = null, $tabname = '', $context = '') { global $conf, $langs, $db, $mysoc; global $form; diff --git a/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php b/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php index f71ddb0ca60..49850bb1d2b 100644 --- a/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php +++ b/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php @@ -1,6 +1,6 @@ -* @copyright 2007-2013 PrestaShop SA -* @license https://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) -* International Registered Trademark & Property of PrestaShop SA +* @author PrestaShop SA +* @copyright 2007-2022 PrestaShop SA +* @license https://opensource.org/licenses/osl-3.0.php Open Software License (OSL 3.0) +* International Registered Trademark & Property of PrestaShop SA * PrestaShop Webservice Library * @package PrestaShopWebservice */ @@ -31,10 +31,11 @@ */ class PrestaShopWebservice { + /** @var string Shop URL */ protected $url; - /** @var string Authentification key */ + /** @var string Authentication key */ protected $key; /** @var boolean is debug activated */ @@ -43,36 +44,40 @@ class PrestaShopWebservice /** @var string PS version */ protected $version; - /** @var string compatible min version of PrestaShop Webservice */ - const PSCOMPATIBLEVERSIONMIN = '1.4.0.0'; - /** @var string compatible max version of PrestaShop Webservice */ - const PSCOMPATIBLEVERSIONMAX = '1.7.99.99'; - + /** @var string Minimal version of PrestaShop to use with this library */ + const PS_COMPATIBLE_VERSIONS_MIN = '1.4.0.0'; + /** @var string Maximal version of PrestaShop to use with this library */ + const PS_COMPATIBLE_VERSIONS_MAX = '8.1.1'; /** * PrestaShopWebservice constructor. Throw an exception when CURL is not installed/activated * * getMessage(); + * echo 'Error : '.$ex->getMessage(); * } * ?> * + * * @param string $url Root URL for the shop - * @param string $key Authentification key + * @param string $key Authentication key * @param mixed $debug Debug mode Activated (true) or deactivated (false) + * + * @throws PrestaShopWebserviceException if curl is not loaded */ public function __construct($url, $key, $debug = true) { if (!extension_loaded('curl')) { - throw new PrestaShopWebserviceException('Please activate the PHP extension \'curl\' to allow use of PrestaShop webservice library'); + throw new PrestaShopWebserviceException( + 'Please activate the PHP extension \'curl\' to allow use of PrestaShop webservice library' + ); } $this->url = $url; $this->key = $key; @@ -82,51 +87,92 @@ class PrestaShopWebservice /** * Take the status code and throw an exception if the server didn't return 200 or 201 code + *

    Unique parameter must take :

    + * 'status_code' => Status code of an HTTP return
    + * 'response' => CURL response + *

    + * + * @param array $request Response elements of CURL request * - * @param int $status_code Status code of an HTTP return * @return void + * @throws PrestaShopWebserviceException if HTTP status code is not 200 or 201 */ - protected function checkStatusCode($status_code) + protected function checkStatusCode($request) { - $error_label = 'This call to PrestaShop Web Services failed and returned an HTTP status of %d. That means: %s.'; - switch ($status_code) { + switch ($request['status_code']) { case 200: case 201: break; case 204: - throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'No content')); + $error_message = 'No content'; + break; case 400: - throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Bad Request')); + $error_message = 'Bad Request'; + break; case 401: - throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Unauthorized')); + $error_message = 'Unauthorized'; + break; case 404: - throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Not Found')); + $error_message = 'Not Found'; + break; case 405: - throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Method Not Allowed')); + $error_message = 'Method Not Allowed'; + break; case 500: - throw new PrestaShopWebserviceException(sprintf($error_label, $status_code, 'Internal Server Error')); + $error_message = 'Internal Server Error'; + break; default: - throw new PrestaShopWebserviceException('This call to PrestaShop Web Services returned an unexpected HTTP status of:'.$status_code); + throw new PrestaShopWebserviceException( + 'This call to PrestaShop Web Services returned an unexpected HTTP status of:' . $request['status_code'] + ); + } + + if (!empty($error_message)) { + $response = $this->parseXML($request['response']); + $errors = $response->children()->children(); + if ($errors && count($errors) > 0) { + foreach ($errors as $error) { + $error_message.= ' - (Code ' . $error->code . '): ' . $error->message; + } + } + $error_label = 'This call to PrestaShop Web Services failed and returned an HTTP status of %d. That means: %s.'; + throw new PrestaShopWebserviceException(sprintf($error_label, $request['status_code'], $error_message)); } } /** - * Handles a CURL request to PrestaShop Webservice. Can throw exception. - * - * @param string $url Resource name - * @param mixed $curl_params CURL parameters (sent to curl_set_opt) - * @return array status_code, response + * Provides default parameters for the curl connection(s) + * @return array Default parameters for curl connection(s) */ - public function executeRequest($url, $curl_params = array()) + protected function getCurlDefaultParams() { $defaultParams = array( CURLOPT_HEADER => true, CURLOPT_RETURNTRANSFER => true, CURLINFO_HEADER_OUT => true, CURLOPT_HTTPAUTH => CURLAUTH_BASIC, - CURLOPT_USERPWD => $this->key.':', - CURLOPT_HTTPHEADER => array('Expect:') + CURLOPT_USERPWD => $this->key . ':', + CURLOPT_HTTPHEADER => array('Expect:'), + //CURLOPT_SSL_VERIFYPEER => false, // reminder, in dev environment sometimes self-signed certificates are used + //CURLOPT_CAINFO => "PATH2CAINFO", // ssl certificate chain checking + //CURLOPT_CAPATH => "PATH2CAPATH", ); + return $defaultParams; + } + + /** + * Handles a CURL request to PrestaShop Webservice. Can throw exception. + * + * @param string $url Resource name + * @param mixed $curl_params CURL parameters (sent to curl_set_opt) + * + * @return array status_code, response, header + * + * @throws PrestaShopWebserviceException + */ + protected function executeRequest($url, $curl_params = array()) + { + $defaultParams = $this->getCurlDefaultParams(); dol_syslog("curl_init url=".$url); $session = curl_init($url); @@ -151,7 +197,7 @@ class PrestaShopWebservice $index = strpos($response, "\r\n\r\n"); if ($index === false && $curl_params[CURLOPT_CUSTOMREQUEST] != 'HEAD') { - throw new PrestaShopWebserviceException('Bad HTTP response'); + throw new PrestaShopWebserviceException('Bad HTTP response ' . $response . curl_error($session)); } $header = substr($response, 0, $index); @@ -170,10 +216,13 @@ class PrestaShopWebservice if (array_key_exists('PSWS-Version', $headerArray)) { $this->version = $headerArray['PSWS-Version']; - if (version_compare(PrestaShopWebservice::PSCOMPATIBLEVERSIONMIN, $headerArray['PSWS-Version']) == 1 || - version_compare(PrestaShopWebservice::PSCOMPATIBLEVERSIONMAX, $headerArray['PSWS-Version']) == -1 + if ( + version_compare(PrestaShopWebservice::PS_COMPATIBLE_VERSIONS_MIN, $headerArray['PSWS-Version']) == 1 || + version_compare(PrestaShopWebservice::PS_COMPATIBLE_VERSIONS_MAX, $headerArray['PSWS-Version']) == -1 ) { - throw new PrestaShopWebserviceException('This library is not compatible with this version of PrestaShop. Please upgrade/downgrade this library'); + throw new PrestaShopWebserviceException( + 'This library is not compatible with this version of PrestaShop. Please upgrade/downgrade this library' + ); } } @@ -183,7 +232,7 @@ class PrestaShopWebservice } $status_code = curl_getinfo($session, CURLINFO_HTTP_CODE); if ($status_code === 0) { - throw new PrestaShopWebserviceException('CURL Error: '.curl_error($session)); + throw new PrestaShopWebserviceException('CURL Error: ' . curl_error($session)); } curl_close($session); if ($this->debug) { @@ -200,19 +249,27 @@ class PrestaShopWebservice /** * Output debug info * - * @param string $title Title - * @param string $content Content - * @return void + * @param string $title Title + * @param string $content Content + * @return void */ public function printDebug($title, $content) { - echo '
    '.dol_escape_htmltag($title).'
    '.dol_escape_htmltag($content).'
    '; + if (php_sapi_name() == 'cli') { + echo $title . PHP_EOL . $content; + } else { + echo '
    ' + . $title + . '
    '
    +				. htmlentities($content)
    +				. '
    '; + } } /** * Return version * - * @return string Version + * @return string Version */ public function getVersion() { @@ -222,9 +279,9 @@ class PrestaShopWebservice /** * Load XML from string. Can throw exception * - * @param string $response String from a CURL response - * @return SimpleXMLElement|boolean status_code, response + * @param string $response String from a CURL response * + * @return SimpleXMLElement status_code, response * @throws PrestaShopWebserviceException */ protected function parseXML($response) @@ -232,14 +289,17 @@ class PrestaShopWebservice if ($response != '') { libxml_clear_errors(); libxml_use_internal_errors(true); - if (!function_exists('simplexml_load_string')) { - throw new PrestaShopWebserviceException('Method simplexml_load_string not available. Your PHP does not support xml.'); + if (LIBXML_VERSION < 20900) { + // Avoid load of external entities (security problem). + // Required only if LIBXML_VERSION < 20900 + libxml_disable_entity_loader(true); } - $xml = simplexml_load_string($response, 'SimpleXMLElement', LIBXML_NOCDATA|LIBXML_NONET); + + $xml = simplexml_load_string(trim($response), 'SimpleXMLElement', LIBXML_NOCDATA|LIBXML_NONET); if (libxml_get_errors()) { $msg = var_export(libxml_get_errors(), true); libxml_clear_errors(); - throw new PrestaShopWebserviceException('HTTP XML response is not parsable: '.$msg); + throw new PrestaShopWebserviceException('HTTP XML response is not parsable: ' . $msg); } return $xml; } else { @@ -254,62 +314,62 @@ class PrestaShopWebservice * 'postXml' => Full XML string to add resource

    * Examples are given in the tutorial

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

    Unique parameter must take :

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

    *

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

    Unique parameter must take :

    @@ -390,9 +451,9 @@ class PrestaShopWebservice * 'putXml' => Modified XML string of a resource

    * Examples are given in the tutorial

    * - * @param array $options Array representing resource to edit. - * @return SimpleXMLElement|boolean status_code, response + * @param array $options Array representing resource to edit. * + * @return SimpleXMLElement * @throws PrestaShopWebserviceException */ public function edit($options) @@ -401,22 +462,74 @@ class PrestaShopWebservice if (isset($options['url'])) { $url = $options['url']; } elseif ((isset($options['resource'], $options['id']) || isset($options['url'])) && $options['putXml']) { - $url = (isset($options['url']) ? $options['url'] : $this->url.'/api/'.$options['resource'].'/'.$options['id']); + $url = (isset($options['url']) ? $options['url'] : + $this->url . '/api/' . $options['resource'] . '/' . $options['id']); $xml = $options['putXml']; if (isset($options['id_shop'])) { - $url .= '&id_shop='.$options['id_shop']; + $url .= '&id_shop=' . $options['id_shop']; } if (isset($options['id_group_shop'])) { - $url .= '&id_group_shop='.$options['id_group_shop']; + $url .= '&id_group_shop=' . $options['id_group_shop']; } } else { throw new PrestaShopWebserviceException('Bad parameters given'); } $request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'PUT', CURLOPT_POSTFIELDS => $xml)); - $this->checkStatusCode($request['status_code']); // check the response validity + $this->checkStatusCode($request);// check the response validity return $this->parseXML($request['response']); } + + /** + * Delete (DELETE) a resource. + * Unique parameter must take :

    + * 'resource' => Resource name
    + * 'id' => ID or array which contains IDs of a resource(s) you want to delete

    + * + * delete(array('resource' => 'orders', 'id' => 1)); + * // Following code will not be executed if an exception is thrown. + * echo 'Successfully deleted.'; + * } + * catch (PrestaShopWebserviceException $ex) + * { + * echo 'Error : '.$ex->getMessage(); + * } + * ?> + * + * + * @param array $options Array representing resource to delete. + * + * @return bool + * @throws PrestaShopWebserviceException + */ + public function delete($options) + { + if (isset($options['url'])) { + $url = $options['url']; + } elseif (isset($options['resource']) && isset($options['id'])) { + $url = (is_array($options['id'])) + ? $this->url . '/api/' . $options['resource'] . '/?id=[' . implode(',', $options['id']) . ']' + : $this->url . '/api/' . $options['resource'] . '/' . $options['id']; + } else { + throw new PrestaShopWebserviceException('Bad parameters given'); + } + + if (isset($options['id_shop'])) { + $url .= '&id_shop=' . $options['id_shop']; + } + if (isset($options['id_group_shop'])) { + $url .= '&id_group_shop=' . $options['id_group_shop']; + } + + $request = $this->executeRequest($url, array(CURLOPT_CUSTOMREQUEST => 'DELETE')); + $this->checkStatusCode($request);// check the response validity + return true; + } } /** diff --git a/htdocs/admin/dolistore/class/PS_WS_LIB-LICENSE.md b/htdocs/admin/dolistore/class/PS_WS_LIB-LICENSE.md new file mode 100644 index 00000000000..0dbd9d23112 --- /dev/null +++ b/htdocs/admin/dolistore/class/PS_WS_LIB-LICENSE.md @@ -0,0 +1,53 @@ +# Open Software License v. 3.0 (OSL-3.0) + +This Open Software License (the "License") applies to any original work of authorship (the "Original Work") whose owner (the "Licensor") has placed the following licensing notice adjacent to the copyright notice for the Original Work: + +Licensed under the Open Software License version 3.0 + +1) **Grant of Copyright License.** Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, for the duration of the copyright, to do the following: + +a) to reproduce the Original Work in copies, either alone or as part of a collective work; + +b) to translate, adapt, alter, transform, modify, or arrange the Original Work, thereby creating derivative works ("Derivative Works") based upon the Original Work; + +c) to distribute or communicate copies of the Original Work and Derivative Works to the public, _with the proviso that copies of Original Work or Derivative Works that You distribute or communicate shall be licensed under this Open Software License_; + +d) to perform the Original Work publicly; and + +e) to display the Original Work publicly. + +2) **Grant** of Patent License. Licensor grants You a worldwide, royalty-free, non-exclusive, sublicensable license, under patent claims owned or controlled by the Licensor that are embodied in the Original Work as furnished by the Licensor, for the duration of the patents, to make, use, sell, offer for sale, have made, and import the Original Work and Derivative Works. + +3) **Grant** of Source Code License. The term "Source Code" means the preferred form of the Original Work for making modifications to it and all available documentation describing how to modify the Original Work. Licensor agrees to provide a machine-readable copy of the Source Code of the Original Work along with each copy of the Original Work that Licensor distributes. Licensor reserves the right to satisfy this obligation by placing a machine-readable copy of the Source Code in an information repository reasonably calculated to permit inexpensive and convenient access by You for as long as Licensor continues to distribute the Original Work. + +4) **Exclusions From License Grant.** Neither the names of Licensor, nor the names of any contributors to the Original Work, nor any of their trademarks or service marks, may be used to endorse or promote products derived from this Original Work without express prior permission of the Licensor. Except as expressly stated herein, nothing in this License grants any license to Licensor's trademarks, copyrights, patents, trade secrets or any other intellectual property. No patent license is granted to make, use, sell, offer for sale, have made, or import embodiments of any patent claims other than the licensed claims defined in Section 2\. No license is granted to the trademarks of Licensor even if such marks are included in the Original Work. Nothing in this License shall be interpreted to prohibit Licensor from licensing under terms different from this License any Original Work that Licensor otherwise would have a right to license. + +5) **External Deployment.** The term "External Deployment" means the use, distribution, or communication of the Original Work or Derivative Works in any way such that the Original Work or Derivative Works may be used by anyone other than You, whether those works are distributed or communicated to those persons or made available as an application intended for use over a network. As an express condition for the grants of license hereunder, You must treat any External Deployment by You of the Original Work or a Derivative Work as a distribution under section 1(c). + +6) **Attribution Rights.** You must retain, in the Source Code of any Derivative Works that You create, all copyright, patent, or trademark notices from the Source Code of the Original Work, as well as any notices of licensing and any descriptive text identified therein as an "Attribution Notice." You must cause the Source Code for any Derivative Works that You create to carry a prominent Attribution Notice reasonably calculated to inform recipients that You have modified the Original Work. + +7) **Warranty of Provenance and Disclaimer of Warranty.** Licensor warrants that the copyright in and to the Original Work and the patent rights granted herein by Licensor are owned by the Licensor or are sublicensed to You under the terms of this License with the permission of the contributor(s) of those copyrights and patent rights. Except as expressly stated in the immediately preceding sentence, the Original Work is provided under this License on an "AS IS" BASIS and WITHOUT WARRANTY, either express or implied, including, without limitation, the warranties of non-infringement, merchantability or fitness for a particular purpose. THE ENTIRE RISK AS TO THE QUALITY OF THE ORIGINAL WORK IS WITH YOU. This DISCLAIMER OF WARRANTY constitutes an essential part of this License. No license to the Original Work is granted by this License except under this disclaimer. + +8) **Limitation of Liability.** Under no circumstances and under no legal theory, whether in tort (including negligence), contract, or otherwise, shall the Licensor be liable to anyone for any indirect, special, incidental, or consequential damages of any character arising as a result of this License or the use of the Original Work including, without limitation, damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses. This limitation of liability shall not apply to the extent applicable law prohibits such limitation. + +9) **Acceptance and Termination.** If, at any time, You expressly assented to this License, that assent indicates your clear and irrevocable acceptance of this License and all of its terms and conditions. If You distribute or communicate copies of the Original Work or a Derivative Work, You must make a reasonable effort under the circumstances to obtain the express assent of recipients to the terms of this License. This License conditions your rights to undertake the activities listed in Section 1, including your right to create Derivative Works based upon the Original Work, and doing so without honoring these terms and conditions is prohibited by copyright law and international treaty. Nothing in this License is intended to affect copyright exceptions and limitations (including "fair use" or "fair dealing"). This License shall terminate immediately and You may no longer exercise any of the rights granted to You by this License upon your failure to honor the conditions in Section 1(c). + +10) **Termination for Patent Action.** This License shall terminate automatically and You may no longer exercise any of the rights granted to You by this License as of the date You commence an action, including a cross-claim or counterclaim, against Licensor or any licensee alleging that the Original Work infringes a patent. This termination provision shall not apply for an action alleging patent infringement by combinations of the Original Work with other software or hardware. + +11) **Jurisdiction, Venue and Governing Law.** Any action or suit relating to this License may be brought only in the courts of a jurisdiction wherein the Licensor resides or in which Licensor conducts its primary business, and under the laws of that jurisdiction excluding its conflict-of-law provisions. The application of the United Nations Convention on Contracts for the International Sale of Goods is expressly excluded. Any use of the Original Work outside the scope of this License or after its termination shall be subject to the requirements and penalties of copyright or patent law in the appropriate jurisdiction. This section shall survive the termination of this License. + +12) **Attorneys' Fees.** In any action to enforce the terms of this License or seeking damages relating thereto, the prevailing party shall be entitled to recover its costs and expenses, including, without limitation, reasonable attorneys' fees and costs incurred in connection with such action, including any appeal of such action. This section shall survive the termination of this License. + +13) **Miscellaneous.** If any provision of this License is held to be unenforceable, such provision shall be reformed only to the extent necessary to make it enforceable. + +14) **Definition of "You" in This License.** "You" throughout this License, whether in upper or lower case, means an individual or a legal entity exercising rights under, and complying with all of the terms of, this License. For legal entities, "You" includes any entity that controls, is controlled by, or is under common control with you. For purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. + +15) **Right to Use.** You may use the Original Work in all ways not otherwise restricted or conditioned by this License or by law, and Licensor promises not to interfere with or be responsible for such uses by You. + +16) **Modification of This License.** This License is Copyright (c) 2005 Lawrence Rosen. Permission is granted to copy, distribute, or communicate this License without modification. Nothing in this License permits You to modify this License as applied to the Original Work or to Derivative Works. However, You may modify the text of this License and copy, distribute or communicate your modified version (the "Modified License") and apply it to other original works of authorship subject to the following conditions: (i) You may not indicate in any way that your Modified License is the "Open Software License" or "OSL" and you may not use those names in the name of your Modified License; (ii) You must replace the notice specified in the first paragraph above with the notice "Licensed under " or with a notice of your own that is not confusingly similar to the notice in this License; and (iii) You may not claim that your original works are open source software unless your Modified License has been approved by Open Source Initiative (OSI) and You comply with its license review and certification process. + +[A brief explanation of this license is available][0]. + + +[0]: http://rosenlaw.com/OSL3.0-explained.htm + diff --git a/htdocs/admin/dolistore/class/README.md b/htdocs/admin/dolistore/class/README.md new file mode 100644 index 00000000000..b0f57af00e7 --- /dev/null +++ b/htdocs/admin/dolistore/class/README.md @@ -0,0 +1,12 @@ +# PrestaShop-webservice-lib + +Source updated from: + +https://github.com/PrestaShop/PrestaShop-webservice-lib/blob/master/PSWebServiceLibrary.php + +## Compatibility analysis + +https://www.gnu.org/licenses/license-list.html#OSL + + + diff --git a/htdocs/admin/eventorganization.php b/htdocs/admin/eventorganization.php index c9991c07a38..7e1b74e336e 100644 --- a/htdocs/admin/eventorganization.php +++ b/htdocs/admin/eventorganization.php @@ -154,7 +154,7 @@ if ($action == 'updateMask') { $tmpobjectkey = GETPOST('object'); if (!empty($tmpobjectkey)) { $constforval = 'EVENTORGANIZATION_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; - if ($conf->global->$constforval == "$value") { + if (getDolGlobalString($constforval) == "$value") { dolibarr_del_const($db, $constforval, $conf->entity); } } @@ -279,7 +279,7 @@ if ($action == 'edit') { print dolJSToSetRandomPassword($constname, 'generate_token'.$constname); } elseif ($val['type'] == 'product') { if (isModEnabled("product") || isModEnabled("service")) { - $selected = (empty($conf->global->$constname) ? '' : $conf->global->$constname); + $selected = getDolGlobalString($constname); $form->select_produits($selected, $constname, '', 0); } } else { diff --git a/htdocs/admin/events.php b/htdocs/admin/events.php index fef00036cc2..afdeca4b7b2 100644 --- a/htdocs/admin/events.php +++ b/htdocs/admin/events.php @@ -122,7 +122,7 @@ foreach ($eventstolog as $key => $arr) { print '
    '; print ''."\n"; } diff --git a/htdocs/admin/external_rss.php b/htdocs/admin/external_rss.php index e85f5aa51ea..7dd152fa3d1 100644 --- a/htdocs/admin/external_rss.php +++ b/htdocs/admin/external_rss.php @@ -193,24 +193,29 @@ print '
    '; print ''; print ''; +print '
    '; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '
    '.$langs->trans("Total").''; $text = dolGetFirstLineOfText(dol_string_nohtmltag($objp->description, 1)); - $trunclength = !getDolGlobalString('ACCOUNTING_LENGTH_DESCRIPTION') ? 32 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION; + $trunclength = getDolGlobalInt('ACCOUNTING_LENGTH_DESCRIPTION', 32); print $form->textwithtooltip(dol_trunc($text, $trunclength), $objp->description); print ''; $text = dolGetFirstLineOfText(dol_string_nohtmltag($facturefourn_static_det->desc, 1)); - $trunclength = !getDolGlobalString('ACCOUNTING_LENGTH_DESCRIPTION') ? 32 : $conf->global->ACCOUNTING_LENGTH_DESCRIPTION; + $trunclength = getDolGlobalInt('ACCOUNTING_LENGTH_DESCRIPTION', 32); print $form->textwithtooltip(dol_trunc($text, $trunclength), $facturefourn_static_det->desc); print ''.$arr['id'].''; $key = 'MAIN_LOGEVENTS_'.$arr['id']; - $value = empty($conf->global->$key) ? '' : $conf->global->$key; + $value = getDolGlobalString($key); print ''; print '
    '; + print ''; print ''; print ''; print ''; -print ''; + +print ''; print ''; print ''; print ''; print ''; -print ''; +print ''; print ''; print ''; print ''; print ''; print '
    '.$langs->trans("NewRSS").''.$langs->trans("Example").'
    '.$langs->trans("Title").''.$langs->trans('RSSUrlExample').'
    '.$langs->trans('RSSUrl').'http://news.google.com/news?ned=us&topic=h&output=rss
    http://www.dolibarr.org/rss
    '; +print ''; + print $form->buttonsSaveCancel("Add", ''); print ''; print ''; @@ -242,7 +247,7 @@ if ($resql) { //print "x".$idrss; $rssparser = new RssParser($db); - $result = $rssparser->parser($conf->global->$keyrssurl, 5, 300, $conf->externalrss->dir_temp); + $result = $rssparser->parser(getDolGlobalString($keyrssurl), 5, 300, $conf->externalrss->dir_temp); print "
    "; print ''."\n"; diff --git a/htdocs/admin/facture.php b/htdocs/admin/facture.php index 036b0661c52..3384a0d31d6 100644 --- a/htdocs/admin/facture.php +++ b/htdocs/admin/facture.php @@ -310,7 +310,7 @@ foreach ($dirmodels as $reldir) { $handle = opendir($dir); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) { - if (!is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) { + if (!is_dir($dir.$file) || (substr($file, 0, 1) != '.' && substr($file, 0, 3) != 'CVS')) { $filebis = $file; $classname = preg_replace('/\.php$/', '', $file); // For compatibility diff --git a/htdocs/admin/fckeditor.php b/htdocs/admin/fckeditor.php index 64dc930e5e9..92a235fc178 100644 --- a/htdocs/admin/fckeditor.php +++ b/htdocs/admin/fckeditor.php @@ -173,7 +173,7 @@ if (empty($conf->use_javascript_ajax)) { } print '
    '; - $value = (isset($conf->global->$constante) ? $conf->global->$constante : 0); + $value = getDolGlobalInt($constante, 0); if ($value == 0) { print ''.img_picto($langs->trans("Disabled"), 'switch_off').''; } elseif ($value == 1) { diff --git a/htdocs/admin/hrm.php b/htdocs/admin/hrm.php index 423b78bc071..6b75e92bfca 100644 --- a/htdocs/admin/hrm.php +++ b/htdocs/admin/hrm.php @@ -159,7 +159,7 @@ if ($action == 'update') { $tmpobjectkey = GETPOST('object'); if (!empty($tmpobjectkey)) { $constforval = 'HRMTEST_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; - if ($conf->global->$constforval == "$value") { + if (getDolGlobalString($constforval) == "$value") { dolibarr_del_const($db, $constforval, $conf->entity); } } @@ -549,7 +549,7 @@ if ($action == 'edit') { print dolJSToSetRandomPassword($constname, 'generate_token' . $constname); } elseif ($val['type'] == 'product') { if (isModEnabled('product') || isModEnabled('service')) { - $selected = (empty($conf->global->$constname) ? '' : $conf->global->$constname); + $selected = getDolGlobalString($constname); $form->select_produits($selected, $constname, '', 0); } } else { diff --git a/htdocs/admin/knowledgemanagement.php b/htdocs/admin/knowledgemanagement.php index ed99e058328..40e92d8270a 100644 --- a/htdocs/admin/knowledgemanagement.php +++ b/htdocs/admin/knowledgemanagement.php @@ -137,7 +137,7 @@ if ($action == 'updateMask') { $tmpobjectkey = GETPOST('object'); if (!empty($tmpobjectkey)) { $constforval = 'KNOWLEDGEMANAGEMENT_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; - if ($conf->global->$constforval == "$value") { + if (getDolGlobalString($constforval) == "$value") { dolibarr_del_const($db, $constforval, $conf->entity); } } diff --git a/htdocs/admin/ldap_contacts.php b/htdocs/admin/ldap_contacts.php index 5e5fd8fb9c0..374685624ba 100644 --- a/htdocs/admin/ldap_contacts.php +++ b/htdocs/admin/ldap_contacts.php @@ -102,7 +102,7 @@ if ($action == 'setvalue' && $user->admin) { $valkey = ''; $key = GETPOST("key"); if ($key) { - $valkey = $conf->global->$key; + $valkey = getDolGlobalString($key); } if (!dolibarr_set_const($db, 'LDAP_KEY_CONTACTS', $valkey, 'chaine', 0, '', $conf->entity)) { $error++; diff --git a/htdocs/admin/ldap_groups.php b/htdocs/admin/ldap_groups.php index 878a6c6029a..36ef3b7ad7c 100644 --- a/htdocs/admin/ldap_groups.php +++ b/htdocs/admin/ldap_groups.php @@ -79,7 +79,7 @@ if ($action == 'setvalue' && $user->admin) { $valkey = ''; $key = GETPOST("key"); if ($key) { - $valkey = $conf->global->$key; + $valkey = getDolGlobalString($key); } if (!dolibarr_set_const($db, 'LDAP_KEY_GROUPS', $valkey, 'chaine', 0, '', $conf->entity)) { $error++; diff --git a/htdocs/admin/ldap_members.php b/htdocs/admin/ldap_members.php index f7a4af5d2fd..2047cb983ca 100644 --- a/htdocs/admin/ldap_members.php +++ b/htdocs/admin/ldap_members.php @@ -147,7 +147,7 @@ if ($action == 'setvalue' && $user->admin) { $valkey = ''; $key = GETPOST("key"); if ($key) { - $valkey = $conf->global->$key; + $valkey = getDolGlobalString($key); } if (!dolibarr_set_const($db, 'LDAP_KEY_MEMBERS', $valkey, 'chaine', 0, '', $conf->entity)) { $error++; diff --git a/htdocs/admin/ldap_members_types.php b/htdocs/admin/ldap_members_types.php index 9c7a517bb1f..26af5ba9191 100644 --- a/htdocs/admin/ldap_members_types.php +++ b/htdocs/admin/ldap_members_types.php @@ -73,7 +73,7 @@ if ($action == 'setvalue' && $user->admin) { $valkey = ''; $key = GETPOST("key"); if ($key) { - $valkey = $conf->global->$key; + $valkey = getDolGlobalString($key); } if (!dolibarr_set_const($db, 'LDAP_KEY_MEMBERS_TYPES', $valkey, 'chaine', 0, '', $conf->entity)) { $error++; diff --git a/htdocs/admin/ldap_users.php b/htdocs/admin/ldap_users.php index d2c287aef78..54863009e0d 100644 --- a/htdocs/admin/ldap_users.php +++ b/htdocs/admin/ldap_users.php @@ -135,7 +135,7 @@ if ($action == 'setvalue' && $user->admin) { $valkey = ''; $key = GETPOST("key"); if ($key) { - $valkey = $conf->global->$key; + $valkey = getDolGlobalString($key); } if (!dolibarr_set_const($db, 'LDAP_KEY_USERS', $valkey, 'chaine', 0, '', $conf->entity)) { $error++; diff --git a/htdocs/admin/mails_templates.php b/htdocs/admin/mails_templates.php index f658d456f8d..cabbe69c319 100644 --- a/htdocs/admin/mails_templates.php +++ b/htdocs/admin/mails_templates.php @@ -1354,7 +1354,7 @@ $db->close(); * @param string $context 'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered * @return void */ -function fieldList($fieldlist, $obj = '', $tabname = '', $context = '') +function fieldList($fieldlist, $obj = null, $tabname = '', $context = '') { global $langs, $user, $db; global $form; diff --git a/htdocs/admin/modules.php b/htdocs/admin/modules.php index 78fed9249ea..eb3938ac088 100644 --- a/htdocs/admin/modules.php +++ b/htdocs/admin/modules.php @@ -851,7 +851,7 @@ if ($mode == 'common' || $mode == 'commonkanban') { } // Activate/Disable and Setup (2 columns) - if (!empty($conf->global->$const_name)) { // If module is already activated + if (getDolGlobalString($const_name)) { // If module is already activated // Set $codeenabledisable $disableSetup = 0; if (!empty($arrayofwarnings[$modName])) { diff --git a/htdocs/admin/notification.php b/htdocs/admin/notification.php index 78765aae04e..2a401df047e 100644 --- a/htdocs/admin/notification.php +++ b/htdocs/admin/notification.php @@ -453,7 +453,7 @@ foreach ($listofnotifiedevents as $notifiedevent) { } $param = 'NOTIFICATION_FIXEDEMAIL_'.$notifiedevent['code'].'_THRESHOLD_HIGHER_'.$reg[1]; - $value = GETPOST('NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_key') ? GETPOST('NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_key', 'alpha') : $conf->global->$param; + $value = GETPOST('NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_key') ? GETPOST('NOTIF_'.$notifiedevent['code'].'_old_'.$reg[1].'_key', 'alpha') : getDolGlobalString($param); $s = ''; // Do not use type="email" here, we must be able to enter a list of email with , separator. $arrayemail = explode(',', $value); @@ -464,7 +464,7 @@ foreach ($listofnotifiedevents as $notifiedevent) { $showwarning++; } } - if ((!empty($conf->global->$param)) && $showwarning) { + if (getDolGlobalString($param) && $showwarning) { $s .= ' '.img_warning($langs->trans("ErrorBadEMail")); } print $form->textwithpicto($s, $langs->trans("YouCanUseCommaSeparatorForSeveralRecipients").'
    '.$langs->trans("YouCanAlsoUseSupervisorKeyword"), 1, 'help', '', 0, 2); diff --git a/htdocs/admin/payment.php b/htdocs/admin/payment.php index f9e04d6f305..5fd744ca88b 100644 --- a/htdocs/admin/payment.php +++ b/htdocs/admin/payment.php @@ -134,7 +134,7 @@ foreach ($dirmodels as $reldir) { $handle = opendir($dir); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) { - if (!is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) { + if (!is_dir($dir.$file) || (substr($file, 0, 1) != '.' && substr($file, 0, 3) != 'CVS')) { $filebis = $file; $classname = preg_replace('/\.php$/', '', $file); // For compatibility diff --git a/htdocs/admin/pdf.php b/htdocs/admin/pdf.php index 30950eae177..26ee5a374f5 100644 --- a/htdocs/admin/pdf.php +++ b/htdocs/admin/pdf.php @@ -367,7 +367,7 @@ for ($i = 1; $i <= 6; $i++) { if ($conf->use_javascript_ajax) { print ajax_constantonoff($keyforconstant); } else { - print $form->selectyesno($keyforconstant, isset($conf->global->$keyforconstant) ? $conf->global->$keyforconstant : 0, 1, $noCountryCode); + print $form->selectyesno($keyforconstant, getDolGlobalString($keyforconstant, 0), 1, $noCountryCode); } print '
    '; print $permlabel; if (getDolGlobalString('MAIN_USE_ADVANCED_PERMS')) { diff --git a/htdocs/admin/propal.php b/htdocs/admin/propal.php index 523930a58b9..23c34f57fcf 100644 --- a/htdocs/admin/propal.php +++ b/htdocs/admin/propal.php @@ -125,38 +125,27 @@ if ($action == 'updateMask') { } else { setEventMessages($langs->trans("Error"), null, 'errors'); } -} elseif ($action == 'set_PROPALE_DRAFT_WATERMARK') { - $draft = GETPOST('PROPALE_DRAFT_WATERMARK', 'alpha'); - - $res = dolibarr_set_const($db, "PROPALE_DRAFT_WATERMARK", trim($draft), 'chaine', 0, '', $conf->entity); - if (!($res > 0)) { - $error++; +} elseif ($action == 'update') { + if (GETPOSTISSET('PROPALE_VALIDITY_DURATION')) { + $value = GETPOST('PROPALE_VALIDITY_DURATION'); + $res = dolibarr_set_const($db, "PROPALE_VALIDITY_DURATION", $value, 'chaine', 0, '', $conf->entity); + if (!($res > 0)) { + $error++; + } } - - if (!$error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'errors'); + if (GETPOSTISSET('PROPALE_DRAFT_WATERMARK')) { + $draft = GETPOST('PROPALE_DRAFT_WATERMARK', 'alpha'); + $res = dolibarr_set_const($db, "PROPALE_DRAFT_WATERMARK", trim($draft), 'chaine', 0, '', $conf->entity); + if (!($res > 0)) { + $error++; + } } -} elseif ($action == 'set_PROPOSAL_FREE_TEXT') { - $freetext = GETPOST('PROPOSAL_FREE_TEXT', 'restricthtml'); // No alpha here, we want exact string - - $res = dolibarr_set_const($db, "PROPOSAL_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity); - - if (!($res > 0)) { - $error++; - } - - if (!$error) { - setEventMessages($langs->trans("SetupSaved"), null, 'mesgs'); - } else { - setEventMessages($langs->trans("Error"), null, 'errors'); - } -} elseif ($action == 'setdefaultduration') { - $res = dolibarr_set_const($db, "PROPALE_VALIDITY_DURATION", $value, 'chaine', 0, '', $conf->entity); - - if (!($res > 0)) { - $error++; + if (GETPOSTISSET('PROPOSAL_FREE_TEXT')) { + $freetext = GETPOST('PROPOSAL_FREE_TEXT', 'restricthtml'); // No alpha here, we want exact string + $res = dolibarr_set_const($db, "PROPOSAL_FREE_TEXT", $freetext, 'chaine', 0, '', $conf->entity); + if (!($res > 0)) { + $error++; + } } if (!$error) { @@ -609,73 +598,22 @@ print '
    '; print load_fiche_titre($langs->trans("OtherOptions"), '', ''); -print ""; +print ''; +print ''; +print ''; +print ''; + +print '
    '; print ""; print "\n"; print '\n"; -print "\n"; print ""; - -print ""; -print ''; -print ""; print ''; print ''; -print '"; -print ''; +print '"; print ''; -print ''; - -// Allow external download -print ''; -print ''; -print ''; - -// Allow OnLine Sign -print ''; -print ''; -print ''; - -// default update prices on cloning a proposal -/* -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -print ''; -*/ - -/* -print ''; -print ''; -print ''; -print '\n"; -print ''; -*/ $substitutionarray = pdf_getSubstitutionArray($langs, null, null, 2); $substitutionarray['__(AnyTranslationKey)__'] = $langs->trans("Translation"); @@ -685,9 +623,6 @@ foreach ($substitutionarray as $key => $val) { } $htmltext .= ''; -print ''; -print ''; -print ''; print '\n"; -print ''; +print ''; +print "\n"; -print ""; -print ''; -print ""; print '\n"; -print ''; +print ''; +print "\n"; + + +// Allow external download +print ''; +print ''; +print ''; + +// Allow OnLine Sign +print ''; +print ''; +print ''; + /* Seems to be not so used. So kept hidden for the moment to avoid dangerous options inflation. if (isModEnabled('facture')) @@ -749,6 +693,9 @@ else print '
    ".$langs->trans("Parameter")."'.$langs->trans("Value")." 
    '.$langs->trans("DefaultProposalDurationValidity").''."'; +print "
    '.$langs->trans("AllowExternalDownload").''; -print ajax_constantonoff('PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD', array(), null, 0, 0, 0, 2, 0, 1); -print '
    '.$langs->trans("AllowOnLineSign").''; -print ajax_constantonoff('PROPOSAL_ALLOW_ONLINESIGN', array(), null, 0, 0, 0, 2, 0, 1); -print '
    ' . $langs->trans('DefaultPuttingPricesUpToDate').''; -if (!empty($conf->use_javascript_ajax)) { - print ajax_constantonoff('PROPOSAL_CLONE_UPDATE_PRICES', array(), $conf->entity, 0, 0, 1, 0); -} else { - if (empty($conf->global->PROPOSAL_CLONE_UPDATE_PRICES)) { - print '' . img_picto($langs->trans('Disabled'), 'switch_off') . ''; - } else { - print '' . img_picto($langs->trans('Enabled'), 'switch_on') . ''; - } -} -print '
    '; -print $langs->trans("UseCustomerContactAsPropalRecipientIfExist"); -print ''; -print $form->selectyesno("value",$conf->global->PROPALE_USE_CUSTOMER_CONTACT_AS_RECIPIENT,1); -print ''; -print ''; -print "
    '; print $form->textwithpicto($langs->trans("FreeLegalTextOnProposal"), $langs->trans("AddCRIfTooLong").'

    '.$htmltext, 1, 'help', '', 0, 2, 'freetexttooltip').'
    '; $variablename = 'PROPOSAL_FREE_TEXT'; @@ -698,23 +633,32 @@ if (!getDolGlobalString('PDF_ALLOW_HTML_FOR_FREE_TEXT')) { $doleditor = new DolEditor($variablename, getDolGlobalString($variablename), '', 80, 'dolibarr_notes'); print $doleditor->Create(); } -print '
    '; -print ''; -print "
    '; print $form->textwithpicto($langs->trans("WatermarkOnDraftProposal"), $htmltext, 1, 'help', '', 0, 2, 'watermarktooltip').'
    '; print '
    '; print ''; -print ''; -print ''; -print "
    '.$langs->trans("AllowExternalDownload").''; +print ajax_constantonoff('PROPOSAL_ALLOW_EXTERNAL_DOWNLOAD', array(), null, 0, 0, 0, 2, 0, 1); +print '
    '.$langs->trans("AllowOnLineSign").''; +print ajax_constantonoff('PROPOSAL_ALLOW_ONLINESIGN', array(), null, 0, 0, 0, 2, 0, 1); +print '
    '; +print '
    '; + +print ''; /* diff --git a/htdocs/admin/security.php b/htdocs/admin/security.php index 23f7a6d0aca..42945587fee 100644 --- a/htdocs/admin/security.php +++ b/htdocs/admin/security.php @@ -20,7 +20,7 @@ /** * \file htdocs/admin/security.php * \ingroup setup - * \brief Page de configuration du module securite + * \brief Page of setup of security */ // Load Dolibarr environment diff --git a/htdocs/admin/supplier_payment.php b/htdocs/admin/supplier_payment.php index df24830d98d..c1e01049a65 100644 --- a/htdocs/admin/supplier_payment.php +++ b/htdocs/admin/supplier_payment.php @@ -209,7 +209,7 @@ foreach ($dirmodels as $reldir) { $handle = opendir($dir); if (is_resource($handle)) { while (($file = readdir($handle)) !== false) { - if (!is_dir($dir.$file) || (substr($file, 0, 1) <> '.' && substr($file, 0, 3) <> 'CVS')) { + if (!is_dir($dir.$file) || (substr($file, 0, 1) != '.' && substr($file, 0, 3) != 'CVS')) { $filebis = $file; $classname = preg_replace('/\.php$/', '', $file); // For compatibility diff --git a/htdocs/admin/syslog.php b/htdocs/admin/syslog.php index 88d590ffc35..a3d5871840b 100644 --- a/htdocs/admin/syslog.php +++ b/htdocs/admin/syslog.php @@ -232,8 +232,8 @@ foreach ($syslogModules as $moduleName) { if (!empty($tmpoption)) { if (GETPOSTISSET($tmpoption)) { $value = GETPOST($tmpoption); - } elseif (!empty($conf->global->$tmpoption)) { - $value = $conf->global->$tmpoption; + } elseif (getDolGlobalString($tmpoption)) { + $value = getDolGlobalString($tmpoption); } } else { $value = (isset($option['default']) ? $option['default'] : ''); diff --git a/htdocs/admin/system/dolibarr.php b/htdocs/admin/system/dolibarr.php index cc7fc970529..c7f07ad0040 100644 --- a/htdocs/admin/system/dolibarr.php +++ b/htdocs/admin/system/dolibarr.php @@ -52,6 +52,12 @@ if ($action == 'getlastversion') { $result = getURLContent('https://sourceforge.net/projects/dolibarr/rss'); //var_dump($result['content']); if (function_exists('simplexml_load_string')) { + if (LIBXML_VERSION < 20900) { + // Avoid load of external entities (security problem). + // Required only if LIBXML_VERSION < 20900 + libxml_disable_entity_loader(true); + } + $sfurl = simplexml_load_string($result['content'], 'SimpleXMLElement', LIBXML_NOCDATA|LIBXML_NONET); } else { setEventMessages($langs->trans("ErrorPHPDoesNotSupport", "xml"), null, 'errors'); diff --git a/htdocs/admin/system/filecheck.php b/htdocs/admin/system/filecheck.php index b0abc81cf7a..a1e04d8db07 100644 --- a/htdocs/admin/system/filecheck.php +++ b/htdocs/admin/system/filecheck.php @@ -176,6 +176,12 @@ if (GETPOST('target') == 'remote') { if (!$xmlarray['curl_error_no'] && $xmlarray['http_code'] != '400' && $xmlarray['http_code'] != '404') { $xmlfile = $xmlarray['content']; //print "xmlfilestart".$xmlfile."xmlfileend"; + if (LIBXML_VERSION < 20900) { + // Avoid load of external entities (security problem). + // Required only if LIBXML_VERSION < 20900 + libxml_disable_entity_loader(true); + } + $xml = simplexml_load_string($xmlfile, 'SimpleXMLElement', LIBXML_NOCDATA|LIBXML_NONET); } else { $errormsg = $langs->trans('XmlNotFound').': '.$xmlremote.' - '.$xmlarray['http_code'].(($xmlarray['http_code'] == 400 && $xmlarray['content']) ? ' '.$xmlarray['content'] : '').' '.$xmlarray['curl_error_no'].' '.$xmlarray['curl_error_msg']; diff --git a/htdocs/admin/system/security.php b/htdocs/admin/system/security.php index 7ad70c385b5..6ad04701a52 100644 --- a/htdocs/admin/system/security.php +++ b/htdocs/admin/system/security.php @@ -117,7 +117,7 @@ print "PHP allow_url_include = ".(ini_get('allow_url_include') //print "PHP safe_mode = ".(ini_get('safe_mode') ? ini_get('safe_mode') : yn(0)).'   '.$langs->trans("Deprecated")." (removed in PHP 5.4)
    \n"; print "PHP disable_functions = "; $arrayoffunctionsdisabled = explode(',', ini_get('disable_functions')); -$arrayoffunctionstodisable = explode(',', 'pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals'); +$arrayoffunctionstodisable = explode(',', 'dl,apache_note,apache_setenv,pcntl_alarm,pcntl_fork,pcntl_waitpid,pcntl_wait,pcntl_wifexited,pcntl_wifstopped,pcntl_wifsignaled,pcntl_wifcontinued,pcntl_wexitstatus,pcntl_wtermsig,pcntl_wstopsig,pcntl_signal,pcntl_signal_get_handler,pcntl_signal_dispatch,pcntl_get_last_error,pcntl_strerror,pcntl_sigprocmask,pcntl_sigwaitinfo,pcntl_sigtimedwait,pcntl_exec,pcntl_getpriority,pcntl_setpriority,pcntl_async_signals,show_source,virtual'); //$arrayoffunctionstodisable[] = 'stream_wrapper_restore'; //$arrayoffunctionstodisable[] = 'stream_wrapper_register'; if ($execmethod == 1) { @@ -740,6 +740,11 @@ print '
    '; print 'MAIN_SECURITY_FORCERP = '.getDolGlobalString('MAIN_SECURITY_FORCERP', ''.$langs->trans("Undefined").'').'   ('.$langs->trans("Recommended").': '.$langs->trans("Undefined").' '.$langs->trans("or")." \"same-origin\" so browser doesn't send any referrer when going into another web site domain)
    "; print '
    '; +print 'MAIN_SECURITY_FORCE_ACCESS_CONTROL_ALLOW_ORIGIN = '.getDolGlobalString('MAIN_SECURITY_FORCE_ACCESS_CONTROL_ALLOW_ORIGIN', ''.$langs->trans("Undefined").'').'   ('.$langs->trans("Recommended").": 1)
    "; +print '
    '; + +// For websites + print 'WEBSITE_MAIN_SECURITY_FORCECSPRO = '.getDolGlobalString('WEBSITE_MAIN_SECURITY_FORCECSPRO', ''.$langs->trans("Undefined").''); print '   ('.$langs->trans("Example").": \"frame-ancestors 'self'; default-src 'self' 'unsafe-inline'; style-src https://cdnjs.cloudflare.com *.googleapis.com; script-src *.transifex.com *.google-analytics.com *.googletagmanager.com; object-src https://youtube.com; frame-src https://youtube.com; img-src * data:;\")
    "; print '
    '; @@ -757,6 +762,7 @@ print '
    '; print 'WEBSITE_MAIN_SECURITY_FORCEPP = '.getDolGlobalString('WEBSITE_MAIN_SECURITY_FORCEPP', ''.$langs->trans("Undefined").'').'   ('.$langs->trans("Example").": \"camera: (); microphone: ();\")
    "; print '
    '; + print ''; diff --git a/htdocs/admin/tools/update.php b/htdocs/admin/tools/update.php index 2bed274fd72..d2b5ed921a8 100644 --- a/htdocs/admin/tools/update.php +++ b/htdocs/admin/tools/update.php @@ -63,6 +63,12 @@ if ($action == 'getlastversion') { $result = getURLContent('https://sourceforge.net/projects/dolibarr/rss'); //var_dump($result['content']); if (function_exists('simplexml_load_string')) { + if (LIBXML_VERSION < 20900) { + // Avoid load of external entities (security problem). + // Required only if LIBXML_VERSION < 20900 + libxml_disable_entity_loader(true); + } + $sfurl = simplexml_load_string($result['content'], 'SimpleXMLElement', LIBXML_NOCDATA|LIBXML_NONET); } else { $sfurl = 'xml_not_available'; diff --git a/htdocs/admin/translation.php b/htdocs/admin/translation.php index b9ccec2a4f5..e23297cc251 100644 --- a/htdocs/admin/translation.php +++ b/htdocs/admin/translation.php @@ -40,13 +40,17 @@ $action = GETPOST('action', 'aZ09'); $optioncss = GETPOST('optionscss', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ09'); +$mode = GETPOST('mode', 'aZ09') ? GETPOST('mode', 'aZ09') : 'searchkey'; + $langcode = GETPOST('langcode', 'alphanohtml'); $transkey = GETPOST('transkey', 'alphanohtml'); -$transvalue = GETPOST('transvalue', 'restricthtml'); +if ($mode == 'searchkey') { + $transvalue = GETPOST('transvalue', 'alphanohtml'); +} else { + $transvalue = GETPOST('transvalue', 'restricthtml'); +} -$mode = GETPOST('mode', 'aZ09') ? GETPOST('mode', 'aZ09') : 'searchkey'; - $limit = GETPOST('limit', 'int') ? GETPOST('limit', 'int') : $conf->liste_limit; $sortfield = GETPOST('sortfield', 'aZ09comma'); $sortorder = GETPOST('sortorder', 'aZ09comma'); diff --git a/htdocs/admin/webhook.php b/htdocs/admin/webhook.php index 155606bc698..cc7527579aa 100644 --- a/htdocs/admin/webhook.php +++ b/htdocs/admin/webhook.php @@ -142,7 +142,7 @@ if ($action == 'updateMask') { $tmpobjectkey = GETPOST('object'); if (!empty($tmpobjectkey)) { $constforval = 'WEBHOOK_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; - if ($conf->global->$constforval == "$value") { + if (getDolGlobalString($constforval) == "$value") { dolibarr_del_const($db, $constforval, $conf->entity); } } @@ -270,7 +270,7 @@ if ($action == 'edit') { print dolJSToSetRandomPassword($constname, 'generate_token'.$constname); } elseif ($val['type'] == 'product') { if (isModEnabled("product") || isModEnabled("service")) { - $selected = (empty($conf->global->$constname) ? '' : $conf->global->$constname); + $selected = getDolGlobalString($constname); $form->select_produits($selected, $constname, '', 0); } } else { @@ -447,7 +447,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { print '
    '; $constforvar = 'WEBHOOK_'.strtoupper($myTmpObjectKey).'_ADDON'; - if ($conf->global->$constforvar == $file) { + if (getDolGlobalString($constforvar) == $file) { print img_picto($langs->trans("Activated"), 'switch_on'); } else { print ''; @@ -589,7 +589,7 @@ foreach ($myTmpObjects as $myTmpObjectKey => $myTmpObjectArray) { // Default print ''; $constforvar = 'WEBHOOK_'.strtoupper($myTmpObjectKey).'_ADDON'; - if ($conf->global->$constforvar == $name) { + if (getDolGlobalString($constforvar) == $name) { //print img_picto($langs->trans("Default"), 'on'); // Even if choice is the default value, we allow to disable it. Replace this with previous line if you need to disable unset print 'scandir).'&label='.urlencode($module->name).'&type='.urlencode($type).'" alt="'.$langs->trans("Disable").'">'.img_picto($langs->trans("Enabled"), 'on').''; diff --git a/htdocs/admin/website.php b/htdocs/admin/website.php index 44a394ebe8f..3a6d4639fbb 100644 --- a/htdocs/admin/website.php +++ b/htdocs/admin/website.php @@ -681,7 +681,7 @@ $db->close(); * @param string $context 'add'=Output field for the "add form", 'edit'=Output field for the "edit form", 'hide'=Output field for the "add form" but we dont want it to be rendered * @return void */ -function fieldListWebsites($fieldlist, $obj = '', $tabname = '', $context = '') +function fieldListWebsites($fieldlist, $obj = null, $tabname = '', $context = '') { global $conf, $langs, $db; global $form; diff --git a/htdocs/admin/workflow.php b/htdocs/admin/workflow.php index f5ff8ecea9a..4d7d3965a90 100644 --- a/htdocs/admin/workflow.php +++ b/htdocs/admin/workflow.php @@ -315,7 +315,7 @@ foreach ($workflowcodes as $key => $params) { if (!empty($conf->use_javascript_ajax)) { print ajax_constantonoff($key); } else { - if (!empty($conf->global->$key)) { + if (getDolGlobalString($key)) { print ''; print img_picto($langs->trans("Activated"), 'switch_on'); print ''; diff --git a/htdocs/admin/workstation.php b/htdocs/admin/workstation.php index e1a73810eb1..de2e7de2e74 100644 --- a/htdocs/admin/workstation.php +++ b/htdocs/admin/workstation.php @@ -120,7 +120,7 @@ if ($action == 'updateMask') { $ret = delDocumentModel($value, $type); if ($ret > 0) { $constforval = strtoupper($tmpobjectkey).'_ADDON_PDF'; - if ($conf->global->$constforval == "$value") { + if (getDolGlobalString($constforval) == "$value") { dolibarr_del_const($db, $constforval, $conf->entity); } } diff --git a/htdocs/api/class/api_login.class.php b/htdocs/api/class/api_login.class.php index 65db4155dae..cd8c4d3efb9 100644 --- a/htdocs/api/class/api_login.class.php +++ b/htdocs/api/class/api_login.class.php @@ -172,6 +172,10 @@ class Login } } + if (!ascii_check($token)) { + throw new RestException(500, 'Error the token for this user has not an hexa format. Try first to reset it.'); + } + //return token return array( 'success' => array( diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php index 292add085d2..0135fb5c413 100644 --- a/htdocs/api/class/api_setup.class.php +++ b/htdocs/api/class/api_setup.class.php @@ -1156,10 +1156,6 @@ class Setup extends DolibarrApi throw new RestException(503, 'Error when retrieving list of extra fields : '.$this->db->lasterror()); } - if (!count($list)) { - throw new RestException(404, 'No extrafield found'); - } - return $list; } @@ -2037,8 +2033,8 @@ class Setup extends DolibarrApi $xmlremote = $conf->global->MAIN_FILECHECK_URL; } $param = 'MAIN_FILECHECK_URL_'.DOL_VERSION; - if (empty($xmlremote) && !empty($conf->global->$param)) { - $xmlremote = $conf->global->$param; + if (empty($xmlremote) && getDolGlobalString($param)) { + $xmlremote = getDolGlobalString($param); } if (empty($xmlremote)) { $xmlremote = 'https://www.dolibarr.org/files/stable/signatures/filelist-'.DOL_VERSION.'.xml'; @@ -2052,6 +2048,12 @@ class Setup extends DolibarrApi throw new RestException(500, $langs->trans("ErrorURLMustEndWith", $xmlremote, '.xml')); } + if (LIBXML_VERSION < 20900) { + // Avoid load of external entities (security problem). + // Required only if LIBXML_VERSION < 20900 + libxml_disable_entity_loader(true); + } + if ($target == 'local') { if (dol_is_file($xmlfile)) { $xml = simplexml_load_file($xmlfile); @@ -2098,7 +2100,7 @@ class Setup extends DolibarrApi // Value found $value = ''; if ($constname && getDolGlobalString($constname) != '') { - $value = $conf->global->$constname; + $value = getDolGlobalString($constname); } $valueforchecksum = (empty($value) ? '0' : $value); diff --git a/htdocs/asset/admin/setup.php b/htdocs/asset/admin/setup.php index a184f667b8e..4232e60e481 100644 --- a/htdocs/asset/admin/setup.php +++ b/htdocs/asset/admin/setup.php @@ -139,7 +139,7 @@ if ($action == 'updateMask') { $tmpobjectkey = GETPOST('object'); if (!empty($tmpobjectkey)) { $constforval = 'ASSET_'.strtoupper($tmpobjectkey).'_ADDON_PDF'; - if ($conf->global->$constforval == "$value") { + if (getDolGlobalString($constforval) == "$value") { dolibarr_del_const($db, $constforval, $conf->entity); } } diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index a69c839f369..e5279635b2a 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -797,7 +797,7 @@ class BlockedLog * Encode data * * @param string $data Data to serialize - * @param string $mode 0=serialize, 1=json_encode + * @param int $mode 0=serialize, 1=json_encode * @return string Value serialized, an object (stdClass) */ public function dolEncodeBlockedData($data, $mode = 0) @@ -817,7 +817,7 @@ class BlockedLog * Decode data * * @param string $data Data to unserialize - * @param string $mode 0=unserialize, 1=json_decode + * @param int $mode 0=unserialize, 1=json_decode * @return object Value unserialized, an object (stdClass) */ public function dolDecodeBlockedData($data, $mode = 0) @@ -852,7 +852,7 @@ class BlockedLog * Create blocked log in database. * * @param User $user Object user that create - * @param int $forcesignature Force signature (for example '0000000000' when we disabled the module) + * @param string $forcesignature Force signature (for example '0000000000' when we disabled the module) * @return int Return integer <0 if KO, >0 if OK */ public function create($user, $forcesignature = '') diff --git a/htdocs/bom/bom_card.php b/htdocs/bom/bom_card.php index 816ad0190a8..f375004b4a4 100644 --- a/htdocs/bom/bom_card.php +++ b/htdocs/bom/bom_card.php @@ -590,7 +590,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ($res == 0 && $object->status >= $object::STATUS_VALIDATED) ? '' : load_fiche_titre($langs->trans('BOMProductsList'), '', 'product'); - print '
    + print ' @@ -642,7 +642,7 @@ if ($object->id > 0 && (empty($action) || ($action != 'edit' && $action != 'crea print ($res == 0 && $object->status >= $object::STATUS_VALIDATED) ? '' : load_fiche_titre($langs->trans('BOMServicesList'), '', 'service'); - print ' + print ' diff --git a/htdocs/bom/class/api_boms.class.php b/htdocs/bom/class/api_boms.class.php index 4b9ccda6b09..89633e0ac6e 100644 --- a/htdocs/bom/class/api_boms.class.php +++ b/htdocs/bom/class/api_boms.class.php @@ -182,9 +182,7 @@ class Boms extends DolibarrApi } else { throw new RestException(503, 'Error when retrieve bom list'); } - if (!count($obj_ret)) { - throw new RestException(404, 'No bom found'); - } + return $obj_ret; } @@ -559,7 +557,7 @@ class Boms extends DolibarrApi * * @return void */ - private function checkRefNumbering(): void + private function checkRefNumbering() { $ref = substr($this->bom->ref, 1, 4); if ($this->bom->status > 0 && $ref == 'PROV') { diff --git a/htdocs/bom/class/bom.class.php b/htdocs/bom/class/bom.class.php index 0dccb4b74e0..108de19475a 100644 --- a/htdocs/bom/class/bom.class.php +++ b/htdocs/bom/class/bom.class.php @@ -602,7 +602,7 @@ class BOM extends CommonObject * @param int $fk_default_workstation Default workstation * @return int Return integer <0 if KO, Id of created object if OK */ - public function addLine($fk_product, $qty, $qty_frozen = 0, $disable_stock_change = 0, $efficiency = 1.0, $position = -1, $fk_bom_child = null, $import_key = null, $fk_unit = '', $array_options = 0, $fk_default_workstation = null) + public function addLine($fk_product, $qty, $qty_frozen = 0, $disable_stock_change = 0, $efficiency = 1.0, $position = -1, $fk_bom_child = null, $import_key = null, $fk_unit = '', $array_options = array(), $fk_default_workstation = null) { global $mysoc, $conf, $langs, $user; @@ -710,7 +710,7 @@ class BOM extends CommonObject * @param int $fk_default_workstation Default workstation * @return int Return integer <0 if KO, Id of updated BOM-Line if OK */ - public function updateLine($rowid, $qty, $qty_frozen = 0, $disable_stock_change = 0, $efficiency = 1.0, $position = -1, $import_key = null, $fk_unit = 0, $array_options = 0, $fk_default_workstation = null) + public function updateLine($rowid, $qty, $qty_frozen = 0, $disable_stock_change = 0, $efficiency = 1.0, $position = -1, $import_key = null, $fk_unit = 0, $array_options = array(), $fk_default_workstation = null) { global $mysoc, $conf, $langs, $user; @@ -1594,7 +1594,7 @@ class BOM extends CommonObject * @param int $level Protection against infinite loop * @return void */ - public function getParentBomTreeRecursive(&$TParentBom, $bom_id = '', $level = 1) + public function getParentBomTreeRecursive(&$TParentBom, $bom_id = 0, $level = 1) { // Protection against infinite loop @@ -1656,7 +1656,7 @@ class BOM extends CommonObject $return .= '
    '.$prod->getNomUrl(1).''; } if (method_exists($this, 'getLibStatut')) { - $return .= '
    '.$this->getLibStatut(3).'
    '; + $return .= '
    '.$this->getLibStatut(3).'
    '; } $return .= ''; diff --git a/htdocs/bom/tpl/linkedobjectblock.tpl.php b/htdocs/bom/tpl/linkedobjectblock.tpl.php index d00340a1322..082936be50a 100644 --- a/htdocs/bom/tpl/linkedobjectblock.tpl.php +++ b/htdocs/bom/tpl/linkedobjectblock.tpl.php @@ -62,7 +62,7 @@ foreach ($linkedObjectBlock as $key => $objectlink) { $product_static->getNomUrl(1); } print '
    '.dol_print_date($objectlink->date_creation, 'day').''.dol_print_date($objectlink->date_creation, 'day').''; if ($user->hasRight('commande', 'lire')) { $total = $total + $objectlink->total_ht; diff --git a/htdocs/bom/tpl/objectline_create.tpl.php b/htdocs/bom/tpl/objectline_create.tpl.php index 3c96a80926f..db3991eac7d 100644 --- a/htdocs/bom/tpl/objectline_create.tpl.php +++ b/htdocs/bom/tpl/objectline_create.tpl.php @@ -127,7 +127,7 @@ if (isModEnabled("product") || isModEnabled("service")) { echo ''; } -if (getDolGlobalString('BOM_SUB_BOM') && $filtertype!=1) { +if (getDolGlobalString('BOM_SUB_BOM') && $filtertype != 1) { print '
    '.$langs->trans("or").'
    '.$langs->trans("BOM"); print $form->select_bom('', 'bom_id', 0, 1, 0, '1', '', 1); } diff --git a/htdocs/bom/tpl/objectline_view.tpl.php b/htdocs/bom/tpl/objectline_view.tpl.php index 035cc7784ed..65e2954c0e3 100644 --- a/htdocs/bom/tpl/objectline_view.tpl.php +++ b/htdocs/bom/tpl/objectline_view.tpl.php @@ -175,7 +175,7 @@ if ($filtertype != 1) { print '
    '; $coldisplay++; if ($res > 0) { - echo $workstation->getNomUrl(); + echo $workstation->getNomUrl(1); } print ''; print $object->price_level; $keyforlabel = 'PRODUIT_MULTIPRICES_LABEL'.$object->price_level; - if (!empty($conf->global->$keyforlabel)) { - print ' - '.$langs->trans($conf->global->$keyforlabel); + if (getDolGlobalString($keyforlabel)) { + print ' - '.$langs->trans(getDolGlobalString($keyforlabel)); } print "
    '.dol_escape_htmltag($label.' '.$objp->num_payment).'
    '.$langs->trans('PaymentMode').''.$labeltype; print $object->num_payment ? ' - '.$object->num_payment : ''; print '
    '; - if ($sumpaid <> $objp->amount) { + if ($sumpaid != $objp->amount) { $namef = "amount_".$objp->id; $nameRemain = "remain_".$objp->id; /* Disabled, we autofil the amount with remain to pay by default diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index 6ec256df84f..cee1d06260a 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -954,7 +954,7 @@ class BonPrelevement extends CommonObject * @param string $type 'direct-debit' or 'bank-transfer' * @param int $did ID of an existing payment request. If $did is defined, we use the existing payment request. * @param int $fk_bank_account Bank account ID the receipt is generated for. Will use the ID into the setup of module Direct Debit or Credit Transfer if 0. - * @param int $sourcetype 'invoice' or 'salary' + * @param string $sourcetype 'invoice' or 'salary' * @return int Return integer <0 if KO, No of invoice included into file if OK */ public function create($banque = 0, $agence = 0, $mode = 'real', $format = 'ALL', $executiondate = '', $notrigger = 0, $type = 'direct-debit', $did = 0, $fk_bank_account = 0, $sourcetype = 'invoice') @@ -1309,7 +1309,7 @@ class BonPrelevement extends CommonObject */ $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6], $type, $sourcetype); - if ($ri <> 0) { + if ($ri != 0) { $error++; } diff --git a/htdocs/compta/prelevement/create.php b/htdocs/compta/prelevement/create.php index 6e06696b6a1..f9cbe577064 100644 --- a/htdocs/compta/prelevement/create.php +++ b/htdocs/compta/prelevement/create.php @@ -111,7 +111,7 @@ if (empty($reshook)) { */ if ($action == 'create' && $permissiontocreate) { $default_account = ($type == 'bank-transfer' ? 'PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT' : 'PRELEVEMENT_ID_BANKACCOUNT'); - //var_dump($default_account);var_dump($conf->global->$default_account);var_dump($id_bankaccount);exit; + //var_dump($default_account);var_dump(getDolGlobalString($default_account));var_dump($id_bankaccount);exit; if ($id_bankaccount != getDolGlobalInt($default_account)) { $res = dolibarr_set_const($db, $default_account, $id_bankaccount, 'chaine', 0, '', $conf->entity); // Set as default diff --git a/htdocs/compta/resultat/clientfourn.php b/htdocs/compta/resultat/clientfourn.php index 6be43d6525d..31189af637a 100644 --- a/htdocs/compta/resultat/clientfourn.php +++ b/htdocs/compta/resultat/clientfourn.php @@ -90,6 +90,7 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e // We define date_start and date_end $year_end = $year_start; $month_start = GETPOST("month") ? GETPOST("month", 'int') : getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); + $month_end = ""; if (!GETPOST('month')) { if (!$year && $month_start > $month_current) { $year_start--; @@ -375,7 +376,7 @@ if ($modecompta == 'BOOKKEEPING') { } - if ($showaccountdetail == 'all' || $resultN <> 0) { + if ($showaccountdetail == 'all' || $resultN != 0) { print '
        '.length_accountg($cpt['account_number']).' - '.$cpt['account_label'].''; if ($modecompta == 'CREANCES-DETTES' || $modecompta == 'BOOKKEEPING') { if (isset($decaiss[$case]) && $decaiss[$case] != 0) { diff --git a/htdocs/compta/sociales/card.php b/htdocs/compta/sociales/card.php index 564de96b4f4..591d1c0a68b 100644 --- a/htdocs/compta/sociales/card.php +++ b/htdocs/compta/sociales/card.php @@ -719,7 +719,7 @@ if ($id > 0) { print ''.dol_print_date($db->jdate($objp->dp), 'day')."".$labeltype.' '.$objp->num_payment."'.price($totalpermonth[$j]).''.price((empty($totalpermonth[$j]) ? 0 : $totalpermonth[$j])).''.price($totalpermonth['total']).''.price((empty($totalpermonth['total']) ? 0 : $totalpermonth['total'])).'
    '; if ($annee < $year_end || ($annee == $year_end && $mois <= $month_end)) { - if ($cum_ht[$case]) { + if (!empty($cum_ht[$case])) { $now_show_delta = 1; // On a trouve le premier mois de la premiere annee generant du chiffre. print ''.price($cum_ht[$case], 1).''; } else { diff --git a/htdocs/compta/stats/supplier_turnover.php b/htdocs/compta/stats/supplier_turnover.php index 245967dcd8b..3a78dc0c6a4 100644 --- a/htdocs/compta/stats/supplier_turnover.php +++ b/htdocs/compta/stats/supplier_turnover.php @@ -328,7 +328,8 @@ $now_show_delta = 0; $minyear = substr($minyearmonth, 0, 4); $maxyear = substr($maxyearmonth, 0, 4); $nowyear = dol_print_date(dol_now('gmt'), "%Y", 'gmt'); -$nowyearmonth = strftime("%Y-%m", dol_now()); +//$nowyearmonth = strftime("%Y-%m", dol_now()); +$nowyearmonth = dol_print_date(dol_now(), "%Y-%m"); $maxyearmonth = max($maxyearmonth, $nowyearmonth); $now = dol_now(); $casenow = dol_print_date($now, "%Y-%m"); diff --git a/htdocs/compta/tva/card.php b/htdocs/compta/tva/card.php index 0b89a923153..65d8cb7de58 100644 --- a/htdocs/compta/tva/card.php +++ b/htdocs/compta/tva/card.php @@ -713,7 +713,7 @@ if ($id > 0) { print ''.img_object($langs->trans("Payment"), "payment").' '.$objp->rowid.''; print ''.dol_print_date($db->jdate($objp->dp), 'day')."".$labeltype.' '.$objp->num_payment."
    '."\n"; @@ -1030,7 +1036,7 @@ print '
    '; // Action column if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { - print ''; diff --git a/htdocs/contrat/class/api_contracts.class.php b/htdocs/contrat/class/api_contracts.class.php index 523eb59ea03..51c3d63d412 100644 --- a/htdocs/contrat/class/api_contracts.class.php +++ b/htdocs/contrat/class/api_contracts.class.php @@ -181,9 +181,7 @@ class Contracts extends DolibarrApi } else { throw new RestException(503, 'Error when retrieve contrat list : '.$this->db->lasterror()); } - if (!count($obj_ret)) { - throw new RestException(404, 'No contract found'); - } + return $obj_ret; } diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index 8cbf96992c9..ac760bd8ecc 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -1474,10 +1474,10 @@ class Contrat extends CommonObject * @param int $pa_ht Buying price HT * @param array $array_options extrafields array * @param string $fk_unit Code of the unit to use. Null to use the default one - * @param string $rang Position + * @param int $rang Position * @return int Return integer <0 if KO, >0 if OK */ - public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type = 'HT', $pu_ttc = 0.0, $info_bits = 0, $fk_fournprice = null, $pa_ht = 0, $array_options = 0, $fk_unit = null, $rang = 0) + public function addline($desc, $pu_ht, $qty, $txtva, $txlocaltax1, $txlocaltax2, $fk_product, $remise_percent, $date_start, $date_end, $price_base_type = 'HT', $pu_ttc = 0.0, $info_bits = 0, $fk_fournprice = null, $pa_ht = 0, $array_options = array(), $fk_unit = null, $rang = 0) { global $user, $langs, $conf, $mysoc; $error = 0; @@ -1706,10 +1706,10 @@ class Contrat extends CommonObject * @param int $pa_ht Buying price HT * @param array $array_options extrafields array * @param string $fk_unit Code of the unit to use. Null to use the default one - * @param string $rang Position + * @param int $rang Position * @return int Return integer <0 if KO, >0 if OK */ - public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx = 0.0, $localtax2tx = 0.0, $date_start_real = '', $date_end_real = '', $price_base_type = 'HT', $info_bits = 0, $fk_fournprice = null, $pa_ht = 0, $array_options = 0, $fk_unit = null, $rang = 0) + public function updateline($rowid, $desc, $pu, $qty, $remise_percent, $date_start, $date_end, $tvatx, $localtax1tx = 0.0, $localtax2tx = 0.0, $date_start_real = '', $date_end_real = '', $price_base_type = 'HT', $info_bits = 0, $fk_fournprice = null, $pa_ht = 0, $array_options = array(), $fk_unit = null, $rang = 0) { global $user, $conf, $langs, $mysoc; @@ -2943,7 +2943,7 @@ class Contrat extends CommonObject $return .= '
    '.$langs->trans("DateContract").' : '.dol_print_date($this->date_contrat, 'day').''; } if (method_exists($this, 'getLibStatut')) { - $return .= '
    '.$this->getLibStatut(7).'
    '; + $return .= '
    '.$this->getLibStatut(7).'
    '; } $return .= ''; $return .= ''; diff --git a/htdocs/contrat/contact.php b/htdocs/contrat/contact.php index 661b316df59..980fa5f29fb 100644 --- a/htdocs/contrat/contact.php +++ b/htdocs/contrat/contact.php @@ -3,6 +3,7 @@ * Copyright (C) 2005-2009 Destailleur Laurent * Copyright (C) 2005-2012 Regis Houssin * Copyright (C) 2017 Ferran Marcet + * Copyright (C) 2023 Christian Foellmann * * 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 @@ -51,7 +52,7 @@ if ($user->socid) { $object = new Contrat($db); // Initialize technical object to manage hooks of page. Note that conf->hooks_modules contains array of hook context -$hookmanager->initHooks(array('contractcard', 'globalcard')); +$hookmanager->initHooks(array('contractcontactcard', 'globalcard')); $permissiontoadd = $user->hasRight('contrat', 'creer'); // Used by the include of actions_addupdatedelete.inc.php and actions_lineupdown.inc.php @@ -62,51 +63,59 @@ $result = restrictedArea($user, 'contrat', $object->id); * Actions */ -if ($action == 'addcontact' && $user->hasRight('contrat', 'creer')) { - $result = $object->fetch($id); +$parameters = array('id'=>$id); +$reshook = $hookmanager->executeHooks('doActions', $parameters, $object, $action); +if ($reshook < 0) { + setEventMessages($hookmanager->error, $hookmanager->errors, 'errors'); +} - if ($result > 0 && $id > 0) { - $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); - $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); - $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); - } +if (empty($reshook)) { + // Add new contact + if ($action == 'addcontact' && $user->hasRight('contrat', 'creer')) { + $result = $object->fetch($id); - if ($result >= 0) { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } else { - if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { - $langs->load("errors"); - $msg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); - } else { - $mesg = $object->error; + if ($result > 0 && $id > 0) { + $contactid = (GETPOST('userid') ? GETPOST('userid') : GETPOST('contactid')); + $typeid = (GETPOST('typecontact') ? GETPOST('typecontact') : GETPOST('type')); + $result = $object->add_contact($contactid, $typeid, GETPOST("source", 'aZ09')); } - setEventMessages($mesg, null, 'errors'); + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } else { + if ($object->error == 'DB_ERROR_RECORD_ALREADY_EXISTS') { + $langs->load("errors"); + $msg = $langs->trans("ErrorThisContactIsAlreadyDefinedAsThisType"); + } else { + $mesg = $object->error; + } + + setEventMessages($mesg, null, 'errors'); + } + } + + // Toggle the status of a contact + if ($action == 'swapstatut' && $user->hasRight('contrat', 'creer')) { + if ($object->fetch($id)) { + $result = $object->swapContactStatus(GETPOST('ligne', 'int')); + } else { + dol_print_error($db, $object->error); + } + } + + // Delete contact + if ($action == 'deletecontact' && $user->hasRight('contrat', 'creer')) { + $object->fetch($id); + $result = $object->delete_contact(GETPOST("lineid", 'int')); + + if ($result >= 0) { + header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); + exit; + } } } -// bascule du statut d'un contact -if ($action == 'swapstatut' && $user->hasRight('contrat', 'creer')) { - if ($object->fetch($id)) { - $result = $object->swapContactStatus(GETPOST('ligne', 'int')); - } else { - dol_print_error($db, $object->error); - } -} - -// Delete contact -if ($action == 'deletecontact' && $user->hasRight('contrat', 'creer')) { - $object->fetch($id); - $result = $object->delete_contact(GETPOST("lineid", 'int')); - - if ($result >= 0) { - header("Location: ".$_SERVER['PHP_SELF']."?id=".$object->id); - exit; - } -} - - /* * View */ diff --git a/htdocs/core/actions_addupdatedelete.inc.php b/htdocs/core/actions_addupdatedelete.inc.php index 8adc3d1f886..754e3eceda3 100644 --- a/htdocs/core/actions_addupdatedelete.inc.php +++ b/htdocs/core/actions_addupdatedelete.inc.php @@ -95,7 +95,7 @@ if ($action == 'add' && !empty($permissiontoadd)) { } elseif ($object->fields[$key]['type'] == 'datetime') { $value = dol_mktime(GETPOST($key.'hour', 'int'), GETPOST($key.'min', 'int'), GETPOST($key.'sec', 'int'), GETPOST($key.'month', 'int'), GETPOST($key.'day', 'int'), GETPOST($key.'year', 'int'), 'tzuserrel'); } elseif ($object->fields[$key]['type'] == 'duration') { - $value = 60 * 60 * GETPOST($key.'hour', 'int') + 60 * GETPOST($key.'min', 'int'); + $value = 60 * 60 * GETPOSTINT($key.'hour') + 60 * GETPOSTINT($key.'min'); } elseif (preg_match('/^(integer|price|real|double)/', $object->fields[$key]['type'])) { $value = price2num(GETPOST($key, 'alphanohtml')); // To fix decimal separator according to lang setup } elseif ($object->fields[$key]['type'] == 'boolean') { diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index 6fbe2440fb3..ebc6d5fe3ae 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -411,7 +411,6 @@ if (($action == 'send' || $action == 'relance') && !GETPOST('addfile') && !GETPO $object->email_tocc = $sendtocc; $object->email_tobcc = $sendtobcc; $object->email_subject = $subject; - $object->email_msgid = $mailfile->msgid; // Call of triggers (you should have set $triggersendname to execute trigger. $trigger_name is deprecated) if (!empty($triggersendname) || !empty($trigger_name)) { diff --git a/htdocs/core/ajax/check_notifications.php b/htdocs/core/ajax/check_notifications.php index 6eb10d15e34..3a56d1df6d3 100644 --- a/htdocs/core/ajax/check_notifications.php +++ b/htdocs/core/ajax/check_notifications.php @@ -128,7 +128,9 @@ if (empty($_SESSION['auto_check_events_not_before']) || $time >= $_SESSION['auto $sql = 'SELECT a.id as id_agenda, a.code, a.datep, a.label, a.location, ar.rowid as id_reminder, ar.dateremind, ar.fk_user as id_user_reminder'; $sql .= ' FROM '.MAIN_DB_PREFIX.'actioncomm as a'; $sql .= ' INNER JOIN '.MAIN_DB_PREFIX.'actioncomm_reminder as ar ON a.id = ar.fk_actioncomm AND ar.fk_user = '.((int) $user->id); - $sql .= " AND ar.typeremind = 'browser' AND ar.dateremind < '".$db->idate(dol_now())."' AND ar.status = 0 AND ar.entity = ".((int) $conf->entity); // No sharing of entity for alerts + $sql .= " AND ar.typeremind = 'browser' AND ar.dateremind < '".$db->idate(dol_now())."'"; + $sql .= " AND ar.status = 0"; + $sql .= " AND ar.entity = ".((int) $conf->entity); // No sharing of entity for alerts $sql .= $db->order('datep', 'ASC'); $sql .= $db->plimit(10); // Avoid too many notification at once diff --git a/htdocs/core/ajax/fileupload.php b/htdocs/core/ajax/fileupload.php index 177154cee3a..25ea79b1939 100644 --- a/htdocs/core/ajax/fileupload.php +++ b/htdocs/core/ajax/fileupload.php @@ -18,7 +18,7 @@ /** * \file htdocs/core/ajax/fileupload.php - * \brief File to return Ajax response on file upload + * \brief File to return Ajax response on common file upload. For large files, see flowjs-server.php */ if (!defined('NOREQUIREMENU')) { @@ -36,8 +36,9 @@ if (!defined('NOREQUIRESOC')) { // Load Dolibarr environment require '../../main.inc.php'; -require_once DOL_DOCUMENT_ROOT.'/core/class/fileupload.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/fileupload.class.php'; // Class to upload common files require_once DOL_DOCUMENT_ROOT.'/core/class/genericobject.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/lib/geturl.lib.php'; $id = GETPOST('fk_element', 'int'); $element = GETPOST('element', 'alpha'); // 'myobject' (myobject=mymodule) or 'myobject@mymodule' or 'myobject_mysubobject' (myobject=mymodule) @@ -83,7 +84,7 @@ header('Pragma: no-cache'); header('Cache-Control: no-store, no-cache, must-revalidate'); header('Content-Disposition: inline; filename="files.json"'); header('X-Content-Type-Options: nosniff'); -header('Access-Control-Allow-Origin: *'); +header('Access-Control-Allow-Origin: '.getRootURLFromURL(DOL_MAIN_URL_ROOT)); header('Access-Control-Allow-Methods: OPTIONS, HEAD, GET, POST, PUT, DELETE'); header('Access-Control-Allow-Headers: X-File-Name, X-File-Type, X-File-Size'); diff --git a/htdocs/core/ajax/onlineSign.php b/htdocs/core/ajax/onlineSign.php index 1ef36091082..49afbcc0953 100644 --- a/htdocs/core/ajax/onlineSign.php +++ b/htdocs/core/ajax/onlineSign.php @@ -70,6 +70,12 @@ $type = $mode; $securekeyseed = ''; if ($type == 'proposal') { $securekeyseed = getDolGlobalString('PROPOSAL_ONLINE_SIGNATURE_SECURITY_TOKEN'); +} elseif ($type == 'contract') { + $securekeyseed = getDolGlobalString('CONTRACT_ONLINE_SIGNATURE_SECURITY_TOKEN'); +} elseif ($type == 'fichinter') { + $securekeyseed = getDolGlobalString('FICHINTER_ONLINE_SIGNATURE_SECURITY_TOKEN'); +} else { + $securekeyseed = getDolGlobalString(strtoupper($type).'_ONLINE_SIGNATURE_SECURITY_TOKEN'); } if (empty($SECUREKEY) || !dol_verifyHash($securekeyseed . $type . $ref . (!isModEnabled('multicompany') ? '' : $entity), $SECUREKEY, '0')) { @@ -152,6 +158,10 @@ if ($action == "importSignature") { //$pdf->Open(); $pagecount = $pdf->setSourceFile($sourcefile); // original PDF + $param = array(); + $param['online_sign_name'] = $online_sign_name; + $param['pathtoimage'] = $upload_dir . $filename; + $s = array(); // Array with size of each page. Exemple array(w'=>210, 'h'=>297); for ($i = 1; $i < ($pagecount + 1); $i++) { try { @@ -159,6 +169,17 @@ if ($action == "importSignature") { $s = $pdf->getTemplatesize($tppl); $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); $pdf->useTemplate($tppl); + + if (getDolGlobalString("PROPAL_SIGNATURE_ON_ALL_PAGES")) { + // A signature image file is 720 x 180 (ratio 1/4) but we use only the size into PDF + // TODO Get position of box from PDF template + + $param['xforimgstart'] = (empty($s['w']) ? 120 : round($s['w'] / 2) + 15); + $param['yforimgstart'] = (empty($s['h']) ? 240 : $s['h'] - 60); + $param['wforimg'] = $s['w'] - 20 - $param['xforimgstart']; + + dolPrintSignatureImage($pdf, $langs, $param); + } } catch (Exception $e) { dol_syslog("Error when manipulating the PDF " . $sourcefile . " by onlineSign: " . $e->getMessage(), LOG_ERR); $response = $e->getMessage(); @@ -166,19 +187,16 @@ if ($action == "importSignature") { } } - // A signature image file is 720 x 180 (ratio 1/4) but we use only the size into PDF - // TODO Get position of box from PDF template - $xforimgstart = (empty($s['w']) ? 120 : round($s['w'] / 2) + 15); - $yforimgstart = (empty($s['h']) ? 240 : $s['h'] - 60); - $wforimg = $s['w'] - 20 - $xforimgstart; + if (!getDolGlobalString("PROPAL_SIGNATURE_ON_ALL_PAGES")) { + // A signature image file is 720 x 180 (ratio 1/4) but we use only the size into PDF + // TODO Get position of box from PDF template - $pdf->SetXY($xforimgstart, $yforimgstart + round($wforimg / 4) - 4); - $pdf->SetFont($default_font, '', $default_font_size - 1); - $pdf->MultiCell($wforimg, 4, $langs->trans("DateSigning") . ': ' . dol_print_date(dol_now(), "daytext", false, $langs, true), 0, 'L'); - $pdf->SetXY($xforimgstart, $yforimgstart + round($wforimg / 4)); - $pdf->MultiCell($wforimg, 4, $langs->trans("Lastname") . ': ' . $online_sign_name, 0, 'L'); + $param['xforimgstart'] = (empty($s['w']) ? 120 : round($s['w'] / 2) + 15); + $param['yforimgstart'] = (empty($s['h']) ? 240 : $s['h'] - 60); + $param['wforimg'] = $s['w'] - 20 - $param['xforimgstart']; - $pdf->Image($upload_dir . $filename, $xforimgstart, $yforimgstart, $wforimg, round($wforimg / 4)); + dolPrintSignatureImage($pdf, $langs, $param); + } //$pdf->Close(); $pdf->Output($newpdffilename, "F"); @@ -294,9 +312,13 @@ if ($action == "importSignature") { $pdf->SetCompression(false); } - //$pdf->Open(); $pagecount = $pdf->setSourceFile($sourcefile); // original PDF + + $param = array(); + $param['online_sign_name'] = $online_sign_name; + $param['pathtoimage'] = $upload_dir . $filename; + $s = array(); // Array with size of each page. Exemple array(w'=>210, 'h'=>297); for ($i = 1; $i < ($pagecount + 1); $i++) { try { @@ -304,6 +326,17 @@ if ($action == "importSignature") { $s = $pdf->getTemplatesize($tppl); $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); $pdf->useTemplate($tppl); + + if (getDolGlobalString("CONTRACT_SIGNATURE_ON_ALL_PAGES")) { + // A signature image file is 720 x 180 (ratio 1/4) but we use only the size into PDF + // TODO Get position of box from PDF template + + $param['xforimgstart'] = 10; + $param['yforimgstart'] = (empty($s['h']) ? 240 : $s['h'] - 65); + $param['wforimg'] = $s['w'] / 2 - $param['xforimgstart']; + + dolPrintSignatureImage($pdf, $langs, $param); + } } catch (Exception $e) { dol_syslog("Error when manipulating some PDF by onlineSign: " . $e->getMessage(), LOG_ERR); $response = $e->getMessage(); @@ -311,13 +344,17 @@ if ($action == "importSignature") { } } - // A signature image file is 720 x 180 (ratio 1/4) but we use only the size into PDF - // TODO Get position of box from PDF template - $xforimgstart = 5; - $yforimgstart = (empty($s['h']) ? 240 : $s['h'] - 65); - $wforimg = $s['w'] / 2 - $xforimgstart; + if (!getDolGlobalString("CONTRACT_SIGNATURE_ON_ALL_PAGES")) { + // A signature image file is 720 x 180 (ratio 1/4) but we use only the size into PDF + // TODO Get position of box from PDF template + + $param['xforimgstart'] = 10; + $param['yforimgstart'] = (empty($s['h']) ? 240 : $s['h'] - 65); + $param['wforimg'] = $s['w'] / 2 - $param['xforimgstart']; + + dolPrintSignatureImage($pdf, $langs, $param); + } - $pdf->Image($upload_dir . $filename, $xforimgstart, $yforimgstart, $wforimg, round($wforimg / 4)); //$pdf->Close(); $pdf->Output($newpdffilename, "F"); @@ -388,9 +425,13 @@ if ($action == "importSignature") { $pdf->SetCompression(false); } - //$pdf->Open(); $pagecount = $pdf->setSourceFile($sourcefile); // original PDF + + $param = array(); + $param['online_sign_name'] = $online_sign_name; + $param['pathtoimage'] = $upload_dir . $filename; + $s = array(); // Array with size of each page. Exemple array(w'=>210, 'h'=>297); for ($i = 1; $i < ($pagecount + 1); $i++) { try { @@ -398,6 +439,17 @@ if ($action == "importSignature") { $s = $pdf->getTemplatesize($tppl); $pdf->AddPage($s['h'] > $s['w'] ? 'P' : 'L'); $pdf->useTemplate($tppl); + + if (getDolGlobalString("FICHINTER_SIGNATURE_ON_ALL_PAGES")) { + // A signature image file is 720 x 180 (ratio 1/4) but we use only the size into PDF + // TODO Get position of box from PDF template + + $param['xforimgstart'] = 111; + $param['yforimgstart'] = (empty($s['h']) ? 250 : $s['h'] - 60); + $param['wforimg'] = $s['w'] - ($param['xforimgstart'] + 16); + + dolPrintSignatureImage($pdf, $langs, $param); + } } catch (Exception $e) { dol_syslog("Error when manipulating some PDF by onlineSign: " . $e->getMessage(), LOG_ERR); $response = $e->getMessage(); @@ -405,23 +457,17 @@ if ($action == "importSignature") { } } - // A signature image file is 720 x 180 (ratio 1/4) but we use only the size into PDF + if (!getDolGlobalString("FICHINTER_SIGNATURE_ON_ALL_PAGES")) { + // A signature image file is 720 x 180 (ratio 1/4) but we use only the size into PDF + // TODO Get position of box from PDF template + $param['xforimgstart'] = 111; + $param['yforimgstart'] = (empty($s['h']) ? 250 : $s['h'] - 60); + $param['wforimg'] = $s['w'] - ($param['xforimgstart'] + 16); + dolPrintSignatureImage($pdf, $langs, $param); + } - // TODO Get position of box from PDF template - $xforimgstart = 105; - $yforimgstart = (empty($s['h']) ? 250 : $s['h'] - 57); - - $wforimg = $s['w'] / 1 - ($xforimgstart + 16); - - $pdf->SetXY(111, 235 +25); - $pdf->SetFont($default_font, '', $default_font_size - 1); - $pdf->MultiCell($wforimg, 4, $langs->trans("DateSigning").': '.dol_print_date(dol_now(), "daytext", false, $langs, true), 0, 'L'); - $pdf->SetXY(111, $pdf->GetY()); - $pdf->MultiCell($wforimg, 4, $langs->trans("Lastname").': '.$online_sign_name, 0, 'L'); - - $pdf->Image($upload_dir.$filename, $xforimgstart, $yforimgstart, $wforimg, round($wforimg / 4)); //$pdf->Close(); $pdf->Output($newpdffilename, "F"); @@ -450,8 +496,7 @@ if ($action == "importSignature") { $object->fetch_thirdparty(); - $upload_dir = $conf->societe->multidir_output[$object->thirdparty->entity] . '/' - . dol_sanitizeFileName($object->thirdparty->id) . '/'; + $upload_dir = $conf->societe->multidir_output[$object->thirdparty->entity] . '/' . dol_sanitizeFileName($object->thirdparty->id) . '/'; $default_font_size = pdf_getPDFFontSize($langs); // Must be after pdf_getInstance $default_font = pdf_getPDFFont($langs); // Must be after pdf_getInstance @@ -563,11 +608,18 @@ if ($action == "importSignature") { $yforimgstart = $yForDate - 5; $wforimg = $s['w'] - 20 - $xforimgstart; - $pdf->SetXY($xforimgstart, $yforimgstart + round($wforimg / 4)); - $pdf->MultiCell($wforimg, 4, $langs->trans("Lastname") . ': ' . $online_sign_name, 0, 'L'); + $param = array(); + $param['online_sign_name'] = $online_sign_name; + $param['pathtoimage'] = $upload_dir . $filename; // A signature image file is 720 x 180 (ratio 1/4) but we use only the size into PDF - $pdf->Image($upload_dir . $filename, $xforimgstart, $yforimgstart, $wforimg, round($wforimg / 4)); + // TODO Get position of box from PDF template + + $param['xforimgstart'] = $xforimgstart; + $param['yforimgstart'] = $yforimgstart; + $param['wforimg'] = $wforimg; + + dolPrintSignatureImage($pdf, $langs, $param); } //$pdf->Close(); $pdf->Output($newpdffilename, "F"); @@ -639,3 +691,32 @@ if ($error) { } echo $response; + + +/** + * Output the signature file + * + * @param TCPDF $pdf PDF handler + * @param Translate $langs Language + * @param array $params Array of params + * @return void + */ +function dolPrintSignatureImage(TCPDF $pdf, $langs, $params) +{ + $default_font_size = pdf_getPDFFontSize($langs); // Must be after pdf_getInstance + $default_font = pdf_getPDFFont($langs); // Must be + $xforimgstart = $params['xforimgstart']; + $yforimgstart = $params['yforimgstart']; + $wforimg = $params['wforimg']; + + $pdf->SetXY($xforimgstart, $yforimgstart + round($wforimg / 4) - 4); + $pdf->SetFont($default_font, '', $default_font_size - 1); + $pdf->SetTextColor(80, 80, 80); + $pdf->MultiCell($wforimg, 4, $langs->trans("Signature") . ': ' . dol_print_date(dol_now(), "day", false, $langs, true). ' - '.$params['online_sign_name'], 0, 'L'); + //$pdf->SetXY($xforimgstart, $yforimgstart + round($wforimg / 4)); + //$pdf->MultiCell($wforimg, 4, $langs->trans("Lastname") . ': ' . $online_sign_name, 0, 'L'); + + $pdf->Image($params['pathtoimage'], $xforimgstart, $yforimgstart, $wforimg, round($wforimg / 4)); + + return; +} diff --git a/htdocs/core/ajax/selectobject.php b/htdocs/core/ajax/selectobject.php index 14372a405b4..edc5eb32998 100644 --- a/htdocs/core/ajax/selectobject.php +++ b/htdocs/core/ajax/selectobject.php @@ -39,34 +39,92 @@ if (!defined('NOREQUIRESOC')) { // Load Dolibarr environment require '../../main.inc.php'; require_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; +require_once DOL_DOCUMENT_ROOT.'/core/class/extrafields.class.php'; -$objectdesc = GETPOST('objectdesc', 'alpha'); +$extrafields = new ExtraFields($db); + +$objectdesc = GETPOST('objectdesc', 'alphanohtml', 0, null, null, 1); $htmlname = GETPOST('htmlname', 'aZ09'); $outjson = (GETPOST('outjson', 'int') ? GETPOST('outjson', 'int') : 0); -$id = GETPOST('id', 'int'); -$filter = GETPOST('filter', 'alphanohtml'); // Universal Syntax filter +$id = GETPOSTINT('id'); +$objectfield = GETPOST('objectfield', 'alpha'); // 'MyObject:field' or 'MyModule_MyObject:field' or 'MyObject:option_field' or 'MyModule_MyObject:option_field' if (empty($htmlname)) { httponly_accessforbidden('Bad value for param htmlname'); } -$InfoFieldList = explode(":", $objectdesc); -$classname = $InfoFieldList[0]; -$classpath = $InfoFieldList[1]; -if (!empty($classpath)) { - dol_include_once($classpath); - if ($classname && class_exists($classname)) { - $objecttmp = new $classname($db); +if (!empty($objectfield)) { + // Recommended method to call selectobject. + // $objectfield is Object:Field that contains the definition (in table $fields or extrafield). Example: 'Societe:t.ddd' or 'Societe:options_xxx' + + $tmparray = explode(':', $objectfield); + $objectdesc = ''; + + // Load object according to $id and $element + $objectforfieldstmp = fetchObjectByElement(0, strtolower($tmparray[0])); + + $reg = array(); + if (preg_match('/^options_(.*)$/', $tmparray[1], $reg)) { + // For a property in extrafields + $key = $reg[1]; + // fetch optionals attributes and labels + $extrafields->fetch_name_optionals_label($objectforfieldstmp->table_element); + + if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key]) && $extrafields->attributes[$objectforfieldstmp->table_element]['type'][$key] == 'link') { + if (!empty($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options'])) { + $tmpextrafields = array_keys($extrafields->attributes[$objectforfieldstmp->table_element]['param'][$key]['options']); + $objectdesc = $tmpextrafields[0]; + } + } + } else { + // For a property in ->fields + $objectdesc = $objectforfieldstmp->fields[$tmparray[1]]['type']; + $objectdesc = preg_replace('/^integer[^:]*:/', '', $objectdesc); } } -if (!is_object($objecttmp)) { - httponly_accessforbidden('Bad value for param objectdesc'); + +if ($objectdesc) { + // Example of value for $objectdesc: + // Bom:bom/class/bom.class.php:0:t.status=1 + // Bom:bom/class/bom.class.php:0:t.status=1:ref + // Bom:bom/class/bom.class.php:0:(t.status:=:1) OR (t.field2:=:2):ref + $InfoFieldList = explode(":", $objectdesc, 4); + $vartmp = (empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]); + $reg = array(); + if (preg_match('/^.*:(\w*)$/', $vartmp, $reg)) { + $InfoFieldList[4] = $reg[1]; // take the sort field + } + $InfoFieldList[3] = preg_replace('/:\w*$/', '', $vartmp); // take the filter field + + $classname = $InfoFieldList[0]; + $classpath = $InfoFieldList[1]; + //$addcreatebuttonornot = empty($InfoFieldList[2]) ? 0 : $InfoFieldList[2]; + $filter = empty($InfoFieldList[3]) ? '' : $InfoFieldList[3]; + $sortfield = empty($InfoFieldList[4]) ? '' : $InfoFieldList[4]; + + // Load object according to $id and $element + $objecttmp = fetchObjectByElement(0, strtolower($InfoFieldList[0])); + + // Fallback to another solution to get $objecttmp + if (empty($objecttmp) && !empty($classpath)) { + dol_include_once($classpath); + + if ($classname && class_exists($classname)) { + $objecttmp = new $classname($db); + } + } } -/* -// Load object according to $id and $element -$object = fetchObjectByElement($id, $element); +// Make some replacement +$sharedentities = getEntity(strtolower($objecttmp->element)); +$filter = str_replace( + array('__ENTITY__', '__SHARED_ENTITIES__', '__USER_ID__', '$ID$'), + array($conf->entity, $sharedentities, $user->id, $id), + $filter +); + +/* $module = $object->module; $element = $object->element; $usesublevelpermission = ($module != $element ? $element : ''); @@ -86,15 +144,13 @@ restrictedArea($user, $objecttmp->element, $id); * View */ -//print ''."\n"; -//print_r($_GET); - -//$langs->load("companies"); - $form = new Form($db); top_httphead($outjson ? 'application/json' : 'text/html'); +//print ''."\n"; +//print_r($_GET); + $arrayresult = $form->selectForFormsList($objecttmp, $htmlname, '', 0, $searchkey, '', '', '', 0, 1, 0, '', $filter); $db->close(); diff --git a/htdocs/core/boxes/box_external_rss.php b/htdocs/core/boxes/box_external_rss.php index 2e4c87c8e2b..f8b7e424a0d 100644 --- a/htdocs/core/boxes/box_external_rss.php +++ b/htdocs/core/boxes/box_external_rss.php @@ -89,7 +89,7 @@ class box_external_rss extends ModeleBoxes $keyforparamtitle = "EXTERNAL_RSS_TITLE_".$site; // Get RSS feed - $url = $conf->global->$keyforparamurl; + $url = getDolGlobalString($keyforparamurl); $rssparser = new RssParser($this->db); $result = $rssparser->parser($url, $this->max, $cachedelay, $conf->externalrss->dir_temp); @@ -98,7 +98,7 @@ class box_external_rss extends ModeleBoxes $description = $rssparser->getDescription(); $link = $rssparser->getLink(); - $title = $langs->trans("BoxTitleLastRssInfos", $max, $conf->global->$keyforparamtitle); + $title = $langs->trans("BoxTitleLastRssInfos", $max, getDolGlobalString($keyforparamtitle)); if ($result < 0 || !empty($rssparser->error)) { // Show warning $errormessage = $langs->trans("FailedToRefreshDataInfoNotUpToDate", ($rssparser->getLastFetchDate() ? dol_print_date($rssparser->getLastFetchDate(), "dayhourtext") : $langs->trans("Unknown"))); diff --git a/htdocs/core/boxes/box_funnel_of_prospection.php b/htdocs/core/boxes/box_funnel_of_prospection.php index 257f351cfca..b2cc183fc2a 100644 --- a/htdocs/core/boxes/box_funnel_of_prospection.php +++ b/htdocs/core/boxes/box_funnel_of_prospection.php @@ -26,6 +26,7 @@ */ include_once DOL_DOCUMENT_ROOT."/core/boxes/modules_boxes.php"; + /** * Class to manage the box to show funnel of prospections */ @@ -56,7 +57,7 @@ class box_funnel_of_prospection extends ModeleBoxes */ public function __construct($db, $param = '') { - global $user, $langs, $conf; + global $user, $langs; // Load translation files required by the page $langs->loadLangs(array('boxes', 'projects')); @@ -64,6 +65,7 @@ class box_funnel_of_prospection extends ModeleBoxes $this->db = $db; $this->enabled = (getDolGlobalInt('MAIN_FEATURES_LEVEL') >= 1 ? 1 : 0); // Not enabled by default, still need some work + //$this->enabled = 1; $this->hidden = empty($user->rights->projet->lire); } @@ -102,6 +104,7 @@ class box_funnel_of_prospection extends ModeleBoxes $sql .= " FROM ".MAIN_DB_PREFIX."c_lead_status as cls"; $sql .= " WHERE active=1"; $sql .= " AND cls.code <> 'LOST'"; + $sql .= " AND cls.code <> 'WON'"; $sql .= $this->db->order('cls.rowid', 'ASC'); $resql = $this->db->query($sql); if ($resql) { @@ -126,9 +129,6 @@ class box_funnel_of_prospection extends ModeleBoxes case 'NEGO': $colorseriesstat[$objp->rowid] = $badgeStatus4; break; - case 'WON': - $colorseriesstat[$objp->rowid] = $badgeStatus6; - break; default: break; } @@ -143,6 +143,7 @@ class box_funnel_of_prospection extends ModeleBoxes $this->info_box_head = array( 'text' => $langs->trans("Statistics").' - '.$langs->trans("BoxTitleFunnelOfProspection"), + 'nbcol' => '2', 'graph' => '1' ); @@ -152,7 +153,7 @@ class box_funnel_of_prospection extends ModeleBoxes $sql .= " WHERE p.entity IN (".getEntity('project').")"; $sql .= " AND p.fk_opp_status = cls.rowid"; $sql .= " AND p.fk_statut = 1"; // Opend projects only - $sql .= " AND cls.code NOT IN ('LOST')"; + $sql .= " AND cls.code NOT IN ('LOST', 'WON')"; $sql .= " GROUP BY p.fk_opp_status, cls.code"; $resql = $this->db->query($sql); @@ -236,6 +237,7 @@ class box_funnel_of_prospection extends ModeleBoxes $dolgraph->setShowPercent(1); $dolgraph->setMirrorGraphValues(true); $dolgraph->setBorderWidth(2); + $dolgraph->setBorderSkip('false'); $dolgraph->SetType(array('horizontalbars')); $dolgraph->SetHeight('200'); $dolgraph->SetWidth('600'); @@ -248,7 +250,7 @@ class box_funnel_of_prospection extends ModeleBoxes $stringtoprint .= ''; $line = 0; - $this->info_box_contents[$line][] = array( + /*$this->info_box_contents[$line][] = array( 'tr' => 'class="nohover left "', 'text' => '' ); @@ -256,7 +258,7 @@ class box_funnel_of_prospection extends ModeleBoxes 'tr' => 'class="nohover left "', 'text' => '' ); - $line++; + $line++;*/ $this->info_box_contents[$line][] = array( 'tr' => '', 'td' => 'class="center nopaddingleftimp nopaddingrightimp" colspan="2"', diff --git a/htdocs/core/boxes/modules_boxes.php b/htdocs/core/boxes/modules_boxes.php index 260baa718ea..941f12cba82 100644 --- a/htdocs/core/boxes/modules_boxes.php +++ b/htdocs/core/boxes/modules_boxes.php @@ -223,7 +223,10 @@ class ModeleBoxes // Can't be abtract as it is instantiated to build "empty" box if (!empty($head['text']) || !empty($head['sublink']) || !empty($head['subpicto'])) { $out .= ''; $out .= ' 0) { + if (!empty($head['nbcol'])) { + $nbcol = $head['nbcol']; + } + if ($nbcol > 1) { $out .= ' colspan="'.$nbcol.'"'; } $out .= '>'; diff --git a/htdocs/core/class/CMailFile.class.php b/htdocs/core/class/CMailFile.class.php index 5f053ae6e18..523897ab916 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -264,12 +264,23 @@ class CMailFile // This convert an embedd file with src="/viewimage.php?modulepart... into a cid link // TODO Exclude viewimage used for the read tracker ? $findimg = $this->findHtmlImages($dolibarr_main_data_root.'/medias'); + if ($findimg<0) { + dol_syslog("CMailFile::CMailfile: Error on findHtmlImages"); + $this->error = 'ErrorInAddAttachementsImageBaseOnMedia'; + return; + } } if (getDolGlobalString('MAIN_MAIL_ADD_INLINE_IMAGES_IF_DATA')) { // Search into the body for error = 'ErrorInAddAttachementsImageBaseOnMedia'; + return; + } + $findimg += $resultImageData; } // Set atleastoneimage if there is at least one embedded file (into ->html_images) @@ -780,12 +791,12 @@ class CMailFile } // Force parameters - //dol_syslog("CMailFile::sendfile conf->global->".$keyforsmtpserver."=".$conf->global->$keyforsmtpserver." cpnf->global->".$keyforsmtpport."=".$conf->global->$keyforsmtpport, LOG_DEBUG); - if (!empty($conf->global->$keyforsmtpserver)) { - ini_set('SMTP', $conf->global->$keyforsmtpserver); + //dol_syslog("CMailFile::sendfile conf->global->".$keyforsmtpserver."=".getDolGlobalString($keyforsmtpserver)." cpnf->global->".$keyforsmtpport."=".$conf->global->$keyforsmtpport, LOG_DEBUG); + if (getDolGlobalString($keyforsmtpserver)) { + ini_set('SMTP', getDolGlobalString($keyforsmtpserver)); } - if (!empty($conf->global->$keyforsmtpport)) { - ini_set('smtp_port', $conf->global->$keyforsmtpport); + if (getDolGlobalString($keyforsmtpport)) { + ini_set('smtp_port', getDolGlobalString($keyforsmtpport)); } $res = true; @@ -869,10 +880,10 @@ class CMailFile } // Restore parameters - if (!empty($conf->global->$keyforsmtpserver)) { + if (getDolGlobalString($keyforsmtpserver)) { ini_restore('SMTP'); } - if (!empty($conf->global->$keyforsmtpport)) { + if (getDolGlobalString($keyforsmtpport)) { ini_restore('smtp_port'); } } elseif ($this->sendmode == 'smtps') { @@ -1059,7 +1070,7 @@ class CMailFile } // If we use SSL/TLS - $server = $conf->global->$keyforsmtpserver; + $server = getDolGlobalString($keyforsmtpserver); $secure = ''; if (!empty($conf->global->$keyfortls) && function_exists('openssl_open')) { $secure = 'ssl'; @@ -1068,7 +1079,7 @@ class CMailFile $secure = 'tls'; } - $this->transport = new Swift_SmtpTransport($server, $conf->global->$keyforsmtpport, $secure); + $this->transport = new Swift_SmtpTransport($server, getDolGlobalString($keyforsmtpport), $secure); if (!empty($conf->global->$keyforsmtpid)) { $this->transport->setUsername($conf->global->$keyforsmtpid); @@ -1137,7 +1148,7 @@ class CMailFile dol_syslog("CMailFile::sendfile: mail end error=".$e->getMessage(), LOG_ERR); } } - if (!empty($conf->global->$keyforsslseflsigned)) { + if (getDolGlobalString($keyforsslseflsigned)) { $this->transport->setStreamOptions(array('ssl' => array('allow_self_signed' => true, 'verify_peer' => false))); } //$smtps->_msgReplyTo = 'reply@web.com'; @@ -1150,7 +1161,7 @@ class CMailFile $this->mailer = new Swift_Mailer($this->transport); // DKIM SIGN - if ($conf->global->MAIN_MAIL_EMAIL_DKIM_ENABLED) { + if (getDolGlobalString('MAIN_MAIL_EMAIL_DKIM_ENABLED')) { $privateKey = $conf->global->MAIN_MAIL_EMAIL_DKIM_PRIVATE_KEY; $domainName = $conf->global->MAIN_MAIL_EMAIL_DKIM_DOMAIN; $selector = $conf->global->MAIN_MAIL_EMAIL_DKIM_SELECTOR; @@ -1902,7 +1913,7 @@ class CMailFile // We search (into mail body this->html), if we find some strings like "... file=xxx.img" // For example when: - // + // $matches = array(); preg_match_all('/src="data:image\/('.implode('|', $extensions).');base64,([^"]+)"/Ui', $this->html, $matches); // If "xxx.ext" or 'xxx.ext' found @@ -1913,7 +1924,7 @@ class CMailFile return -1; } - $i = 0; + $i = count($this->html_images); foreach ($matches[1] as $key => $ext) { // We save the image to send in disk $filecontent = $matches[2][$key]; diff --git a/htdocs/core/class/comment.class.php b/htdocs/core/class/comment.class.php index 3bae32d81e3..491c84f2a11 100644 --- a/htdocs/core/class/comment.class.php +++ b/htdocs/core/class/comment.class.php @@ -177,7 +177,7 @@ class Comment extends CommonObject * Load object in memory from database * * @param int $id Id object - * @param int $ref ref object + * @param string $ref ref object * @return int Return integer <0 if KO, 0 if not found, >0 if OK */ public function fetch($id, $ref = '') diff --git a/htdocs/core/class/commondocgenerator.class.php b/htdocs/core/class/commondocgenerator.class.php index e211cd631d0..81683c81d18 100644 --- a/htdocs/core/class/commondocgenerator.class.php +++ b/htdocs/core/class/commondocgenerator.class.php @@ -825,7 +825,7 @@ abstract class CommonDocGenerator * * @param Expedition $object Main object to use as data source * @param Translate $outputlangs Lang object to use for output - * @param array $array_key Name of the key for return array + * @param string $array_key Name of the key for return array * @return array Array of substitution */ public function get_substitutionarray_shipment($object, $outputlangs, $array_key = 'object') @@ -1189,7 +1189,7 @@ abstract class CommonDocGenerator * @param bool $insertAfterTarget insert before or after target column ? * @return int new rank on success and -1 on error */ - public function insertNewColumnDef($newColKey, $defArray, $targetCol = false, $insertAfterTarget = false) + public function insertNewColumnDef($newColKey, $defArray, $targetCol = '', $insertAfterTarget = false) { // prepare wanted rank $rank = -1; @@ -1712,7 +1712,7 @@ abstract class CommonDocGenerator $def = array( 'rank' => intval($extrafields->attributes[$object->table_element]['pos'][$key]), 'width' => 25, // in mm - 'status' => boolval($enabled), + 'status' => (bool) $enabled, 'title' => array( 'label' => $outputlangs->transnoentities($label) ), diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index ef31fb50485..627f1b8c0e7 100644 --- a/htdocs/core/class/commonobject.class.php +++ b/htdocs/core/class/commonobject.class.php @@ -93,7 +93,7 @@ abstract class CommonObject public $element; /** - * @var int The related element + * @var string Fieldname with ID of parent key if this field has a parent */ public $fk_element; @@ -167,8 +167,9 @@ abstract class CommonObject * @var CommonObject To store a cloned copy of object before to edit it and keep track of old properties */ public $oldcopy; + /** - * @var CommonObject To store old value of a modified ref + * @var string To store old value of a modified ref */ public $oldref; @@ -1737,8 +1738,6 @@ abstract class CommonObject public function fetch_thirdparty($force_thirdparty_id = 0) { // phpcs:enable - global $conf; - if (empty($this->socid) && empty($this->fk_soc) && empty($force_thirdparty_id)) { return 0; } @@ -3660,7 +3659,7 @@ abstract class CommonObject } if (!empty($MODULE)) { - if (!empty($conf->global->$MODULE)) { + if (getDolGlobalString($MODULE)) { $modsactivated = explode(',', getDolGlobalString($MODULE)); foreach ($modsactivated as $mod) { if (isModEnabled($mod)) { @@ -4343,7 +4342,7 @@ abstract class CommonObject * @return int >0 if OK, <0 if KO * @see add_object_linked(), updateObjectLinked(), fetchObjectLinked() */ - public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = '', $f_user = null, $notrigger = 0) + public function deleteObjectLinked($sourceid = null, $sourcetype = '', $targetid = null, $targettype = '', $rowid = 0, $f_user = null, $notrigger = 0) { global $user; $deletesource = false; @@ -4848,7 +4847,7 @@ abstract class CommonObject $qty = $obj->qty; $total_ht = $obj->total_ht; - $total_discount_line = floatval(price2num(($pu_ht * $qty) - $total_ht, 'MT')); + $total_discount_line = (float) price2num(($pu_ht * $qty) - $total_ht, 'MT'); $total_discount += $total_discount_line; $i++; @@ -5627,7 +5626,9 @@ abstract class CommonObject $file = $prefix."_".$modele.".modules.php"; } - // On verifie l'emplacement du modele + $file = dol_sanitizeFileName($file); + + // We chack if file exists $file = dol_buildpath($reldir.$modelspath.$file, 0); if (file_exists($file)) { $filefound = $file; @@ -5647,18 +5648,21 @@ abstract class CommonObject return -1; } - // If generator was found - global $db; // Required to solve a conception default making an include of code using $db instead of $this->db just after. + // Sanitize $filefound + $filefound = dol_sanitizePathName($filefound); - require_once $file; + // If generator was found + global $db; // Required to solve a conception default making an include of some code that uses $db instead of $this->db just after. + + require_once $filefound; $obj = new $classname($this->db); // If generator is ODT, we must have srctemplatepath defined, if not we set it. if ($obj->type == 'odt' && empty($srctemplatepath)) { $varfortemplatedir = $obj->scandir; - if ($varfortemplatedir && !empty($conf->global->$varfortemplatedir)) { - $dirtoscan = $conf->global->$varfortemplatedir; + if ($varfortemplatedir && getDolGlobalString($varfortemplatedir)) { + $dirtoscan = getDolGlobalString($varfortemplatedir); $listoffiles = array(); @@ -5966,8 +5970,8 @@ abstract class CommonObject $keyforfieldname = strtoupper($newelement.'_DEFAULT_'.$fieldname); //var_dump($keyforfieldname); - if (isset($conf->global->$keyforfieldname)) { - return $conf->global->$keyforfieldname; + if (getDolGlobalString($keyforfieldname)) { + return getDolGlobalString($keyforfieldname); } // TODO Ad here a scan into table llx_overwrite_default with a filter on $this->element and $fieldname @@ -7707,7 +7711,8 @@ abstract class CommonObject } } - $out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, empty($val['disabled']) ? 0 : 1); + //$out = $form->selectForForms($param_list[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, (empty($val['disabled']) ? 0 : 1), ''); + $out = $form->selectForForms($param_list_array[0], $keyprefix.$key.$keysuffix, $value, $showempty, '', '', $morecss, $moreparam, 0, (empty($val['disabled']) ? 0 : 1), '', $this->element.':'.$key.$keysuffix); if (!empty($param_list_array[2])) { // If the entry into $fields is set, we must add a create button if ((!GETPOSTISSET('backtopage') || strpos(GETPOST('backtopage'), $_SERVER['PHP_SELF']) === 0) // // To avoid to open several times the 'Plus' button (we accept only one level) @@ -8486,7 +8491,7 @@ abstract class CommonObject * @param string $display_type "card" for form display, "line" for document line display (extrafields on propal line, order line, etc...) * @return string String with html content to show */ - public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = 0, $display_type = 'card') + public function showOptionals($extrafields, $mode = 'view', $params = null, $keysuffix = '', $keyprefix = '', $onetrtd = '', $display_type = 'card') { global $db, $conf, $langs, $action, $form, $hookmanager; diff --git a/htdocs/core/class/commonorder.class.php b/htdocs/core/class/commonorder.class.php index e5f92cf14d2..dc5de2b9863 100644 --- a/htdocs/core/class/commonorder.class.php +++ b/htdocs/core/class/commonorder.class.php @@ -63,7 +63,7 @@ abstract class CommonOrder extends CommonObject $return .= '
    '.price($this->total_ht, 0, $langs, 0, -1, -1, $conf->currency).' '.$langs->trans('HT').'
    '; } if (method_exists($this, 'getLibStatut')) { - $return .= '
    '.$this->getLibStatut(3).'
    '; + $return .= '
    '.$this->getLibStatut(3).'
    '; } $return .= ''; $return .= ''; diff --git a/htdocs/core/class/commonpeople.class.php b/htdocs/core/class/commonpeople.class.php index aac008ac91b..2b1145edb7f 100644 --- a/htdocs/core/class/commonpeople.class.php +++ b/htdocs/core/class/commonpeople.class.php @@ -276,8 +276,6 @@ trait CommonPeople */ public function setUpperOrLowerCase() { - global $conf; - if (getDolGlobalString('MAIN_FIRST_TO_UPPER')) { $this->lastname = dol_ucwords(dol_strtolower($this->lastname)); $this->firstname = dol_ucwords(dol_strtolower($this->firstname)); diff --git a/htdocs/core/class/cunits.class.php b/htdocs/core/class/cunits.class.php index 4c7f1246587..e09a6ce88fb 100644 --- a/htdocs/core/class/cunits.class.php +++ b/htdocs/core/class/cunits.class.php @@ -424,7 +424,7 @@ class CUnits extends CommonDict */ public function unitConverter($value, $fk_unit, $fk_new_unit = 0) { - $value = floatval(price2num($value)); + $value = (float) price2num($value); $fk_unit = intval($fk_unit); // Calcul en unité de base @@ -463,10 +463,10 @@ class CUnits extends CommonDict // TODO : if base exists in unit dictionary table, remove this convertion exception and update convertion infos in database. // Example time hour currently scale 3600 will become scale 2 base 60 if ($unit->unit_type == 'time') { - return floatval($unit->scale); + return (float) $unit->scale; } - return pow($base, floatval($unit->scale)); + return pow($base, (float) $unit->scale); } } diff --git a/htdocs/core/class/discount.class.php b/htdocs/core/class/discount.class.php index f92ce30e087..abb82dd9e2e 100644 --- a/htdocs/core/class/discount.class.php +++ b/htdocs/core/class/discount.class.php @@ -152,8 +152,6 @@ class DiscountAbsolute */ public function fetch($rowid, $fk_facture_source = 0, $fk_invoice_supplier_source = 0) { - global $conf; - // Check parameters if (!$rowid && !$fk_facture_source && !$fk_invoice_supplier_source) { $this->error = 'ErrorBadParameters'; @@ -532,7 +530,7 @@ class DiscountAbsolute * @param int $multicurrency Return multicurrency_amount instead of amount * @return int Return integer <0 if KO, amount otherwise */ - public function getAvailableDiscounts($company = '', $user = '', $filter = '', $maxvalue = 0, $discount_type = 0, $multicurrency = 0) + public function getAvailableDiscounts($company = null, $user = null, $filter = '', $maxvalue = 0, $discount_type = 0, $multicurrency = 0) { global $conf; diff --git a/htdocs/core/class/doleditor.class.php b/htdocs/core/class/doleditor.class.php index 4a9d216bca2..00e4b72d721 100644 --- a/htdocs/core/class/doleditor.class.php +++ b/htdocs/core/class/doleditor.class.php @@ -54,7 +54,7 @@ class DolEditor * * @param string $htmlname HTML name of WYSIWIG field * @param string $content Content of WYSIWIG field - * @param int $width Width in pixel of edit area (auto by default) + * @param int|string $width Width in pixel of edit area (auto by default) * @param int $height Height in pixel of edit area (200px by default) * @param string $toolbarname Name of bar set to use ('Full', 'dolibarr_notes[_encoded]', 'dolibarr_details[_encoded]'=the less featured, 'dolibarr_mailings[_encoded]', 'dolibarr_readonly'). * @param string $toolbarlocation Deprecated. Not used @@ -67,7 +67,7 @@ class DolEditor * @param int $readonly 0=Read/Edit, 1=Read only * @param array $poscursor Array for initial cursor position array('x'=>x, 'y'=>y) */ - public function __construct($htmlname, $content, $width = '', $height = 200, $toolbarname = 'Basic', $toolbarlocation = 'In', $toolbarstartexpanded = false, $uselocalbrowser = 1, $okforextendededitor = true, $rows = 0, $cols = 0, $readonly = 0, $poscursor = array()) + public function __construct($htmlname, $content, $width = '', $height = 200, $toolbarname = 'Basic', $toolbarlocation = 'In', $toolbarstartexpanded = false, $uselocalbrowser = 1, $okforextendededitor = true, $rows = 0, $cols = '', $readonly = 0, $poscursor = array()) { global $conf; @@ -195,6 +195,7 @@ class DolEditor /* property:xxx is same than CKEDITOR.config.property = xxx */ customConfig: ckeditorConfig, removePlugins: \''.dol_escape_js($pluginstodisable).'\', + versionCheck: false, readOnly: '.($this->readonly ? 'true' : 'false').', htmlEncodeOutput: '.dol_escape_js($htmlencode_force).', allowedContent: '.($disallowAnyContent ? 'false' : 'true').', /* Advanced Content Filter (ACF) is own when allowedContent is false */ @@ -263,7 +264,7 @@ class DolEditor if ($titlecontent) { $out .= '
    '.$titlecontent; - $out .= '   -   '.dol_escape_htmltag($langs->trans("ShowMoreLines")).'     '; + $out .= '   -   '.dol_escape_htmltag($langs->trans("ShowMoreLines")).'     '; $out .= '
    '; $out .= ' - - -
    -

    -
    '.$this->serviceName.'
    - -
    '; - return $b; - } - - /** - * serialize the parsed wsdl - * - * @param mixed $debug whether to put debug=1 in endpoint URL - * @return string serialization of WSDL - * @access public - */ - function serialize($debug = 0) - { - $xml = ''; - $xml .= "\nnamespaces as $k => $v) { - $xml .= " xmlns:$k=\"$v\""; - } - // 10.9.02 - add poulter fix for wsdl and tns declarations - if (isset($this->namespaces['wsdl'])) { - $xml .= " xmlns=\"" . $this->namespaces['wsdl'] . "\""; - } - if (isset($this->namespaces['tns'])) { - $xml .= " targetNamespace=\"" . $this->namespaces['tns'] . "\""; - } - $xml .= '>'; - // imports - if (sizeof($this->import) > 0) { - foreach($this->import as $ns => $list) { - foreach ($list as $ii) { - if ($ii['location'] != '') { - $xml .= ''; - } else { - $xml .= ''; - } - } - } - } - // types - if (count($this->schemas)>=1) { - $xml .= "\n\n"; - foreach ($this->schemas as $ns => $list) { - foreach ($list as $xs) { - $xml .= $xs->serializeSchema(); - } - } - $xml .= ''; - } - // messages - if (count($this->messages) >= 1) { - foreach($this->messages as $msgName => $msgParts) { - $xml .= "\n'; - if(is_array($msgParts)){ - foreach($msgParts as $partName => $partType) { - // print 'serializing '.$partType.', sv: '.$this->XMLSchemaVersion.'
    '; - if (strpos($partType, ':')) { - $typePrefix = $this->getPrefixFromNamespace($this->getPrefix($partType)); - } elseif (isset($this->typemap[$this->namespaces['xsd']][$partType])) { - // print 'checking typemap: '.$this->XMLSchemaVersion.'
    '; - $typePrefix = 'xsd'; - } else { - foreach($this->typemap as $ns => $types) { - if (isset($types[$partType])) { - $typePrefix = $this->getPrefixFromNamespace($ns); - } - } - if (!isset($typePrefix)) { - die("$partType has no namespace!"); - } - } - $ns = $this->getNamespaceFromPrefix($typePrefix); - $localPart = $this->getLocalPart($partType); - $typeDef = $this->getTypeDef($localPart, $ns); - if ($typeDef['typeClass'] == 'element') { - $elementortype = 'element'; - if (substr($localPart, -1) == '^') { - $localPart = substr($localPart, 0, -1); - } - } else { - $elementortype = 'type'; - } - $xml .= "\n" . ' '; - } - } - $xml .= '
    '; - } - } - // bindings & porttypes - if (count($this->bindings) >= 1) { - $binding_xml = ''; - $portType_xml = ''; - foreach($this->bindings as $bindingName => $attrs) { - $binding_xml .= "\n'; - $binding_xml .= "\n" . ' '; - $portType_xml .= "\n'; - foreach($attrs['operations'] as $opName => $opParts) { - $binding_xml .= "\n" . ' '; - $binding_xml .= "\n" . ' '; - if (isset($opParts['input']['encodingStyle']) && $opParts['input']['encodingStyle'] != '') { - $enc_style = ' encodingStyle="' . $opParts['input']['encodingStyle'] . '"'; - } else { - $enc_style = ''; - } - $binding_xml .= "\n" . ' '; - if (isset($opParts['output']['encodingStyle']) && $opParts['output']['encodingStyle'] != '') { - $enc_style = ' encodingStyle="' . $opParts['output']['encodingStyle'] . '"'; - } else { - $enc_style = ''; - } - $binding_xml .= "\n" . ' '; - $binding_xml .= "\n" . ' '; - $portType_xml .= "\n" . ' ' . htmlspecialchars($opParts['documentation']) . ''; - } - $portType_xml .= "\n" . ' '; - $portType_xml .= "\n" . ' '; - $portType_xml .= "\n" . ' '; - } - $portType_xml .= "\n" . ''; - $binding_xml .= "\n" . ''; - } - $xml .= $portType_xml . $binding_xml; - } - // services - $xml .= "\nserviceName . '">'; - if (count($this->ports) >= 1) { - foreach($this->ports as $pName => $attrs) { - $xml .= "\n" . ' '; - $xml .= "\n" . ' '; - $xml .= "\n" . ' '; - } - } - $xml .= "\n" . ''; - return $xml . "\n"; - } - - /** - * determine whether a set of parameters are unwrapped - * when they are expect to be wrapped, Microsoft-style. - * - * @param string $type the type (element name) of the wrapper - * @param array $parameters the parameter values for the SOAP call - * @return boolean whether they parameters are unwrapped (and should be wrapped) - * @access private - */ - function parametersMatchWrapped($type, &$parameters) { - $this->debug("in parametersMatchWrapped type=$type, parameters="); - $this->appendDebug($this->varDump($parameters)); - - // split type into namespace:unqualified-type - if (strpos($type, ':')) { - $uqType = substr($type, strrpos($type, ':') + 1); - $ns = substr($type, 0, strrpos($type, ':')); - $this->debug("in parametersMatchWrapped: got a prefixed type: $uqType, $ns"); - if ($this->getNamespaceFromPrefix($ns)) { - $ns = $this->getNamespaceFromPrefix($ns); - $this->debug("in parametersMatchWrapped: expanded prefixed type: $uqType, $ns"); - } - } else { - // TODO: should the type be compared to types in XSD, and the namespace - // set to XSD if the type matches? - $this->debug("in parametersMatchWrapped: No namespace for type $type"); - $ns = ''; - $uqType = $type; - } - - // get the type information - if (!$typeDef = $this->getTypeDef($uqType, $ns)) { - $this->debug("in parametersMatchWrapped: $type ($uqType) is not a supported type."); - return false; - } - $this->debug("in parametersMatchWrapped: found typeDef="); - $this->appendDebug($this->varDump($typeDef)); - if (substr($uqType, -1) == '^') { - $uqType = substr($uqType, 0, -1); - } - $phpType = $typeDef['phpType']; - $arrayType = (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : ''); - $this->debug("in parametersMatchWrapped: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: $arrayType"); - - // we expect a complexType or element of complexType - if ($phpType != 'struct') { - $this->debug("in parametersMatchWrapped: not a struct"); - return false; - } - - // see whether the parameter names match the elements - if (isset($typeDef['elements']) && is_array($typeDef['elements'])) { - $elements = 0; - $matches = 0; - foreach ($typeDef['elements'] as $name => $attrs) { - if (isset($parameters[$name])) { - $this->debug("in parametersMatchWrapped: have parameter named $name"); - $matches++; - } else { - $this->debug("in parametersMatchWrapped: do not have parameter named $name"); - } - $elements++; - } - - $this->debug("in parametersMatchWrapped: $matches parameter names match $elements wrapped parameter names"); - if ($matches == 0) { - return false; - } - return true; - } - - // since there are no elements for the type, if the user passed no - // parameters, the parameters match wrapped. - $this->debug("in parametersMatchWrapped: no elements type $ns:$uqType"); - return count($parameters) == 0; - } - - /** - * serialize PHP values according to a WSDL message definition - * contrary to the method name, this is not limited to RPC - * - * TODO - * - multi-ref serialization - * - validate PHP values against type definitions, return errors if invalid - * - * @param string $operation operation name - * @param string $direction (input|output) - * @param mixed $parameters parameter value(s) - * @param string $bindingType (soap|soap12) - * @return mixed parameters serialized as XML or false on error (e.g. operation not found) - * @access public - */ - function serializeRPCParameters($operation, $direction, $parameters, $bindingType = 'soap') { - $this->debug("in serializeRPCParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion, bindingType=$bindingType"); - $this->appendDebug('parameters=' . $this->varDump($parameters)); - - if ($direction != 'input' && $direction != 'output') { - $this->debug('The value of the \$direction argument needs to be either "input" or "output"'); - $this->setError('The value of the \$direction argument needs to be either "input" or "output"'); - return false; - } - if (!$opData = $this->getOperationData($operation, $bindingType)) { - $this->debug('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType); - $this->setError('Unable to retrieve WSDL data for operation: ' . $operation . ' bindingType: ' . $bindingType); - return false; - } - $this->debug('in serializeRPCParameters: opData:'); - $this->appendDebug($this->varDump($opData)); - - // Get encoding style for output and set to current - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) { - $encodingStyle = $opData['output']['encodingStyle']; - $enc_style = $encodingStyle; - } - - // set input params - $xml = ''; - if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) { - $parts = &$opData[$direction]['parts']; - $part_count = sizeof($parts); - $style = $opData['style']; - $use = $opData[$direction]['use']; - $this->debug("have $part_count part(s) to serialize using $style/$use"); - if (is_array($parameters)) { - $parametersArrayType = $this->isArraySimpleOrStruct($parameters); - $parameter_count = count($parameters); - $this->debug("have $parameter_count parameter(s) provided as $parametersArrayType to serialize"); - // check for Microsoft-style wrapped parameters - if ($style == 'document' && $use == 'literal' && $part_count == 1 && isset($parts['parameters'])) { - $this->debug('check whether the caller has wrapped the parameters'); - if ($direction == 'output' && $parametersArrayType == 'arraySimple' && $parameter_count == 1) { - // TODO: consider checking here for double-wrapping, when - // service function wraps, then NuSOAP wraps again - $this->debug("change simple array to associative with 'parameters' element"); - $parameters['parameters'] = $parameters[0]; - unset($parameters[0]); - } - if (($parametersArrayType == 'arrayStruct' || $parameter_count == 0) && !isset($parameters['parameters'])) { - $this->debug('check whether caller\'s parameters match the wrapped ones'); - if ($this->parametersMatchWrapped($parts['parameters'], $parameters)) { - $this->debug('wrap the parameters for the caller'); - $parameters = array('parameters' => $parameters); - $parameter_count = 1; - } - } - } - foreach ($parts as $name => $type) { - $this->debug("serializing part $name of type $type"); - // Track encoding style - if (isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) { - $encodingStyle = $opData[$direction]['encodingStyle']; - $enc_style = $encodingStyle; - } else { - $enc_style = false; - } - // NOTE: add error handling here - // if serializeType returns false, then catch global error and fault - if ($parametersArrayType == 'arraySimple') { - $p = array_shift($parameters); - $this->debug('calling serializeType w/indexed param'); - $xml .= $this->serializeType($name, $type, $p, $use, $enc_style); - } elseif (isset($parameters[$name])) { - $this->debug('calling serializeType w/named param'); - $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style); - } else { - // TODO: only send nillable - $this->debug('calling serializeType w/null param'); - $xml .= $this->serializeType($name, $type, null, $use, $enc_style); - } - } - } else { - $this->debug('no parameters passed.'); - } - } - $this->debug("serializeRPCParameters returning: $xml"); - return $xml; - } - - /** - * serialize a PHP value according to a WSDL message definition - * - * TODO - * - multi-ref serialization - * - validate PHP values against type definitions, return errors if invalid - * - * @param string $operation operation name - * @param string $direction (input|output) - * @param mixed $parameters parameter value(s) - * @return mixed parameters serialized as XML or false on error (e.g. operation not found) - * @access public - * @deprecated - */ - function serializeParameters($operation, $direction, $parameters) - { - $this->debug("in serializeParameters: operation=$operation, direction=$direction, XMLSchemaVersion=$this->XMLSchemaVersion"); - $this->appendDebug('parameters=' . $this->varDump($parameters)); - - if ($direction != 'input' && $direction != 'output') { - $this->debug('The value of the \$direction argument needs to be either "input" or "output"'); - $this->setError('The value of the \$direction argument needs to be either "input" or "output"'); - return false; - } - if (!$opData = $this->getOperationData($operation)) { - $this->debug('Unable to retrieve WSDL data for operation: ' . $operation); - $this->setError('Unable to retrieve WSDL data for operation: ' . $operation); - return false; - } - $this->debug('opData:'); - $this->appendDebug($this->varDump($opData)); - - // Get encoding style for output and set to current - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - if(($direction == 'input') && isset($opData['output']['encodingStyle']) && ($opData['output']['encodingStyle'] != $encodingStyle)) { - $encodingStyle = $opData['output']['encodingStyle']; - $enc_style = $encodingStyle; - } - - // set input params - $xml = ''; - if (isset($opData[$direction]['parts']) && sizeof($opData[$direction]['parts']) > 0) { - - $use = $opData[$direction]['use']; - $this->debug("use=$use"); - $this->debug('got ' . count($opData[$direction]['parts']) . ' part(s)'); - if (is_array($parameters)) { - $parametersArrayType = $this->isArraySimpleOrStruct($parameters); - $this->debug('have ' . $parametersArrayType . ' parameters'); - foreach($opData[$direction]['parts'] as $name => $type) { - $this->debug('serializing part "'.$name.'" of type "'.$type.'"'); - // Track encoding style - if(isset($opData[$direction]['encodingStyle']) && $encodingStyle != $opData[$direction]['encodingStyle']) { - $encodingStyle = $opData[$direction]['encodingStyle']; - $enc_style = $encodingStyle; - } else { - $enc_style = false; - } - // NOTE: add error handling here - // if serializeType returns false, then catch global error and fault - if ($parametersArrayType == 'arraySimple') { - $p = array_shift($parameters); - $this->debug('calling serializeType w/indexed param'); - $xml .= $this->serializeType($name, $type, $p, $use, $enc_style); - } elseif (isset($parameters[$name])) { - $this->debug('calling serializeType w/named param'); - $xml .= $this->serializeType($name, $type, $parameters[$name], $use, $enc_style); - } else { - // TODO: only send nillable - $this->debug('calling serializeType w/null param'); - $xml .= $this->serializeType($name, $type, null, $use, $enc_style); - } - } - } else { - $this->debug('no parameters passed.'); - } - } - $this->debug("serializeParameters returning: $xml"); - return $xml; - } - - /** - * serializes a PHP value according a given type definition - * - * @param string $name name of value (part or element) - * @param string $type XML schema type of value (type or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $use use for part (encoded|literal) - * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style) - * @param boolean $unqualified a kludge for what should be XML namespace form handling - * @return string value serialized as an XML string - * @access private - */ - function serializeType($name, $type, $value, $use='encoded', $encodingStyle=false, $unqualified=false) - { - $this->debug("in serializeType: name=$name, type=$type, use=$use, encodingStyle=$encodingStyle, unqualified=" . ($unqualified ? "unqualified" : "qualified")); - $this->appendDebug("value=" . $this->varDump($value)); - if($use == 'encoded' && $encodingStyle) { - $encodingStyle = ' SOAP-ENV:encodingStyle="' . $encodingStyle . '"'; - } - - // if a soapval has been supplied, let its type override the WSDL - if (is_object($value) && get_class($value) == 'soapval') { - if ($value->type_ns) { - $type = $value->type_ns . ':' . $value->type; - $forceType = true; - $this->debug("in serializeType: soapval overrides type to $type"); - } elseif ($value->type) { - $type = $value->type; - $forceType = true; - $this->debug("in serializeType: soapval overrides type to $type"); - } else { - $forceType = false; - $this->debug("in serializeType: soapval does not override type"); - } - $attrs = $value->attributes; - $value = $value->value; - $this->debug("in serializeType: soapval overrides value to $value"); - if ($attrs) { - if (!is_array($value)) { - $value['!'] = $value; - } - foreach ($attrs as $n => $v) { - $value['!' . $n] = $v; - } - $this->debug("in serializeType: soapval provides attributes"); - } - } else { - $forceType = false; - } - - $xml = ''; - if (strpos($type, ':')) { - $uqType = substr($type, strrpos($type, ':') + 1); - $ns = substr($type, 0, strrpos($type, ':')); - $this->debug("in serializeType: got a prefixed type: $uqType, $ns"); - if ($this->getNamespaceFromPrefix($ns)) { - $ns = $this->getNamespaceFromPrefix($ns); - $this->debug("in serializeType: expanded prefixed type: $uqType, $ns"); - } - - if($ns == $this->XMLSchemaVersion || $ns == 'http://schemas.xmlsoap.org/soap/encoding/'){ - $this->debug('in serializeType: type namespace indicates XML Schema or SOAP Encoding type'); - if ($unqualified && $use == 'literal') { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$name$elementNS/>"; - } else { - // TODO: depends on nillable, which should be checked before calling this method - $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if ($uqType == 'Array') { - // JBoss/Axis does this sometimes - return $this->serialize_val($value, $name, false, false, false, false, $use); - } - if ($uqType == 'boolean') { - if ((is_string($value) && $value == 'false') || (! $value)) { - $value = 'false'; - } else { - $value = 'true'; - } - } - if ($uqType == 'string' && gettype($value) == 'string') { - $value = $this->expandEntities($value); - } - if (($uqType == 'long' || $uqType == 'unsignedLong') && gettype($value) == 'double') { - $value = sprintf("%.0lf", $value); - } - // it's a scalar - // TODO: what about null/nil values? - // check type isn't a custom type extending xmlschema namespace - if (!$this->getTypeDef($uqType, $ns)) { - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value"; - } else { - $xml = "<$name$elementNS>$value"; - } - } else { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - $this->debug('custom type extends XML Schema or SOAP Encoding namespace (yuck)'); - } else if ($ns == 'http://xml.apache.org/xml-soap') { - $this->debug('in serializeType: appears to be Apache SOAP type'); - if ($uqType == 'Map') { - $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap'); - if (! $tt_prefix) { - $this->debug('in serializeType: Add namespace for Apache SOAP type'); - $tt_prefix = 'ns' . rand(1000, 9999); - $this->namespaces[$tt_prefix] = 'http://xml.apache.org/xml-soap'; - // force this to be added to usedNamespaces - $tt_prefix = $this->getPrefixFromNamespace('http://xml.apache.org/xml-soap'); - } - $contents = ''; - foreach($value as $k => $v) { - $this->debug("serializing map element: key $k, value $v"); - $contents .= ''; - $contents .= $this->serialize_val($k,'key',false,false,false,false,$use); - $contents .= $this->serialize_val($v,'value',false,false,false,false,$use); - $contents .= ''; - } - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\">$contents"; - } else { - $xml = "<$name>$contents"; - } - } else { - $xml = "<$name xsi:type=\"" . $tt_prefix . ":$uqType\"$encodingStyle>$contents"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - $this->debug('in serializeType: Apache SOAP type, but only support Map'); - } - } else { - // TODO: should the type be compared to types in XSD, and the namespace - // set to XSD if the type matches? - $this->debug("in serializeType: No namespace for type $type"); - $ns = ''; - $uqType = $type; - } - if(!$typeDef = $this->getTypeDef($uqType, $ns)){ - $this->setError("$type ($uqType) is not a supported type."); - $this->debug("in serializeType: $type ($uqType) is not a supported type."); - return false; - } else { - $this->debug("in serializeType: found typeDef"); - $this->appendDebug('typeDef=' . $this->varDump($typeDef)); - if (substr($uqType, -1) == '^') { - $uqType = substr($uqType, 0, -1); - } - } - if (!isset($typeDef['phpType'])) { - $this->setError("$type ($uqType) has no phpType."); - $this->debug("in serializeType: $type ($uqType) has no phpType."); - return false; - } - $phpType = $typeDef['phpType']; - $this->debug("in serializeType: uqType: $uqType, ns: $ns, phptype: $phpType, arrayType: " . (isset($typeDef['arrayType']) ? $typeDef['arrayType'] : '') ); - // if php type == struct, map value to the element names - if ($phpType == 'struct') { - if (isset($typeDef['typeClass']) && $typeDef['typeClass'] == 'element') { - $elementName = $uqType; - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - $elementNS = " xmlns=\"\""; - } - } else { - $elementName = $name; - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs and nillable - $xml = "<$elementName$elementNS/>"; - } else { - $xml = "<$elementName$elementNS xsi:nil=\"true\" xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if (is_object($value)) { - $value = get_object_vars($value); - } - if (is_array($value)) { - $elementAttrs = $this->serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType); - if ($use == 'literal') { - if ($forceType) { - $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">"; - } else { - $xml = "<$elementName$elementNS$elementAttrs>"; - } - } else { - $xml = "<$elementName$elementNS$elementAttrs xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>"; - } - - if (isset($typeDef['simpleContent']) && $typeDef['simpleContent'] == 'true') { - if (isset($value['!'])) { - $xml .= $value['!']; - $this->debug("in serializeType: serialized simpleContent for type $type"); - } else { - $this->debug("in serializeType: no simpleContent to serialize for type $type"); - } - } else { - // complexContent - $xml .= $this->serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use, $encodingStyle); - } - $xml .= ""; - } else { - $this->debug("in serializeType: phpType is struct, but value is not an array"); - $this->setError("phpType is struct, but value is not an array: see debug output for details"); - $xml = ''; - } - } elseif ($phpType == 'array') { - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if (is_null($value)) { - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$name$elementNS/>"; - } else { - $xml = "<$name$elementNS xsi:nil=\"true\" xsi:type=\"" . - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') . - ":Array\" " . - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') . - ':arrayType="' . - $this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) . - ':' . - $this->getLocalPart($typeDef['arrayType'])."[0]\"/>"; - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - if (isset($typeDef['multidimensional'])) { - $nv = array(); - foreach($value as $v) { - $cols = ',' . sizeof($v); - $nv = array_merge($nv, $v); - } - $value = $nv; - } else { - $cols = ''; - } - if (is_array($value) && sizeof($value) >= 1) { - $rows = sizeof($value); - $contents = ''; - foreach($value as $k => $v) { - $this->debug("serializing array element: $k, $v of type: $typeDef[arrayType]"); - //if (strpos($typeDef['arrayType'], ':') ) { - if (!in_array($typeDef['arrayType'],$this->typemap['http://www.w3.org/2001/XMLSchema'])) { - $contents .= $this->serializeType('item', $typeDef['arrayType'], $v, $use); - } else { - $contents .= $this->serialize_val($v, 'item', $typeDef['arrayType'], null, $this->XMLSchemaVersion, false, $use); - } - } - } else { - $rows = 0; - $contents = null; - } - // TODO: for now, an empty value will be serialized as a zero element - // array. Revisit this when coding the handling of null/nil values. - if ($use == 'literal') { - $xml = "<$name$elementNS>" - .$contents - .""; - } else { - $xml = "<$name$elementNS xsi:type=\"".$this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/').':Array" '. - $this->getPrefixFromNamespace('http://schemas.xmlsoap.org/soap/encoding/') - .':arrayType="' - .$this->getPrefixFromNamespace($this->getPrefix($typeDef['arrayType'])) - .":".$this->getLocalPart($typeDef['arrayType'])."[$rows$cols]\">" - .$contents - .""; - } - } elseif ($phpType == 'scalar') { - if (isset($typeDef['form']) && ($typeDef['form'] == 'qualified')) { - $elementNS = " xmlns=\"$ns\""; - } else { - if ($unqualified) { - $elementNS = " xmlns=\"\""; - } else { - $elementNS = ''; - } - } - if ($use == 'literal') { - if ($forceType) { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\">$value"; - } else { - $xml = "<$name$elementNS>$value"; - } - } else { - $xml = "<$name$elementNS xsi:type=\"" . $this->getPrefixFromNamespace($ns) . ":$uqType\"$encodingStyle>$value"; - } - } - $this->debug("in serializeType: returning: $xml"); - return $xml; - } - - /** - * serializes the attributes for a complexType - * - * @param array $typeDef our internal representation of an XML schema type (or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $ns the namespace of the type - * @param string $uqType the local part of the type - * @return string value serialized as an XML string - * @access private - */ - function serializeComplexTypeAttributes($typeDef, $value, $ns, $uqType) { - $this->debug("serializeComplexTypeAttributes for XML Schema type $ns:$uqType"); - $xml = ''; - if (isset($typeDef['extensionBase'])) { - $nsx = $this->getPrefix($typeDef['extensionBase']); - $uqTypex = $this->getLocalPart($typeDef['extensionBase']); - if ($this->getNamespaceFromPrefix($nsx)) { - $nsx = $this->getNamespaceFromPrefix($nsx); - } - if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) { - $this->debug("serialize attributes for extension base $nsx:$uqTypex"); - $xml .= $this->serializeComplexTypeAttributes($typeDefx, $value, $nsx, $uqTypex); - } else { - $this->debug("extension base $nsx:$uqTypex is not a supported type"); - } - } - if (isset($typeDef['attrs']) && is_array($typeDef['attrs'])) { - $this->debug("serialize attributes for XML Schema type $ns:$uqType"); - if (is_array($value)) { - $xvalue = $value; - } elseif (is_object($value)) { - $xvalue = get_object_vars($value); - } else { - $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType"); - $xvalue = array(); - } - foreach ($typeDef['attrs'] as $aName => $attrs) { - if (isset($xvalue['!' . $aName])) { - $xname = '!' . $aName; - $this->debug("value provided for attribute $aName with key $xname"); - } elseif (isset($xvalue[$aName])) { - $xname = $aName; - $this->debug("value provided for attribute $aName with key $xname"); - } elseif (isset($attrs['default'])) { - $xname = '!' . $aName; - $xvalue[$xname] = $attrs['default']; - $this->debug('use default value of ' . $xvalue[$aName] . ' for attribute ' . $aName); - } else { - $xname = ''; - $this->debug("no value provided for attribute $aName"); - } - if ($xname) { - $xml .= " $aName=\"" . $this->expandEntities($xvalue[$xname]) . "\""; - } - } - } else { - $this->debug("no attributes to serialize for XML Schema type $ns:$uqType"); - } - return $xml; - } - - /** - * serializes the elements for a complexType - * - * @param array $typeDef our internal representation of an XML schema type (or element) - * @param mixed $value a native PHP value (parameter value) - * @param string $ns the namespace of the type - * @param string $uqType the local part of the type - * @param string $use use for part (encoded|literal) - * @param string $encodingStyle SOAP encoding style for the value (if different than the enclosing style) - * @return string value serialized as an XML string - * @access private - */ - function serializeComplexTypeElements($typeDef, $value, $ns, $uqType, $use='encoded', $encodingStyle=false) { - $this->debug("in serializeComplexTypeElements for XML Schema type $ns:$uqType"); - $xml = ''; - if (isset($typeDef['extensionBase'])) { - $nsx = $this->getPrefix($typeDef['extensionBase']); - $uqTypex = $this->getLocalPart($typeDef['extensionBase']); - if ($this->getNamespaceFromPrefix($nsx)) { - $nsx = $this->getNamespaceFromPrefix($nsx); - } - if ($typeDefx = $this->getTypeDef($uqTypex, $nsx)) { - $this->debug("serialize elements for extension base $nsx:$uqTypex"); - $xml .= $this->serializeComplexTypeElements($typeDefx, $value, $nsx, $uqTypex, $use, $encodingStyle); - } else { - $this->debug("extension base $nsx:$uqTypex is not a supported type"); - } - } - if (isset($typeDef['elements']) && is_array($typeDef['elements'])) { - $this->debug("in serializeComplexTypeElements, serialize elements for XML Schema type $ns:$uqType"); - if (is_array($value)) { - $xvalue = $value; - } elseif (is_object($value)) { - $xvalue = get_object_vars($value); - } else { - $this->debug("value is neither an array nor an object for XML Schema type $ns:$uqType"); - $xvalue = array(); - } - // toggle whether all elements are present - ideally should validate against schema - if (count($typeDef['elements']) != count($xvalue)){ - $optionals = true; - } - foreach ($typeDef['elements'] as $eName => $attrs) { - if (!isset($xvalue[$eName])) { - if (isset($attrs['default'])) { - $xvalue[$eName] = $attrs['default']; - $this->debug('use default value of ' . $xvalue[$eName] . ' for element ' . $eName); - } - } - // if user took advantage of a minOccurs=0, then only serialize named parameters - if (isset($optionals) - && (!isset($xvalue[$eName])) - && ( (!isset($attrs['nillable'])) || $attrs['nillable'] != 'true') - ){ - if (isset($attrs['minOccurs']) && $attrs['minOccurs'] <> '0') { - $this->debug("apparent error: no value provided for element $eName with minOccurs=" . $attrs['minOccurs']); - } - // do nothing - $this->debug("no value provided for complexType element $eName and element is not nillable, so serialize nothing"); - } else { - // get value - if (isset($xvalue[$eName])) { - $v = $xvalue[$eName]; - } else { - $v = null; - } - if (isset($attrs['form'])) { - $unqualified = ($attrs['form'] == 'unqualified'); - } else { - $unqualified = false; - } - if (isset($attrs['maxOccurs']) && ($attrs['maxOccurs'] == 'unbounded' || $attrs['maxOccurs'] > 1) && isset($v) && is_array($v) && $this->isArraySimpleOrStruct($v) == 'arraySimple') { - $vv = $v; - foreach ($vv as $k => $v) { - if (isset($attrs['type']) || isset($attrs['ref'])) { - // serialize schema-defined type - $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified); - } else { - // serialize generic type (can this ever really happen?) - $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use"); - $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use); - } - } - } else { - if (is_null($v) && isset($attrs['minOccurs']) && $attrs['minOccurs'] == '0') { - // do nothing - } elseif (is_null($v) && isset($attrs['nillable']) && $attrs['nillable'] == 'true') { - // TODO: serialize a nil correctly, but for now serialize schema-defined type - $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified); - } elseif (isset($attrs['type']) || isset($attrs['ref'])) { - // serialize schema-defined type - $xml .= $this->serializeType($eName, isset($attrs['type']) ? $attrs['type'] : $attrs['ref'], $v, $use, $encodingStyle, $unqualified); - } else { - // serialize generic type (can this ever really happen?) - $this->debug("calling serialize_val() for $v, $eName, false, false, false, false, $use"); - $xml .= $this->serialize_val($v, $eName, false, false, false, false, $use); - } - } - } - } - } else { - $this->debug("no elements to serialize for XML Schema type $ns:$uqType"); - } - return $xml; - } - - /** - * adds an XML Schema complex type to the WSDL types - * - * @param string $name - * @param string $typeClass (complexType|simpleType|attribute) - * @param string $phpType currently supported are array and struct (php assoc array) - * @param string $compositor (all|sequence|choice) - * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param array $elements e.g. array ( name => array(name=>'',type=>'') ) - * @param array $attrs e.g. array(array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'xsd:string[]')) - * @param string $arrayType as namespace:name (xsd:string) - * @see nusoap_xmlschema - * @access public - */ - function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType='') { - if (count($elements) > 0) { - $eElements = array(); - foreach($elements as $n => $e){ - // expand each element - $ee = array(); - foreach ($e as $k => $v) { - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $ee[$k] = $v; - } - $eElements[$n] = $ee; - } - $elements = $eElements; - } - - if (count($attrs) > 0) { - foreach($attrs as $n => $a){ - // expand each attribute - foreach ($a as $k => $v) { - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $aa[$k] = $v; - } - $eAttrs[$n] = $aa; - } - $attrs = $eAttrs; - } - - $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase; - $arrayType = strpos($arrayType,':') ? $this->expandQname($arrayType) : $arrayType; - - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addComplexType($name,$typeClass,$phpType,$compositor,$restrictionBase,$elements,$attrs,$arrayType); - } - - /** - * adds an XML Schema simple type to the WSDL types - * - * @param string $name - * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param string $typeClass (should always be simpleType) - * @param string $phpType (should always be scalar) - * @param array $enumeration array of values - * @see nusoap_xmlschema - * @access public - */ - function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) { - $restrictionBase = strpos($restrictionBase,':') ? $this->expandQname($restrictionBase) : $restrictionBase; - - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addSimpleType($name, $restrictionBase, $typeClass, $phpType, $enumeration); - } - - /** - * adds an element to the WSDL types - * - * @param array $attrs attributes that must include name and type - * @see nusoap_xmlschema - * @access public - */ - function addElement($attrs) { - $typens = isset($this->namespaces['types']) ? $this->namespaces['types'] : $this->namespaces['tns']; - $this->schemas[$typens][0]->addElement($attrs); - } - - /** - * register an operation with the server - * - * @param string $name operation (method) name - * @param array $in assoc array of input values: key = param name, value = param type - * @param array $out assoc array of output values: key = param name, value = param type - * @param string $namespace optional The namespace for the operation - * @param string $soapaction optional The soapaction for the operation - * @param string $style (rpc|document) optional The style for the operation Note: when 'document' is specified, parameter and return wrappers are created for you automatically - * @param string $use (encoded|literal) optional The use for the parameters (cannot mix right now) - * @param string $documentation optional The description to include in the WSDL - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @access public - */ - function addOperation($name, $in = false, $out = false, $namespace = false, $soapaction = false, $style = 'rpc', $use = 'encoded', $documentation = '', $encodingStyle = ''){ - if ($use == 'encoded' && $encodingStyle == '') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } - - if ($style == 'document') { - $elements = array(); - foreach ($in as $n => $t) { - $elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified'); - } - $this->addComplexType($name . 'RequestType', 'complexType', 'struct', 'all', '', $elements); - $this->addElement(array('name' => $name, 'type' => $name . 'RequestType')); - $in = array('parameters' => 'tns:' . $name . '^'); - - $elements = array(); - foreach ($out as $n => $t) { - $elements[$n] = array('name' => $n, 'type' => $t, 'form' => 'unqualified'); - } - $this->addComplexType($name . 'ResponseType', 'complexType', 'struct', 'all', '', $elements); - $this->addElement(array('name' => $name . 'Response', 'type' => $name . 'ResponseType', 'form' => 'qualified')); - $out = array('parameters' => 'tns:' . $name . 'Response' . '^'); - } - - // get binding - $this->bindings[ $this->serviceName . 'Binding' ]['operations'][$name] = - array( - 'name' => $name, - 'binding' => $this->serviceName . 'Binding', - 'endpoint' => $this->endpoint, - 'soapAction' => $soapaction, - 'style' => $style, - 'input' => array( - 'use' => $use, - 'namespace' => $namespace, - 'encodingStyle' => $encodingStyle, - 'message' => $name . 'Request', - 'parts' => $in), - 'output' => array( - 'use' => $use, - 'namespace' => $namespace, - 'encodingStyle' => $encodingStyle, - 'message' => $name . 'Response', - 'parts' => $out), - 'namespace' => $namespace, - 'transport' => 'http://schemas.xmlsoap.org/soap/http', - 'documentation' => $documentation); - // add portTypes - // add messages - if($in) - { - foreach($in as $pName => $pType) - { - if(strpos($pType,':')) { - $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType); - } - $this->messages[$name.'Request'][$pName] = $pType; - } - } else { - $this->messages[$name.'Request']= '0'; - } - if($out) - { - foreach($out as $pName => $pType) - { - if(strpos($pType,':')) { - $pType = $this->getNamespaceFromPrefix($this->getPrefix($pType)).":".$this->getLocalPart($pType); - } - $this->messages[$name.'Response'][$pName] = $pType; - } - } else { - $this->messages[$name.'Response']= '0'; - } - return true; - } -} - -?> \ No newline at end of file diff --git a/htdocs/includes/nusoap/lib/class.wsdlcache.php b/htdocs/includes/nusoap/lib/class.wsdlcache.php deleted file mode 100644 index 8468850eb90..00000000000 --- a/htdocs/includes/nusoap/lib/class.wsdlcache.php +++ /dev/null @@ -1,208 +0,0 @@ - -* @author Ingo Fischer -* @access public -*/ -class nusoap_wsdlcache { - /** - * @var resource - * @access private - */ - var $fplock; - /** - * @var integer - * @access private - */ - var $cache_lifetime; - /** - * @var string - * @access private - */ - var $cache_dir; - /** - * @var string - * @access public - */ - var $debug_str = ''; - - /** - * constructor - * - * @param string $cache_dir directory for cache-files - * @param integer $cache_lifetime lifetime for caching-files in seconds or 0 for unlimited - * @access public - */ - function __construct($cache_dir='.', $cache_lifetime=0) { - $this->fplock = array(); - $this->cache_dir = $cache_dir != '' ? $cache_dir : '.'; - $this->cache_lifetime = $cache_lifetime; - } - - /** - * creates the filename used to cache a wsdl instance - * - * @param string $wsdl The URL of the wsdl instance - * @return string The filename used to cache the instance - * @access private - */ - function createFilename($wsdl) { - return $this->cache_dir.'/wsdlcache-' . md5($wsdl); - } - - /** - * adds debug data to the class level debug string - * - * @param string $string debug data - * @access private - */ - function debug($string){ - $this->debug_str .= get_class($this).": $string\n"; - } - - /** - * gets a wsdl instance from the cache - * - * @param string $wsdl The URL of the wsdl instance - * @return object wsdl The cached wsdl instance, null if the instance is not in the cache - * @access public - */ - function get($wsdl) { - $filename = $this->createFilename($wsdl); - if ($this->obtainMutex($filename, "r")) { - // check for expired WSDL that must be removed from the cache - if ($this->cache_lifetime > 0) { - if (file_exists($filename) && (time() - filemtime($filename) > $this->cache_lifetime)) { - unlink($filename); - $this->debug("Expired $wsdl ($filename) from cache"); - $this->releaseMutex($filename); - return null; - } - } - // see what there is to return - if (!file_exists($filename)) { - $this->debug("$wsdl ($filename) not in cache (1)"); - $this->releaseMutex($filename); - return null; - } - $fp = @fopen($filename, "r"); - if ($fp) { - $s = implode("", @file($filename)); - fclose($fp); - $this->debug("Got $wsdl ($filename) from cache"); - } else { - $s = null; - $this->debug("$wsdl ($filename) not in cache (2)"); - } - $this->releaseMutex($filename); - return (!is_null($s)) ? unserialize($s) : null; - } else { - $this->debug("Unable to obtain mutex for $filename in get"); - } - return null; - } - - /** - * obtains the local mutex - * - * @param string $filename The Filename of the Cache to lock - * @param string $mode The open-mode ("r" or "w") or the file - affects lock-mode - * @return boolean Lock successfully obtained ?! - * @access private - */ - function obtainMutex($filename, $mode) { - if (isset($this->fplock[md5($filename)])) { - $this->debug("Lock for $filename already exists"); - return false; - } - $this->fplock[md5($filename)] = fopen($filename.".lock", "w"); - if ($mode == "r") { - return flock($this->fplock[md5($filename)], LOCK_SH); - } else { - return flock($this->fplock[md5($filename)], LOCK_EX); - } - } - - /** - * adds a wsdl instance to the cache - * - * @param object wsdl $wsdl_instance The wsdl instance to add - * @return boolean WSDL successfully cached - * @access public - */ - function put($wsdl_instance) { - $filename = $this->createFilename($wsdl_instance->wsdl); - $s = serialize($wsdl_instance); - if ($this->obtainMutex($filename, "w")) { - $fp = fopen($filename, "w"); - if (! $fp) { - $this->debug("Cannot write $wsdl_instance->wsdl ($filename) in cache"); - $this->releaseMutex($filename); - return false; - } - fputs($fp, $s); - fclose($fp); - $this->debug("Put $wsdl_instance->wsdl ($filename) in cache"); - $this->releaseMutex($filename); - return true; - } else { - $this->debug("Unable to obtain mutex for $filename in put"); - } - return false; - } - - /** - * releases the local mutex - * - * @param string $filename The Filename of the Cache to lock - * @return boolean Lock successfully released - * @access private - */ - function releaseMutex($filename) { - $ret = flock($this->fplock[md5($filename)], LOCK_UN); - fclose($this->fplock[md5($filename)]); - unset($this->fplock[md5($filename)]); - if (! $ret) { - $this->debug("Not able to release lock for $filename"); - } - return $ret; - } - - /** - * removes a wsdl instance from the cache - * - * @param string $wsdl The URL of the wsdl instance - * @return boolean Whether there was an instance to remove - * @access public - */ - function remove($wsdl) { - $filename = $this->createFilename($wsdl); - if (!file_exists($filename)) { - $this->debug("$wsdl ($filename) not in cache to be removed"); - return false; - } - // ignore errors obtaining mutex - $this->obtainMutex($filename, "w"); - $ret = unlink($filename); - $this->debug("Removed ($ret) $wsdl ($filename) from cache"); - $this->releaseMutex($filename); - return $ret; - } -} - -/** - * For backward compatibility - */ -class wsdlcache extends nusoap_wsdlcache { -} -?> diff --git a/htdocs/includes/nusoap/lib/class.xmlschema.php b/htdocs/includes/nusoap/lib/class.xmlschema.php deleted file mode 100644 index 3934453f8d2..00000000000 --- a/htdocs/includes/nusoap/lib/class.xmlschema.php +++ /dev/null @@ -1,972 +0,0 @@ - -* @author Scott Nichol -* @access public -*/ -class nusoap_xmlschema extends nusoap_base { - - // files - var $schema = ''; - var $xml = ''; - // namespaces - var $enclosingNamespaces; - // schema info - var $schemaInfo = array(); - var $schemaTargetNamespace = ''; - // types, elements, attributes defined by the schema - var $attributes = array(); - var $complexTypes = array(); - var $complexTypeStack = array(); - var $currentComplexType = null; - var $elements = array(); - var $elementStack = array(); - var $currentElement = null; - var $simpleTypes = array(); - var $simpleTypeStack = array(); - var $currentSimpleType = null; - // imports - var $imports = array(); - // parser vars - var $parser; - var $position = 0; - var $depth = 0; - var $depth_array = array(); - var $message = array(); - var $defaultNamespace = array(); - - /** - * constructor - * - * @param string $schema schema document URI - * @param string $xml xml document URI - * @param string $namespaces namespaces defined in enclosing XML - * @access public - */ - function __construct($schema='',$xml='',$namespaces=array()){ - parent::__construct(); - $this->debug('nusoap_xmlschema class instantiated, inside constructor'); - // files - $this->schema = $schema; - $this->xml = $xml; - - // namespaces - $this->enclosingNamespaces = $namespaces; - $this->namespaces = array_merge($this->namespaces, $namespaces); - - // parse schema file - if($schema != ''){ - $this->debug('initial schema file: '.$schema); - $this->parseFile($schema, 'schema'); - } - - // parse xml file - if($xml != ''){ - $this->debug('initial xml file: '.$xml); - $this->parseFile($xml, 'xml'); - } - - } - - /** - * parse an XML file - * - * @param string $xml path/URL to XML file - * @param string $type (schema | xml) - * @return boolean - * @access public - */ - function parseFile($xml,$type){ - // parse xml file - if($xml != ""){ - $xmlStr = @join("",@file($xml)); - if($xmlStr == ""){ - $msg = 'Error reading XML from '.$xml; - $this->setError($msg); - $this->debug($msg); - return false; - } else { - $this->debug("parsing $xml"); - $this->parseString($xmlStr,$type); - $this->debug("done parsing $xml"); - return true; - } - } - return false; - } - - /** - * parse an XML string - * - * @param string $xml path or URL - * @param string $type (schema|xml) - * @access private - */ - function parseString($xml,$type){ - // parse xml string - if($xml != ""){ - - // Create an XML parser. - $this->parser = xml_parser_create(); - // Set the options for parsing the XML data. - xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); - - // Set the object for the parser. - xml_set_object($this->parser, $this); - - // Set the element handlers for the parser. - if($type == "schema"){ - xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement'); - xml_set_character_data_handler($this->parser,'schemaCharacterData'); - } elseif($type == "xml"){ - xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement'); - xml_set_character_data_handler($this->parser,'xmlCharacterData'); - } - - // Parse the XML file. - if(!xml_parse($this->parser,$xml,true)){ - // Display an error message. - $errstr = sprintf('XML error parsing XML schema on line %d: %s', - xml_get_current_line_number($this->parser), - xml_error_string(xml_get_error_code($this->parser)) - ); - $this->debug($errstr); - $this->debug("XML payload:\n" . $xml); - $this->setError($errstr); - } - - xml_parser_free($this->parser); - } else{ - $this->debug('no xml passed to parseString()!!'); - $this->setError('no xml passed to parseString()!!'); - } - } - - /** - * gets a type name for an unnamed type - * - * @param string Element name - * @return string A type name for an unnamed type - * @access private - */ - function CreateTypeName($ename) { - $scope = ''; - for ($i = 0; $i < count($this->complexTypeStack); $i++) { - $scope .= $this->complexTypeStack[$i] . '_'; - } - return $scope . $ename . '_ContainedType'; - } - - /** - * start-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @param string $attrs associative array of attributes - * @access private - */ - function schemaStartElement($parser, $name, $attrs) { - - // position in the total number of elements, starting from 0 - $pos = $this->position++; - $depth = $this->depth++; - // set self as current value for this depth - $this->depth_array[$depth] = $pos; - $this->message[$pos] = array('cdata' => ''); - if ($depth > 0) { - $this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]]; - } else { - $this->defaultNamespace[$pos] = false; - } - - // get element prefix - if($prefix = $this->getPrefix($name)){ - // get unqualified name - $name = $this->getLocalPart($name); - } else { - $prefix = ''; - } - - // loop thru attributes, expanding, and registering namespace declarations - if(count($attrs) > 0){ - foreach($attrs as $k => $v){ - // if ns declarations, add to class level array of valid namespaces - if(preg_match('/^xmlns/',$k)){ - //$this->xdebug("$k: $v"); - //$this->xdebug('ns_prefix: '.$this->getPrefix($k)); - if($ns_prefix = substr(strrchr($k,':'),1)){ - //$this->xdebug("Add namespace[$ns_prefix] = $v"); - $this->namespaces[$ns_prefix] = $v; - } else { - $this->defaultNamespace[$pos] = $v; - if (! $this->getPrefixFromNamespace($v)) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $v; - } - } - if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){ - $this->XMLSchemaVersion = $v; - $this->namespaces['xsi'] = $v.'-instance'; - } - } - } - foreach($attrs as $k => $v){ - // expand each attribute - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $eAttrs[$k] = $v; - } - $attrs = $eAttrs; - } else { - $attrs = array(); - } - // find status, register data - switch($name){ - case 'all': // (optional) compositor content for a complexType - case 'choice': - case 'group': - case 'sequence': - //$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement"); - $this->complexTypes[$this->currentComplexType]['compositor'] = $name; - //if($name == 'all' || $name == 'sequence'){ - // $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - //} - break; - case 'attribute': // complexType attribute - //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']); - $this->xdebug("parsing attribute:"); - $this->appendDebug($this->varDump($attrs)); - if (!isset($attrs['form'])) { - // TODO: handle globals - $attrs['form'] = $this->schemaInfo['attributeFormDefault']; - } - if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { - $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - if (!strpos($v, ':')) { - // no namespace in arrayType attribute value... - if ($this->defaultNamespace[$pos]) { - // ...so use the default - $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } - } - } - if(isset($attrs['name'])){ - $this->attributes[$attrs['name']] = $attrs; - $aname = $attrs['name']; - } elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){ - if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { - $aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } else { - $aname = ''; - } - } elseif(isset($attrs['ref'])){ - $aname = $attrs['ref']; - $this->attributes[$attrs['ref']] = $attrs; - } - - if($this->currentComplexType){ // This should *always* be - $this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs; - } - // arrayType attribute - if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){ - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - $prefix = $this->getPrefix($aname); - if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){ - $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } else { - $v = ''; - } - if(strpos($v,'[,]')){ - $this->complexTypes[$this->currentComplexType]['multidimensional'] = true; - } - $v = substr($v,0,strpos($v,'[')); // clip the [] - if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){ - $v = $this->XMLSchemaVersion.':'.$v; - } - $this->complexTypes[$this->currentComplexType]['arrayType'] = $v; - } - break; - case 'complexContent': // (optional) content for a complexType - $this->xdebug("do nothing for element $name"); - break; - case 'complexType': - array_push($this->complexTypeStack, $this->currentComplexType); - if(isset($attrs['name'])){ - // TODO: what is the scope of named complexTypes that appear - // nested within other c complexTypes? - $this->xdebug('processing named complexType '.$attrs['name']); - //$this->currentElement = false; - $this->currentComplexType = $attrs['name']; - $this->complexTypes[$this->currentComplexType] = $attrs; - $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; - // This is for constructs like - // - // - // - // - // - if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){ - $this->xdebug('complexType is unusual array'); - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } else { - $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - } - } else { - $name = $this->CreateTypeName($this->currentElement); - $this->xdebug('processing unnamed complexType for element ' . $this->currentElement . ' named ' . $name); - $this->currentComplexType = $name; - //$this->currentElement = false; - $this->complexTypes[$this->currentComplexType] = $attrs; - $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; - // This is for constructs like - // - // - // - // - // - if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){ - $this->xdebug('complexType is unusual array'); - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } else { - $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - } - } - $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'false'; - break; - case 'element': - array_push($this->elementStack, $this->currentElement); - if (!isset($attrs['form'])) { - if ($this->currentComplexType) { - $attrs['form'] = $this->schemaInfo['elementFormDefault']; - } else { - // global - $attrs['form'] = 'qualified'; - } - } - if(isset($attrs['type'])){ - $this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']); - if (! $this->getPrefix($attrs['type'])) { - if ($this->defaultNamespace[$pos]) { - $attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type']; - $this->xdebug('used default namespace to make type ' . $attrs['type']); - } - } - // This is for constructs like - // - // - // - // - // - if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') { - $this->xdebug('arrayType for unusual array is ' . $attrs['type']); - $this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type']; - } - $this->currentElement = $attrs['name']; - $ename = $attrs['name']; - } elseif(isset($attrs['ref'])){ - $this->xdebug("processing element as ref to ".$attrs['ref']); - $this->currentElement = "ref to ".$attrs['ref']; - $ename = $this->getLocalPart($attrs['ref']); - } else { - $type = $this->CreateTypeName($this->currentComplexType . '_' . $attrs['name']); - $this->xdebug("processing untyped element " . $attrs['name'] . ' type ' . $type); - $this->currentElement = $attrs['name']; - $attrs['type'] = $this->schemaTargetNamespace . ':' . $type; - $ename = $attrs['name']; - } - if (isset($ename) && $this->currentComplexType) { - $this->xdebug("add element $ename to complexType $this->currentComplexType"); - $this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs; - } elseif (!isset($attrs['ref'])) { - $this->xdebug("add element $ename to elements array"); - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - } - break; - case 'enumeration': // restriction value list member - $this->xdebug('enumeration ' . $attrs['value']); - if ($this->currentSimpleType) { - $this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value']; - } elseif ($this->currentComplexType) { - $this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value']; - } - break; - case 'extension': // simpleContent or complexContent type extension - $this->xdebug('extension ' . $attrs['base']); - if ($this->currentComplexType) { - $ns = $this->getPrefix($attrs['base']); - if ($ns == '') { - $this->complexTypes[$this->currentComplexType]['extensionBase'] = $this->schemaTargetNamespace . ':' . $attrs['base']; - } else { - $this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base']; - } - } else { - $this->xdebug('no current complexType to set extensionBase'); - } - break; - case 'import': - if (isset($attrs['schemaLocation'])) { - $this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']); - $this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false); - } else { - $this->xdebug('import namespace ' . $attrs['namespace']); - $this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true); - if (! $this->getPrefixFromNamespace($attrs['namespace'])) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace']; - } - } - break; - case 'include': - if (isset($attrs['schemaLocation'])) { - $this->xdebug('include into namespace ' . $this->schemaTargetNamespace . ' from ' . $attrs['schemaLocation']); - $this->imports[$this->schemaTargetNamespace][] = array('location' => $attrs['schemaLocation'], 'loaded' => false); - } else { - $this->xdebug('ignoring invalid XML Schema construct: include without schemaLocation attribute'); - } - break; - case 'list': // simpleType value list - $this->xdebug("do nothing for element $name"); - break; - case 'restriction': // simpleType, simpleContent or complexContent value restriction - $this->xdebug('restriction ' . $attrs['base']); - if($this->currentSimpleType){ - $this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base']; - } elseif($this->currentComplexType){ - $this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base']; - if(strstr($attrs['base'],':') == ':Array'){ - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } - } - break; - case 'schema': - $this->schemaInfo = $attrs; - $this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix); - if (isset($attrs['targetNamespace'])) { - $this->schemaTargetNamespace = $attrs['targetNamespace']; - } - if (!isset($attrs['elementFormDefault'])) { - $this->schemaInfo['elementFormDefault'] = 'unqualified'; - } - if (!isset($attrs['attributeFormDefault'])) { - $this->schemaInfo['attributeFormDefault'] = 'unqualified'; - } - break; - case 'simpleContent': // (optional) content for a complexType - if ($this->currentComplexType) { // This should *always* be - $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'true'; - } else { - $this->xdebug("do nothing for element $name because there is no current complexType"); - } - break; - case 'simpleType': - array_push($this->simpleTypeStack, $this->currentSimpleType); - if(isset($attrs['name'])){ - $this->xdebug("processing simpleType for name " . $attrs['name']); - $this->currentSimpleType = $attrs['name']; - $this->simpleTypes[ $attrs['name'] ] = $attrs; - $this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType'; - $this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar'; - } else { - $name = $this->CreateTypeName($this->currentComplexType . '_' . $this->currentElement); - $this->xdebug('processing unnamed simpleType for element ' . $this->currentElement . ' named ' . $name); - $this->currentSimpleType = $name; - //$this->currentElement = false; - $this->simpleTypes[$this->currentSimpleType] = $attrs; - $this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar'; - } - break; - case 'union': // simpleType type list - $this->xdebug("do nothing for element $name"); - break; - default: - $this->xdebug("do not have any logic to process element $name"); - } - } - - /** - * end-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @access private - */ - function schemaEndElement($parser, $name) { - // bring depth down a notch - $this->depth--; - // position of current element is equal to the last value left in depth_array for my depth - if(isset($this->depth_array[$this->depth])){ - $pos = $this->depth_array[$this->depth]; - } - // get element prefix - if ($prefix = $this->getPrefix($name)){ - // get unqualified name - $name = $this->getLocalPart($name); - } else { - $prefix = ''; - } - // move on... - if($name == 'complexType'){ - $this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)')); - $this->xdebug($this->varDump($this->complexTypes[$this->currentComplexType])); - $this->currentComplexType = array_pop($this->complexTypeStack); - //$this->currentElement = false; - } - if($name == 'element'){ - $this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)')); - $this->currentElement = array_pop($this->elementStack); - } - if($name == 'simpleType'){ - $this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)')); - $this->xdebug($this->varDump($this->simpleTypes[$this->currentSimpleType])); - $this->currentSimpleType = array_pop($this->simpleTypeStack); - } - } - - /** - * element content handler - * - * @param string $parser XML parser object - * @param string $data element content - * @access private - */ - function schemaCharacterData($parser, $data){ - $pos = $this->depth_array[$this->depth - 1]; - $this->message[$pos]['cdata'] .= $data; - } - - /** - * serialize the schema - * - * @access public - */ - function serializeSchema(){ - - $schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion); - $xml = ''; - // imports - if (sizeof($this->imports) > 0) { - foreach($this->imports as $ns => $list) { - foreach ($list as $ii) { - if ($ii['location'] != '') { - $xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n"; - } else { - $xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n"; - } - } - } - } - // complex types - foreach($this->complexTypes as $typeName => $attrs){ - $contentStr = ''; - // serialize child elements - if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){ - foreach($attrs['elements'] as $element => $eParts){ - if(isset($eParts['ref'])){ - $contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n"; - } else { - $contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\""; - foreach ($eParts as $aName => $aValue) { - // handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable - if ($aName != 'name' && $aName != 'type') { - $contentStr .= " $aName=\"$aValue\""; - } - } - $contentStr .= "/>\n"; - } - } - // compositor wraps elements - if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) { - $contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." \n"; - } - } - // attributes - if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){ - foreach($attrs['attrs'] as $attr => $aParts){ - $contentStr .= " <$schemaPrefix:attribute"; - foreach ($aParts as $a => $v) { - if ($a == 'ref' || $a == 'type') { - $contentStr .= " $a=\"".$this->contractQName($v).'"'; - } elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') { - $this->usedNamespaces['wsdl'] = $this->namespaces['wsdl']; - $contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"'; - } else { - $contentStr .= " $a=\"$v\""; - } - } - $contentStr .= "/>\n"; - } - } - // if restriction - if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){ - $contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." \n"; - // complex or simple content - if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){ - $contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." \n"; - } - } - // finalize complex type - if($contentStr != ''){ - $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." \n"; - } else { - $contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n"; - } - $xml .= $contentStr; - } - // simple types - if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){ - foreach($this->simpleTypes as $typeName => $eParts){ - $xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\">\n"; - if (isset($eParts['enumeration'])) { - foreach ($eParts['enumeration'] as $e) { - $xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n"; - } - } - $xml .= " \n "; - } - } - // elements - if(isset($this->elements) && count($this->elements) > 0){ - foreach($this->elements as $element => $eParts){ - $xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n"; - } - } - // attributes - if(isset($this->attributes) && count($this->attributes) > 0){ - foreach($this->attributes as $attr => $aParts){ - $xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>"; - } - } - // finish 'er up - $attr = ''; - foreach ($this->schemaInfo as $k => $v) { - if ($k == 'elementFormDefault' || $k == 'attributeFormDefault') { - $attr .= " $k=\"$v\""; - } - } - $el = "<$schemaPrefix:schema$attr targetNamespace=\"$this->schemaTargetNamespace\"\n"; - foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) { - $el .= " xmlns:$nsp=\"$ns\""; - } - $xml = $el . ">\n".$xml."\n"; - return $xml; - } - - /** - * adds debug data to the clas level debug string - * - * @param string $string debug data - * @access private - */ - function xdebug($string){ - $this->debug('<' . $this->schemaTargetNamespace . '> '.$string); - } - - /** - * get the PHP type of a user defined type in the schema - * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays - * returns false if no type exists, or not w/ the given namespace - * else returns a string that is either a native php type, or 'struct' - * - * @param string $type name of defined type - * @param string $ns namespace of type - * @return mixed - * @access public - * @deprecated - */ - function getPHPType($type,$ns){ - if(isset($this->typemap[$ns][$type])){ - //print "found type '$type' and ns $ns in typemap
    "; - return $this->typemap[$ns][$type]; - } elseif(isset($this->complexTypes[$type])){ - //print "getting type '$type' and ns $ns from complexTypes array
    "; - return $this->complexTypes[$type]['phpType']; - } - return false; - } - - /** - * returns an associative array of information about a given type - * returns false if no type exists by the given name - * - * For a complexType typeDef = array( - * 'restrictionBase' => '', - * 'phpType' => '', - * 'compositor' => '(sequence|all)', - * 'elements' => array(), // refs to elements array - * 'attrs' => array() // refs to attributes array - * ... and so on (see addComplexType) - * ) - * - * For simpleType or element, the array has different keys. - * - * @param string $type - * @return mixed - * @access public - * @see addComplexType - * @see addSimpleType - * @see addElement - */ - function getTypeDef($type){ - //$this->debug("in getTypeDef for type $type"); - if (substr($type, -1) == '^') { - $is_element = 1; - $type = substr($type, 0, -1); - } else { - $is_element = 0; - } - - if((! $is_element) && isset($this->complexTypes[$type])){ - $this->xdebug("in getTypeDef, found complexType $type"); - return $this->complexTypes[$type]; - } elseif((! $is_element) && isset($this->simpleTypes[$type])){ - $this->xdebug("in getTypeDef, found simpleType $type"); - if (!isset($this->simpleTypes[$type]['phpType'])) { - // get info for type to tack onto the simple type - // TODO: can this ever really apply (i.e. what is a simpleType really?) - $uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1); - $ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':')); - $etype = $this->getTypeDef($uqType); - if ($etype) { - $this->xdebug("in getTypeDef, found type for simpleType $type:"); - $this->xdebug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $this->simpleTypes[$type]['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $this->simpleTypes[$type]['elements'] = $etype['elements']; - } - } - } - return $this->simpleTypes[$type]; - } elseif(isset($this->elements[$type])){ - $this->xdebug("in getTypeDef, found element $type"); - if (!isset($this->elements[$type]['phpType'])) { - // get info for type to tack onto the element - $uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1); - $ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':')); - $etype = $this->getTypeDef($uqType); - if ($etype) { - $this->xdebug("in getTypeDef, found type for element $type:"); - $this->xdebug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $this->elements[$type]['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $this->elements[$type]['elements'] = $etype['elements']; - } - if (isset($etype['extensionBase'])) { - $this->elements[$type]['extensionBase'] = $etype['extensionBase']; - } - } elseif ($ns == 'http://www.w3.org/2001/XMLSchema') { - $this->xdebug("in getTypeDef, element $type is an XSD type"); - $this->elements[$type]['phpType'] = 'scalar'; - } - } - return $this->elements[$type]; - } elseif(isset($this->attributes[$type])){ - $this->xdebug("in getTypeDef, found attribute $type"); - return $this->attributes[$type]; - } elseif (preg_match('/_ContainedType$/', $type)) { - $this->xdebug("in getTypeDef, have an untyped element $type"); - $typeDef['typeClass'] = 'simpleType'; - $typeDef['phpType'] = 'scalar'; - $typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string'; - return $typeDef; - } - $this->xdebug("in getTypeDef, did not find $type"); - return false; - } - - /** - * returns a sample serialization of a given type, or false if no type by the given name - * - * @param string $type name of type - * @return mixed - * @access public - * @deprecated - */ - function serializeTypeDef($type){ - //print "in sTD() for type $type
    "; - if($typeDef = $this->getTypeDef($type)){ - $str .= '<'.$type; - if(is_array($typeDef['attrs'])){ - foreach($typeDef['attrs'] as $attName => $data){ - $str .= " $attName=\"{type = ".$data['type']."}\""; - } - } - $str .= " xmlns=\"".$this->schema['targetNamespace']."\""; - if(count($typeDef['elements']) > 0){ - $str .= ">"; - foreach($typeDef['elements'] as $element => $eData){ - $str .= $this->serializeTypeDef($element); - } - $str .= ""; - } elseif($typeDef['typeClass'] == 'element') { - $str .= ">"; - } else { - $str .= "/>"; - } - return $str; - } - return false; - } - - /** - * returns HTML form elements that allow a user - * to enter values for creating an instance of the given type. - * - * @param string $name name for type instance - * @param string $type name of type - * @return string - * @access public - * @deprecated - */ - function typeToForm($name,$type){ - // get typedef - if($typeDef = $this->getTypeDef($type)){ - // if struct - if($typeDef['phpType'] == 'struct'){ - $buffer .= '
    '; + print ''; $searchpicto = $form->showFilterButtons('left'); print $searchpicto; print '
    '; - foreach($typeDef['elements'] as $child => $childDef){ - $buffer .= " - - "; - } - $buffer .= '
    $childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):
    '; - // if array - } elseif($typeDef['phpType'] == 'array'){ - $buffer .= ''; - for($i=0;$i < 3; $i++){ - $buffer .= " - - "; - } - $buffer .= '
    array item (type: $typeDef[arrayType]):
    '; - // if scalar - } else { - $buffer .= ""; - } - } else { - $buffer .= ""; - } - return $buffer; - } - - /** - * adds a complex type to the schema - * - * example: array - * - * addType( - * 'ArrayOfstring', - * 'complexType', - * 'array', - * '', - * 'SOAP-ENC:Array', - * array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'), - * 'xsd:string' - * ); - * - * example: PHP associative array ( SOAP Struct ) - * - * addType( - * 'SOAPStruct', - * 'complexType', - * 'struct', - * 'all', - * array('myVar'=> array('name'=>'myVar','type'=>'string') - * ); - * - * @param name - * @param typeClass (complexType|simpleType|attribute) - * @param phpType: currently supported are array and struct (php assoc array) - * @param compositor (all|sequence|choice) - * @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param elements = array ( name = array(name=>'',type=>'') ) - * @param attrs = array( - * array( - * 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType", - * "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]" - * ) - * ) - * @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string) - * @access public - * @see getTypeDef - */ - function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){ - $this->complexTypes[$name] = array( - 'name' => $name, - 'typeClass' => $typeClass, - 'phpType' => $phpType, - 'compositor'=> $compositor, - 'restrictionBase' => $restrictionBase, - 'elements' => $elements, - 'attrs' => $attrs, - 'arrayType' => $arrayType - ); - - $this->xdebug("addComplexType $name:"); - $this->appendDebug($this->varDump($this->complexTypes[$name])); - } - - /** - * adds a simple type to the schema - * - * @param string $name - * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param string $typeClass (should always be simpleType) - * @param string $phpType (should always be scalar) - * @param array $enumeration array of values - * @access public - * @see nusoap_xmlschema - * @see getTypeDef - */ - function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) { - $this->simpleTypes[$name] = array( - 'name' => $name, - 'typeClass' => $typeClass, - 'phpType' => $phpType, - 'type' => $restrictionBase, - 'enumeration' => $enumeration - ); - - $this->xdebug("addSimpleType $name:"); - $this->appendDebug($this->varDump($this->simpleTypes[$name])); - } - - /** - * adds an element to the schema - * - * @param array $attrs attributes that must include name and type - * @see nusoap_xmlschema - * @access public - */ - function addElement($attrs) { - if (! $this->getPrefix($attrs['type'])) { - $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type']; - } - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - - $this->xdebug("addElement " . $attrs['name']); - $this->appendDebug($this->varDump($this->elements[ $attrs['name'] ])); - } -} - -/** - * Backward compatibility - */ -class XMLSchema extends nusoap_xmlschema { -} - - -?> \ No newline at end of file diff --git a/htdocs/includes/nusoap/lib/nusoap.php b/htdocs/includes/nusoap/lib/nusoap.php index 4f6208aa604..143503e77af 100644 --- a/htdocs/includes/nusoap/lib/nusoap.php +++ b/htdocs/includes/nusoap/lib/nusoap.php @@ -1,6 +1,7 @@ . +License along with this library; if not, write to the Free Software +Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA The NuSOAP project home is: http://sourceforge.net/projects/nusoap/ @@ -71,822 +73,856 @@ require_once('class.soap_server.php');*/ // cf. http://www.webkreator.com/php/techniques/php-static-class-variables.html $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'] = 9; + /** -* -* nusoap_base -* -* @author Dietrich Ayala -* @author Scott Nichol -* @access public -*/ -class nusoap_base { - /** - * Identification for HTTP headers. - * - * @var string - * @access private - */ - var $title = 'NuSOAP'; - /** - * Version for HTTP headers. - * - * @var string - * @access private - */ - var $version = '0.9.5'; - /** - * CVS revision for HTTP headers. - * - * @var string - * @access private - */ - var $revision = '1.15'; + * + * nusoap_base + * + * @author Dietrich Ayala + * @author Scott Nichol + * @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $ + * @access public + */ +class nusoap_base +{ + /** + * Identification for HTTP headers. + * + * @var string + * @access private + */ + var $title = 'NuSOAP'; + /** + * Version for HTTP headers. + * + * @var string + * @access private + */ + var $version = '0.9.11'; + /** + * CVS revision for HTTP headers. + * + * @var string + * @access private + */ + var $revision = '$Revision: 1.123 $'; /** * Current error string (manipulated by getError/setError) - * - * @var string - * @access private - */ - var $error_str = ''; + * + * @var string + * @access private + */ + var $error_str = ''; /** * Current debug string (manipulated by debug/appendDebug/clearDebug/getDebug/getDebugAsXMLComment) - * - * @var string - * @access private - */ + * + * @var string + * @access private + */ var $debug_str = ''; /** - * toggles automatic encoding of special characters as entities - * (should always be true, I think) - * - * @var boolean - * @access private - */ - var $charencoding = true; - /** - * the debug level for this instance - * - * @var integer - * @access private - */ - var $debugLevel; + * toggles automatic encoding of special characters as entities + * (should always be true, I think) + * + * @var boolean + * @access private + */ + var $charencoding = true; + /** + * the debug level for this instance + * + * @var integer + * @access private + */ + var $debugLevel; /** - * set schema version - * - * @var string - * @access public - */ - var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema'; + * set schema version + * + * @var string + * @access public + */ + var $XMLSchemaVersion = 'http://www.w3.org/2001/XMLSchema'; /** - * charset encoding for outgoing messages - * - * @var string - * @access public - */ + * charset encoding for outgoing messages + * + * @var string + * @access public + */ var $soap_defencoding = 'ISO-8859-1'; - //var $soap_defencoding = 'UTF-8'; + //var $soap_defencoding = 'UTF-8'; - /** - * namespaces in an array of prefix => uri - * - * this is "seeded" by a set of constants, but it may be altered by code - * - * @var array - * @access public - */ - var $namespaces = array( - 'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', - 'xsd' => 'http://www.w3.org/2001/XMLSchema', - 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance', - 'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/' - ); + /** + * namespaces in an array of prefix => uri + * + * this is "seeded" by a set of constants, but it may be altered by code + * + * @var array + * @access public + */ + var $namespaces = array( + 'SOAP-ENV' => 'http://schemas.xmlsoap.org/soap/envelope/', + 'xsd' => 'http://www.w3.org/2001/XMLSchema', + 'xsi' => 'http://www.w3.org/2001/XMLSchema-instance', + 'SOAP-ENC' => 'http://schemas.xmlsoap.org/soap/encoding/' + ); - /** - * namespaces used in the current context, e.g. during serialization - * - * @var array - * @access private - */ - var $usedNamespaces = array(); + /** + * namespaces used in the current context, e.g. during serialization + * + * @var array + * @access private + */ + var $usedNamespaces = array(); - /** - * XML Schema types in an array of uri => (array of xml type => php type) - * is this legacy yet? - * no, this is used by the nusoap_xmlschema class to verify type => namespace mappings. - * @var array - * @access public - */ - var $typemap = array( - 'http://www.w3.org/2001/XMLSchema' => array( - 'string'=>'string','boolean'=>'boolean','float'=>'double','double'=>'double','decimal'=>'double', - 'duration'=>'','dateTime'=>'string','time'=>'string','date'=>'string','gYearMonth'=>'', - 'gYear'=>'','gMonthDay'=>'','gDay'=>'','gMonth'=>'','hexBinary'=>'string','base64Binary'=>'string', - // abstract "any" types - 'anyType'=>'string','anySimpleType'=>'string', - // derived datatypes - 'normalizedString'=>'string','token'=>'string','language'=>'','NMTOKEN'=>'','NMTOKENS'=>'','Name'=>'','NCName'=>'','ID'=>'', - 'IDREF'=>'','IDREFS'=>'','ENTITY'=>'','ENTITIES'=>'','integer'=>'integer','nonPositiveInteger'=>'integer', - 'negativeInteger'=>'integer','long'=>'integer','int'=>'integer','short'=>'integer','byte'=>'integer','nonNegativeInteger'=>'integer', - 'unsignedLong'=>'','unsignedInt'=>'','unsignedShort'=>'','unsignedByte'=>'','positiveInteger'=>''), - 'http://www.w3.org/2000/10/XMLSchema' => array( - 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', - 'float'=>'double','dateTime'=>'string', - 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), - 'http://www.w3.org/1999/XMLSchema' => array( - 'i4'=>'','int'=>'integer','boolean'=>'boolean','string'=>'string','double'=>'double', - 'float'=>'double','dateTime'=>'string', - 'timeInstant'=>'string','base64Binary'=>'string','base64'=>'string','ur-type'=>'array'), - 'http://soapinterop.org/xsd' => array('SOAPStruct'=>'struct'), - 'http://schemas.xmlsoap.org/soap/encoding/' => array('base64'=>'string','array'=>'array','Array'=>'array'), - 'http://xml.apache.org/xml-soap' => array('Map') - ); + /** + * XML Schema types in an array of uri => (array of xml type => php type) + * is this legacy yet? + * no, this is used by the nusoap_xmlschema class to verify type => namespace mappings. + * + * @var array + * @access public + */ + var $typemap = array( + 'http://www.w3.org/2001/XMLSchema' => array( + 'string' => 'string', 'boolean' => 'boolean', 'float' => 'double', 'double' => 'double', 'decimal' => 'double', + 'duration' => '', 'dateTime' => 'string', 'time' => 'string', 'date' => 'string', 'gYearMonth' => '', + 'gYear' => '', 'gMonthDay' => '', 'gDay' => '', 'gMonth' => '', 'hexBinary' => 'string', 'base64Binary' => 'string', + // abstract "any" types + 'anyType' => 'string', 'anySimpleType' => 'string', + // derived datatypes + 'normalizedString' => 'string', 'token' => 'string', 'language' => '', 'NMTOKEN' => '', 'NMTOKENS' => '', 'Name' => '', 'NCName' => '', 'ID' => '', + 'IDREF' => '', 'IDREFS' => '', 'ENTITY' => '', 'ENTITIES' => '', 'integer' => 'integer', 'nonPositiveInteger' => 'integer', + 'negativeInteger' => 'integer', 'long' => 'integer', 'int' => 'integer', 'short' => 'integer', 'byte' => 'integer', 'nonNegativeInteger' => 'integer', + 'unsignedLong' => '', 'unsignedInt' => '', 'unsignedShort' => '', 'unsignedByte' => '', 'positiveInteger' => ''), + 'http://www.w3.org/2000/10/XMLSchema' => array( + 'i4' => '', 'int' => 'integer', 'boolean' => 'boolean', 'string' => 'string', 'double' => 'double', + 'float' => 'double', 'dateTime' => 'string', + 'timeInstant' => 'string', 'base64Binary' => 'string', 'base64' => 'string', 'ur-type' => 'array'), + 'http://www.w3.org/1999/XMLSchema' => array( + 'i4' => '', 'int' => 'integer', 'boolean' => 'boolean', 'string' => 'string', 'double' => 'double', + 'float' => 'double', 'dateTime' => 'string', + 'timeInstant' => 'string', 'base64Binary' => 'string', 'base64' => 'string', 'ur-type' => 'array'), + 'http://soapinterop.org/xsd' => array('SOAPStruct' => 'struct'), + 'http://schemas.xmlsoap.org/soap/encoding/' => array('base64' => 'string', 'array' => 'array', 'Array' => 'array'), + 'http://xml.apache.org/xml-soap' => array('Map') + ); - /** - * XML entities to convert - * - * @var array - * @access public - * @deprecated - * @see expandEntities - */ - var $xmlEntities = array('quot' => '"','amp' => '&', - 'lt' => '<','gt' => '>','apos' => "'"); + /** + * XML entities to convert + * + * @var array + * @access public + * @deprecated + * @see expandEntities + */ + var $xmlEntities = array('quot' => '"', 'amp' => '&', + 'lt' => '<', 'gt' => '>', 'apos' => "'"); - /** - * constructor - * - * @access public - */ - function __construct() { - $this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel']; - } + /** + * HTTP Content-type to be used for SOAP calls and responses + * + * @var string + */ + var $contentType = "text/xml"; - /** - * gets the global debug level, which applies to future instances - * - * @return integer Debug level 0-9, where 0 turns off - * @access public - */ - function getGlobalDebugLevel() { - return $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel']; - } - /** - * sets the global debug level, which applies to future instances - * - * @param int $level Debug level 0-9, where 0 turns off - * @access public - */ - function setGlobalDebugLevel($level) { - $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'] = $level; - } + /** + * constructor + * + * @access public + */ + function __construct() + { + $this->debugLevel = $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel']; + } - /** - * gets the debug level for this instance - * - * @return int Debug level 0-9, where 0 turns off - * @access public - */ - function getDebugLevel() { - return $this->debugLevel; - } + /** + * gets the global debug level, which applies to future instances + * + * @return integer Debug level 0-9, where 0 turns off + * @access public + */ + function getGlobalDebugLevel() + { + return $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel']; + } - /** - * sets the debug level for this instance - * - * @param int $level Debug level 0-9, where 0 turns off - * @access public - */ - function setDebugLevel($level) { - $this->debugLevel = $level; - } + /** + * sets the global debug level, which applies to future instances + * + * @param int $level Debug level 0-9, where 0 turns off + * @access public + */ + function setGlobalDebugLevel($level) + { + $GLOBALS['_transient']['static']['nusoap_base']['globalDebugLevel'] = $level; + } - /** - * adds debug data to the instance debug string with formatting - * - * @param string $string debug data - * @access private - */ - function debug($string){ - if ($this->debugLevel > 0) { - $this->appendDebug($this->getmicrotime().' '.get_class($this).": $string\n"); - } - } + /** + * gets the debug level for this instance + * + * @return int Debug level 0-9, where 0 turns off + * @access public + */ + function getDebugLevel() + { + return $this->debugLevel; + } - /** - * adds debug data to the instance debug string without formatting - * - * @param string $string debug data - * @access public - */ - function appendDebug($string){ - if ($this->debugLevel > 0) { - // it would be nice to use a memory stream here to use - // memory more efficiently - $this->debug_str .= $string; - } - } + /** + * sets the debug level for this instance + * + * @param int $level Debug level 0-9, where 0 turns off + * @access public + */ + function setDebugLevel($level) + { + $this->debugLevel = $level; + } - /** - * clears the current debug data for this instance - * - * @access public - */ - function clearDebug() { - // it would be nice to use a memory stream here to use - // memory more efficiently - $this->debug_str = ''; - } + /** + * adds debug data to the instance debug string with formatting + * + * @param string $string debug data + * @access private + */ + function debug($string) + { + if ($this->debugLevel > 0) { + $this->appendDebug($this->getmicrotime() . ' ' . get_class($this) . ": $string\n"); + } + } - /** - * gets the current debug data for this instance - * - * @return debug data - * @access public - */ - function &getDebug() { - // it would be nice to use a memory stream here to use - // memory more efficiently - return $this->debug_str; - } + /** + * adds debug data to the instance debug string without formatting + * + * @param string $string debug data + * @access public + */ + function appendDebug($string) + { + if ($this->debugLevel > 0) { + // it would be nice to use a memory stream here to use + // memory more efficiently + $this->debug_str .= $string; + } + } - /** - * gets the current debug data for this instance as an XML comment - * this may change the contents of the debug data - * - * @return debug data as an XML comment - * @access public - */ - function &getDebugAsXMLComment() { - // it would be nice to use a memory stream here to use - // memory more efficiently - while (strpos($this->debug_str, '--')) { - $this->debug_str = str_replace('--', '- -', $this->debug_str); - } - $ret = ""; - return $ret; - } + /** + * clears the current debug data for this instance + * + * @access public + */ + function clearDebug() + { + // it would be nice to use a memory stream here to use + // memory more efficiently + $this->debug_str = ''; + } - /** - * expands entities, e.g. changes '<' to '<'. - * - * @param string $val The string in which to expand entities. - * @access private - */ - function expandEntities($val) { - if ($this->charencoding) { - $val = str_replace('&', '&', $val); - $val = str_replace("'", ''', $val); - $val = str_replace('"', '"', $val); - $val = str_replace('<', '<', $val); - $val = str_replace('>', '>', $val); - } - return $val; - } + /** + * gets the current debug data for this instance + * + * @return string data + * @access public + */ + function &getDebug() + { + // it would be nice to use a memory stream here to use + // memory more efficiently + return $this->debug_str; + } - /** - * returns error string if present - * - * @return mixed error string or false - * @access public - */ - function getError(){ - if($this->error_str != ''){ - return $this->error_str; - } - return false; - } + /** + * gets the current debug data for this instance as an XML comment + * this may change the contents of the debug data + * + * @return string data as an XML comment + * @access public + */ + function &getDebugAsXMLComment() + { + // it would be nice to use a memory stream here to use + // memory more efficiently + while (strpos($this->debug_str, '--')) { + $this->debug_str = str_replace('--', '- -', $this->debug_str); + } + $ret = ""; + return $ret; + } - /** - * sets error string - * - * @return boolean $string error string - * @access private - */ - function setError($str){ - $this->error_str = $str; - } + /** + * expands entities, e.g. changes '<' to '<'. + * + * @param string $val The string in which to expand entities. + * @access private + */ + function expandEntities($val) + { + if ($this->charencoding) { + $val = str_replace('&', '&', $val); + $val = str_replace("'", ''', $val); + $val = str_replace('"', '"', $val); + $val = str_replace('<', '<', $val); + $val = str_replace('>', '>', $val); + } + return $val; + } - /** - * detect if array is a simple array or a struct (associative array) - * - * @param mixed $val The PHP array - * @return string (arraySimple|arrayStruct) - * @access private - */ - function isArraySimpleOrStruct($val) { + /** + * returns error string if present + * + * @return false|string error string or false + * @access public + */ + function getError() + { + if ($this->error_str != '') { + return $this->error_str; + } + return false; + } + + /** + * sets error string + * + * @return void + * @access private + */ + function setError($str) + { + $this->error_str = $str; + } + + /** + * detect if array is a simple array or a struct (associative array) + * + * @param mixed $val The PHP array + * @return string (arraySimple|arrayStruct) + * @access private + */ + function isArraySimpleOrStruct($val) + { $keyList = array_keys($val); - foreach ($keyList as $keyListValue) { - if (!is_int($keyListValue)) { - return 'arrayStruct'; - } - } - return 'arraySimple'; - } - - /** - * serializes PHP values in accordance w/ section 5. Type information is - * not serialized if $use == 'literal'. - * - * @param mixed $val The value to serialize - * @param string $name The name (local part) of the XML element - * @param string $type The XML schema type (local part) for the element - * @param string $name_ns The namespace for the name of the XML element - * @param string $type_ns The namespace for the type of the element - * @param array $attributes The attributes to serialize as name=>value pairs - * @param string $use The WSDL "use" (encoded|literal) - * @param boolean $soapval Whether this is called from soapval. - * @return string The serialized element, possibly with child elements - * @access public - */ - function serialize_val($val,$name=false,$type=false,$name_ns=false,$type_ns=false,$attributes=false,$use='encoded',$soapval=false) { - $this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use, soapval=$soapval"); - $this->appendDebug('value=' . $this->varDump($val)); - $this->appendDebug('attributes=' . $this->varDump($attributes)); - - if (is_object($val) && get_class($val) == 'soapval' && (! $soapval)) { - $this->debug("serialize_val: serialize soapval"); - $xml = $val->serialize($use); - $this->appendDebug($val->getDebug()); - $val->clearDebug(); - $this->debug("serialize_val of soapval returning $xml"); - return $xml; + foreach ($keyList as $keyListValue) { + if (!is_int($keyListValue)) { + return 'arrayStruct'; + } + } + return 'arraySimple'; + } + + /** + * serializes PHP values in accordance w/ section 5. Type information is + * not serialized if $use == 'literal'. + * + * @param mixed $val The value to serialize + * @param string $name The name (local part) of the XML element + * @param string $type The XML schema type (local part) for the element + * @param string $name_ns The namespace for the name of the XML element + * @param string $type_ns The namespace for the type of the element + * @param array $attributes The attributes to serialize as name=>value pairs + * @param string $use The WSDL "use" (encoded|literal) + * @param boolean $soapval Whether this is called from soapval. + * @return string The serialized element, possibly with child elements + * @access public + */ + function serialize_val($val, $name = false, $type = false, $name_ns = false, $type_ns = false, $attributes = false, $use = 'encoded', $soapval = false) + { + $this->debug("in serialize_val: name=$name, type=$type, name_ns=$name_ns, type_ns=$type_ns, use=$use, soapval=$soapval"); + $this->appendDebug('value=' . $this->varDump($val)); + $this->appendDebug('attributes=' . $this->varDump($attributes)); + + if (is_object($val) && get_class($val) == 'soapval' && (!$soapval)) { + $this->debug("serialize_val: serialize soapval"); + $xml = $val->serialize($use); + $this->appendDebug($val->getDebug()); + $val->clearDebug(); + $this->debug("serialize_val of soapval returning $xml"); + return $xml; + } + // force valid name if necessary + if (is_numeric($name)) { + $name = '__numeric_' . $name; + } elseif (!$name) { + $name = 'noname'; + } + // if name has ns, add ns prefix to name + $xmlns = ''; + if ($name_ns) { + $prefix = 'nu' . rand(1000, 9999); + $name = $prefix . ':' . $name; + $xmlns .= " xmlns:$prefix=\"$name_ns\""; + } + // if type is prefixed, create type prefix + if ($type_ns != '' && $type_ns == $this->namespaces['xsd']) { + // need to fix this. shouldn't default to xsd if no ns specified + // w/o checking against typemap + $type_prefix = 'xsd'; + } elseif ($type_ns) { + $type_prefix = 'ns' . rand(1000, 9999); + $xmlns .= " xmlns:$type_prefix=\"$type_ns\""; + } + // serialize attributes if present + $atts = ''; + if ($attributes) { + foreach ($attributes as $k => $v) { + $atts .= " $k=\"" . $this->expandEntities($v) . '"'; + } + } + // serialize null value + if (is_null($val)) { + $this->debug("serialize_val: serialize null"); + if ($use == 'literal') { + // TODO: depends on minOccurs + $xml = "<$name$xmlns$atts/>"; + } else { + if (isset($type) && isset($type_prefix)) { + $type_str = " xsi:type=\"$type_prefix:$type\""; + } else { + $type_str = ''; + } + $xml = "<$name$xmlns$type_str$atts xsi:nil=\"true\"/>"; + } + $this->debug("serialize_val returning $xml"); + return $xml; } - // force valid name if necessary - if (is_numeric($name)) { - $name = '__numeric_' . $name; - } elseif (! $name) { - $name = 'noname'; - } - // if name has ns, add ns prefix to name - $xmlns = ''; - if($name_ns){ - $prefix = 'nu'.rand(1000,9999); - $name = $prefix.':'.$name; - $xmlns .= " xmlns:$prefix=\"$name_ns\""; - } - // if type is prefixed, create type prefix - if($type_ns != '' && $type_ns == $this->namespaces['xsd']){ - // need to fix this. shouldn't default to xsd if no ns specified - // w/o checking against typemap - $type_prefix = 'xsd'; - } elseif($type_ns){ - $type_prefix = 'ns'.rand(1000,9999); - $xmlns .= " xmlns:$type_prefix=\"$type_ns\""; - } - // serialize attributes if present - $atts = ''; - if($attributes){ - foreach($attributes as $k => $v){ - $atts .= " $k=\"".$this->expandEntities($v).'"'; - } - } - // serialize null value - if (is_null($val)) { - $this->debug("serialize_val: serialize null"); - if ($use == 'literal') { - // TODO: depends on minOccurs - $xml = "<$name$xmlns$atts/>"; - $this->debug("serialize_val returning $xml"); - return $xml; - } else { - if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = ''; - } - $xml = "<$name$xmlns$type_str$atts xsi:nil=\"true\"/>"; - $this->debug("serialize_val returning $xml"); - return $xml; - } - } // serialize if an xsd built-in primitive type - if($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])){ - $this->debug("serialize_val: serialize xsd built-in primitive type"); - if (is_bool($val)) { - if ($type == 'boolean') { - $val = $val ? 'true' : 'false'; - } elseif (! $val) { - $val = 0; - } - } else if (is_string($val)) { - $val = $this->expandEntities($val); - } - if ($use == 'literal') { - $xml = "<$name$xmlns$atts>$val"; - $this->debug("serialize_val returning $xml"); - return $xml; - } else { - $xml = "<$name$xmlns xsi:type=\"xsd:$type\"$atts>$val"; - $this->debug("serialize_val returning $xml"); - return $xml; - } + if ($type != '' && isset($this->typemap[$this->XMLSchemaVersion][$type])) { + $this->debug("serialize_val: serialize xsd built-in primitive type"); + if (is_bool($val)) { + if ($type == 'boolean') { + $val = $val ? 'true' : 'false'; + } elseif (!$val) { + $val = 0; + } + } elseif (is_string($val)) { + $val = $this->expandEntities($val); + } + if ($use == 'literal') { + $xml = "<$name$xmlns$atts>$val"; + } else { + $xml = "<$name$xmlns xsi:type=\"xsd:$type\"$atts>$val"; + } + $this->debug("serialize_val returning $xml"); + return $xml; } - // detect type and serialize - $xml = ''; - switch(true) { - case (is_bool($val) || $type == 'boolean'): - $this->debug("serialize_val: serialize boolean"); - if ($type == 'boolean') { - $val = $val ? 'true' : 'false'; - } elseif (! $val) { - $val = 0; - } - if ($use == 'literal') { - $xml .= "<$name$xmlns$atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val"; - } - break; - case (is_int($val) || is_long($val) || $type == 'int'): - $this->debug("serialize_val: serialize int"); - if ($use == 'literal') { - $xml .= "<$name$xmlns$atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val"; - } - break; - case (is_float($val)|| is_double($val) || $type == 'float'): - $this->debug("serialize_val: serialize float"); - if ($use == 'literal') { - $xml .= "<$name$xmlns$atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val"; - } - break; - case (is_string($val) || $type == 'string'): - $this->debug("serialize_val: serialize string"); - $val = $this->expandEntities($val); - if ($use == 'literal') { - $xml .= "<$name$xmlns$atts>$val"; - } else { - $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val"; - } - break; - case is_object($val): - $this->debug("serialize_val: serialize object"); - if (get_class($val) == 'soapval') { - $this->debug("serialize_val: serialize soapval object"); - $pXml = $val->serialize($use); - $this->appendDebug($val->getDebug()); - $val->clearDebug(); - } else { - if (! $name) { - $name = get_class($val); - $this->debug("In serialize_val, used class name $name as element name"); - } else { - $this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val)); - } - foreach(get_object_vars($val) as $k => $v){ - $pXml = isset($pXml) ? $pXml.$this->serialize_val($v,$k,false,false,false,false,$use) : $this->serialize_val($v,$k,false,false,false,false,$use); - } - } - if(isset($type) && isset($type_prefix)){ - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = ''; - } - if ($use == 'literal') { - $xml .= "<$name$xmlns$atts>$pXml"; - } else { - $xml .= "<$name$xmlns$type_str$atts>$pXml"; - } - break; - break; - case (is_array($val) || $type): - // detect if struct or array - $valueType = $this->isArraySimpleOrStruct($val); - if($valueType=='arraySimple' || preg_match('/^ArrayOf/',$type)){ - $this->debug("serialize_val: serialize array"); - $i = 0; - if(is_array($val) && count($val)> 0){ - foreach($val as $v){ - if(is_object($v) && get_class($v) == 'soapval'){ - $tt_ns = $v->type_ns; - $tt = $v->type; - } elseif (is_array($v)) { - $tt = $this->isArraySimpleOrStruct($v); - } else { - $tt = gettype($v); - } - $array_types[$tt] = 1; - // TODO: for literal, the name should be $name - // @CHANGE This is to have tag name with name reported by wsdl and not "item" - //$xml .= $this->serialize_val($v,'item',false,false,false,false,$use); - $tmp=preg_replace('/s$/i','',$name); - $xml .= $this->serialize_val($v,$tmp?$tmp:'item',false,false,false,false,$use); + // detect type and serialize + $xml = ''; + switch (true) { + case (is_bool($val) || $type == 'boolean'): + $this->debug("serialize_val: serialize boolean"); + if ($type == 'boolean') { + $val = $val ? 'true' : 'false'; + } elseif (!$val) { + $val = 0; + } + if ($use == 'literal') { + $xml .= "<$name$xmlns$atts>$val"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:boolean\"$atts>$val"; + } + break; + case (is_int($val) || is_long($val) || $type == 'int'): + $this->debug("serialize_val: serialize int"); + if ($use == 'literal') { + $xml .= "<$name$xmlns$atts>$val"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:int\"$atts>$val"; + } + break; + case (is_float($val) || is_double($val) || $type == 'float'): + $this->debug("serialize_val: serialize float"); + if ($use == 'literal') { + $xml .= "<$name$xmlns$atts>$val"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:float\"$atts>$val"; + } + break; + case (is_string($val) || $type == 'string'): + $this->debug("serialize_val: serialize string"); + $val = $this->expandEntities($val); + if ($use == 'literal') { + $xml .= "<$name$xmlns$atts>$val"; + } else { + $xml .= "<$name$xmlns xsi:type=\"xsd:string\"$atts>$val"; + } + break; + case is_object($val): + $this->debug("serialize_val: serialize object"); + $pXml = ""; + if (get_class($val) == 'soapval') { + $this->debug("serialize_val: serialize soapval object"); + $pXml = $val->serialize($use); + $this->appendDebug($val->getDebug()); + $val->clearDebug(); + } else { + if (!$name) { + $name = get_class($val); + $this->debug("In serialize_val, used class name $name as element name"); + } else { + $this->debug("In serialize_val, do not override name $name for element name for class " . get_class($val)); + } + foreach (get_object_vars($val) as $k => $v) { + $pXml = isset($pXml) ? $pXml . $this->serialize_val($v, $k, false, false, false, false, $use) : $this->serialize_val($v, $k, false, false, false, false, $use); + } + } + if (isset($type) && isset($type_prefix)) { + $type_str = " xsi:type=\"$type_prefix:$type\""; + } else { + $type_str = ''; + } + if ($use == 'literal') { + $xml .= "<$name$xmlns$atts>$pXml"; + } else { + $xml .= "<$name$xmlns$type_str$atts>$pXml"; + } + break; + case (is_array($val) || $type): + // detect if struct or array + $valueType = $this->isArraySimpleOrStruct($val); + if ($valueType == 'arraySimple' || preg_match('/^ArrayOf/', $type)) { + $this->debug("serialize_val: serialize array"); + $i = 0; + if (is_array($val) && count($val) > 0) { + $array_types = array (); + $tt_ns = ""; + $tt = ""; + foreach ($val as $v) { + if (is_object($v) && get_class($v) == 'soapval') { + $tt_ns = $v->type_ns; + $tt = $v->type; + } elseif (is_array($v)) { + $tt = $this->isArraySimpleOrStruct($v); + } else { + $tt = gettype($v); + } + $array_types[$tt] = 1; + // TODO: for literal, the name should be $name + $xml .= $this->serialize_val($v, 'item', false, false, false, false, $use); ++$i; - } - if(count($array_types) > 1){ - $array_typename = 'xsd:anyType'; - } elseif(isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) { - if ($tt == 'integer') { - $tt = 'int'; - } - $array_typename = 'xsd:'.$tt; - } elseif(isset($tt) && $tt == 'arraySimple'){ - $array_typename = 'SOAP-ENC:Array'; - } elseif(isset($tt) && $tt == 'arrayStruct'){ - $array_typename = 'unnamed_struct_use_soapval'; - } else { - // if type is prefixed, create type prefix - if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']){ - $array_typename = 'xsd:' . $tt; - } elseif ($tt_ns) { - $tt_prefix = 'ns' . rand(1000, 9999); - $array_typename = "$tt_prefix:$tt"; - $xmlns .= " xmlns:$tt_prefix=\"$tt_ns\""; - } else { - $array_typename = $tt; - } - } - $array_type = $i; - if ($use == 'literal') { - $type_str = ''; - } else if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"".$array_typename."[$array_type]\""; - } - // empty array - } else { - if ($use == 'literal') { - $type_str = ''; - } else if (isset($type) && isset($type_prefix)) { - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\""; - } - } - // TODO: for array in literal, there is no wrapper here - $xml = "<$name$xmlns$type_str$atts>".$xml.""; - } else { - // got a struct - $this->debug("serialize_val: serialize struct"); - if(isset($type) && isset($type_prefix)){ - $type_str = " xsi:type=\"$type_prefix:$type\""; - } else { - $type_str = ''; - } - if ($use == 'literal') { - $xml .= "<$name$xmlns$atts>"; - } else { - $xml .= "<$name$xmlns$type_str$atts>"; - } - foreach($val as $k => $v){ - // Apache Map - if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') { - $xml .= ''; - $xml .= $this->serialize_val($k,'key',false,false,false,false,$use); - $xml .= $this->serialize_val($v,'value',false,false,false,false,$use); - $xml .= ''; - } else { - $xml .= $this->serialize_val($v,$k,false,false,false,false,$use); - } - } - $xml .= ""; - } - break; - default: - $this->debug("serialize_val: serialize unknown"); - $xml .= 'not detected, got '.gettype($val).' for '.$val; - break; - } - $this->debug("serialize_val returning $xml"); - return $xml; - } + } + if (count($array_types) > 1) { + $array_typename = 'xsd:anyType'; + } elseif (isset($tt) && isset($this->typemap[$this->XMLSchemaVersion][$tt])) { + if ($tt == 'integer') { + $tt = 'int'; + } + $array_typename = 'xsd:' . $tt; + } elseif (isset($tt) && $tt == 'arraySimple') { + $array_typename = 'SOAP-ENC:Array'; + } elseif (isset($tt) && $tt == 'arrayStruct') { + $array_typename = 'unnamed_struct_use_soapval'; + } else { + // if type is prefixed, create type prefix + if ($tt_ns != '' && $tt_ns == $this->namespaces['xsd']) { + $array_typename = 'xsd:' . $tt; + } elseif ($tt_ns) { + $tt_prefix = 'ns' . rand(1000, 9999); + $array_typename = "$tt_prefix:$tt"; + $xmlns .= " xmlns:$tt_prefix=\"$tt_ns\""; + } else { + $array_typename = $tt; + } + } + $array_type = $i; + if ($use == 'literal') { + $type_str = ''; + } elseif (isset($type) && isset($type_prefix)) { + $type_str = " xsi:type=\"$type_prefix:$type\""; + } else { + $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"" . $array_typename . "[$array_type]\""; + } + // empty array + } else { + if ($use == 'literal') { + $type_str = ''; + } elseif (isset($type) && isset($type_prefix)) { + $type_str = " xsi:type=\"$type_prefix:$type\""; + } else { + $type_str = " xsi:type=\"SOAP-ENC:Array\" SOAP-ENC:arrayType=\"xsd:anyType[0]\""; + } + } + // TODO: for array in literal, there is no wrapper here + $xml = "<$name$xmlns$type_str$atts>" . $xml . ""; + } else { + // got a struct + $this->debug("serialize_val: serialize struct"); + if (isset($type) && isset($type_prefix)) { + $type_str = " xsi:type=\"$type_prefix:$type\""; + } else { + $type_str = ''; + } + if ($use == 'literal') { + $xml .= "<$name$xmlns$atts>"; + } else { + $xml .= "<$name$xmlns$type_str$atts>"; + } + foreach ($val as $k => $v) { + // Apache Map + if ($type == 'Map' && $type_ns == 'http://xml.apache.org/xml-soap') { + $xml .= ''; + $xml .= $this->serialize_val($k, 'key', false, false, false, false, $use); + $xml .= $this->serialize_val($v, 'value', false, false, false, false, $use); + $xml .= ''; + } else { + $xml .= $this->serialize_val($v, $k, false, false, false, false, $use); + } + } + $xml .= ""; + } + break; + default: + $this->debug("serialize_val: serialize unknown"); + $xml .= 'not detected, got ' . gettype($val) . ' for ' . $val; + break; + } + $this->debug("serialize_val returning $xml"); + return $xml; + } /** - * serializes a message - * - * @param string $body the XML of the SOAP body - * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array - * @param array $namespaces optional the namespaces used in generating the body and headers - * @param string $style optional (rpc|document) - * @param string $use optional (encoded|literal) - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @return string the message - * @access public - */ - function serializeEnvelope($body,$headers=false,$namespaces=array(),$style='rpc',$use='encoded',$encodingStyle='http://schemas.xmlsoap.org/soap/encoding/'){ - // TODO: add an option to automatically run utf8_encode on $body and $headers - // if $this->soap_defencoding is UTF-8. Not doing this automatically allows - // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1 + * serializes a message + * + * @param string $body the XML of the SOAP body + * @param mixed $headers optional string of XML with SOAP header content, or array of soapval objects for SOAP headers, or associative array + * @param array $namespaces optional the namespaces used in generating the body and headers + * @param string $style optional (rpc|document) + * @param string $use optional (encoded|literal) + * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) + * @return string the message + * @access public + */ + function serializeEnvelope($body, $headers = false, $namespaces = array(), $style = 'rpc', $use = 'encoded', $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/') + { + // TODO: add an option to automatically run utf8_encode on $body and $headers + // if $this->soap_defencoding is UTF-8. Not doing this automatically allows + // one to send arbitrary UTF-8 characters, not just characters that map to ISO-8859-1 - $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle"); - $this->debug("headers:"); - $this->appendDebug($this->varDump($headers)); - $this->debug("namespaces:"); - $this->appendDebug($this->varDump($namespaces)); + $this->debug("In serializeEnvelope length=" . strlen($body) . " body (max 1000 characters)=" . substr($body, 0, 1000) . " style=$style use=$use encodingStyle=$encodingStyle"); + $this->debug("headers:"); + $this->appendDebug($this->varDump($headers)); + $this->debug("namespaces:"); + $this->appendDebug($this->varDump($namespaces)); - // serialize namespaces - $ns_string = ''; - foreach(array_merge($this->namespaces,$namespaces) as $k => $v){ - $ns_string .= " xmlns:$k=\"$v\""; - } - if($encodingStyle) { - $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string"; - } + // serialize namespaces + $ns_string = ''; + foreach (array_merge($this->namespaces, $namespaces) as $k => $v) { + $ns_string .= " xmlns:$k=\"$v\""; + } + if ($encodingStyle) { + $ns_string = " SOAP-ENV:encodingStyle=\"$encodingStyle\"$ns_string"; + } - // serialize headers - if($headers){ - if (is_array($headers)) { - $xml = ''; - foreach ($headers as $k => $v) { - if (is_object($v) && get_class($v) == 'soapval') { - $xml .= $this->serialize_val($v, false, false, false, false, false, $use); - } else { - $xml .= $this->serialize_val($v, $k, false, false, false, false, $use); - } - } - $headers = $xml; - $this->debug("In serializeEnvelope, serialized array of headers to $headers"); - } - $headers = "".$headers.""; - } - // serialize envelope + // serialize headers + if ($headers) { + if (is_array($headers)) { + $xml = ''; + foreach ($headers as $k => $v) { + if (is_object($v) && get_class($v) == 'soapval') { + $xml .= $this->serialize_val($v, false, false, false, false, false, $use); + } else { + $xml .= $this->serialize_val($v, $k, false, false, false, false, $use); + } + } + $headers = $xml; + $this->debug("In serializeEnvelope, serialized array of headers to $headers"); + } + $headers = "" . $headers . ""; + } + // serialize envelope + return + 'soap_defencoding . '"?' . ">" . + '" . + $headers . + "" . + $body . + "" . + ""; + } + + /** + * formats a string to be inserted into an HTML stream + * + * @param string $str The string to format + * @return string The formatted string + * @access public + * @deprecated + */ + function formatDump($str) + { + $str = htmlspecialchars($str); + return nl2br($str); + } + + /** + * contracts (changes namespace to prefix) a qualified name + * + * @param string $qname qname + * @return string contracted qname + * @access private + */ + function contractQname($qname) + { + // get element namespace + //$this->xdebug("Contract $qname"); + if (strrpos($qname, ':')) { + // get unqualified name + $name = substr($qname, strrpos($qname, ':') + 1); + // get ns + $ns = substr($qname, 0, strrpos($qname, ':')); + $p = $this->getPrefixFromNamespace($ns); + if ($p) { + return $p . ':' . $name; + } + } + return $qname; + } + + /** + * expands (changes prefix to namespace) a qualified name + * + * @param string $qname qname + * @return string expanded qname + * @access private + */ + function expandQname($qname) + { + // get element prefix + if (strpos($qname, ':') && !preg_match('/^http:\/\//', $qname)) { + // get unqualified name + $name = substr(strstr($qname, ':'), 1); + // get ns prefix + $prefix = substr($qname, 0, strpos($qname, ':')); + if (isset($this->namespaces[$prefix])) { + return $this->namespaces[$prefix] . ':' . $name; + } else { + return $qname; + } + } else { + return $qname; + } + } + + /** + * returns the local part of a prefixed string + * returns the original string, if not prefixed + * + * @param string $str The prefixed string + * @return string The local part + * @access public + */ + function getLocalPart($str) + { + if ($sstr = strrchr($str, ':')) { + // get unqualified name + return substr($sstr, 1); + } else { + return $str; + } + } + + /** + * returns the prefix part of a prefixed string + * returns false, if not prefixed + * + * @param string $str The prefixed string + * @return false|string The prefix or false if there is no prefix + * @access public + */ + function getPrefix($str) + { + if ($pos = strrpos($str, ':')) { + // get prefix + return substr($str, 0, $pos); + } + return false; + } + + /** + * pass it a prefix, it returns a namespace + * + * @param string $prefix The prefix + * @return mixed The namespace, false if no namespace has the specified prefix + * @access public + */ + function getNamespaceFromPrefix($prefix) + { + if (isset($this->namespaces[$prefix])) { + return $this->namespaces[$prefix]; + } + //$this->setError("No namespace registered for prefix '$prefix'"); + return false; + } + + /** + * returns the prefix for a given namespace (or prefix) + * or false if no prefixes registered for the given namespace + * + * @param string $ns The namespace + * @return false|string The prefix, false if the namespace has no prefixes + * @access public + */ + function getPrefixFromNamespace($ns) + { + foreach ($this->namespaces as $p => $n) { + if ($ns == $n || $ns == $p) { + $this->usedNamespaces[$p] = $n; + return $p; + } + } + return false; + } + + /** + * returns the time in ODBC canonical form with microseconds + * + * @return string The time in ODBC canonical form with microseconds + * @access public + */ + function getmicrotime() + { + if (function_exists('gettimeofday')) { + $tod = gettimeofday(); + $sec = $tod['sec']; + $usec = $tod['usec']; + } else { + $sec = time(); + $usec = 0; + } + $dtx = new DateTime("@$sec"); return - 'soap_defencoding .'"?'.">". - '". - $headers. - "". - $body. - "". - ""; + date_format($dtx, 'Y-m-d H:i:s') . '.' . sprintf('%06d', $usec); } - /** - * formats a string to be inserted into an HTML stream - * - * @param string $str The string to format - * @return string The formatted string - * @access public - * @deprecated - */ - function formatDump($str){ - $str = htmlspecialchars($str); - return nl2br($str); - } - - /** - * contracts (changes namespace to prefix) a qualified name - * - * @param string $qname qname - * @return string contracted qname - * @access private - */ - function contractQname($qname){ - // get element namespace - //$this->xdebug("Contract $qname"); - if (strrpos($qname, ':')) { - // get unqualified name - $name = substr($qname, strrpos($qname, ':') + 1); - // get ns - $ns = substr($qname, 0, strrpos($qname, ':')); - $p = $this->getPrefixFromNamespace($ns); - if ($p) { - return $p . ':' . $name; - } - return $qname; - } else { - return $qname; - } - } - - /** - * expands (changes prefix to namespace) a qualified name - * - * @param string $qname qname - * @return string expanded qname - * @access private - */ - function expandQname($qname){ - // get element prefix - if(strpos($qname,':') && !preg_match('/^http:\/\//',$qname)){ - // get unqualified name - $name = substr(strstr($qname,':'),1); - // get ns prefix - $prefix = substr($qname,0,strpos($qname,':')); - if(isset($this->namespaces[$prefix])){ - return $this->namespaces[$prefix].':'.$name; - } else { - return $qname; - } - } else { - return $qname; - } - } - /** - * returns the local part of a prefixed string - * returns the original string, if not prefixed - * - * @param string $str The prefixed string - * @return string The local part - * @access public - */ - function getLocalPart($str){ - if($sstr = strrchr($str,':')){ - // get unqualified name - return substr( $sstr, 1 ); - } else { - return $str; - } - } + * Returns a string with the output of var_dump + * + * @param mixed $data The variable to var_dump + * @return string The output of var_dump + * @access public + */ + function varDump($data) + { + ob_start(); + var_dump($data); + $ret_val = ob_get_contents(); + ob_end_clean(); + return $ret_val; + } - /** - * returns the prefix part of a prefixed string - * returns false, if not prefixed - * - * @param string $str The prefixed string - * @return mixed The prefix or false if there is no prefix - * @access public - */ - function getPrefix($str){ - if($pos = strrpos($str,':')){ - // get prefix - return substr($str,0,$pos); - } - return false; - } - - /** - * pass it a prefix, it returns a namespace - * - * @param string $prefix The prefix - * @return mixed The namespace, false if no namespace has the specified prefix - * @access public - */ - function getNamespaceFromPrefix($prefix){ - if (isset($this->namespaces[$prefix])) { - return $this->namespaces[$prefix]; - } - //$this->setError("No namespace registered for prefix '$prefix'"); - return false; - } - - /** - * returns the prefix for a given namespace (or prefix) - * or false if no prefixes registered for the given namespace - * - * @param string $ns The namespace - * @return mixed The prefix, false if the namespace has no prefixes - * @access public - */ - function getPrefixFromNamespace($ns) { - foreach ($this->namespaces as $p => $n) { - if ($ns == $n || $ns == $p) { - $this->usedNamespaces[$p] = $n; - return $p; - } - } - return false; - } - - /** - * returns the time in ODBC canonical form with microseconds - * - * @return string The time in ODBC canonical form with microseconds - * @access public - */ - function getmicrotime() { - if (function_exists('gettimeofday')) { - $tod = gettimeofday(); - $sec = $tod['sec']; - $usec = $tod['usec']; - } else { - $sec = time(); - $usec = 0; - } - return strftime('%Y-%m-%d %H:%M:%S', $sec) . '.' . sprintf('%06d', $usec); - } - - /** - * Returns a string with the output of var_dump - * - * @param mixed $data The variable to var_dump - * @return string The output of var_dump - * @access public - */ - function varDump($data) { - ob_start(); - var_dump($data); - $ret_val = ob_get_contents(); - ob_end_clean(); - return $ret_val; - } - - /** - * represents the object as a string - * - * @return string - * @access public - */ - function __toString() { - return $this->varDump($this); - } + /** + * represents the object as a string + * + * @return string + * @access public + */ + function __toString() + { + return $this->varDump($this); + } } // XML Schema Datatype Helper Functions @@ -894,1441 +930,1460 @@ class nusoap_base { //xsd:dateTime helpers /** -* convert unix timestamp to ISO 8601 compliant date string -* -* @param int $timestamp Unix time stamp -* @param boolean $utc Whether the time stamp is UTC or local -* @return mixed ISO 8601 date string or false -* @access public -*/ -function timestamp_to_iso8601($timestamp,$utc=true){ - $datestr = date('Y-m-d\TH:i:sO',$timestamp); - $pos = strrpos($datestr, "+"); - if ($pos === FALSE) { - $pos = strrpos($datestr, "-"); - } - if ($pos !== FALSE) { - if (strlen($datestr) == $pos + 5) { - $datestr = substr($datestr, 0, $pos + 3) . ':' . substr($datestr, -2); - } - } - if($utc){ - $pattern = '/'. - '([0-9]{4})-'. // centuries & years CCYY- - '([0-9]{2})-'. // months MM- - '([0-9]{2})'. // days DD - 'T'. // separator T - '([0-9]{2}):'. // hours hh: - '([0-9]{2}):'. // minutes mm: - '([0-9]{2})(\.[0-9]*)?'. // seconds ss.ss... - '(Z|[+\-][0-9]{2}:?[0-9]{2})?'. // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's - '/'; + * convert unix timestamp to ISO 8601 compliant date string + * + * @param int $timestamp Unix time stamp + * @param boolean $utc Whether the time stamp is UTC or local + * @return false|string ISO 8601 date string or false + * @access public + */ +function timestamp_to_iso8601($timestamp, $utc = true) +{ + $datestr = date('Y-m-d\TH:i:sO', $timestamp); + $pos = strrpos($datestr, "+"); + if ($pos === false) { + $pos = strrpos($datestr, "-"); + } + if ($pos !== false) { + if (strlen($datestr) == $pos + 5) { + $datestr = substr($datestr, 0, $pos + 3) . ':' . substr($datestr, -2); + } + } + if ($utc) { + $pattern = '/' . + '([0-9]{4})-' . // centuries & years CCYY- + '([0-9]{2})-' . // months MM- + '([0-9]{2})' . // days DD + 'T' . // separator T + '([0-9]{2}):' . // hours hh: + '([0-9]{2}):' . // minutes mm: + '([0-9]{2})(\.[0-9]*)?' . // seconds ss.ss... + '(Z|[+\-][0-9]{2}:?[0-9]{2})?' . // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's + '/'; - if(preg_match($pattern,$datestr,$regs)){ - return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ',$regs[1],$regs[2],$regs[3],$regs[4],$regs[5],$regs[6]); - } - return false; - } else { - return $datestr; - } + if (preg_match($pattern, $datestr, $regs)) { + return sprintf('%04d-%02d-%02dT%02d:%02d:%02dZ', $regs[1], $regs[2], $regs[3], $regs[4], $regs[5], $regs[6]); + } + return false; + } else { + return $datestr; + } } /** -* convert ISO 8601 compliant date string to unix timestamp -* -* @param string $datestr ISO 8601 compliant date string -* @return mixed Unix timestamp (int) or false -* @access public -*/ -function iso8601_to_timestamp($datestr){ - $pattern = '/'. - '([0-9]{4})-'. // centuries & years CCYY- - '([0-9]{2})-'. // months MM- - '([0-9]{2})'. // days DD - 'T'. // separator T - '([0-9]{2}):'. // hours hh: - '([0-9]{2}):'. // minutes mm: - '([0-9]{2})(\.[0-9]+)?'. // seconds ss.ss... - '(Z|[+\-][0-9]{2}:?[0-9]{2})?'. // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's - '/'; - if(preg_match($pattern,$datestr,$regs)){ - // not utc - if($regs[8] != 'Z'){ - $op = substr($regs[8],0,1); - $h = substr($regs[8],1,2); - $m = substr($regs[8],strlen($regs[8])-2,2); - if($op == '-'){ - $regs[4] = $regs[4] + $h; - $regs[5] = $regs[5] + $m; - } elseif($op == '+'){ - $regs[4] = $regs[4] - $h; - $regs[5] = $regs[5] - $m; - } - } - return gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); + * convert ISO 8601 compliant date string to unix timestamp + * + * @param string $datestr ISO 8601 compliant date string + * @return false|int Unix timestamp (int) or false + * @access public + */ +function iso8601_to_timestamp($datestr) +{ + $pattern = '/' . + '([0-9]{4})-' . // centuries & years CCYY- + '([0-9]{2})-' . // months MM- + '([0-9]{2})' . // days DD + 'T' . // separator T + '([0-9]{2}):' . // hours hh: + '([0-9]{2}):' . // minutes mm: + '([0-9]{2})(\.[0-9]+)?' . // seconds ss.ss... + '(Z|[+\-][0-9]{2}:?[0-9]{2})?' . // Z to indicate UTC, -/+HH:MM:SS.SS... for local tz's + '/'; + if (preg_match($pattern, $datestr, $regs)) { + // not utc + if ($regs[8] != 'Z') { + $op = substr($regs[8], 0, 1); + $h = substr($regs[8], 1, 2); + $m = substr($regs[8], strlen($regs[8]) - 2, 2); + if ($op == '-') { + $regs[4] = intval ($regs[4]) + intval ($h); + $regs[5] = intval ($regs[5]) + intval ($m); + } elseif ($op == '+') { + $regs[4] = intval ($regs[4]) - intval ($h); + $regs[5] = intval ($regs[5]) - intval ($m); + } + } + return gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]); // return strtotime("$regs[1]-$regs[2]-$regs[3] $regs[4]:$regs[5]:$regs[6]Z"); - } else { - return false; - } + } else { + return false; + } } /** -* sleeps some number of microseconds -* -* @param string $usec the number of microseconds to sleep -* @access public -* @deprecated -*/ + * sleeps some number of microseconds + * + * @param string $usec the number of microseconds to sleep + * @access public + * @deprecated + */ function usleepWindows($usec) { - $start = gettimeofday(); + $start = gettimeofday(); - do - { - $stop = gettimeofday(); - $timePassed = 1000000 * ($stop['sec'] - $start['sec']) - + $stop['usec'] - $start['usec']; - } - while ($timePassed < $usec); + do { + $stop = gettimeofday(); + $timePassed = 1000000 * ($stop['sec'] - $start['sec']) + + $stop['usec'] - $start['usec']; + } while ($timePassed < $usec); } -?> -* @access public -*/ -class nusoap_fault extends nusoap_base { - /** - * The fault code (client|server) - * @var string - * @access private - */ - var $faultcode; - /** - * The fault actor - * @var string - * @access private - */ - var $faultactor; - /** - * The fault string, a description of the fault - * @var string - * @access private - */ - var $faultstring; - /** - * The fault detail, typically a string or array of string - * @var mixed - * @access private - */ - var $faultdetail; + * Contains information for a SOAP fault. + * Mainly used for returning faults from deployed functions + * in a server instance. + * + * @author Dietrich Ayala + * @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $ + * @access public + */ +class nusoap_fault extends nusoap_base +{ + /** + * The fault code (client|server) + * + * @var string + * @access private + */ + var $faultcode; + /** + * The fault actor + * + * @var string + * @access private + */ + var $faultactor; + /** + * The fault string, a description of the fault + * + * @var string + * @access private + */ + var $faultstring; + /** + * The fault detail, typically a string or array of string + * + * @var mixed + * @access private + */ + var $faultdetail; - /** - * constructor - * - * @param string $faultcode (SOAP-ENV:Client | SOAP-ENV:Server) - * @param string $faultactor only used when msg routed between multiple actors - * @param string $faultstring human readable error message - * @param mixed $faultdetail detail, typically a string or array of string - */ - function __construct($faultcode,$faultactor='',$faultstring='',$faultdetail=''){ - parent::__construct(); - $this->faultcode = $faultcode; - $this->faultactor = $faultactor; - $this->faultstring = $faultstring; - $this->faultdetail = $faultdetail; - } + /** + * constructor + * + * @param string $faultcode (SOAP-ENV:Client | SOAP-ENV:Server) + * @param string $faultactor only used when msg routed between multiple actors + * @param string $faultstring human readable error message + * @param mixed $faultdetail detail, typically a string or array of string + */ + function __construct($faultcode, $faultactor = '', $faultstring = '', $faultdetail = '') + { + parent::__construct(); + $this->faultcode = $faultcode; + $this->faultactor = $faultactor; + $this->faultstring = $faultstring; + $this->faultdetail = $faultdetail; + } - /** - * serialize a fault - * - * @return string The serialization of the fault instance. - * @access public - */ - function serialize(){ - $ns_string = ''; - foreach($this->namespaces as $k => $v){ - $ns_string .= "\n xmlns:$k=\"$v\""; - } - $return_msg = - 'soap_defencoding.'"?>'. - '\n". - ''. - ''. - $this->serialize_val($this->faultcode, 'faultcode'). - $this->serialize_val($this->faultactor, 'faultactor'). - $this->serialize_val($this->faultstring, 'faultstring'). - $this->serialize_val($this->faultdetail, 'detail'). - ''. - ''. - ''; - return $return_msg; - } + /** + * serialize a fault + * + * @return string The serialization of the fault instance. + * @access public + */ + function serialize() + { + $ns_string = ''; + foreach ($this->namespaces as $k => $v) { + $ns_string .= "\n xmlns:$k=\"$v\""; + } + + return 'soap_defencoding . '"?>' . + '\n" . + '' . + '' . + $this->serialize_val($this->faultcode, 'faultcode') . + $this->serialize_val($this->faultstring, 'faultstring') . + $this->serialize_val($this->faultactor, 'faultactor') . + $this->serialize_val($this->faultdetail, 'detail') . + '' . + '' . + ''; + } } + /** * Backward compatibility */ -class soap_fault extends nusoap_fault { +class soap_fault extends nusoap_fault +{ } -?> -* @author Scott Nichol -* @access public -*/ -class nusoap_xmlschema extends nusoap_base { + * parses an XML Schema, allows access to it's data, other utility methods. + * imperfect, no validation... yet, but quite functional. + * + * @author Dietrich Ayala + * @author Scott Nichol + * @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $ + * @access public + */ +class nusoap_xmlschema extends nusoap_base +{ - // files - var $schema = ''; - var $xml = ''; - // namespaces - var $enclosingNamespaces; - // schema info - var $schemaInfo = array(); - var $schemaTargetNamespace = ''; - // types, elements, attributes defined by the schema - var $attributes = array(); - var $complexTypes = array(); - var $complexTypeStack = array(); - var $currentComplexType = null; - var $elements = array(); - var $elementStack = array(); - var $currentElement = null; - var $simpleTypes = array(); - var $simpleTypeStack = array(); - var $currentSimpleType = null; - // imports - var $imports = array(); - // parser vars - var $parser; - var $position = 0; - var $depth = 0; - var $depth_array = array(); - var $message = array(); - var $defaultNamespace = array(); - - /** - * constructor - * - * @param string $schema schema document URI - * @param string $xml xml document URI - * @param string $namespaces namespaces defined in enclosing XML - * @access public - */ - function __construct($schema='',$xml='',$namespaces=array()){ - parent::__construct(); - $this->debug('nusoap_xmlschema class instantiated, inside constructor'); - // files - $this->schema = $schema; - $this->xml = $xml; - - // namespaces - $this->enclosingNamespaces = $namespaces; - $this->namespaces = array_merge($this->namespaces, $namespaces); - - // parse schema file - if($schema != ''){ - $this->debug('initial schema file: '.$schema); - $this->parseFile($schema, 'schema'); - } - - // parse xml file - if($xml != ''){ - $this->debug('initial xml file: '.$xml); - $this->parseFile($xml, 'xml'); - } - - } + // files + var $schema = ''; + var $xml = ''; + // namespaces + var $enclosingNamespaces; + // schema info + var $schemaInfo = array(); + var $schemaTargetNamespace = ''; + // types, elements, attributes defined by the schema + var $attributes = array(); + var $complexTypes = array(); + var $complexTypeStack = array(); + var $currentComplexType = null; + var $elements = array(); + var $elementStack = array(); + var $currentElement = null; + var $simpleTypes = array(); + var $simpleTypeStack = array(); + var $currentSimpleType = null; + // imports + var $imports = array(); + // parser vars + var $parser; + var $position = 0; + var $depth = 0; + var $depth_array = array(); + var $message = array(); + var $defaultNamespace = array(); /** - * parse an XML file - * - * @param string $xml path/URL to XML file - * @param string $type (schema | xml) - * @return boolean - * @access public - */ - function parseFile($xml,$type){ - // parse xml file - if($xml != ""){ - $xmlStr = @join("",@file($xml)); - if($xmlStr == ""){ - $msg = 'Error reading XML from '.$xml; - $this->setError($msg); - $this->debug($msg); - return false; - } else { - $this->debug("parsing $xml"); - $this->parseString($xmlStr,$type); - $this->debug("done parsing $xml"); - return true; - } - } - return false; - } + * constructor + * + * @param string $schema schema document URI + * @param string $xml xml document URI + * @param string $namespaces namespaces defined in enclosing XML + * @access public + */ + function __construct($schema = '', $xml = '', $namespaces = array()) + { + parent::__construct(); + $this->debug('nusoap_xmlschema class instantiated, inside constructor'); + // files + $this->schema = $schema; + $this->xml = $xml; - /** - * parse an XML string - * - * @param string $xml path or URL - * @param string $type (schema|xml) - * @access private - */ - function parseString($xml,$type){ - // parse xml string - if($xml != ""){ + // namespaces + $this->enclosingNamespaces = $namespaces; + $this->namespaces = array_merge($this->namespaces, $namespaces); - // Create an XML parser. - $this->parser = xml_parser_create(); - // Set the options for parsing the XML data. - xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); + // parse schema file + if ($schema != '') { + $this->debug('initial schema file: ' . $schema); + $this->parseFile($schema, 'schema'); + } - // Set the object for the parser. - xml_set_object($this->parser, $this); + // parse xml file + if ($xml != '') { + $this->debug('initial xml file: ' . $xml); + $this->parseFile($xml, 'xml'); + } - // Set the element handlers for the parser. - if($type == "schema"){ - xml_set_element_handler($this->parser, 'schemaStartElement','schemaEndElement'); - xml_set_character_data_handler($this->parser,'schemaCharacterData'); - } elseif($type == "xml"){ - xml_set_element_handler($this->parser, 'xmlStartElement','xmlEndElement'); - xml_set_character_data_handler($this->parser,'xmlCharacterData'); - } + } - // Parse the XML file. - if(!xml_parse($this->parser,$xml,true)){ - // Display an error message. - $errstr = sprintf('XML error parsing XML schema on line %d: %s', - xml_get_current_line_number($this->parser), - xml_error_string(xml_get_error_code($this->parser)) - ); - $this->debug($errstr); - $this->debug("XML payload:\n" . $xml); - $this->setError($errstr); - } + /** + * parse an XML file + * + * @param string $xml path/URL to XML file + * @param string $type (schema | xml) + * @return boolean + * @access public + */ + function parseFile($xml, $type) + { + // parse xml file + if ($xml != "") { + $xmlStr = @join("", @file($xml)); + if ($xmlStr == "") { + $msg = 'Error reading XML from ' . $xml; + $this->setError($msg); + $this->debug($msg); + return false; + } else { + $this->debug("parsing $xml"); + $this->parseString($xmlStr, $type); + $this->debug("done parsing $xml"); + return true; + } + } + return false; + } - xml_parser_free($this->parser); - } else{ - $this->debug('no xml passed to parseString()!!'); - $this->setError('no xml passed to parseString()!!'); - } - } + /** + * parse an XML string + * + * @param string $xml path or URL + * @param string $type (schema|xml) + * @access private + */ + function parseString($xml, $type) + { + // parse xml string + if ($xml != "") { - /** - * gets a type name for an unnamed type - * - * @param string Element name - * @return string A type name for an unnamed type - * @access private - */ - function CreateTypeName($ename) { - $scope = ''; - for ($i = 0; $i < count($this->complexTypeStack); $i++) { - $scope .= $this->complexTypeStack[$i] . '_'; - } - return $scope . $ename . '_ContainedType'; - } + // Create an XML parser. + $this->parser = xml_parser_create(); + // Set the options for parsing the XML data. + xml_parser_set_option($this->parser, XML_OPTION_CASE_FOLDING, 0); - /** - * start-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @param string $attrs associative array of attributes - * @access private - */ - function schemaStartElement($parser, $name, $attrs) { + // Set the object for the parser. + xml_set_object($this->parser, $this); - // position in the total number of elements, starting from 0 - $pos = $this->position++; - $depth = $this->depth++; - // set self as current value for this depth - $this->depth_array[$depth] = $pos; - $this->message[$pos] = array('cdata' => ''); - if ($depth > 0) { - $this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]]; - } else { - $this->defaultNamespace[$pos] = false; - } + // Set the element handlers for the parser. + if ($type == "schema") { + xml_set_element_handler($this->parser, 'schemaStartElement', 'schemaEndElement'); + xml_set_character_data_handler($this->parser, 'schemaCharacterData'); + } elseif ($type == "xml") { + xml_set_element_handler($this->parser, 'xmlStartElement', 'xmlEndElement'); + xml_set_character_data_handler($this->parser, 'xmlCharacterData'); + } - // get element prefix - if($prefix = $this->getPrefix($name)){ - // get unqualified name - $name = $this->getLocalPart($name); - } else { - $prefix = ''; + libxml_disable_entity_loader(true); // Avoid load of external entities (security problem). Required only for libxml < 2. + + // Parse the XML file. + if (!xml_parse($this->parser, $xml, true)) { + // Display an error message. + $errstr = sprintf('XML error parsing XML schema on line %d: %s', + xml_get_current_line_number($this->parser), + xml_error_string(xml_get_error_code($this->parser)) + ); + $this->debug($errstr); + $this->debug("XML payload:\n" . $xml); + $this->setError($errstr); + } + + xml_parser_free($this->parser); + unset($this->parser); + } else { + $this->debug('no xml passed to parseString()!!'); + $this->setError('no xml passed to parseString()!!'); + } + } + + /** + * gets a type name for an unnamed type + * + * @param string $ename Element name + * @return string A type name for an unnamed type + * @access private + */ + function CreateTypeName($ename) + { + $scope = ''; + for ($i = 0; $i < count($this->complexTypeStack); $i++) { + $scope .= $this->complexTypeStack[$i] . '_'; + } + return $scope . $ename . '_ContainedType'; + } + + /** + * start-element handler + * + * @param string $parser XML parser object + * @param string $name element name + * @param array $attrs associative array of attributes + * @access private + */ + function schemaStartElement($parser, $name, $attrs) + { + + // position in the total number of elements, starting from 0 + $pos = $this->position++; + $depth = $this->depth++; + // set self as current value for this depth + $this->depth_array[$depth] = $pos; + $this->message[$pos] = array('cdata' => ''); + if ($depth > 0) { + $this->defaultNamespace[$pos] = $this->defaultNamespace[$this->depth_array[$depth - 1]]; + } else { + $this->defaultNamespace[$pos] = false; + } + + // get element prefix + if ($prefix = $this->getPrefix($name)) { + // get unqualified name + $name = $this->getLocalPart($name); + } else { + $prefix = ''; } // loop thru attributes, expanding, and registering namespace declarations - if(count($attrs) > 0){ - foreach($attrs as $k => $v){ + if (count($attrs) > 0) { + foreach ($attrs as $k => $v) { // if ns declarations, add to class level array of valid namespaces - if(preg_match('/^xmlns/',$k)){ - //$this->xdebug("$k: $v"); - //$this->xdebug('ns_prefix: '.$this->getPrefix($k)); - if($ns_prefix = substr(strrchr($k,':'),1)){ - //$this->xdebug("Add namespace[$ns_prefix] = $v"); - $this->namespaces[$ns_prefix] = $v; - } else { - $this->defaultNamespace[$pos] = $v; - if (! $this->getPrefixFromNamespace($v)) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $v; - } - } - if($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema'){ - $this->XMLSchemaVersion = $v; - $this->namespaces['xsi'] = $v.'-instance'; - } - } - } - foreach($attrs as $k => $v){ + if (preg_match('/^xmlns/', $k)) { + //$this->xdebug("$k: $v"); + //$this->xdebug('ns_prefix: '.$this->getPrefix($k)); + if ($ns_prefix = substr(strrchr($k, ':'), 1)) { + //$this->xdebug("Add namespace[$ns_prefix] = $v"); + $this->namespaces[$ns_prefix] = $v; + } else { + $this->defaultNamespace[$pos] = $v; + if (!$this->getPrefixFromNamespace($v)) { + $this->namespaces['ns' . (count($this->namespaces) + 1)] = $v; + } + } + if ($v == 'http://www.w3.org/2001/XMLSchema' || $v == 'http://www.w3.org/1999/XMLSchema' || $v == 'http://www.w3.org/2000/10/XMLSchema') { + $this->XMLSchemaVersion = $v; + $this->namespaces['xsi'] = $v . '-instance'; + } + } + } + $eAttrs = array (); + foreach ($attrs as $k => $v) { // expand each attribute - $k = strpos($k,':') ? $this->expandQname($k) : $k; - $v = strpos($v,':') ? $this->expandQname($v) : $v; - $eAttrs[$k] = $v; - } - $attrs = $eAttrs; + $k = strpos($k, ':') ? $this->expandQname($k) : $k; + $v = strpos($v, ':') ? $this->expandQname($v) : $v; + $eAttrs[$k] = $v; + } + $attrs = $eAttrs; } else { - $attrs = array(); + $attrs = array(); } - // find status, register data - switch($name){ - case 'all': // (optional) compositor content for a complexType - case 'choice': - case 'group': - case 'sequence': - //$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement"); - $this->complexTypes[$this->currentComplexType]['compositor'] = $name; - //if($name == 'all' || $name == 'sequence'){ - // $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - //} - break; - case 'attribute': // complexType attribute - //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']); - $this->xdebug("parsing attribute:"); - $this->appendDebug($this->varDump($attrs)); - if (!isset($attrs['form'])) { - // TODO: handle globals - $attrs['form'] = $this->schemaInfo['attributeFormDefault']; - } - if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { - $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - if (!strpos($v, ':')) { - // no namespace in arrayType attribute value... - if ($this->defaultNamespace[$pos]) { - // ...so use the default - $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } - } - } - if(isset($attrs['name'])){ - $this->attributes[$attrs['name']] = $attrs; - $aname = $attrs['name']; - } elseif(isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType'){ - if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { - $aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } else { - $aname = ''; - } - } elseif(isset($attrs['ref'])){ - $aname = $attrs['ref']; + // find status, register data + switch ($name) { + case 'all': // (optional) compositor content for a complexType + case 'choice': + case 'group': + case 'sequence': + //$this->xdebug("compositor $name for currentComplexType: $this->currentComplexType and currentElement: $this->currentElement"); + $this->complexTypes[$this->currentComplexType]['compositor'] = $name; + //if($name == 'all' || $name == 'sequence'){ + // $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; + //} + break; + case 'attribute': // complexType attribute + //$this->xdebug("parsing attribute $attrs[name] $attrs[ref] of value: ".$attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']); + $this->xdebug("parsing attribute:"); + $this->appendDebug($this->varDump($attrs)); + if (!isset($attrs['form'])) { + // TODO: handle globals + $attrs['form'] = $this->schemaInfo['attributeFormDefault']; + } + if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { + $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; + if (!strpos($v, ':')) { + // no namespace in arrayType attribute value... + if ($this->defaultNamespace[$pos]) { + // ...so use the default + $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'] = $this->defaultNamespace[$pos] . ':' . $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; + } + } + } + if (isset($attrs['name'])) { + $this->attributes[$attrs['name']] = $attrs; + $aname = $attrs['name']; + } elseif (isset($attrs['ref']) && $attrs['ref'] == 'http://schemas.xmlsoap.org/soap/encoding/:arrayType') { + if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { + $aname = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; + } else { + $aname = ''; + } + } elseif (isset($attrs['ref'])) { + $aname = $attrs['ref']; $this->attributes[$attrs['ref']] = $attrs; - } + } else { + $aname = ''; + } - if($this->currentComplexType){ // This should *always* be - $this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs; - } - // arrayType attribute - if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType'){ - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - $prefix = $this->getPrefix($aname); - if(isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])){ - $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; - } else { - $v = ''; - } - if(strpos($v,'[,]')){ + if ($this->currentComplexType) { // This should *always* be + $this->complexTypes[$this->currentComplexType]['attrs'][$aname] = $attrs; + } + // arrayType attribute + if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']) || $this->getLocalPart($aname) == 'arrayType') { + $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; + if (isset($attrs['http://schemas.xmlsoap.org/wsdl/:arrayType'])) { + $v = $attrs['http://schemas.xmlsoap.org/wsdl/:arrayType']; + } else { + $v = ''; + } + if (strpos($v, '[,]')) { $this->complexTypes[$this->currentComplexType]['multidimensional'] = true; } - $v = substr($v,0,strpos($v,'[')); // clip the [] - if(!strpos($v,':') && isset($this->typemap[$this->XMLSchemaVersion][$v])){ - $v = $this->XMLSchemaVersion.':'.$v; + $v = substr($v, 0, strpos($v, '[')); // clip the [] + if (!strpos($v, ':') && isset($this->typemap[$this->XMLSchemaVersion][$v])) { + $v = $this->XMLSchemaVersion . ':' . $v; } $this->complexTypes[$this->currentComplexType]['arrayType'] = $v; - } - break; - case 'complexContent': // (optional) content for a complexType - $this->xdebug("do nothing for element $name"); - break; - case 'complexType': - array_push($this->complexTypeStack, $this->currentComplexType); - if(isset($attrs['name'])){ - // TODO: what is the scope of named complexTypes that appear - // nested within other c complexTypes? - $this->xdebug('processing named complexType '.$attrs['name']); - //$this->currentElement = false; - $this->currentComplexType = $attrs['name']; - $this->complexTypes[$this->currentComplexType] = $attrs; - $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; - // This is for constructs like - // - // - // - // - // - if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){ - $this->xdebug('complexType is unusual array'); - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } else { - $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - } - } else { - $name = $this->CreateTypeName($this->currentElement); - $this->xdebug('processing unnamed complexType for element ' . $this->currentElement . ' named ' . $name); - $this->currentComplexType = $name; - //$this->currentElement = false; - $this->complexTypes[$this->currentComplexType] = $attrs; - $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; - // This is for constructs like - // - // - // - // - // - if(isset($attrs['base']) && preg_match('/:Array$/',$attrs['base'])){ - $this->xdebug('complexType is unusual array'); - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } else { - $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; - } - } - $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'false'; - break; - case 'element': - array_push($this->elementStack, $this->currentElement); - if (!isset($attrs['form'])) { - if ($this->currentComplexType) { - $attrs['form'] = $this->schemaInfo['elementFormDefault']; - } else { - // global - $attrs['form'] = 'qualified'; - } - } - if(isset($attrs['type'])){ - $this->xdebug("processing typed element ".$attrs['name']." of type ".$attrs['type']); - if (! $this->getPrefix($attrs['type'])) { - if ($this->defaultNamespace[$pos]) { - $attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type']; - $this->xdebug('used default namespace to make type ' . $attrs['type']); - } - } - // This is for constructs like - // - // - // - // - // - if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') { - $this->xdebug('arrayType for unusual array is ' . $attrs['type']); - $this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type']; - } - $this->currentElement = $attrs['name']; - $ename = $attrs['name']; - } elseif(isset($attrs['ref'])){ - $this->xdebug("processing element as ref to ".$attrs['ref']); - $this->currentElement = "ref to ".$attrs['ref']; - $ename = $this->getLocalPart($attrs['ref']); - } else { - $type = $this->CreateTypeName($this->currentComplexType . '_' . $attrs['name']); - $this->xdebug("processing untyped element " . $attrs['name'] . ' type ' . $type); - $this->currentElement = $attrs['name']; - $attrs['type'] = $this->schemaTargetNamespace . ':' . $type; - $ename = $attrs['name']; - } - if (isset($ename) && $this->currentComplexType) { - $this->xdebug("add element $ename to complexType $this->currentComplexType"); - $this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs; - } elseif (!isset($attrs['ref'])) { - $this->xdebug("add element $ename to elements array"); - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; - } - break; - case 'enumeration': // restriction value list member - $this->xdebug('enumeration ' . $attrs['value']); - if ($this->currentSimpleType) { - $this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value']; - } elseif ($this->currentComplexType) { - $this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value']; - } - break; - case 'extension': // simpleContent or complexContent type extension - $this->xdebug('extension ' . $attrs['base']); - if ($this->currentComplexType) { - $ns = $this->getPrefix($attrs['base']); - if ($ns == '') { - $this->complexTypes[$this->currentComplexType]['extensionBase'] = $this->schemaTargetNamespace . ':' . $attrs['base']; - } else { - $this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base']; - } - } else { - $this->xdebug('no current complexType to set extensionBase'); - } - break; - case 'import': - if (isset($attrs['schemaLocation'])) { - $this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']); + } + break; + case 'complexContent': // (optional) content for a complexType + $this->xdebug("do nothing for element $name"); + break; + case 'complexType': + $this->complexTypeStack[] = $this->currentComplexType; + if (isset($attrs['name'])) { + // TODO: what is the scope of named complexTypes that appear + // nested within other c complexTypes? + $this->xdebug('processing named complexType ' . $attrs['name']); + //$this->currentElement = false; + $this->currentComplexType = $attrs['name']; + } else { + $name = $this->CreateTypeName($this->currentElement); + $this->xdebug('processing unnamed complexType for element ' . $this->currentElement . ' named ' . $name); + $this->currentComplexType = $name; + //$this->currentElement = false; + } + $this->complexTypes[$this->currentComplexType] = $attrs; + $this->complexTypes[$this->currentComplexType]['typeClass'] = 'complexType'; + // This is for constructs like + // + // + // + // + // + if (isset($attrs['base']) && preg_match('/:Array$/', $attrs['base'])) { + $this->xdebug('complexType is unusual array'); + $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; + } else { + $this->complexTypes[$this->currentComplexType]['phpType'] = 'struct'; + } + $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'false'; + break; + case 'element': + $this->elementStack[] = $this->currentElement; + if (!isset($attrs['form'])) { + if ($this->currentComplexType) { + $attrs['form'] = $this->schemaInfo['elementFormDefault']; + } else { + // global + $attrs['form'] = 'qualified'; + } + } + if (isset($attrs['type'])) { + $this->xdebug("processing typed element " . $attrs['name'] . " of type " . $attrs['type']); + if (!$this->getPrefix($attrs['type'])) { + if ($this->defaultNamespace[$pos]) { + $attrs['type'] = $this->defaultNamespace[$pos] . ':' . $attrs['type']; + $this->xdebug('used default namespace to make type ' . $attrs['type']); + } + } + // This is for constructs like + // + // + // + // + // + if ($this->currentComplexType && $this->complexTypes[$this->currentComplexType]['phpType'] == 'array') { + $this->xdebug('arrayType for unusual array is ' . $attrs['type']); + $this->complexTypes[$this->currentComplexType]['arrayType'] = $attrs['type']; + } + $this->currentElement = $attrs['name']; + $ename = $attrs['name']; + } elseif (isset($attrs['ref'])) { + $this->xdebug("processing element as ref to " . $attrs['ref']); + $this->currentElement = "ref to " . $attrs['ref']; + $ename = $this->getLocalPart($attrs['ref']); + } else { + $type = $this->CreateTypeName($this->currentComplexType . '_' . $attrs['name']); + $this->xdebug("processing untyped element " . $attrs['name'] . ' type ' . $type); + $this->currentElement = $attrs['name']; + $attrs['type'] = $this->schemaTargetNamespace . ':' . $type; + $ename = $attrs['name']; + } + if (isset($ename) && $this->currentComplexType) { + $this->xdebug("add element $ename to complexType $this->currentComplexType"); + $this->complexTypes[$this->currentComplexType]['elements'][$ename] = $attrs; + } elseif (!isset($attrs['ref'])) { + $this->xdebug("add element $ename to elements array"); + $this->elements[$attrs['name']] = $attrs; + $this->elements[$attrs['name']]['typeClass'] = 'element'; + } + break; + case 'enumeration': // restriction value list member + $this->xdebug('enumeration ' . $attrs['value']); + if ($this->currentSimpleType) { + $this->simpleTypes[$this->currentSimpleType]['enumeration'][] = $attrs['value']; + } elseif ($this->currentComplexType) { + $this->complexTypes[$this->currentComplexType]['enumeration'][] = $attrs['value']; + } + break; + case 'extension': // simpleContent or complexContent type extension + $this->xdebug('extension ' . $attrs['base']); + if ($this->currentComplexType) { + $ns = $this->getPrefix($attrs['base']); + if ($ns == '') { + $this->complexTypes[$this->currentComplexType]['extensionBase'] = $this->schemaTargetNamespace . ':' . $attrs['base']; + } else { + $this->complexTypes[$this->currentComplexType]['extensionBase'] = $attrs['base']; + } + } else { + $this->xdebug('no current complexType to set extensionBase'); + } + break; + case 'import': + if (isset($attrs['schemaLocation'])) { + $this->xdebug('import namespace ' . $attrs['namespace'] . ' from ' . $attrs['schemaLocation']); $this->imports[$attrs['namespace']][] = array('location' => $attrs['schemaLocation'], 'loaded' => false); - } else { - $this->xdebug('import namespace ' . $attrs['namespace']); + } else { + $this->xdebug('import namespace ' . $attrs['namespace']); $this->imports[$attrs['namespace']][] = array('location' => '', 'loaded' => true); - if (! $this->getPrefixFromNamespace($attrs['namespace'])) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace']; - } - } - break; - case 'include': - if (isset($attrs['schemaLocation'])) { - $this->xdebug('include into namespace ' . $this->schemaTargetNamespace . ' from ' . $attrs['schemaLocation']); + if (!$this->getPrefixFromNamespace($attrs['namespace'])) { + $this->namespaces['ns' . (count($this->namespaces) + 1)] = $attrs['namespace']; + } + } + break; + case 'include': + if (isset($attrs['schemaLocation'])) { + $this->xdebug('include into namespace ' . $this->schemaTargetNamespace . ' from ' . $attrs['schemaLocation']); $this->imports[$this->schemaTargetNamespace][] = array('location' => $attrs['schemaLocation'], 'loaded' => false); - } else { - $this->xdebug('ignoring invalid XML Schema construct: include without schemaLocation attribute'); - } - break; - case 'list': // simpleType value list - $this->xdebug("do nothing for element $name"); - break; - case 'restriction': // simpleType, simpleContent or complexContent value restriction - $this->xdebug('restriction ' . $attrs['base']); - if($this->currentSimpleType){ - $this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base']; - } elseif($this->currentComplexType){ - $this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base']; - if(strstr($attrs['base'],':') == ':Array'){ - $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; - } - } - break; - case 'schema': - $this->schemaInfo = $attrs; - $this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix); - if (isset($attrs['targetNamespace'])) { - $this->schemaTargetNamespace = $attrs['targetNamespace']; - } - if (!isset($attrs['elementFormDefault'])) { - $this->schemaInfo['elementFormDefault'] = 'unqualified'; - } - if (!isset($attrs['attributeFormDefault'])) { - $this->schemaInfo['attributeFormDefault'] = 'unqualified'; - } - break; - case 'simpleContent': // (optional) content for a complexType - if ($this->currentComplexType) { // This should *always* be - $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'true'; - } else { - $this->xdebug("do nothing for element $name because there is no current complexType"); - } - break; - case 'simpleType': - array_push($this->simpleTypeStack, $this->currentSimpleType); - if(isset($attrs['name'])){ - $this->xdebug("processing simpleType for name " . $attrs['name']); - $this->currentSimpleType = $attrs['name']; - $this->simpleTypes[ $attrs['name'] ] = $attrs; - $this->simpleTypes[ $attrs['name'] ]['typeClass'] = 'simpleType'; - $this->simpleTypes[ $attrs['name'] ]['phpType'] = 'scalar'; - } else { - $name = $this->CreateTypeName($this->currentComplexType . '_' . $this->currentElement); - $this->xdebug('processing unnamed simpleType for element ' . $this->currentElement . ' named ' . $name); - $this->currentSimpleType = $name; - //$this->currentElement = false; - $this->simpleTypes[$this->currentSimpleType] = $attrs; - $this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar'; - } - break; - case 'union': // simpleType type list - $this->xdebug("do nothing for element $name"); - break; - default: - $this->xdebug("do not have any logic to process element $name"); - } - } - - /** - * end-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @access private - */ - function schemaEndElement($parser, $name) { - // bring depth down a notch - $this->depth--; - // position of current element is equal to the last value left in depth_array for my depth - if(isset($this->depth_array[$this->depth])){ - $pos = $this->depth_array[$this->depth]; + } else { + $this->xdebug('ignoring invalid XML Schema construct: include without schemaLocation attribute'); + } + break; + case 'list': // simpleType value list + $this->xdebug("do nothing for element $name"); + break; + case 'restriction': // simpleType, simpleContent or complexContent value restriction + $this->xdebug('restriction ' . $attrs['base']); + if ($this->currentSimpleType) { + $this->simpleTypes[$this->currentSimpleType]['type'] = $attrs['base']; + } elseif ($this->currentComplexType) { + $this->complexTypes[$this->currentComplexType]['restrictionBase'] = $attrs['base']; + if (strstr($attrs['base'], ':') == ':Array') { + $this->complexTypes[$this->currentComplexType]['phpType'] = 'array'; + } + } + break; + case 'schema': + $this->schemaInfo = $attrs; + $this->schemaInfo['schemaVersion'] = $this->getNamespaceFromPrefix($prefix); + if (isset($attrs['targetNamespace'])) { + $this->schemaTargetNamespace = $attrs['targetNamespace']; + } + if (!isset($attrs['elementFormDefault'])) { + $this->schemaInfo['elementFormDefault'] = 'unqualified'; + } + if (!isset($attrs['attributeFormDefault'])) { + $this->schemaInfo['attributeFormDefault'] = 'unqualified'; + } + break; + case 'simpleContent': // (optional) content for a complexType + if ($this->currentComplexType) { // This should *always* be + $this->complexTypes[$this->currentComplexType]['simpleContent'] = 'true'; + } else { + $this->xdebug("do nothing for element $name because there is no current complexType"); + } + break; + case 'simpleType': + $this->simpleTypeStack[] = $this->currentSimpleType; + if (isset($attrs['name'])) { + $this->xdebug("processing simpleType for name " . $attrs['name']); + $this->currentSimpleType = $attrs['name']; + $this->simpleTypes[$attrs['name']] = $attrs; + $this->simpleTypes[$attrs['name']]['typeClass'] = 'simpleType'; + $this->simpleTypes[$attrs['name']]['phpType'] = 'scalar'; + } else { + $name = $this->CreateTypeName($this->currentComplexType . '_' . $this->currentElement); + $this->xdebug('processing unnamed simpleType for element ' . $this->currentElement . ' named ' . $name); + $this->currentSimpleType = $name; + //$this->currentElement = false; + $this->simpleTypes[$this->currentSimpleType] = $attrs; + $this->simpleTypes[$this->currentSimpleType]['phpType'] = 'scalar'; + } + break; + case 'union': // simpleType type list + $this->xdebug("do nothing for element $name"); + break; + default: + $this->xdebug("do not have any logic to process element $name"); } - // get element prefix - if ($prefix = $this->getPrefix($name)){ - // get unqualified name - $name = $this->getLocalPart($name); - } else { - $prefix = ''; - } - // move on... - if($name == 'complexType'){ - $this->xdebug('done processing complexType ' . ($this->currentComplexType ? $this->currentComplexType : '(unknown)')); - $this->xdebug($this->varDump($this->complexTypes[$this->currentComplexType])); - $this->currentComplexType = array_pop($this->complexTypeStack); - //$this->currentElement = false; - } - if($name == 'element'){ - $this->xdebug('done processing element ' . ($this->currentElement ? $this->currentElement : '(unknown)')); - $this->currentElement = array_pop($this->elementStack); - } - if($name == 'simpleType'){ - $this->xdebug('done processing simpleType ' . ($this->currentSimpleType ? $this->currentSimpleType : '(unknown)')); - $this->xdebug($this->varDump($this->simpleTypes[$this->currentSimpleType])); - $this->currentSimpleType = array_pop($this->simpleTypeStack); - } - } - - /** - * element content handler - * - * @param string $parser XML parser object - * @param string $data element content - * @access private - */ - function schemaCharacterData($parser, $data){ - $pos = $this->depth_array[$this->depth - 1]; - $this->message[$pos]['cdata'] .= $data; - } - - /** - * serialize the schema - * - * @access public - */ - function serializeSchema(){ - - $schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion); - $xml = ''; - // imports - if (sizeof($this->imports) > 0) { - foreach($this->imports as $ns => $list) { - foreach ($list as $ii) { - if ($ii['location'] != '') { - $xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n"; - } else { - $xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n"; - } - } - } - } - // complex types - foreach($this->complexTypes as $typeName => $attrs){ - $contentStr = ''; - // serialize child elements - if(isset($attrs['elements']) && (count($attrs['elements']) > 0)){ - foreach($attrs['elements'] as $element => $eParts){ - if(isset($eParts['ref'])){ - $contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n"; - } else { - $contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\""; - foreach ($eParts as $aName => $aValue) { - // handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable - if ($aName != 'name' && $aName != 'type') { - $contentStr .= " $aName=\"$aValue\""; - } - } - $contentStr .= "/>\n"; - } - } - // compositor wraps elements - if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) { - $contentStr = " <$schemaPrefix:$attrs[compositor]>\n".$contentStr." \n"; - } - } - // attributes - if(isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)){ - foreach($attrs['attrs'] as $attr => $aParts){ - $contentStr .= " <$schemaPrefix:attribute"; - foreach ($aParts as $a => $v) { - if ($a == 'ref' || $a == 'type') { - $contentStr .= " $a=\"".$this->contractQName($v).'"'; - } elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') { - $this->usedNamespaces['wsdl'] = $this->namespaces['wsdl']; - $contentStr .= ' wsdl:arrayType="'.$this->contractQName($v).'"'; - } else { - $contentStr .= " $a=\"$v\""; - } - } - $contentStr .= "/>\n"; - } - } - // if restriction - if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != ''){ - $contentStr = " <$schemaPrefix:restriction base=\"".$this->contractQName($attrs['restrictionBase'])."\">\n".$contentStr." \n"; - // complex or simple content - if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)){ - $contentStr = " <$schemaPrefix:complexContent>\n".$contentStr." \n"; - } - } - // finalize complex type - if($contentStr != ''){ - $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n".$contentStr." \n"; - } else { - $contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n"; - } - $xml .= $contentStr; - } - // simple types - if(isset($this->simpleTypes) && count($this->simpleTypes) > 0){ - foreach($this->simpleTypes as $typeName => $eParts){ - $xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"".$this->contractQName($eParts['type'])."\">\n"; - if (isset($eParts['enumeration'])) { - foreach ($eParts['enumeration'] as $e) { - $xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n"; - } - } - $xml .= " \n "; - } - } - // elements - if(isset($this->elements) && count($this->elements) > 0){ - foreach($this->elements as $element => $eParts){ - $xml .= " <$schemaPrefix:element name=\"$element\" type=\"".$this->contractQName($eParts['type'])."\"/>\n"; - } - } - // attributes - if(isset($this->attributes) && count($this->attributes) > 0){ - foreach($this->attributes as $attr => $aParts){ - $xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"".$this->contractQName($aParts['type'])."\"\n/>"; - } - } - // finish 'er up - $attr = ''; - foreach ($this->schemaInfo as $k => $v) { - if ($k == 'elementFormDefault' || $k == 'attributeFormDefault') { - $attr .= " $k=\"$v\""; - } - } - $el = "<$schemaPrefix:schema$attr targetNamespace=\"$this->schemaTargetNamespace\"\n"; - foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) { - $el .= " xmlns:$nsp=\"$ns\""; - } - $xml = $el . ">\n".$xml."\n"; - return $xml; - } - - /** - * adds debug data to the clas level debug string - * - * @param string $string debug data - * @access private - */ - function xdebug($string){ - $this->debug('<' . $this->schemaTargetNamespace . '> '.$string); - } - - /** - * get the PHP type of a user defined type in the schema - * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays - * returns false if no type exists, or not w/ the given namespace - * else returns a string that is either a native php type, or 'struct' - * - * @param string $type name of defined type - * @param string $ns namespace of type - * @return mixed - * @access public - * @deprecated - */ - function getPHPType($type,$ns){ - if(isset($this->typemap[$ns][$type])){ - //print "found type '$type' and ns $ns in typemap
    "; - return $this->typemap[$ns][$type]; - } elseif(isset($this->complexTypes[$type])){ - //print "getting type '$type' and ns $ns from complexTypes array
    "; - return $this->complexTypes[$type]['phpType']; - } - return false; - } - - /** - * returns an associative array of information about a given type - * returns false if no type exists by the given name - * - * For a complexType typeDef = array( - * 'restrictionBase' => '', - * 'phpType' => '', - * 'compositor' => '(sequence|all)', - * 'elements' => array(), // refs to elements array - * 'attrs' => array() // refs to attributes array - * ... and so on (see addComplexType) - * ) - * - * For simpleType or element, the array has different keys. - * - * @param string $type - * @return mixed - * @access public - * @see addComplexType - * @see addSimpleType - * @see addElement - */ - function getTypeDef($type){ - //$this->debug("in getTypeDef for type $type"); - if (substr($type, -1) == '^') { - $is_element = 1; - $type = substr($type, 0, -1); - } else { - $is_element = 0; - } - - if((! $is_element) && isset($this->complexTypes[$type])){ - $this->xdebug("in getTypeDef, found complexType $type"); - return $this->complexTypes[$type]; - } elseif((! $is_element) && isset($this->simpleTypes[$type])){ - $this->xdebug("in getTypeDef, found simpleType $type"); - if (!isset($this->simpleTypes[$type]['phpType'])) { - // get info for type to tack onto the simple type - // TODO: can this ever really apply (i.e. what is a simpleType really?) - $uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1); - $ns = substr($this->simpleTypes[$type]['type'], 0, strrpos($this->simpleTypes[$type]['type'], ':')); - $etype = $this->getTypeDef($uqType); - if ($etype) { - $this->xdebug("in getTypeDef, found type for simpleType $type:"); - $this->xdebug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $this->simpleTypes[$type]['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $this->simpleTypes[$type]['elements'] = $etype['elements']; - } - } - } - return $this->simpleTypes[$type]; - } elseif(isset($this->elements[$type])){ - $this->xdebug("in getTypeDef, found element $type"); - if (!isset($this->elements[$type]['phpType'])) { - // get info for type to tack onto the element - $uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1); - $ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':')); - $etype = $this->getTypeDef($uqType); - if ($etype) { - $this->xdebug("in getTypeDef, found type for element $type:"); - $this->xdebug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $this->elements[$type]['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $this->elements[$type]['elements'] = $etype['elements']; - } - if (isset($etype['extensionBase'])) { - $this->elements[$type]['extensionBase'] = $etype['extensionBase']; - } - } elseif ($ns == 'http://www.w3.org/2001/XMLSchema') { - $this->xdebug("in getTypeDef, element $type is an XSD type"); - $this->elements[$type]['phpType'] = 'scalar'; - } - } - return $this->elements[$type]; - } elseif(isset($this->attributes[$type])){ - $this->xdebug("in getTypeDef, found attribute $type"); - return $this->attributes[$type]; - } elseif (preg_match('/_ContainedType$/', $type)) { - $this->xdebug("in getTypeDef, have an untyped element $type"); - $typeDef['typeClass'] = 'simpleType'; - $typeDef['phpType'] = 'scalar'; - $typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string'; - return $typeDef; - } - $this->xdebug("in getTypeDef, did not find $type"); - return false; - } - - /** - * returns a sample serialization of a given type, or false if no type by the given name - * - * @param string $type name of type - * @return mixed - * @access public - * @deprecated - */ - function serializeTypeDef($type){ - //print "in sTD() for type $type
    "; - if($typeDef = $this->getTypeDef($type)){ - $str .= '<'.$type; - if(is_array($typeDef['attrs'])){ - foreach($typeDef['attrs'] as $attName => $data){ - $str .= " $attName=\"{type = ".$data['type']."}\""; - } - } - $str .= " xmlns=\"".$this->schema['targetNamespace']."\""; - if(count($typeDef['elements']) > 0){ - $str .= ">"; - foreach($typeDef['elements'] as $element => $eData){ - $str .= $this->serializeTypeDef($element); - } - $str .= ""; - } elseif($typeDef['typeClass'] == 'element') { - $str .= ">"; - } else { - $str .= "/>"; - } - return $str; - } - return false; } /** - * returns HTML form elements that allow a user - * to enter values for creating an instance of the given type. - * - * @param string $name name for type instance - * @param string $type name of type - * @return string - * @access public - * @deprecated - */ - function typeToForm($name,$type){ - // get typedef - if($typeDef = $this->getTypeDef($type)){ - // if struct - if($typeDef['phpType'] == 'struct'){ - $buffer .= ''; - foreach($typeDef['elements'] as $child => $childDef){ - $buffer .= " - - "; - } - $buffer .= '
    $childDef[name] (type: ".$this->getLocalPart($childDef['type'])."):
    '; - // if array - } elseif($typeDef['phpType'] == 'array'){ - $buffer .= ''; - for($i=0;$i < 3; $i++){ - $buffer .= " + * end-element handler + * + * @param string $parser XML parser object + * @param string $name element name + * @access private + */ + function schemaEndElement($parser, $name) + { + // bring depth down a notch + $this->depth--; + // get element prefix + if ($this->getPrefix($name)) { + // get unqualified name + $name = $this->getLocalPart($name); + } + // move on... + if ($name == 'complexType') { + $this->xdebug('done processing complexType ' . ($this->currentComplexType ?: '(unknown)')); + $this->xdebug($this->varDump($this->complexTypes[$this->currentComplexType])); + $this->currentComplexType = array_pop($this->complexTypeStack); + //$this->currentElement = false; + } + if ($name == 'element') { + $this->xdebug('done processing element ' . ($this->currentElement ?: '(unknown)')); + $this->currentElement = array_pop($this->elementStack); + } + if ($name == 'simpleType') { + $this->xdebug('done processing simpleType ' . ($this->currentSimpleType ?: '(unknown)')); + $this->xdebug($this->varDump($this->simpleTypes[$this->currentSimpleType])); + $this->currentSimpleType = array_pop($this->simpleTypeStack); + } + } + + /** + * element content handler + * + * @param string $parser XML parser object + * @param string $data element content + * @access private + */ + function schemaCharacterData($parser, $data) + { + $pos = $this->depth_array[$this->depth - 1]; + $this->message[$pos]['cdata'] .= $data; + } + + /** + * serialize the schema + * + * @access public + */ + function serializeSchema() + { + + $schemaPrefix = $this->getPrefixFromNamespace($this->XMLSchemaVersion); + $xml = ''; + // imports + if (sizeof($this->imports) > 0) { + foreach ($this->imports as $ns => $list) { + foreach ($list as $ii) { + if ($ii['location'] != '') { + $xml .= " <$schemaPrefix:import location=\"" . $ii['location'] . '" namespace="' . $ns . "\" />\n"; + } else { + $xml .= " <$schemaPrefix:import namespace=\"" . $ns . "\" />\n"; + } + } + } + } + // complex types + foreach ($this->complexTypes as $typeName => $attrs) { + $contentStr = ''; + // serialize child elements + if (isset($attrs['elements']) && (count($attrs['elements']) > 0)) { + foreach ($attrs['elements'] as $element => $eParts) { + if (isset($eParts['ref'])) { + $contentStr .= " <$schemaPrefix:element ref=\"$element\"/>\n"; + } else { + $contentStr .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\""; + foreach ($eParts as $aName => $aValue) { + // handle, e.g., abstract, default, form, minOccurs, maxOccurs, nillable + if ($aName != 'name' && $aName != 'type') { + $contentStr .= " $aName=\"$aValue\""; + } + } + $contentStr .= "/>\n"; + } + } + // compositor wraps elements + if (isset($attrs['compositor']) && ($attrs['compositor'] != '')) { + $contentStr = " <$schemaPrefix:$attrs[compositor]>\n" . $contentStr . " \n"; + } + } + // attributes + if (isset($attrs['attrs']) && (count($attrs['attrs']) >= 1)) { + foreach ($attrs['attrs'] as $aParts) { + $contentStr .= " <$schemaPrefix:attribute"; + foreach ($aParts as $a => $v) { + if ($a == 'ref' || $a == 'type') { + $contentStr .= " $a=\"" . $this->contractQName($v) . '"'; + } elseif ($a == 'http://schemas.xmlsoap.org/wsdl/:arrayType') { + $this->usedNamespaces['wsdl'] = $this->namespaces['wsdl']; + $contentStr .= ' wsdl:arrayType="' . $this->contractQName($v) . '"'; + } else { + $contentStr .= " $a=\"$v\""; + } + } + $contentStr .= "/>\n"; + } + } + // if restriction + if (isset($attrs['restrictionBase']) && $attrs['restrictionBase'] != '') { + $contentStr = " <$schemaPrefix:restriction base=\"" . $this->contractQName($attrs['restrictionBase']) . "\">\n" . $contentStr . " \n"; + // complex or simple content + if ((isset($attrs['elements']) && count($attrs['elements']) > 0) || (isset($attrs['attrs']) && count($attrs['attrs']) > 0)) { + $contentStr = " <$schemaPrefix:complexContent>\n" . $contentStr . " \n"; + } + } + // finalize complex type + if ($contentStr != '') { + $contentStr = " <$schemaPrefix:complexType name=\"$typeName\">\n" . $contentStr . " \n"; + } else { + $contentStr = " <$schemaPrefix:complexType name=\"$typeName\"/>\n"; + } + $xml .= $contentStr; + } + // simple types + if (isset($this->simpleTypes) && count($this->simpleTypes) > 0) { + foreach ($this->simpleTypes as $typeName => $eParts) { + $xml .= " <$schemaPrefix:simpleType name=\"$typeName\">\n <$schemaPrefix:restriction base=\"" . $this->contractQName($eParts['type']) . "\">\n"; + if (isset($eParts['enumeration'])) { + foreach ($eParts['enumeration'] as $e) { + $xml .= " <$schemaPrefix:enumeration value=\"$e\"/>\n"; + } + } + $xml .= " \n "; + } + } + // elements + if (isset($this->elements) && count($this->elements) > 0) { + foreach ($this->elements as $element => $eParts) { + $xml .= " <$schemaPrefix:element name=\"$element\" type=\"" . $this->contractQName($eParts['type']) . "\"/>\n"; + } + } + // attributes + if (isset($this->attributes) && count($this->attributes) > 0) { + foreach ($this->attributes as $attr => $aParts) { + $xml .= " <$schemaPrefix:attribute name=\"$attr\" type=\"" . $this->contractQName($aParts['type']) . "\"\n/>"; + } + } + // finish 'er up + $attr = ''; + foreach ($this->schemaInfo as $k => $v) { + if ($k == 'elementFormDefault' || $k == 'attributeFormDefault') { + $attr .= " $k=\"$v\""; + } + } + $el = "<$schemaPrefix:schema$attr targetNamespace=\"$this->schemaTargetNamespace\"\n"; + foreach (array_diff($this->usedNamespaces, $this->enclosingNamespaces) as $nsp => $ns) { + $el .= " xmlns:$nsp=\"$ns\""; + } + + return $el . ">\n" . $xml . "\n"; + } + + /** + * adds debug data to the clas level debug string + * + * @param string $string debug data + * @access private + */ + function xdebug($string) + { + $this->debug('<' . $this->schemaTargetNamespace . '> ' . $string); + } + + /** + * get the PHP type of a user defined type in the schema + * PHP type is kind of a misnomer since it actually returns 'struct' for assoc. arrays + * returns false if no type exists, or not w/ the given namespace + * else returns a string that is either a native php type, or 'struct' + * + * @param string $type name of defined type + * @param string $ns namespace of type + * @return mixed + * @access public + * @deprecated + */ + function getPHPType($type, $ns) + { + if (isset($this->typemap[$ns][$type])) { + //print "found type '$type' and ns $ns in typemap
    "; + return $this->typemap[$ns][$type]; + } elseif (isset($this->complexTypes[$type])) { + //print "getting type '$type' and ns $ns from complexTypes array
    "; + return $this->complexTypes[$type]['phpType']; + } + return false; + } + + /** + * returns an associative array of information about a given type + * returns false if no type exists by the given name + * + * For a complexType typeDef = array( + * 'restrictionBase' => '', + * 'phpType' => '', + * 'compositor' => '(sequence|all)', + * 'elements' => array(), // refs to elements array + * 'attrs' => array() // refs to attributes array + * ... and so on (see addComplexType) + * ) + * + * For simpleType or element, the array has different keys. + * + * @param string $type + * @return mixed + * @access public + * @see addComplexType + * @see addSimpleType + * @see addElement + */ + function getTypeDef($type) + { + //$this->debug("in getTypeDef for type $type"); + if (substr($type, -1) == '^') { + $is_element = 1; + $type = substr($type, 0, -1); + } else { + $is_element = 0; + } + + if ((!$is_element) && isset($this->complexTypes[$type])) { + $this->xdebug("in getTypeDef, found complexType $type"); + return $this->complexTypes[$type]; + } elseif ((!$is_element) && isset($this->simpleTypes[$type])) { + $this->xdebug("in getTypeDef, found simpleType $type"); + if (!isset($this->simpleTypes[$type]['phpType'])) { + // get info for type to tack onto the simple type + // TODO: can this ever really apply (i.e. what is a simpleType really?) + $uqType = substr($this->simpleTypes[$type]['type'], strrpos($this->simpleTypes[$type]['type'], ':') + 1); + $etype = $this->getTypeDef($uqType); + if ($etype) { + $this->xdebug("in getTypeDef, found type for simpleType $type:"); + $this->xdebug($this->varDump($etype)); + if (isset($etype['phpType'])) { + $this->simpleTypes[$type]['phpType'] = $etype['phpType']; + } + if (isset($etype['elements'])) { + $this->simpleTypes[$type]['elements'] = $etype['elements']; + } + } + } + return $this->simpleTypes[$type]; + } elseif (isset($this->elements[$type])) { + $this->xdebug("in getTypeDef, found element $type"); + if (!isset($this->elements[$type]['phpType'])) { + // get info for type to tack onto the element + $uqType = substr($this->elements[$type]['type'], strrpos($this->elements[$type]['type'], ':') + 1); + $ns = substr($this->elements[$type]['type'], 0, strrpos($this->elements[$type]['type'], ':')); + $etype = $this->getTypeDef($uqType); + if ($etype) { + $this->xdebug("in getTypeDef, found type for element $type:"); + $this->xdebug($this->varDump($etype)); + if (isset($etype['phpType'])) { + $this->elements[$type]['phpType'] = $etype['phpType']; + } + if (isset($etype['elements'])) { + $this->elements[$type]['elements'] = $etype['elements']; + } + if (isset($etype['extensionBase'])) { + $this->elements[$type]['extensionBase'] = $etype['extensionBase']; + } + } elseif ($ns == 'http://www.w3.org/2001/XMLSchema') { + $this->xdebug("in getTypeDef, element $type is an XSD type"); + $this->elements[$type]['phpType'] = 'scalar'; + } + } + return $this->elements[$type]; + } elseif (isset($this->attributes[$type])) { + $this->xdebug("in getTypeDef, found attribute $type"); + return $this->attributes[$type]; + } elseif (preg_match('/_ContainedType$/', $type)) { + $this->xdebug("in getTypeDef, have an untyped element $type"); + $typeDef['typeClass'] = 'simpleType'; + $typeDef['phpType'] = 'scalar'; + $typeDef['type'] = 'http://www.w3.org/2001/XMLSchema:string'; + return $typeDef; + } + $this->xdebug("in getTypeDef, did not find $type"); + return false; + } + + /** + * returns a sample serialization of a given type, or false if no type by the given name + * + * @param string $type name of type + * @return false|string + * @access public + */ + function serializeTypeDef($type) + { + $str = ''; + //print "in sTD() for type $type
    "; + if ($typeDef = $this->getTypeDef($type)) { + $str .= '<' . $type; + if (is_array($typeDef['attrs'])) { + foreach ($typeDef['attrs'] as $attName => $data) { + $str .= " $attName=\"{type = " . $data['type'] . "}\""; + } + } + $str .= " xmlns=\"" . $this->schema['targetNamespace'] . "\""; + if (count($typeDef['elements']) > 0) { + $str .= ">"; + foreach ($typeDef['elements'] as $element => $eData) { + $str .= $this->serializeTypeDef($element); + } + $str .= ""; + } elseif ($typeDef['typeClass'] == 'element') { + $str .= ">"; + } else { + $str .= "/>"; + } + return $str; + } + return false; + } + + /** + * returns HTML form elements that allow a user + * to enter values for creating an instance of the given type. + * + * @param string $name name for type instance + * @param string $type name of type + * @return string + * @access public + * @deprecated + */ + function typeToForm($name, $type) + { + $buffer = ''; + // get typedef + if ($typeDef = $this->getTypeDef($type)) { + // if struct + if ($typeDef['phpType'] == 'struct') { + $buffer .= '
    '; + foreach ($typeDef['elements'] as $childDef) { + $buffer .= " + + "; + } + $buffer .= '
    $childDef[name] (type: " . $this->getLocalPart($childDef['type']) . "):
    '; + // if array + } elseif ($typeDef['phpType'] == 'array') { + $buffer .= ''; + $buffer .= str_repeat (" - "; - } - $buffer .= '
    array item (type: $typeDef[arrayType]):
    '; - // if scalar - } else { - $buffer .= ""; - } - } else { - $buffer .= ""; - } - return $buffer; - } +
    '; + // if scalar + } else { + $buffer .= ""; + } + } else { + $buffer .= ""; + } + return $buffer; + } - /** - * adds a complex type to the schema - * - * example: array - * - * addType( - * 'ArrayOfstring', - * 'complexType', - * 'array', - * '', - * 'SOAP-ENC:Array', - * array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'), - * 'xsd:string' - * ); - * - * example: PHP associative array ( SOAP Struct ) - * - * addType( - * 'SOAPStruct', - * 'complexType', - * 'struct', - * 'all', - * array('myVar'=> array('name'=>'myVar','type'=>'string') - * ); - * - * @param name - * @param typeClass (complexType|simpleType|attribute) - * @param phpType: currently supported are array and struct (php assoc array) - * @param compositor (all|sequence|choice) - * @param restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param elements = array ( name = array(name=>'',type=>'') ) - * @param attrs = array( - * array( - * 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType", - * "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]" - * ) - * ) - * @param arrayType: namespace:name (http://www.w3.org/2001/XMLSchema:string) - * @access public - * @see getTypeDef - */ - function addComplexType($name,$typeClass='complexType',$phpType='array',$compositor='',$restrictionBase='',$elements=array(),$attrs=array(),$arrayType=''){ - $this->complexTypes[$name] = array( - 'name' => $name, - 'typeClass' => $typeClass, - 'phpType' => $phpType, - 'compositor'=> $compositor, - 'restrictionBase' => $restrictionBase, - 'elements' => $elements, - 'attrs' => $attrs, - 'arrayType' => $arrayType - ); + /** + * adds a complex type to the schema + * example: array + * addType( + * 'ArrayOfstring', + * 'complexType', + * 'array', + * '', + * 'SOAP-ENC:Array', + * array('ref'=>'SOAP-ENC:arrayType','wsdl:arrayType'=>'string[]'), + * 'xsd:string' + * ); + * example: PHP associative array ( SOAP Struct ) + * addType( + * 'SOAPStruct', + * 'complexType', + * 'struct', + * 'all', + * array('myVar'=> array('name'=>'myVar','type'=>'string') + * ); + * + * @param string $name + * @param string $typeClass (complexType|simpleType|attribute) + * @param string $phpType : currently supported are array and struct (php assoc array) + * @param string $compositor (all|sequence|choice) + * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) + * @param array $elements = array ( name = array(name=>'',type=>'') ) + * @param array $attrs = array( + * array( + * 'ref' => "http://schemas.xmlsoap.org/soap/encoding/:arrayType", + * "http://schemas.xmlsoap.org/wsdl/:arrayType" => "string[]" + * ) + * ) + * @param array $arrayType : namespace:name (http://www.w3.org/2001/XMLSchema:string) + * + * @access public + * @see getTypeDef + */ + function addComplexType($name, $typeClass = 'complexType', $phpType = 'array', $compositor = '', $restrictionBase = '', $elements = array(), $attrs = array(), $arrayType = '') + { + $this->complexTypes[$name] = array( + 'name' => $name, + 'typeClass' => $typeClass, + 'phpType' => $phpType, + 'compositor' => $compositor, + 'restrictionBase' => $restrictionBase, + 'elements' => $elements, + 'attrs' => $attrs, + 'arrayType' => $arrayType + ); - $this->xdebug("addComplexType $name:"); - $this->appendDebug($this->varDump($this->complexTypes[$name])); - } + $this->xdebug("addComplexType $name:"); + $this->appendDebug($this->varDump($this->complexTypes[$name])); + } - /** - * adds a simple type to the schema - * - * @param string $name - * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) - * @param string $typeClass (should always be simpleType) - * @param string $phpType (should always be scalar) - * @param array $enumeration array of values - * @access public - * @see nusoap_xmlschema - * @see getTypeDef - */ - function addSimpleType($name, $restrictionBase='', $typeClass='simpleType', $phpType='scalar', $enumeration=array()) { - $this->simpleTypes[$name] = array( - 'name' => $name, - 'typeClass' => $typeClass, - 'phpType' => $phpType, - 'type' => $restrictionBase, - 'enumeration' => $enumeration - ); + /** + * adds a simple type to the schema + * + * @param string $name + * @param string $restrictionBase namespace:name (http://schemas.xmlsoap.org/soap/encoding/:Array) + * @param string $typeClass (should always be simpleType) + * @param string $phpType (should always be scalar) + * @param array $enumeration array of values + * @access public + * @see nusoap_xmlschema + * @see getTypeDef + */ + function addSimpleType($name, $restrictionBase = '', $typeClass = 'simpleType', $phpType = 'scalar', $enumeration = array()) + { + $this->simpleTypes[$name] = array( + 'name' => $name, + 'typeClass' => $typeClass, + 'phpType' => $phpType, + 'type' => $restrictionBase, + 'enumeration' => $enumeration + ); - $this->xdebug("addSimpleType $name:"); - $this->appendDebug($this->varDump($this->simpleTypes[$name])); - } + $this->xdebug("addSimpleType $name:"); + $this->appendDebug($this->varDump($this->simpleTypes[$name])); + } - /** - * adds an element to the schema - * - * @param array $attrs attributes that must include name and type - * @see nusoap_xmlschema - * @access public - */ - function addElement($attrs) { - if (! $this->getPrefix($attrs['type'])) { - $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type']; - } - $this->elements[ $attrs['name'] ] = $attrs; - $this->elements[ $attrs['name'] ]['typeClass'] = 'element'; + /** + * adds an element to the schema + * + * @param array $attrs attributes that must include name and type + * @see nusoap_xmlschema + * @access public + */ + function addElement($attrs) + { + if (!$this->getPrefix($attrs['type'])) { + $attrs['type'] = $this->schemaTargetNamespace . ':' . $attrs['type']; + } + $this->elements[$attrs['name']] = $attrs; + $this->elements[$attrs['name']]['typeClass'] = 'element'; - $this->xdebug("addElement " . $attrs['name']); - $this->appendDebug($this->varDump($this->elements[ $attrs['name'] ])); - } + $this->xdebug("addElement " . $attrs['name']); + $this->appendDebug($this->varDump($this->elements[$attrs['name']])); + } } /** * Backward compatibility */ -class XMLSchema extends nusoap_xmlschema { -} - -?> -* @access public -*/ -class soapval extends nusoap_base { - /** - * The XML element name - * - * @var string - * @access private - */ - var $name; - /** - * The XML type name (string or false) - * - * @var mixed - * @access private - */ - var $type; - /** - * The PHP value - * - * @var mixed - * @access private - */ - var $value; - /** - * The XML element namespace (string or false) - * - * @var mixed - * @access private - */ - var $element_ns; - /** - * The XML type namespace (string or false) - * - * @var mixed - * @access private - */ - var $type_ns; - /** - * The XML element attributes (array or false) - * - * @var mixed - * @access private - */ - var $attributes; - - /** - * constructor - * - * @param string $name optional name - * @param mixed $type optional type name - * @param mixed $value optional value - * @param mixed $element_ns optional namespace of value - * @param mixed $type_ns optional namespace of type - * @param mixed $attributes associative array of attributes to add to element serialization - * @access public - */ - function __construct($name='soapval',$type=false,$value=-1,$element_ns=false,$type_ns=false,$attributes=false) { - parent::__construct(); - $this->name = $name; - $this->type = $type; - $this->value = $value; - $this->element_ns = $element_ns; - $this->type_ns = $type_ns; - $this->attributes = $attributes; - } - - /** - * return serialized value - * - * @param string $use The WSDL use value (encoded|literal) - * @return string XML data - * @access public - */ - function serialize($use='encoded') { - return $this->serialize_val($this->value, $this->name, $this->type, $this->element_ns, $this->type_ns, $this->attributes, $use, true); - } - - /** - * decodes a soapval object into a PHP native type - * - * @return mixed - * @access public - */ - function decode(){ - return $this->value; - } +class XMLSchema extends nusoap_xmlschema +{ } +/** + * For creating serializable abstractions of native PHP types. This class + * allows element name/namespace, XSD type, and XML attributes to be + * associated with a value. This is extremely useful when WSDL is not + * used, but is also useful when WSDL is used with polymorphic types, including + * xsd:anyType and user-defined types. + * + * @author Dietrich Ayala + * @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $ + * @access public + */ +class soapval extends nusoap_base +{ + /** + * The XML element name + * + * @var string + * @access private + */ + var $name; + /** + * The XML type name (string or false) + * + * @var mixed + * @access private + */ + var $type; + /** + * The PHP value + * + * @var mixed + * @access private + */ + var $value; + /** + * The XML element namespace (string or false) + * + * @var mixed + * @access private + */ + var $element_ns; + /** + * The XML type namespace (string or false) + * + * @var mixed + * @access private + */ + var $type_ns; + /** + * The XML element attributes (array or false) + * + * @var mixed + * @access private + */ + var $attributes; -?>name = $name; + $this->type = $type; + $this->value = $value; + $this->element_ns = $element_ns; + $this->type_ns = $type_ns; + $this->attributes = $attributes; + } + + /** + * return serialized value + * + * @param string $use The WSDL use value (encoded|literal) + * @return string XML data + * @access public + */ + function serialize($use = 'encoded') + { + return $this->serialize_val($this->value, $this->name, $this->type, $this->element_ns, $this->type_ns, $this->attributes, $use, true); + } + + /** + * decodes a soapval object into a PHP native type + * + * @return mixed + * @access public + */ + function decode() + { + return $this->value; + } +} /** -* transport class for sending/receiving data via HTTP and HTTPS -* NOTE: PHP must be compiled with the CURL extension for HTTPS support -* -* @author Dietrich Ayala -* @author Scott Nichol -* @access public -*/ -class soap_transport_http extends nusoap_base { + * transport class for sending/receiving data via HTTP and HTTPS + * NOTE: PHP must be compiled with the CURL extension for HTTPS support + * + * @author Dietrich Ayala + * @author Scott Nichol + * @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $ + * @access public + */ +class soap_transport_http extends nusoap_base +{ - var $url = ''; - var $uri = ''; - var $digest_uri = ''; - var $scheme = ''; - var $host = ''; - var $port = ''; - var $path = ''; - var $request_method = 'POST'; - var $protocol_version = '1.0'; - var $encoding = ''; - var $outgoing_headers = array(); - var $incoming_headers = array(); - var $incoming_cookies = array(); - var $outgoing_payload = ''; - var $incoming_payload = ''; - var $response_status_line; // HTTP response status line - var $useSOAPAction = true; - var $persistentConnection = false; - var $ch = false; // cURL handle - var $ch_options = array(); // cURL custom options - var $use_curl = false; // force cURL use - var $proxy = null; // proxy information (associative array) - var $username = ''; - var $password = ''; - var $authtype = ''; - var $digestRequest = array(); - var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional) - // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem' - // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem' - // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem' - // passphrase: SSL key password/passphrase - // certpassword: SSL certificate password - // verifypeer: default is 1 - // verifyhost: default is 1 + var $query = ''; + var $tryagain = false; + var $url = ''; + var $uri = ''; + var $digest_uri = ''; + var $scheme = ''; + var $host = ''; + var $port = ''; + var $path = ''; + var $request_method = 'POST'; + var $protocol_version = '1.0'; + var $encoding = ''; + var $outgoing_headers = array(); + var $incoming_headers = array(); + var $incoming_cookies = array(); + var $outgoing_payload = ''; + var $incoming_payload = ''; + var $response_status_line; // HTTP response status line + var $useSOAPAction = true; + var $persistentConnection = false; + var $ch = false; // cURL handle + var $ch_options = array(); // cURL custom options + var $use_curl = false; // force cURL use + var $proxy = null; // proxy information (associative array) + var $username = ''; + var $password = ''; + var $authtype = ''; + var $digestRequest = array(); + var $certRequest = array(); // keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional) + // cainfofile: certificate authority file, e.g. '$pathToPemFiles/rootca.pem' + // sslcertfile: SSL certificate file, e.g. '$pathToPemFiles/mycert.pem' + // sslkeyfile: SSL key file, e.g. '$pathToPemFiles/mykey.pem' + // passphrase: SSL key password/passphrase + // certpassword: SSL certificate password + // verifypeer: default is 1 + // verifyhost: default is 1 - /** - * constructor - * - * @param string $url The URL to which to connect - * @param array $curl_options User-specified cURL options - * @param boolean $use_curl Whether to try to force cURL use - * @access public - */ - function __construct($url, $curl_options = NULL, $use_curl = false){ - parent::__construct(); - $this->debug("ctor url=$url use_curl=$use_curl curl_options:"); - $this->appendDebug($this->varDump($curl_options)); - $this->setURL($url); - if (is_array($curl_options)) { - $this->ch_options = $curl_options; - } - $this->use_curl = $use_curl; - preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev); - $this->setHeader('User-Agent', $this->title.'/'.$this->version.(isset($rev[1])?' ('.$rev[1].')':'')); - } + /** @var false|resource */ + var $fp; + var $errno; - /** - * sets a cURL option - * - * @param mixed $option The cURL option (always integer?) - * @param mixed $value The cURL option value - * @access private - */ - function setCurlOption($option, $value) { - $this->debug("setCurlOption option=$option, value="); - $this->appendDebug($this->varDump($value)); - curl_setopt($this->ch, $option, $value); - } + /** + * constructor + * + * @param string $url The URL to which to connect + * @param array $curl_options User-specified cURL options + * @param boolean $use_curl Whether to try to force cURL use + * @access public + */ + function __construct($url, $curl_options = null, $use_curl = false) + { + parent::__construct(); + $this->debug("ctor url=$url use_curl=$use_curl curl_options:"); + $this->appendDebug($this->varDump($curl_options)); + $this->setURL($url); + if (is_array($curl_options)) { + $this->ch_options = $curl_options; + } + $this->use_curl = $use_curl; + preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev); + $this->setHeader('User-Agent', $this->title . '/' . $this->version . ' (' . $rev[1] . ')'); + } - /** - * sets an HTTP header - * - * @param string $name The name of the header - * @param string $value The value of the header - * @access private - */ - function setHeader($name, $value) { - $this->outgoing_headers[$name] = $value; - $this->debug("set header $name: $value"); - } + /** + * sets a cURL option + * + * @param mixed $option The cURL option (always integer?) + * @param mixed $value The cURL option value + * @access private + */ + function setCurlOption($option, $value) + { + $this->debug("setCurlOption option=$option, value="); + $this->appendDebug($this->varDump($value)); + curl_setopt($this->ch, $option, $value); + } - /** - * unsets an HTTP header - * - * @param string $name The name of the header - * @access private - */ - function unsetHeader($name) { - if (isset($this->outgoing_headers[$name])) { - $this->debug("unset header $name"); - unset($this->outgoing_headers[$name]); - } - } + /** + * sets an HTTP header + * + * @param string $name The name of the header + * @param string $value The value of the header + * @access private + */ + function setHeader($name, $value) + { + $this->outgoing_headers[$name] = $value; + $this->debug("set header $name: $value"); + } - /** - * sets the URL to which to connect - * - * @param string $url The URL to which to connect - * @access private - */ - function setURL($url) { - $this->url = $url; + /** + * unsets an HTTP header + * + * @param string $name The name of the header + * @access private + */ + function unsetHeader($name) + { + if (isset($this->outgoing_headers[$name])) { + $this->debug("unset header $name"); + unset($this->outgoing_headers[$name]); + } + } - $u = parse_url($url); - foreach($u as $k => $v){ - $this->debug("parsed URL $k = $v"); - $this->$k = $v; - } + /** + * sets the URL to which to connect + * + * @param string $url The URL to which to connect + * @access private + */ + function setURL($url) + { + $this->url = $url; - // add any GET params to path - if(isset($u['query']) && $u['query'] != ''){ + $u = parse_url($url); + foreach ($u as $k => $v) { + $this->debug("parsed URL $k = $v"); + $this->$k = $v; + } + + // add any GET params to path + if (isset($u['query']) && $u['query'] != '') { $this->path .= '?' . $u['query']; - } + } - // set default port - if(!isset($u['port'])){ - if($u['scheme'] == 'https'){ - $this->port = 443; - } else { - $this->port = 80; - } - } + // set default port + if (!isset($u['port'])) { + if ($u['scheme'] == 'https') { + $this->port = 443; + } else { + $this->port = 80; + } + } - $this->uri = $this->path; - $this->digest_uri = $this->uri; + $this->uri = $this->path; + $this->digest_uri = $this->uri; - // build headers - if (!isset($u['port'])) { - $this->setHeader('Host', $this->host); - } else { - $this->setHeader('Host', $this->host.':'.$this->port); - } + // build headers + if (!isset($u['port'])) { + $this->setHeader('Host', $this->host); + } else { + $this->setHeader('Host', $this->host . ':' . $this->port); + } - if (isset($u['user']) && $u['user'] != '') { - $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : ''); - } - } + if (isset($u['user']) && $u['user'] != '') { + $this->setCredentials(urldecode($u['user']), isset($u['pass']) ? urldecode($u['pass']) : ''); + } + } - /** - * gets the I/O method to use - * - * @return string I/O method to use (socket|curl|unknown) - * @access private - */ - function io_method() { - if ($this->use_curl || ($this->scheme == 'https') || ($this->scheme == 'http' && $this->authtype == 'ntlm') || ($this->scheme == 'http' && is_array($this->proxy) && $this->proxy['authtype'] == 'ntlm')) - return 'curl'; - if (($this->scheme == 'http' || $this->scheme == 'ssl') && $this->authtype != 'ntlm' && (!is_array($this->proxy) || $this->proxy['authtype'] != 'ntlm')) - return 'socket'; - return 'unknown'; - } + /** + * gets the I/O method to use + * + * @return string I/O method to use (socket|curl|unknown) + * @access private + */ + function io_method() + { + if ($this->use_curl || ($this->scheme == 'https') || ($this->scheme == 'http' && $this->authtype == 'ntlm') || ($this->scheme == 'http' && is_array($this->proxy) && $this->proxy['authtype'] == 'ntlm')) { + return 'curl'; + } + if (($this->scheme == 'http' || $this->scheme == 'ssl') && $this->authtype != 'ntlm' && (!is_array($this->proxy) || $this->proxy['authtype'] != 'ntlm')) { + return 'socket'; + } + return 'unknown'; + } - /** - * establish an HTTP connection - * - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @return boolean true if connected, false if not - * @access private - */ - function connect($connection_timeout=0,$response_timeout=30){ - // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like - // "regular" socket. - // TODO: disabled for now because OpenSSL must be *compiled* in (not just - // loaded), and until PHP5 stream_get_wrappers is not available. + /** + * establish an HTTP connection + * + * @param integer $connection_timeout set connection timeout in seconds + * @param integer $response_timeout set response timeout in seconds + * @return boolean true if connected, false if not + * @access private + */ + function connect($connection_timeout = 0, $response_timeout = 30) + { + // For PHP 4.3 with OpenSSL, change https scheme to ssl, then treat like + // "regular" socket. + // TODO: disabled for now because OpenSSL must be *compiled* in (not just + // loaded), and until PHP5 stream_get_wrappers is not available. // if ($this->scheme == 'https') { // if (version_compare(phpversion(), '4.3.0') >= 0) { // if (extension_loaded('openssl')) { @@ -2337,2261 +2392,2355 @@ class soap_transport_http extends nusoap_base { // } // } // } - $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port"); - if ($this->io_method() == 'socket') { - if (!is_array($this->proxy)) { - $host = $this->host; - $port = $this->port; - } else { - $host = $this->proxy['host']; - $port = $this->proxy['port']; - } + $this->debug("connect connection_timeout $connection_timeout, response_timeout $response_timeout, scheme $this->scheme, host $this->host, port $this->port"); + if ($this->io_method() == 'socket') { + if (!is_array($this->proxy)) { + $host = $this->host; + } else { + $host = $this->proxy['host']; + } - // use persistent connection - if($this->persistentConnection && isset($this->fp) && is_resource($this->fp)){ - if (!feof($this->fp)) { - $this->debug('Re-use persistent connection'); - return true; - } - fclose($this->fp); - $this->debug('Closed persistent connection at EOF'); - } + // use persistent connection + if ($this->persistentConnection && isset($this->fp) && is_resource($this->fp)) { + if (!feof($this->fp)) { + $this->debug('Re-use persistent connection'); + return true; + } + fclose($this->fp); + $this->debug('Closed persistent connection at EOF'); + } - // munge host if using OpenSSL - if ($this->scheme == 'ssl') { - $host = 'ssl://' . $host; - } - $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout); + // munge host if using OpenSSL + if ($this->scheme == 'ssl') { + $host = 'ssl://' . $host; + } + $this->debug('calling fsockopen with host ' . $host . ' connection_timeout ' . $connection_timeout); - // open socket - if($connection_timeout > 0){ - $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str, $connection_timeout); - } else { - $this->fp = @fsockopen( $host, $this->port, $this->errno, $this->error_str); - } + // open socket + if ($connection_timeout > 0) { + $this->fp = @fsockopen($host, $this->port, $this->errno, $this->error_str, $connection_timeout); + } else { + $this->fp = @fsockopen($host, $this->port, $this->errno, $this->error_str); + } - // test pointer - if(!$this->fp) { - $msg = 'Couldn\'t open socket connection to server ' . $this->url; - if ($this->errno) { - $msg .= ', Error ('.$this->errno.'): '.$this->error_str; - } else { - $msg .= ' prior to connect(). This is often a problem looking up the host name.'; - } - $this->debug($msg); - $this->setError($msg); - return false; - } + // test pointer + if (!$this->fp) { + $msg = 'Couldn\'t open socket connection to server ' . $this->url; + if ($this->errno) { + $msg .= ', Error (' . $this->errno . '): ' . $this->error_str; + } else { + $msg .= ' prior to connect(). This is often a problem looking up the host name.'; + } + $this->debug($msg); + $this->setError($msg); + return false; + } - // set response timeout - $this->debug('set response timeout to ' . $response_timeout); - socket_set_timeout( $this->fp, $response_timeout); + // set response timeout + $this->debug('set response timeout to ' . $response_timeout); + socket_set_timeout($this->fp, $response_timeout, 0); - $this->debug('socket connected'); - return true; - } else if ($this->io_method() == 'curl') { - if (!extension_loaded('curl')) { + $this->debug('socket connected'); + return true; + } elseif ($this->io_method() == 'curl') { + if (!extension_loaded('curl')) { // $this->setError('cURL Extension, or OpenSSL extension w/ PHP version >= 4.3 is required for HTTPS'); - $this->setError('The PHP cURL Extension is required for HTTPS or NLTM. You will need to re-build or update your PHP to include cURL or change php.ini to load the PHP cURL extension.'); - return false; - } - // Avoid warnings when PHP does not have these options - if (defined('CURLOPT_CONNECTIONTIMEOUT')) - $CURLOPT_CONNECTIONTIMEOUT = CURLOPT_CONNECTIONTIMEOUT; - else - $CURLOPT_CONNECTIONTIMEOUT = 78; - if (defined('CURLOPT_HTTPAUTH')) - $CURLOPT_HTTPAUTH = CURLOPT_HTTPAUTH; - else - $CURLOPT_HTTPAUTH = 107; - if (defined('CURLOPT_PROXYAUTH')) - $CURLOPT_PROXYAUTH = CURLOPT_PROXYAUTH; - else - $CURLOPT_PROXYAUTH = 111; - if (defined('CURLAUTH_BASIC')) - $CURLAUTH_BASIC = CURLAUTH_BASIC; - else - $CURLAUTH_BASIC = 1; - if (defined('CURLAUTH_DIGEST')) - $CURLAUTH_DIGEST = CURLAUTH_DIGEST; - else - $CURLAUTH_DIGEST = 2; - if (defined('CURLAUTH_NTLM')) - $CURLAUTH_NTLM = CURLAUTH_NTLM; - else - $CURLAUTH_NTLM = 8; + $this->setError('The PHP cURL Extension is required for HTTPS or NLTM. You will need to re-build or update your PHP to include cURL or change php.ini to load the PHP cURL extension.'); + return false; + } + // Avoid warnings when PHP does not have these options + if (defined('CURLOPT_CONNECTIONTIMEOUT')) { + $CURLOPT_CONNECTIONTIMEOUT = CURLOPT_CONNECTIONTIMEOUT; + } else { + $CURLOPT_CONNECTIONTIMEOUT = 78; + } + if (defined('CURLOPT_HTTPAUTH')) { + $CURLOPT_HTTPAUTH = CURLOPT_HTTPAUTH; + } else { + $CURLOPT_HTTPAUTH = 107; + } + if (defined('CURLOPT_PROXYAUTH')) { + $CURLOPT_PROXYAUTH = CURLOPT_PROXYAUTH; + } else { + $CURLOPT_PROXYAUTH = 111; + } + if (defined('CURLAUTH_BASIC')) { + $CURLAUTH_BASIC = CURLAUTH_BASIC; + } else { + $CURLAUTH_BASIC = 1; + } + if (defined('CURLAUTH_DIGEST')) { + $CURLAUTH_DIGEST = CURLAUTH_DIGEST; + } else { + $CURLAUTH_DIGEST = 2; + } + if (defined('CURLAUTH_NTLM')) { + $CURLAUTH_NTLM = CURLAUTH_NTLM; + } else { + $CURLAUTH_NTLM = 8; + } - $this->debug('connect using cURL'); - // init CURL - $this->ch = curl_init(); - // set url - $hostURL = ($this->port != '') ? "$this->scheme://$this->host:$this->port" : "$this->scheme://$this->host"; - // add path - $hostURL .= $this->path; - $this->setCurlOption(CURLOPT_URL, $hostURL); - // follow location headers (re-directs) - if (ini_get('safe_mode') || ini_get('open_basedir')) { - $this->debug('safe_mode or open_basedir set, so do not set CURLOPT_FOLLOWLOCATION'); - $this->debug('safe_mode = '); - $this->appendDebug($this->varDump(ini_get('safe_mode'))); - $this->debug('open_basedir = '); - $this->appendDebug($this->varDump(ini_get('open_basedir'))); - } else { - $this->setCurlOption(CURLOPT_FOLLOWLOCATION, 1); - } - // ask for headers in the response output - $this->setCurlOption(CURLOPT_HEADER, 1); - // ask for the response output as the return value - $this->setCurlOption(CURLOPT_RETURNTRANSFER, 1); - // encode - // We manage this ourselves through headers and encoding + $this->debug('connect using cURL'); + // init CURL + $this->ch = curl_init(); + // set url + $hostURL = ($this->port != '') ? "$this->scheme://$this->host:$this->port" : "$this->scheme://$this->host"; + // add path + $hostURL .= $this->path; + $this->setCurlOption(CURLOPT_URL, $hostURL); + // follow location headers (re-directs) + if (ini_get('safe_mode') || ini_get('open_basedir')) { + $this->debug('safe_mode or open_basedir set, so do not set CURLOPT_FOLLOWLOCATION'); + $this->debug('safe_mode = '); + $this->appendDebug($this->varDump(ini_get('safe_mode'))); + $this->debug('open_basedir = '); + $this->appendDebug($this->varDump(ini_get('open_basedir'))); + } else { + $this->setCurlOption(CURLOPT_FOLLOWLOCATION, 1); + } + // ask for headers in the response output + $this->setCurlOption(CURLOPT_HEADER, 1); + // ask for the response output as the return value + $this->setCurlOption(CURLOPT_RETURNTRANSFER, 1); + // encode + // We manage this ourselves through headers and encoding // if(function_exists('gzuncompress')){ // $this->setCurlOption(CURLOPT_ENCODING, 'deflate'); // } - // persistent connection - if ($this->persistentConnection) { - // I believe the following comment is now bogus, having applied to - // the code when it used CURLOPT_CUSTOMREQUEST to send the request. - // The way we send data, we cannot use persistent connections, since - // there will be some "junk" at the end of our request. - //$this->setCurlOption(CURL_HTTP_VERSION_1_1, true); - $this->persistentConnection = false; - $this->setHeader('Connection', 'close'); - } - // set timeouts - if ($connection_timeout != 0) { - $this->setCurlOption($CURLOPT_CONNECTIONTIMEOUT, $connection_timeout); - } - if ($response_timeout != 0) { - $this->setCurlOption(CURLOPT_TIMEOUT, $response_timeout); - } + // persistent connection + if ($this->persistentConnection) { + // I believe the following comment is now bogus, having applied to + // the code when it used CURLOPT_CUSTOMREQUEST to send the request. + // The way we send data, we cannot use persistent connections, since + // there will be some "junk" at the end of our request. + //$this->setCurlOption(CURL_HTTP_VERSION_1_1, true); + $this->persistentConnection = false; + $this->setHeader('Connection', 'close'); + } + // set timeouts + if ($connection_timeout != 0) { + $this->setCurlOption($CURLOPT_CONNECTIONTIMEOUT, $connection_timeout); + } + if ($response_timeout != 0) { + $this->setCurlOption(CURLOPT_TIMEOUT, $response_timeout); + } - if ($this->scheme == 'https') { - $this->debug('set cURL SSL verify options'); - // recent versions of cURL turn on peer/host checking by default, - // while PHP binaries are not compiled with a default location for the - // CA cert bundle, so disable peer/host checking. - //$this->setCurlOption(CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt'); - $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0); - $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0); + if ($this->scheme == 'https') { + $this->debug('set cURL SSL verify options'); + // recent versions of cURL turn on peer/host checking by default, + // while PHP binaries are not compiled with a default location for the + // CA cert bundle, so disable peer/host checking. + //$this->setCurlOption(CURLOPT_CAINFO, 'f:\php-4.3.2-win32\extensions\curl-ca-bundle.crt'); + $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 0); + $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 0); - // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo) - if ($this->authtype == 'certificate') { - $this->debug('set cURL certificate options'); - if (isset($this->certRequest['cainfofile'])) { - $this->setCurlOption(CURLOPT_CAINFO, $this->certRequest['cainfofile']); - } - if (isset($this->certRequest['verifypeer'])) { - $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']); - } else { - $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 1); - } - if (isset($this->certRequest['verifyhost'])) { - $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']); - } else { - $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 1); - } - if (isset($this->certRequest['sslcertfile'])) { - $this->setCurlOption(CURLOPT_SSLCERT, $this->certRequest['sslcertfile']); - } - if (isset($this->certRequest['sslkeyfile'])) { - $this->setCurlOption(CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']); - } - if (isset($this->certRequest['passphrase'])) { - $this->setCurlOption(CURLOPT_SSLKEYPASSWD, $this->certRequest['passphrase']); - } - if (isset($this->certRequest['certpassword'])) { - $this->setCurlOption(CURLOPT_SSLCERTPASSWD, $this->certRequest['certpassword']); - } - } - } - if ($this->authtype && ($this->authtype != 'certificate')) { - if ($this->username) { - $this->debug('set cURL username/password'); - $this->setCurlOption(CURLOPT_USERPWD, "$this->username:$this->password"); - } - if ($this->authtype == 'basic') { - $this->debug('set cURL for Basic authentication'); - $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_BASIC); - } - if ($this->authtype == 'digest') { - $this->debug('set cURL for digest authentication'); - $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_DIGEST); - } - if ($this->authtype == 'ntlm') { - $this->debug('set cURL for NTLM authentication'); - $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_NTLM); - } - } - if (is_array($this->proxy)) { - $this->debug('set cURL proxy options'); - if ($this->proxy['port'] != '') { - $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host'].':'.$this->proxy['port']); - } else { - $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host']); - } - if ($this->proxy['username'] || $this->proxy['password']) { - $this->debug('set cURL proxy authentication options'); - $this->setCurlOption(CURLOPT_PROXYUSERPWD, $this->proxy['username'].':'.$this->proxy['password']); - if ($this->proxy['authtype'] == 'basic') { - $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_BASIC); - } - if ($this->proxy['authtype'] == 'ntlm') { - $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_NTLM); - } - } - } - $this->debug('cURL connection set up'); - return true; - } else { - $this->setError('Unknown scheme ' . $this->scheme); - $this->debug('Unknown scheme ' . $this->scheme); - return false; - } - } + // support client certificates (thanks Tobias Boes, Doug Anarino, Eryan Ariobowo) + if ($this->authtype == 'certificate') { + $this->debug('set cURL certificate options'); + if (isset($this->certRequest['cainfofile'])) { + $this->setCurlOption(CURLOPT_CAINFO, $this->certRequest['cainfofile']); + } + if (isset($this->certRequest['verifypeer'])) { + $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, $this->certRequest['verifypeer']); + } else { + $this->setCurlOption(CURLOPT_SSL_VERIFYPEER, 1); + } + if (isset($this->certRequest['verifyhost'])) { + $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, $this->certRequest['verifyhost']); + } else { + $this->setCurlOption(CURLOPT_SSL_VERIFYHOST, 1); + } + if (isset($this->certRequest['sslcertfile'])) { + $this->setCurlOption(CURLOPT_SSLCERT, $this->certRequest['sslcertfile']); + } + if (isset($this->certRequest['sslkeyfile'])) { + $this->setCurlOption(CURLOPT_SSLKEY, $this->certRequest['sslkeyfile']); + } + if (isset($this->certRequest['passphrase'])) { + $this->setCurlOption(CURLOPT_SSLKEYPASSWD, $this->certRequest['passphrase']); + } + if (isset($this->certRequest['certpassword'])) { + $this->setCurlOption(CURLOPT_SSLCERTPASSWD, $this->certRequest['certpassword']); + } + } + } + if ($this->authtype && ($this->authtype != 'certificate')) { + if ($this->username) { + $this->debug('set cURL username/password'); + $this->setCurlOption(CURLOPT_USERPWD, "$this->username:$this->password"); + } + if ($this->authtype == 'basic') { + $this->debug('set cURL for Basic authentication'); + $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_BASIC); + } + if ($this->authtype == 'digest') { + $this->debug('set cURL for digest authentication'); + $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_DIGEST); + } + if ($this->authtype == 'ntlm') { + $this->debug('set cURL for NTLM authentication'); + $this->setCurlOption($CURLOPT_HTTPAUTH, $CURLAUTH_NTLM); + } + } + if (is_array($this->proxy)) { + $this->debug('set cURL proxy options'); + if ($this->proxy['port'] != '') { + $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host'] . ':' . $this->proxy['port']); + } else { + $this->setCurlOption(CURLOPT_PROXY, $this->proxy['host']); + } + if ($this->proxy['username'] || $this->proxy['password']) { + $this->debug('set cURL proxy authentication options'); + $this->setCurlOption(CURLOPT_PROXYUSERPWD, $this->proxy['username'] . ':' . $this->proxy['password']); + if ($this->proxy['authtype'] == 'basic') { + $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_BASIC); + } + if ($this->proxy['authtype'] == 'ntlm') { + $this->setCurlOption($CURLOPT_PROXYAUTH, $CURLAUTH_NTLM); + } + } + } + $this->debug('cURL connection set up'); + return true; + } else { + $this->setError('Unknown scheme ' . $this->scheme); + $this->debug('Unknown scheme ' . $this->scheme); + return false; + } + } - /** - * sends the SOAP request and gets the SOAP response via HTTP[S] - * - * @param string $data message data - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @param array $cookies cookies to send - * @return string data - * @access public - */ - function send($data, $timeout=0, $response_timeout=30, $cookies=NULL) { + /** + * sends the SOAP request and gets the SOAP response via HTTP[S] + * + * @param string $data message data + * @param integer $timeout set connection timeout in seconds + * @param integer $response_timeout set response timeout in seconds + * @param array $cookies cookies to send + * @return string data + * @access public + */ + function send($data, $timeout = 0, $response_timeout = 30, $cookies = null) + { + $this->debug('entered send() with data of length: ' . strlen($data)); - $this->debug('entered send() with data of length: '.strlen($data)); + $respdata = ""; + $this->tryagain = true; + $tries = 0; + while ($this->tryagain) { + $this->tryagain = false; + if ($tries++ < 2) { + // make connnection + if (!$this->connect($timeout, $response_timeout)) { + return false; + } - $this->tryagain = true; - $tries = 0; - while ($this->tryagain) { - $this->tryagain = false; - if ($tries++ < 2) { - // make connnection - if (!$this->connect($timeout, $response_timeout)){ - return false; - } + // send request + if (!$this->sendRequest($data, $cookies)) { + return false; + } - // send request - if (!$this->sendRequest($data, $cookies)){ - return false; - } - - // get response - $respdata = $this->getResponse(); - } else { - $this->setError("Too many tries to get an OK response ($this->response_status_line)"); - } - } - $this->debug('end of send()'); - return $respdata; - } + // get response + $respdata = $this->getResponse(); + } else { + $this->setError("Too many tries to get an OK response ($this->response_status_line)"); + } + } + $this->debug('end of send()'); + return $respdata; + } - /** - * sends the SOAP request and gets the SOAP response via HTTPS using CURL - * - * @param string $data message data - * @param integer $timeout set connection timeout in seconds - * @param integer $response_timeout set response timeout in seconds - * @param array $cookies cookies to send - * @return string data - * @access public - * @deprecated - */ - function sendHTTPS($data, $timeout=0, $response_timeout=30, $cookies) { - return $this->send($data, $timeout, $response_timeout, $cookies); - } + /** + * sends the SOAP request and gets the SOAP response via HTTPS using CURL + * + * @param string $data message data + * @param integer $timeout set connection timeout in seconds + * @param integer $response_timeout set response timeout in seconds + * @param array $cookies cookies to send + * @return string data + * @access public + */ + function sendHTTPS($data, $timeout = 0, $response_timeout = 30, $cookies = NULL) + { + return $this->send($data, $timeout, $response_timeout, $cookies); + } - /** - * if authenticating, set user credentials here - * - * @param string $username - * @param string $password - * @param string $authtype (basic|digest|certificate|ntlm) - * @param array $digestRequest (keys must be nonce, nc, realm, qop) - * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) - * @access public - */ - function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) { - $this->debug("setCredentials username=$username authtype=$authtype digestRequest="); - $this->appendDebug($this->varDump($digestRequest)); - $this->debug("certRequest="); - $this->appendDebug($this->varDump($certRequest)); - // cf. RFC 2617 - if ($authtype == 'basic') { - $this->setHeader('Authorization', 'Basic '.base64_encode(str_replace(':','',$username).':'.$password)); - } elseif ($authtype == 'digest') { - if (isset($digestRequest['nonce'])) { - $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1; + /** + * if authenticating, set user credentials here + * + * @param string $username + * @param string $password + * @param string $authtype (basic|digest|certificate|ntlm) + * @param array $digestRequest (keys must be nonce, nc, realm, qop) + * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) + * @access public + */ + function setCredentials($username, $password, $authtype = 'basic', $digestRequest = array(), $certRequest = array()) + { + $this->debug("setCredentials username=$username authtype=$authtype digestRequest="); + $this->appendDebug($this->varDump($digestRequest)); + $this->debug("certRequest="); + $this->appendDebug($this->varDump($certRequest)); + // cf. RFC 2617 + if ($authtype == 'basic') { + $this->setHeader('Authorization', 'Basic ' . base64_encode(str_replace(':', '', $username) . ':' . $password)); + } elseif ($authtype == 'digest') { + if (isset($digestRequest['nonce'])) { + $digestRequest['nc'] = isset($digestRequest['nc']) ? $digestRequest['nc']++ : 1; - // calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html) + // calculate the Digest hashes (calculate code based on digest implementation found at: http://www.rassoc.com/gregr/weblog/stories/2002/07/09/webServicesSecurityHttpDigestAuthenticationWithoutActiveDirectory.html) - // A1 = unq(username-value) ":" unq(realm-value) ":" passwd - $A1 = $username. ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password; + // A1 = unq(username-value) ":" unq(realm-value) ":" passwd + $A1 = $username . ':' . (isset($digestRequest['realm']) ? $digestRequest['realm'] : '') . ':' . $password; - // H(A1) = MD5(A1) - $HA1 = md5($A1); + // H(A1) = MD5(A1) + $HA1 = md5($A1); - // A2 = Method ":" digest-uri-value - $A2 = $this->request_method . ':' . $this->digest_uri; + // A2 = Method ":" digest-uri-value + $A2 = $this->request_method . ':' . $this->digest_uri; - // H(A2) - $HA2 = md5($A2); + // H(A2) + $HA2 = md5($A2); - // KD(secret, data) = H(concat(secret, ":", data)) - // if qop == auth: - // request-digest = <"> < KD ( H(A1), unq(nonce-value) - // ":" nc-value - // ":" unq(cnonce-value) - // ":" unq(qop-value) - // ":" H(A2) - // ) <"> - // if qop is missing, - // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <"> + // KD(secret, data) = H(concat(secret, ":", data)) + // if qop == auth: + // request-digest = <"> < KD ( H(A1), unq(nonce-value) + // ":" nc-value + // ":" unq(cnonce-value) + // ":" unq(qop-value) + // ":" H(A2) + // ) <"> + // if qop is missing, + // request-digest = <"> < KD ( H(A1), unq(nonce-value) ":" H(A2) ) > <"> - $unhashedDigest = ''; - $nonce = isset($digestRequest['nonce']) ? $digestRequest['nonce'] : ''; - $cnonce = $nonce; - if ($digestRequest['qop'] != '') { - $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2; - } else { - $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2; - } + $nonce = $digestRequest['nonce']; + $cnonce = $nonce; + if ($digestRequest['qop'] != '') { + $unhashedDigest = $HA1 . ':' . $nonce . ':' . sprintf("%08d", $digestRequest['nc']) . ':' . $cnonce . ':' . $digestRequest['qop'] . ':' . $HA2; + } else { + $unhashedDigest = $HA1 . ':' . $nonce . ':' . $HA2; + } - $hashedDigest = md5($unhashedDigest); + $hashedDigest = md5($unhashedDigest); - $opaque = ''; - if (isset($digestRequest['opaque'])) { - $opaque = ', opaque="' . $digestRequest['opaque'] . '"'; - } + $opaque = ''; + if (isset($digestRequest['opaque'])) { + $opaque = ', opaque="' . $digestRequest['opaque'] . '"'; + } - $this->setHeader('Authorization', 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . $opaque . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"'); - } - } elseif ($authtype == 'certificate') { - $this->certRequest = $certRequest; - $this->debug('Authorization header not set for certificate'); - } elseif ($authtype == 'ntlm') { - // do nothing - $this->debug('Authorization header not set for ntlm'); - } - $this->username = $username; - $this->password = $password; - $this->authtype = $authtype; - $this->digestRequest = $digestRequest; - } + $this->setHeader('Authorization', 'Digest username="' . $username . '", realm="' . $digestRequest['realm'] . '", nonce="' . $nonce . '", uri="' . $this->digest_uri . $opaque . '", cnonce="' . $cnonce . '", nc=' . sprintf("%08x", $digestRequest['nc']) . ', qop="' . $digestRequest['qop'] . '", response="' . $hashedDigest . '"'); + } + } elseif ($authtype == 'certificate') { + $this->certRequest = $certRequest; + $this->debug('Authorization header not set for certificate'); + } elseif ($authtype == 'ntlm') { + // do nothing + $this->debug('Authorization header not set for ntlm'); + } + $this->username = $username; + $this->password = $password; + $this->authtype = $authtype; + $this->digestRequest = $digestRequest; + } - /** - * set the soapaction value - * - * @param string $soapaction - * @access public - */ - function setSOAPAction($soapaction) { - $this->setHeader('SOAPAction', '"' . $soapaction . '"'); - } + /** + * set the soapaction value + * + * @param string $soapaction + * @access public + */ + function setSOAPAction($soapaction) + { + $this->setHeader('SOAPAction', '"' . $soapaction . '"'); + } - /** - * use http encoding - * - * @param string $enc encoding style. supported values: gzip, deflate, or both - * @access public - */ - function setEncoding($enc='gzip, deflate') { - if (function_exists('gzdeflate')) { - $this->protocol_version = '1.1'; - $this->setHeader('Accept-Encoding', $enc); - if (!isset($this->outgoing_headers['Connection'])) { - $this->setHeader('Connection', 'close'); - $this->persistentConnection = false; - } - // deprecated as of PHP 5.3.0 - //set_magic_quotes_runtime(0); - $this->encoding = $enc; - } - } + /** + * use http encoding + * + * @param string $enc encoding style. supported values: gzip, deflate, or both + * @access public + */ + function setEncoding($enc = 'gzip, deflate') + { + if (function_exists('gzdeflate')) { + $this->protocol_version = '1.1'; + $this->setHeader('Accept-Encoding', $enc); + if (!isset($this->outgoing_headers['Connection'])) { + $this->setHeader('Connection', 'close'); + $this->persistentConnection = false; + } + // deprecated as of PHP 5.3.0 + //set_magic_quotes_runtime(0); + $this->encoding = $enc; + } + } - /** - * set proxy info here - * - * @param string $proxyhost use an empty string to remove proxy - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @param string $proxyauthtype (basic|ntlm) - * @access public - */ - function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 'basic') { - if ($proxyhost) { - $this->proxy = array( - 'host' => $proxyhost, - 'port' => $proxyport, - 'username' => $proxyusername, - 'password' => $proxypassword, - 'authtype' => $proxyauthtype - ); - if ($proxyusername != '' && $proxypassword != '' && $proxyauthtype = 'basic') { - $this->setHeader('Proxy-Authorization', ' Basic '.base64_encode($proxyusername.':'.$proxypassword)); - } - } else { - $this->debug('remove proxy'); - $proxy = null; - unsetHeader('Proxy-Authorization'); - } - } + /** + * set proxy info here + * + * @param string $proxyhost use an empty string to remove proxy + * @param string $proxyport + * @param string $proxyusername + * @param string $proxypassword + * @param string $proxyauthtype (basic|ntlm) + * @access public + */ + function setProxy($proxyhost, $proxyport, $proxyusername = '', $proxypassword = '', $proxyauthtype = 'basic') + { + if ($proxyhost) { + $this->proxy = array( + 'host' => $proxyhost, + 'port' => $proxyport, + 'username' => $proxyusername, + 'password' => $proxypassword, + 'authtype' => $proxyauthtype + ); + if ($proxyusername != '' && $proxypassword != '' && $proxyauthtype == 'basic') { + $this->setHeader('Proxy-Authorization', ' Basic ' . base64_encode($proxyusername . ':' . $proxypassword)); + } + } else { + $this->debug('remove proxy'); + $this->unsetHeader('Proxy-Authorization'); + } + } - /** - * Test if the given string starts with a header that is to be skipped. - * Skippable headers result from chunked transfer and proxy requests. - * - * @param string $data The string to check. - * @returns boolean Whether a skippable header was found. - * @access private - */ - function isSkippableCurlHeader(&$data) { - $skipHeaders = array( 'HTTP/1.1 100', - 'HTTP/1.0 301', - 'HTTP/1.1 301', - 'HTTP/1.0 302', - 'HTTP/1.1 302', - 'HTTP/1.0 401', - 'HTTP/1.1 401', - 'HTTP/1.0 200 Connection established'); - foreach ($skipHeaders as $hd) { - $prefix = substr($data, 0, strlen($hd)); - if ($prefix == $hd) return true; - } + /** + * Test if the given string starts with a header that is to be skipped. + * Skippable headers result from chunked transfer and proxy requests. + * + * @param string $data The string to check. + * @returns boolean Whether a skippable header was found. + * @access private + */ + function isSkippableCurlHeader($data) + { + $skipHeaders = array('HTTP/1.1 100', + 'HTTP/1.0 301', + 'HTTP/1.1 301', + 'HTTP/1.0 302', + 'HTTP/1.1 302', + 'HTTP/1.0 401', + 'HTTP/1.1 401', + 'HTTP/1.0 200 Connection established', + 'HTTP/1.1 200 Connection established'); + foreach ($skipHeaders as $hd) { + $prefix = substr($data, 0, strlen($hd)); + if ($prefix == $hd) { + return true; + } + } - return false; - } + return false; + } - /** - * decode a string that is encoded w/ "chunked' transfer encoding - * as defined in RFC2068 19.4.6 - * - * @param string $buffer - * @param string $lb - * @returns string - * @access public - * @deprecated - */ - function decodeChunked($buffer, $lb){ - // length := 0 - $length = 0; - $new = ''; + /** + * decode a string that is encoded w/ "chunked' transfer encoding + * as defined in RFC2068 19.4.6 + * + * @param string $buffer + * @param string $lb + * @returns string + * @access public + * @deprecated + */ + function decodeChunked($buffer, $lb) + { + $new = ''; - // read chunk-size, chunk-extension (if any) and CRLF - // get the position of the linebreak - $chunkend = strpos($buffer, $lb); - if ($chunkend == FALSE) { - $this->debug('no linebreak found in decodeChunked'); - return $new; - } - $temp = substr($buffer,0,$chunkend); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend + strlen($lb); - // while (chunk-size > 0) { - while ($chunk_size > 0) { - $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size"); - $chunkend = strpos( $buffer, $lb, $chunkstart + $chunk_size); + // read chunk-size, chunk-extension (if any) and CRLF + // get the position of the linebreak + $chunkend = strpos($buffer, $lb); + if (!$chunkend) { + $this->debug('no linebreak found in decodeChunked'); + return $new; + } + $temp = substr($buffer, 0, $chunkend); + $chunk_size = hexdec(trim($temp)); + $chunkstart = $chunkend + strlen($lb); + // while (chunk-size > 0) { + while ($chunk_size > 0) { + $this->debug("chunkstart: $chunkstart chunk_size: $chunk_size"); + $chunkend = strpos($buffer, $lb, $chunkstart + $chunk_size); - // Just in case we got a broken connection - if ($chunkend == FALSE) { - $chunk = substr($buffer,$chunkstart); - // append chunk-data to entity-body - $new .= $chunk; - $length += strlen($chunk); - break; - } + // Just in case we got a broken connection + if (!$chunkend) { + $chunk = substr($buffer, $chunkstart); + // append chunk-data to entity-body + $new .= $chunk; + break; + } - // read chunk-data and CRLF - $chunk = substr($buffer,$chunkstart,$chunkend-$chunkstart); - // append chunk-data to entity-body - $new .= $chunk; - // length := length + chunk-size - $length += strlen($chunk); - // read chunk-size and CRLF - $chunkstart = $chunkend + strlen($lb); + // read chunk-data and CRLF + $chunk = substr($buffer, $chunkstart, $chunkend - $chunkstart); + // append chunk-data to entity-body + $new .= $chunk; + // length := length + chunk-size + // read chunk-size and CRLF + $chunkstart = $chunkend + strlen($lb); - $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb); - if ($chunkend == FALSE) { - break; //Just in case we got a broken connection - } - $temp = substr($buffer,$chunkstart,$chunkend-$chunkstart); - $chunk_size = hexdec( trim($temp) ); - $chunkstart = $chunkend; - } - return $new; - } + $chunkend = strpos($buffer, $lb, $chunkstart) + strlen($lb); + if (!$chunkend) { + break; //Just in case we got a broken connection + } + $temp = substr($buffer, $chunkstart, $chunkend - $chunkstart); + $chunk_size = hexdec(trim($temp)); + $chunkstart = $chunkend; + } + return $new; + } - /** - * Writes the payload, including HTTP headers, to $this->outgoing_payload. - * - * @param string $data HTTP body - * @param string $cookie_str data for HTTP Cookie header - * @return void - * @access private - */ - function buildPayload($data, $cookie_str = '') { - // Note: for cURL connections, $this->outgoing_payload is ignored, - // as is the Content-Length header, but these are still created as - // debugging guides. + /** + * Writes the payload, including HTTP headers, to $this->outgoing_payload. + * + * @param string $data HTTP body + * @param string $cookie_str data for HTTP Cookie header + * @return void + * @access private + */ + function buildPayload($data, $cookie_str = '') + { + // Note: for cURL connections, $this->outgoing_payload is ignored, + // as is the Content-Length header, but these are still created as + // debugging guides. - // add content-length header - if ($this->request_method != 'GET') { - $this->setHeader('Content-Length', strlen($data)); - } + // add content-length header + if ($this->request_method != 'GET') { + $this->setHeader('Content-Length', strlen($data)); + } - // start building outgoing payload: - if ($this->proxy) { - $uri = $this->url; - } else { - $uri = $this->uri; - } - $req = "$this->request_method $uri HTTP/$this->protocol_version"; - $this->debug("HTTP request: $req"); - $this->outgoing_payload = "$req\r\n"; + // start building outgoing payload: + if ($this->proxy) { + $uri = $this->url; + } else { + $uri = $this->uri; + } + $req = "$this->request_method $uri HTTP/$this->protocol_version"; + $this->debug("HTTP request: $req"); + $this->outgoing_payload = "$req\r\n"; - // loop thru headers, serializing - foreach($this->outgoing_headers as $k => $v){ - $hdr = $k.': '.$v; - $this->debug("HTTP header: $hdr"); - $this->outgoing_payload .= "$hdr\r\n"; - } + // loop thru headers, serializing + foreach ($this->outgoing_headers as $k => $v) { + $hdr = $k . ': ' . $v; + $this->debug("HTTP header: $hdr"); + $this->outgoing_payload .= "$hdr\r\n"; + } - // add any cookies - if ($cookie_str != '') { - $hdr = 'Cookie: '.$cookie_str; - $this->debug("HTTP header: $hdr"); - $this->outgoing_payload .= "$hdr\r\n"; - } + // add any cookies + if ($cookie_str != '') { + $hdr = 'Cookie: ' . $cookie_str; + $this->debug("HTTP header: $hdr"); + $this->outgoing_payload .= "$hdr\r\n"; + } - // header/body separator - $this->outgoing_payload .= "\r\n"; + // header/body separator + $this->outgoing_payload .= "\r\n"; - // add data - $this->outgoing_payload .= $data; - } + // add data + $this->outgoing_payload .= $data; + } - /** - * sends the SOAP request via HTTP[S] - * - * @param string $data message data - * @param array $cookies cookies to send - * @return boolean true if OK, false if problem - * @access private - */ - function sendRequest($data, $cookies = NULL) { - // build cookie string - $cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https'))); + /** + * sends the SOAP request via HTTP[S] + * + * @param string $data message data + * @param array $cookies cookies to send + * @return boolean true if OK, false if problem + * @access private + */ + function sendRequest($data, $cookies = null) + { + // build cookie string + $cookie_str = $this->getCookiesForRequest($cookies, (($this->scheme == 'ssl') || ($this->scheme == 'https'))); - // build payload - $this->buildPayload($data, $cookie_str); + // build payload + $this->buildPayload($data, $cookie_str); - if ($this->io_method() == 'socket') { - // send payload - if(!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) { - $this->setError('couldn\'t write message data to socket'); - $this->debug('couldn\'t write message data to socket'); - return false; - } - $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload)); - return true; - } else if ($this->io_method() == 'curl') { - // set payload - // cURL does say this should only be the verb, and in fact it - // turns out that the URI and HTTP version are appended to this, which - // some servers refuse to work with (so we no longer use this method!) - //$this->setCurlOption(CURLOPT_CUSTOMREQUEST, $this->outgoing_payload); - $curl_headers = array(); - foreach($this->outgoing_headers as $k => $v){ - if ($k == 'Connection' || $k == 'Content-Length' || $k == 'Host' || $k == 'Authorization' || $k == 'Proxy-Authorization') { - $this->debug("Skip cURL header $k: $v"); - } else { - $curl_headers[] = "$k: $v"; - } - } - if ($cookie_str != '') { - $curl_headers[] = 'Cookie: ' . $cookie_str; - } - $this->setCurlOption(CURLOPT_HTTPHEADER, $curl_headers); - $this->debug('set cURL HTTP headers'); - if ($this->request_method == "POST") { - $this->setCurlOption(CURLOPT_POST, 1); - $this->setCurlOption(CURLOPT_POSTFIELDS, $data); - $this->debug('set cURL POST data'); - } else { - } - // insert custom user-set cURL options - foreach ($this->ch_options as $key => $val) { - $this->setCurlOption($key, $val); - } + if ($this->io_method() == 'socket') { + // send payload + if (!fputs($this->fp, $this->outgoing_payload, strlen($this->outgoing_payload))) { + $this->setError('couldn\'t write message data to socket'); + $this->debug('couldn\'t write message data to socket'); + return false; + } + $this->debug('wrote data to socket, length = ' . strlen($this->outgoing_payload)); + return true; + } elseif ($this->io_method() == 'curl') { + // set payload + // cURL does say this should only be the verb, and in fact it + // turns out that the URI and HTTP version are appended to this, which + // some servers refuse to work with (so we no longer use this method!) + //$this->setCurlOption(CURLOPT_CUSTOMREQUEST, $this->outgoing_payload); + $curl_headers = array(); + foreach ($this->outgoing_headers as $k => $v) { + if ($k == 'Connection' || $k == 'Content-Length' || $k == 'Host' || $k == 'Authorization' || $k == 'Proxy-Authorization') { + $this->debug("Skip cURL header $k: $v"); + } else { + $curl_headers[] = "$k: $v"; + } + } + if ($cookie_str != '') { + $curl_headers[] = 'Cookie: ' . $cookie_str; + } + $this->setCurlOption(CURLOPT_HTTPHEADER, $curl_headers); + $this->debug('set cURL HTTP headers'); + if ($this->request_method == "POST") { + $this->setCurlOption(CURLOPT_POST, 1); + $this->setCurlOption(CURLOPT_POSTFIELDS, $data); + $this->debug('set cURL POST data'); + } + // insert custom user-set cURL options + foreach ($this->ch_options as $key => $val) { + $this->setCurlOption($key, $val); + } - $this->debug('set cURL payload'); - return true; - } - } + $this->debug('set cURL payload'); + return true; + } + return false; + } - /** - * gets the SOAP response via HTTP[S] - * - * @return string the response (also sets member variables like incoming_payload) - * @access private - */ - function getResponse(){ - $this->incoming_payload = ''; + /** + * gets the SOAP response via HTTP[S] + * + * @return string the response (also sets member variables like incoming_payload) + * @access private + */ + function getResponse() + { + $this->incoming_payload = ''; + $header_array = array (); + $data = ''; - if ($this->io_method() == 'socket') { - // loop until headers have been retrieved - $data = ''; - while (!isset($lb)){ + if ($this->io_method() == 'socket') { + // loop until headers have been retrieved + $pos = 0; + while (!isset($lb)) { + // We might EOF during header read. + if (feof($this->fp)) { + $this->incoming_payload = $data; + $this->debug('found no headers before EOF after length ' . strlen($data)); + $this->debug("received before EOF:\n" . $data); + $this->setError('server failed to send headers'); + return false; + } - // We might EOF during header read. - if(feof($this->fp)) { - $this->incoming_payload = $data; - $this->debug('found no headers before EOF after length ' . strlen($data)); - $this->debug("received before EOF:\n" . $data); - $this->setError('server failed to send headers'); - return false; - } + $tmp = fgets($this->fp, 256); + $tmplen = strlen($tmp); + $this->debug("read line of $tmplen bytes: " . trim($tmp)); - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read line of $tmplen bytes: " . trim($tmp)); + if ($tmplen == 0) { + $this->incoming_payload = $data; + $this->debug('socket read of headers timed out after length ' . strlen($data)); + $this->debug("read before timeout: " . $data); + $this->setError('socket read of headers timed out'); + return false; + } - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of headers timed out after length ' . strlen($data)); - $this->debug("read before timeout: " . $data); - $this->setError('socket read of headers timed out'); - return false; - } + $data .= $tmp; + $pos = strpos($data, "\r\n\r\n"); + if ($pos > 1) { + $lb = "\r\n"; + } else { + $pos = strpos($data, "\n\n"); + if ($pos > 1) { + $lb = "\n"; + } + } + // remove 100 headers + if (isset($lb) && preg_match('/^HTTP\/1.1 100/', $data)) { + unset($lb); + $data = ''; + }// + } + // store header data + $this->incoming_payload .= $data; + $this->debug('found end of headers after length ' . strlen($data)); + // process headers + $header_data = trim(substr($data, 0, $pos)); + $header_array = explode($lb, $header_data); + $this->incoming_headers = array(); + $this->incoming_cookies = array(); + foreach ($header_array as $header_line) { + $arr = explode(':', $header_line, 2); + if (count($arr) > 1) { + $header_name = strtolower(trim($arr[0])); + $this->incoming_headers[$header_name] = trim($arr[1]); + if ($header_name == 'set-cookie') { + // TODO: allow multiple cookies from parseCookie + $cookie = $this->parseCookie(trim($arr[1])); + if ($cookie) { + $this->incoming_cookies[] = $cookie; + $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); + } else { + $this->debug('did not find cookie in ' . trim($arr[1])); + } + } + } elseif (isset($header_name)) { + // append continuation line to previous header + $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; + } + } - $data .= $tmp; - $pos = strpos($data,"\r\n\r\n"); - if($pos > 1){ - $lb = "\r\n"; - } else { - $pos = strpos($data,"\n\n"); - if($pos > 1){ - $lb = "\n"; - } - } - // remove 100 headers - if (isset($lb) && preg_match('/^HTTP\/1.1 100/',$data)) { - unset($lb); - $data = ''; - }// - } - // store header data - $this->incoming_payload .= $data; - $this->debug('found end of headers after length ' . strlen($data)); - // process headers - $header_data = trim(substr($data,0,$pos)); - $header_array = explode($lb,$header_data); - $this->incoming_headers = array(); - $this->incoming_cookies = array(); - foreach($header_array as $header_line){ - $arr = explode(':',$header_line, 2); - if(count($arr) > 1){ - $header_name = strtolower(trim($arr[0])); - $this->incoming_headers[$header_name] = trim($arr[1]); - if ($header_name == 'set-cookie') { - // TODO: allow multiple cookies from parseCookie - $cookie = $this->parseCookie(trim($arr[1])); - if ($cookie) { - $this->incoming_cookies[] = $cookie; - $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); - } else { - $this->debug('did not find cookie in ' . trim($arr[1])); - } - } - } else if (isset($header_name)) { - // append continuation line to previous header - $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; - } - } + // loop until msg has been received + if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') { + $content_length = 2147483647; // ignore any content-length header + $chunked = true; + $this->debug("want to read chunked content"); + } elseif (isset($this->incoming_headers['content-length'])) { + $content_length = $this->incoming_headers['content-length']; + $chunked = false; + $this->debug("want to read content of length $content_length"); + } else { + $content_length = 2147483647; + $chunked = false; + $this->debug("want to read content to EOF"); + } + $data = ''; + do { + if ($chunked) { + $tmp = fgets($this->fp, 256); + $tmplen = strlen($tmp); + $this->debug("read chunk line of $tmplen bytes"); + if ($tmplen == 0) { + $this->incoming_payload = $data; + $this->debug('socket read of chunk length timed out after length ' . strlen($data)); + $this->debug("read before timeout:\n" . $data); + $this->setError('socket read of chunk length timed out'); + return false; + } + $content_length = hexdec(trim($tmp)); + $this->debug("chunk length $content_length"); + } + $strlen = 0; + while (($strlen < $content_length) && (!feof($this->fp))) { + $readlen = min(8192, $content_length - $strlen); + $tmp = fread($this->fp, $readlen); + $tmplen = strlen($tmp); + $this->debug("read buffer of $tmplen bytes"); + if (($tmplen == 0) && (!feof($this->fp))) { + $this->incoming_payload = $data; + $this->debug('socket read of body timed out after length ' . strlen($data)); + $this->debug("read before timeout:\n" . $data); + $this->setError('socket read of body timed out'); + return false; + } + $strlen += $tmplen; + $data .= $tmp; + } + if ($chunked && ($content_length > 0)) { + $tmp = fgets($this->fp, 256); + $tmplen = strlen($tmp); + $this->debug("read chunk terminator of $tmplen bytes"); + if ($tmplen == 0) { + $this->incoming_payload = $data; + $this->debug('socket read of chunk terminator timed out after length ' . strlen($data)); + $this->debug("read before timeout:\n" . $data); + $this->setError('socket read of chunk terminator timed out'); + return false; + } + } + } while ($chunked && ($content_length > 0) && (!feof($this->fp))); + if (feof($this->fp)) { + $this->debug('read to EOF'); + } + $this->debug('read body of length ' . strlen($data)); + $this->incoming_payload .= $data; + $this->debug('received a total of ' . strlen($this->incoming_payload) . ' bytes of data from server'); - // loop until msg has been received - if (isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked') { - $content_length = 2147483647; // ignore any content-length header - $chunked = true; - $this->debug("want to read chunked content"); - } elseif (isset($this->incoming_headers['content-length'])) { - $content_length = $this->incoming_headers['content-length']; - $chunked = false; - $this->debug("want to read content of length $content_length"); - } else { - $content_length = 2147483647; - $chunked = false; - $this->debug("want to read content to EOF"); - } - $data = ''; - do { - if ($chunked) { - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read chunk line of $tmplen bytes"); - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of chunk length timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of chunk length timed out'); - return false; - } - $content_length = hexdec(trim($tmp)); - $this->debug("chunk length $content_length"); - } - $strlen = 0; - while (($strlen < $content_length) && (!feof($this->fp))) { - $readlen = min(8192, $content_length - $strlen); - $tmp = fread($this->fp, $readlen); - $tmplen = strlen($tmp); - $this->debug("read buffer of $tmplen bytes"); - if (($tmplen == 0) && (!feof($this->fp))) { - $this->incoming_payload = $data; - $this->debug('socket read of body timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of body timed out'); - return false; - } - $strlen += $tmplen; - $data .= $tmp; - } - if ($chunked && ($content_length > 0)) { - $tmp = fgets($this->fp, 256); - $tmplen = strlen($tmp); - $this->debug("read chunk terminator of $tmplen bytes"); - if ($tmplen == 0) { - $this->incoming_payload = $data; - $this->debug('socket read of chunk terminator timed out after length ' . strlen($data)); - $this->debug("read before timeout:\n" . $data); - $this->setError('socket read of chunk terminator timed out'); - return false; - } - } - } while ($chunked && ($content_length > 0) && (!feof($this->fp))); - if (feof($this->fp)) { - $this->debug('read to EOF'); - } - $this->debug('read body of length ' . strlen($data)); - $this->incoming_payload .= $data; - $this->debug('received a total of '.strlen($this->incoming_payload).' bytes of data from server'); + // close filepointer + if ( + (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') || + (!$this->persistentConnection) || feof($this->fp) + ) { + fclose($this->fp); + $this->fp = false; + $this->debug('closed socket'); + } - // close filepointer - if( - (isset($this->incoming_headers['connection']) && strtolower($this->incoming_headers['connection']) == 'close') || - (! $this->persistentConnection) || feof($this->fp)){ - fclose($this->fp); - $this->fp = false; - $this->debug('closed socket'); - } + // connection was closed unexpectedly + if ($this->incoming_payload == '') { + $this->setError('no response from server'); + return false; + } - // connection was closed unexpectedly - if($this->incoming_payload == ''){ - $this->setError('no response from server'); - return false; - } - - // decode transfer-encoding + // decode transfer-encoding // if(isset($this->incoming_headers['transfer-encoding']) && strtolower($this->incoming_headers['transfer-encoding']) == 'chunked'){ // if(!$data = $this->decodeChunked($data, $lb)){ // $this->setError('Decoding of chunked data failed'); // return false; // } - //print "
    \nde-chunked:\n---------------\n$data\n\n---------------\n
    "; - // set decoded payload + //print "
    \nde-chunked:\n---------------\n$data\n\n---------------\n
    "; + // set decoded payload // $this->incoming_payload = $header_data.$lb.$lb.$data; // } - } else if ($this->io_method() == 'curl') { - // send and receive - $this->debug('send and receive with cURL'); - $this->incoming_payload = curl_exec($this->ch); - $data = $this->incoming_payload; + } elseif ($this->io_method() == 'curl') { + // send and receive + $this->debug('send and receive with cURL'); + $this->incoming_payload = curl_exec($this->ch); + $data = $this->incoming_payload; - $cErr = curl_error($this->ch); - if ($cErr != '') { - $err = 'cURL ERROR: '.curl_errno($this->ch).': '.$cErr.'
    '; - // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE - foreach(curl_getinfo($this->ch) as $k => $v){ - $err .= "$k: $v
    "; - } - $this->debug($err); - $this->setError($err); - curl_close($this->ch); - return false; - } else { - //echo '
    ';
    -			//var_dump(curl_getinfo($this->ch));
    -			//echo '
    '; - } - // close curl - $this->debug('No cURL error, closing cURL'); - curl_close($this->ch); + $cErr = curl_error($this->ch); + if ($cErr != '') { + $err = 'cURL ERROR: ' . curl_errno($this->ch) . ': ' . $cErr . '
    '; + // TODO: there is a PHP bug that can cause this to SEGV for CURLINFO_CONTENT_TYPE + foreach (curl_getinfo($this->ch) as $k => $v) { + if (is_array($v)) { + $this->debug("$k: " . json_encode($v)); + } else { + $this->debug("$k: $v
    "); + } + } + $this->debug($err); + $this->setError($err); + curl_close($this->ch); + return false; + } + // close curl + $this->debug('No cURL error, closing cURL'); + curl_close($this->ch); - // try removing skippable headers - $savedata = $data; - while ($this->isSkippableCurlHeader($data)) { - $this->debug("Found HTTP header to skip"); - if ($pos = strpos($data,"\r\n\r\n")) { - $data = ltrim(substr($data,$pos)); - } elseif($pos = strpos($data,"\n\n") ) { - $data = ltrim(substr($data,$pos)); - } - } + // try removing skippable headers + $savedata = $data; + while ($this->isSkippableCurlHeader($data)) { + $this->debug("Found HTTP header to skip"); + if ($pos = strpos($data, "\r\n\r\n")) { + $data = ltrim(substr($data, $pos)); + } elseif ($pos = strpos($data, "\n\n")) { + $data = ltrim(substr($data, $pos)); + } + } - if ($data == '') { - // have nothing left; just remove 100 header(s) - $data = $savedata; - while (preg_match('/^HTTP\/1.1 100/',$data)) { - if ($pos = strpos($data,"\r\n\r\n")) { - $data = ltrim(substr($data,$pos)); - } elseif($pos = strpos($data,"\n\n") ) { - $data = ltrim(substr($data,$pos)); - } - } - } + if ($data == '') { + // have nothing left; just remove 100 header(s) + $data = $savedata; + while (preg_match('/^HTTP\/1.1 100/', $data)) { + if ($pos = strpos($data, "\r\n\r\n")) { + $data = ltrim(substr($data, $pos)); + } elseif ($pos = strpos($data, "\n\n")) { + $data = ltrim(substr($data, $pos)); + } + } + } - // separate content from HTTP headers - if ($pos = strpos($data,"\r\n\r\n")) { - $lb = "\r\n"; - } elseif( $pos = strpos($data,"\n\n")) { - $lb = "\n"; - } else { - $this->debug('no proper separation of headers and document'); - $this->setError('no proper separation of headers and document'); - return false; - } - $header_data = trim(substr($data,0,$pos)); - $header_array = explode($lb,$header_data); - $data = ltrim(substr($data,$pos)); - $this->debug('found proper separation of headers and document'); - $this->debug('cleaned data, stringlen: '.strlen($data)); - // clean headers - foreach ($header_array as $header_line) { - $arr = explode(':',$header_line,2); - if(count($arr) > 1){ - $header_name = strtolower(trim($arr[0])); - $this->incoming_headers[$header_name] = trim($arr[1]); - if ($header_name == 'set-cookie') { - // TODO: allow multiple cookies from parseCookie - $cookie = $this->parseCookie(trim($arr[1])); - if ($cookie) { - $this->incoming_cookies[] = $cookie; - $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); - } else { - $this->debug('did not find cookie in ' . trim($arr[1])); - } - } - } else if (isset($header_name)) { - // append continuation line to previous header - $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; - } - } - } + // separate content from HTTP headers + if ($pos = strpos($data, "\r\n\r\n")) { + $lb = "\r\n"; + } elseif ($pos = strpos($data, "\n\n")) { + $lb = "\n"; + } else { + $this->debug('no proper separation of headers and document'); + $this->setError('no proper separation of headers and document'); + return false; + } + $header_data = trim(substr($data, 0, $pos)); + $header_array = explode($lb, $header_data); + $data = ltrim(substr($data, $pos)); + $this->debug('found proper separation of headers and document'); + $this->debug('cleaned data, stringlen: ' . strlen($data)); + // clean headers + foreach ($header_array as $header_line) { + $arr = explode(':', $header_line, 2); + if (count($arr) > 1) { + $header_name = strtolower(trim($arr[0])); + $this->incoming_headers[$header_name] = trim($arr[1]); + if ($header_name == 'set-cookie') { + // TODO: allow multiple cookies from parseCookie + $cookie = $this->parseCookie(trim($arr[1])); + if ($cookie) { + $this->incoming_cookies[] = $cookie; + $this->debug('found cookie: ' . $cookie['name'] . ' = ' . $cookie['value']); + } else { + $this->debug('did not find cookie in ' . trim($arr[1])); + } + } + } elseif (isset($header_name)) { + // append continuation line to previous header + $this->incoming_headers[$header_name] .= $lb . ' ' . $header_line; + } + } + } - $this->response_status_line = $header_array[0]; - $arr = explode(' ', $this->response_status_line, 3); - $http_version = $arr[0]; - $http_status = intval($arr[1]); - $http_reason = count($arr) > 2 ? $arr[2] : ''; + $this->response_status_line = $header_array[0]; + $arr = explode(' ', $this->response_status_line, 3); + $http_status = intval($arr[1]); + $http_reason = count($arr) > 2 ? $arr[2] : ''; - // see if we need to resend the request with http digest authentication - if (isset($this->incoming_headers['location']) && ($http_status == 301 || $http_status == 302)) { - $this->debug("Got $http_status $http_reason with Location: " . $this->incoming_headers['location']); - $this->setURL($this->incoming_headers['location']); - $this->tryagain = true; - return false; - } + // see if we need to resend the request with http digest authentication + if (isset($this->incoming_headers['location']) && ($http_status == 301 || $http_status == 302)) { + $this->debug("Got $http_status $http_reason with Location: " . $this->incoming_headers['location']); + $this->setURL($this->incoming_headers['location']); + $this->tryagain = true; + return false; + } - // see if we need to resend the request with http digest authentication - if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) { - $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']); - if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) { - $this->debug('Server wants digest authentication'); - // remove "Digest " from our elements - $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']); + // see if we need to resend the request with http digest authentication + if (isset($this->incoming_headers['www-authenticate']) && $http_status == 401) { + $this->debug("Got 401 $http_reason with WWW-Authenticate: " . $this->incoming_headers['www-authenticate']); + if (strstr($this->incoming_headers['www-authenticate'], "Digest ")) { + $this->debug('Server wants digest authentication'); + // remove "Digest " from our elements + $digestString = str_replace('Digest ', '', $this->incoming_headers['www-authenticate']); - // parse elements into array - $digestElements = explode(',', $digestString); - foreach ($digestElements as $val) { - $tempElement = explode('=', trim($val), 2); - $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]); - } + // parse elements into array + $digestElements = explode(',', $digestString); + foreach ($digestElements as $val) { + $tempElement = explode('=', trim($val), 2); + $digestRequest[$tempElement[0]] = str_replace("\"", '', $tempElement[1]); + } - // should have (at least) qop, realm, nonce - if (isset($digestRequest['nonce'])) { - $this->setCredentials($this->username, $this->password, 'digest', $digestRequest); - $this->tryagain = true; - return false; - } - } - $this->debug('HTTP authentication failed'); - $this->setError('HTTP authentication failed'); - return false; - } + // should have (at least) qop, realm, nonce + if (isset($digestRequest['nonce'])) { + $this->setCredentials($this->username, $this->password, 'digest', $digestRequest); + $this->tryagain = true; + return false; + } + } + $this->debug('HTTP authentication failed'); + $this->setError('HTTP authentication failed'); + return false; + } - if ( - ($http_status >= 300 && $http_status <= 307) || - ($http_status >= 400 && $http_status <= 417) || - ($http_status >= 501 && $http_status <= 505) - ) { - $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)"); - return false; - } + if ( + ($http_status >= 300 && $http_status <= 307) || + ($http_status >= 400 && $http_status <= 417) || + ($http_status >= 501 && $http_status <= 505) + ) { + $this->setError("Unsupported HTTP response status $http_status $http_reason (soapclient->response has contents of the response)"); + return false; + } - // decode content-encoding - if(isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != ''){ - if(strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip'){ - // if decoding works, use it. else assume data wasn't gzencoded - if(function_exists('gzinflate')){ - //$timer->setMarker('starting decoding of gzip/deflated content'); - // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress) - // this means there are no Zlib headers, although there should be - $this->debug('The gzinflate function exists'); - $datalen = strlen($data); - if ($this->incoming_headers['content-encoding'] == 'deflate') { - if ($degzdata = @gzinflate($data)) { - $data = $degzdata; - $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes'); - if (strlen($data) < $datalen) { - // test for the case that the payload has been compressed twice - $this->debug('The inflated payload is smaller than the gzipped one; try again'); - if ($degzdata = @gzinflate($data)) { - $data = $degzdata; - $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes'); - } - } - } else { - $this->debug('Error using gzinflate to inflate the payload'); - $this->setError('Error using gzinflate to inflate the payload'); - } - } elseif ($this->incoming_headers['content-encoding'] == 'gzip') { - if ($degzdata = @gzinflate(substr($data, 10))) { // do our best - $data = $degzdata; - $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes'); - if (strlen($data) < $datalen) { - // test for the case that the payload has been compressed twice - $this->debug('The un-gzipped payload is smaller than the gzipped one; try again'); - if ($degzdata = @gzinflate(substr($data, 10))) { - $data = $degzdata; - $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes'); - } - } - } else { - $this->debug('Error using gzinflate to un-gzip the payload'); - $this->setError('Error using gzinflate to un-gzip the payload'); - } - } - //$timer->setMarker('finished decoding of gzip/deflated content'); - //print "\nde-inflated:\n---------------\n$data\n-------------\n"; - // set decoded payload - $this->incoming_payload = $header_data.$lb.$lb.$data; - } else { - $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); - $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); - } - } else { - $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); - $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); - } - } else { - $this->debug('No Content-Encoding header'); - } + // decode content-encoding + if (isset($this->incoming_headers['content-encoding']) && $this->incoming_headers['content-encoding'] != '') { + if (strtolower($this->incoming_headers['content-encoding']) == 'deflate' || strtolower($this->incoming_headers['content-encoding']) == 'gzip') { + $header_data = ""; + // if decoding works, use it. else assume data wasn't gzencoded + if (function_exists('gzinflate')) { + //$timer->setMarker('starting decoding of gzip/deflated content'); + // IIS 5 requires gzinflate instead of gzuncompress (similar to IE 5 and gzdeflate v. gzcompress) + // this means there are no Zlib headers, although there should be + $this->debug('The gzinflate function exists'); + $datalen = strlen($data); + if ($this->incoming_headers['content-encoding'] == 'deflate') { + if ($degzdata = @gzinflate($data)) { + $data = $degzdata; + $this->debug('The payload has been inflated to ' . strlen($data) . ' bytes'); + if (strlen($data) < $datalen) { + // test for the case that the payload has been compressed twice + $this->debug('The inflated payload is smaller than the gzipped one; try again'); + if ($degzdata = @gzinflate($data)) { + $data = $degzdata; + $this->debug('The payload has been inflated again to ' . strlen($data) . ' bytes'); + } + } + } else { + $this->debug('Error using gzinflate to inflate the payload'); + $this->setError('Error using gzinflate to inflate the payload'); + } + } elseif ($this->incoming_headers['content-encoding'] == 'gzip') { + if ($degzdata = @gzinflate(substr($data, 10))) { // do our best + $data = $degzdata; + $this->debug('The payload has been un-gzipped to ' . strlen($data) . ' bytes'); + if (strlen($data) < $datalen) { + // test for the case that the payload has been compressed twice + $this->debug('The un-gzipped payload is smaller than the gzipped one; try again'); + if ($degzdata = @gzinflate(substr($data, 10))) { + $data = $degzdata; + $this->debug('The payload has been un-gzipped again to ' . strlen($data) . ' bytes'); + } + } + } else { + $this->debug('Error using gzinflate to un-gzip the payload'); + $this->setError('Error using gzinflate to un-gzip the payload'); + } + } + //$timer->setMarker('finished decoding of gzip/deflated content'); + //print "\nde-inflated:\n---------------\n$data\n-------------\n"; + // set decoded payload + $this->incoming_payload = $header_data . (isset ($lb) ? $lb : "") . (isset ($lb) ? $lb : "") . $data; + } else { + $this->debug('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); + $this->setError('The server sent compressed data. Your php install must have the Zlib extension compiled in to support this.'); + } + } else { + $this->debug('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); + $this->setError('Unsupported Content-Encoding ' . $this->incoming_headers['content-encoding']); + } + } else { + $this->debug('No Content-Encoding header'); + } - if(strlen($data) == 0){ - $this->debug('no data after headers!'); - $this->setError('no data present after HTTP headers'); - return false; - } + if (strlen($data) == 0) { + $this->debug('no data after headers!'); + $this->setError('no data present after HTTP headers'); + return false; + } - return $data; - } + return $data; + } - /** - * sets the content-type for the SOAP message to be sent - * - * @param string $type the content type, MIME style - * @param mixed $charset character set used for encoding (or false) - * @access public - */ - function setContentType($type, $charset = false) { - $this->setHeader('Content-Type', $type . ($charset ? '; charset=' . $charset : '')); - } + /** + * sets the content-type for the SOAP message to be sent + * + * @param string $type the content type, MIME style + * @param mixed $charset character set used for encoding (or false) + * @access public + */ + function setContentType($type, $charset = false) + { + $this->setHeader('Content-Type', $type . ($charset ? '; charset=' . $charset : '')); + } - /** - * specifies that an HTTP persistent connection should be used - * - * @return boolean whether the request was honored by this method. - * @access public - */ - function usePersistentConnection(){ - if (isset($this->outgoing_headers['Accept-Encoding'])) { - return false; - } - $this->protocol_version = '1.1'; - $this->persistentConnection = true; - $this->setHeader('Connection', 'Keep-Alive'); - return true; - } + /** + * specifies that an HTTP persistent connection should be used + * + * @return boolean whether the request was honored by this method. + * @access public + */ + function usePersistentConnection() + { + if (isset($this->outgoing_headers['Accept-Encoding'])) { + return false; + } + $this->protocol_version = '1.1'; + $this->persistentConnection = true; + $this->setHeader('Connection', 'Keep-Alive'); + return true; + } - /** - * parse an incoming Cookie into it's parts - * - * @param string $cookie_str content of cookie - * @return array with data of that cookie - * @access private - */ - /* + /** + * parse an incoming Cookie into it's parts + * + * @param string $cookie_str content of cookie + * @return array with data of that cookie + * @access private + */ + /* * TODO: allow a Set-Cookie string to be parsed into multiple cookies */ - function parseCookie($cookie_str) { - $cookie_str = str_replace('; ', ';', $cookie_str) . ';'; - $data = preg_split('/;/', $cookie_str); - $value_str = $data[0]; + function parseCookie($cookie_str) + { + $cookie_str = str_replace('; ', ';', $cookie_str) . ';'; + $data = explode (';', $cookie_str); + $value_str = $data[0]; - $cookie_param = 'domain='; - $start = strpos($cookie_str, $cookie_param); - if ($start > 0) { - $domain = substr($cookie_str, $start + strlen($cookie_param)); - $domain = substr($domain, 0, strpos($domain, ';')); - } else { - $domain = ''; - } + $cookie_param = 'domain='; + $start = strpos($cookie_str, $cookie_param); + if ($start > 0) { + $domain = substr($cookie_str, $start + strlen($cookie_param)); + $domain = substr($domain, 0, strpos($domain, ';')); + } else { + $domain = ''; + } - $cookie_param = 'expires='; - $start = strpos($cookie_str, $cookie_param); - if ($start > 0) { - $expires = substr($cookie_str, $start + strlen($cookie_param)); - $expires = substr($expires, 0, strpos($expires, ';')); - } else { - $expires = ''; - } + $cookie_param = 'expires='; + $start = strpos($cookie_str, $cookie_param); + if ($start > 0) { + $expires = substr($cookie_str, $start + strlen($cookie_param)); + $expires = substr($expires, 0, strpos($expires, ';')); + } else { + $expires = ''; + } - $cookie_param = 'path='; - $start = strpos($cookie_str, $cookie_param); - if ( $start > 0 ) { - $path = substr($cookie_str, $start + strlen($cookie_param)); - $path = substr($path, 0, strpos($path, ';')); - } else { - $path = '/'; - } + $cookie_param = 'path='; + $start = strpos($cookie_str, $cookie_param); + if ($start > 0) { + $path = substr($cookie_str, $start + strlen($cookie_param)); + $path = substr($path, 0, strpos($path, ';')); + } else { + $path = '/'; + } - $cookie_param = ';secure;'; - if (strpos($cookie_str, $cookie_param) !== FALSE) { - $secure = true; - } else { - $secure = false; - } + $cookie_param = ';secure;'; + if (strpos($cookie_str, $cookie_param) !== false) { + $secure = true; + } else { + $secure = false; + } - $sep_pos = strpos($value_str, '='); + $sep_pos = strpos($value_str, '='); - if ($sep_pos) { - $name = substr($value_str, 0, $sep_pos); - $value = substr($value_str, $sep_pos + 1); - $cookie= array( 'name' => $name, - 'value' => $value, - 'domain' => $domain, - 'path' => $path, - 'expires' => $expires, - 'secure' => $secure - ); - return $cookie; - } - return false; - } + if ($sep_pos) { + $name = substr($value_str, 0, $sep_pos); + $value = substr($value_str, $sep_pos + 1); - /** - * sort out cookies for the current request - * - * @param array $cookies array with all cookies - * @param boolean $secure is the send-content secure or not? - * @return string for Cookie-HTTP-Header - * @access private - */ - function getCookiesForRequest($cookies, $secure=false) { - $cookie_str = ''; - if ((! is_null($cookies)) && (is_array($cookies))) { - foreach ($cookies as $cookie) { - if (! is_array($cookie)) { - continue; - } - $this->debug("check cookie for validity: ".$cookie['name'].'='.$cookie['value']); - if ((isset($cookie['expires'])) && (! empty($cookie['expires']))) { - if (strtotime($cookie['expires']) <= time()) { - $this->debug('cookie has expired'); - continue; - } - } - if ((isset($cookie['domain'])) && (! empty($cookie['domain']))) { - $domain = preg_quote($cookie['domain']); - if (! preg_match("'.*$domain$'i", $this->host)) { - $this->debug('cookie has different domain'); - continue; - } - } - if ((isset($cookie['path'])) && (! empty($cookie['path']))) { - $path = preg_quote($cookie['path']); - if (! preg_match("'^$path.*'i", $this->path)) { - $this->debug('cookie is for a different path'); - continue; - } - } - if ((! $secure) && (isset($cookie['secure'])) && ($cookie['secure'])) { - $this->debug('cookie is secure, transport is not'); - continue; - } - $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; '; - $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']); - } - } - return $cookie_str; - } + return array('name' => $name, + 'value' => $value, + 'domain' => $domain, + 'path' => $path, + 'expires' => $expires, + 'secure' => $secure + ); + } + return array (); + } + + /** + * sort out cookies for the current request + * + * @param array $cookies array with all cookies + * @param boolean $secure is the send-content secure or not? + * @return string for Cookie-HTTP-Header + * @access private + */ + function getCookiesForRequest($cookies, $secure = false) + { + $cookie_str = ''; + if ((is_array($cookies))) { + foreach ($cookies as $cookie) { + if (!is_array($cookie)) { + continue; + } + $this->debug("check cookie for validity: " . $cookie['name'] . '=' . $cookie['value']); + if ((isset($cookie['expires'])) && (!empty($cookie['expires']))) { + if (strtotime($cookie['expires']) <= time()) { + $this->debug('cookie has expired'); + continue; + } + } + if ((isset($cookie['domain'])) && (!empty($cookie['domain']))) { + $domain = preg_quote($cookie['domain'], "'"); + if (!preg_match("'.*$domain$'i", $this->host)) { + $this->debug('cookie has different domain'); + continue; + } + } + if ((isset($cookie['path'])) && (!empty($cookie['path']))) { + $path = preg_quote($cookie['path'], "'"); + if (!preg_match("'^$path.*'i", $this->path)) { + $this->debug('cookie is for a different path'); + continue; + } + } + if ((!$secure) && (isset($cookie['secure'])) && ($cookie['secure'])) { + $this->debug('cookie is secure, transport is not'); + continue; + } + $cookie_str .= $cookie['name'] . '=' . $cookie['value'] . '; '; + $this->debug('add cookie to Cookie-String: ' . $cookie['name'] . '=' . $cookie['value']); + } + } + return $cookie_str; + } } -?> -* @author Scott Nichol -* @access public -*/ -class nusoap_server extends nusoap_base { - /** - * HTTP headers of request - * @var array - * @access private - */ - var $headers = array(); - /** - * HTTP request - * @var string - * @access private - */ - var $request = ''; - /** - * SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text) - * @var string - * @access public - */ - var $requestHeaders = ''; - /** - * SOAP Headers from request (parsed) - * @var mixed - * @access public - */ - var $requestHeader = NULL; - /** - * SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text) - * @var string - * @access public - */ - var $document = ''; - /** - * SOAP payload for request (text) - * @var string - * @access public - */ - var $requestSOAP = ''; - /** - * requested method namespace URI - * @var string - * @access private - */ - var $methodURI = ''; - /** - * name of method requested - * @var string - * @access private - */ - var $methodname = ''; - /** - * method parameters from request - * @var array - * @access private - */ - var $methodparams = array(); - /** - * SOAP Action from request - * @var string - * @access private - */ - var $SOAPAction = ''; - /** - * character set encoding of incoming (request) messages - * @var string - * @access public - */ - var $xml_encoding = ''; - /** - * toggles whether the parser decodes element content w/ utf8_decode() - * @var boolean - * @access public - */ + * + * nusoap_server allows the user to create a SOAP server + * that is capable of receiving messages and returning responses + * + * @author Dietrich Ayala + * @author Scott Nichol + * @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $ + * @access public + */ +class nusoap_server extends nusoap_base +{ + /** + * HTTP headers of request + * + * @var array + * @access private + */ + var $headers = array(); + /** + * HTTP request + * + * @var string + * @access private + */ + var $request = ''; + /** + * SOAP headers from request (incomplete namespace resolution; special characters not escaped) (text) + * + * @var string + * @access public + */ + var $requestHeaders = ''; + /** + * SOAP Headers from request (parsed) + * + * @var mixed + * @access public + */ + var $requestHeader = null; + /** + * SOAP body request portion (incomplete namespace resolution; special characters not escaped) (text) + * + * @var string + * @access public + */ + var $document = ''; + /** + * SOAP payload for request (text) + * + * @var string + * @access public + */ + var $requestSOAP = ''; + /** + * requested method namespace URI + * + * @var string + * @access private + */ + var $methodURI = ''; + /** + * name of method requested + * + * @var string + * @access private + */ + var $methodname = ''; + /** + * name of the response tag name + * + * @var string + * @access private + */ + var $responseTagName = ''; + /** + * method parameters from request + * + * @var array + * @access private + */ + var $methodparams = array(); + /** + * SOAP Action from request + * + * @var string + * @access private + */ + var $SOAPAction = ''; + /** + * character set encoding of incoming (request) messages + * + * @var string + * @access public + */ + var $xml_encoding = ''; + /** + * toggles whether the parser decodes element content w/ utf8_decode() + * + * @var boolean + * @access public + */ var $decode_utf8 = true; - /** - * HTTP headers of response - * @var array - * @access public - */ - var $outgoing_headers = array(); - /** - * HTTP response - * @var string - * @access private - */ - var $response = ''; - /** - * SOAP headers for response (text or array of soapval or associative array) - * @var mixed - * @access public - */ - var $responseHeaders = ''; - /** - * SOAP payload for response (text) - * @var string - * @access private - */ - var $responseSOAP = ''; - /** - * method return value to place in response - * @var mixed - * @access private - */ - var $methodreturn = false; - /** - * whether $methodreturn is a string of literal XML - * @var boolean - * @access public - */ - var $methodreturnisliteralxml = false; - /** - * SOAP fault for response (or false) - * @var mixed - * @access private - */ - var $fault = false; - /** - * text indication of result (for debugging) - * @var string - * @access private - */ - var $result = 'successful'; - - /** - * assoc array of operations => opData; operations are added by the register() - * method or by parsing an external WSDL definition - * @var array - * @access private - */ - var $operations = array(); - /** - * wsdl instance (if one) - * @var mixed - * @access private - */ - var $wsdl = false; - /** - * URL for WSDL (if one) - * @var mixed - * @access private - */ - var $externalWSDLURL = false; - /** - * whether to append debug to response as XML comment - * @var boolean - * @access public - */ - var $debug_flag = false; - - - /** - * constructor - * the optional parameter is a path to a WSDL file that you'd like to bind the server instance to. - * - * @param mixed $wsdl file path or URL (string), or wsdl instance (object) - * @access public - */ - function __construct($wsdl=false) { - parent::__construct(); - // turn on debugging? - global $debug; - global $HTTP_SERVER_VARS; - - if (isset($_SERVER)) { - $this->debug("_SERVER is defined:"); - $this->appendDebug($this->varDump($_SERVER)); - } elseif (isset($HTTP_SERVER_VARS)) { - $this->debug("HTTP_SERVER_VARS is defined:"); - $this->appendDebug($this->varDump($HTTP_SERVER_VARS)); - } else { - $this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined."); - } - - if (isset($debug)) { - $this->debug("In nusoap_server, set debug_flag=$debug based on global flag"); - $this->debug_flag = $debug; - } elseif (isset($_SERVER['QUERY_STRING'])) { - $qs = explode('&', $_SERVER['QUERY_STRING']); - foreach ($qs as $v) { - if (substr($v, 0, 6) == 'debug=') { - $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #1"); - $this->debug_flag = substr($v, 6); - } - } - } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { - $qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']); - foreach ($qs as $v) { - if (substr($v, 0, 6) == 'debug=') { - $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #2"); - $this->debug_flag = substr($v, 6); - } - } - } - - // wsdl - if($wsdl){ - $this->debug("In nusoap_server, WSDL is specified"); - if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) { - $this->wsdl = $wsdl; - $this->externalWSDLURL = $this->wsdl->wsdl; - $this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL); - } else { - $this->debug('Create wsdl from ' . $wsdl); - $this->wsdl = new wsdl($wsdl); - $this->externalWSDLURL = $wsdl; - } - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if($err = $this->wsdl->getError()){ - die('WSDL ERROR: '.$err); - } - } - } - - /** - * processes request and returns response - * - * @param string $data usually is the value of $HTTP_RAW_POST_DATA - * @access public - */ - function service($data){ - global $HTTP_SERVER_VARS; - - if (isset($_SERVER['REQUEST_METHOD'])) { - $rm = $_SERVER['REQUEST_METHOD']; - } elseif (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) { - $rm = $HTTP_SERVER_VARS['REQUEST_METHOD']; - } else { - $rm = ''; - } - - if (isset($_SERVER['QUERY_STRING'])) { - $qs = $_SERVER['QUERY_STRING']; - } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { - $qs = $HTTP_SERVER_VARS['QUERY_STRING']; - } else { - $qs = ''; - } - $this->debug("In service, request method=$rm query string=$qs strlen(\$data)=" . strlen($data)); - - if ($rm == 'POST') { - $this->debug("In service, invoke the request"); - $this->parse_request($data); - if (! $this->fault) { - $this->invoke_method(); - } - if (! $this->fault) { - $this->serialize_return(); - } - $this->send_response(); - } elseif (preg_match('/wsdl/', $qs) ){ - $this->debug("In service, this is a request for WSDL"); - if ($this->externalWSDLURL){ - if (strpos($this->externalWSDLURL, "http://") !== false) { // assume URL - $this->debug("In service, re-direct for WSDL"); - header('Location: '.$this->externalWSDLURL); - } else { // assume file - $this->debug("In service, use file passthru for WSDL"); - header("Content-Type: text/xml\r\n"); - $pos = strpos($this->externalWSDLURL, "file://"); - if ($pos === false) { - $filename = $this->externalWSDLURL; - } else { - $filename = substr($this->externalWSDLURL, $pos + 7); - } - $fp = fopen($this->externalWSDLURL, 'r'); - fpassthru($fp); - } - } elseif ($this->wsdl) { - $this->debug("In service, serialize WSDL"); - header("Content-Type: text/xml; charset=ISO-8859-1\r\n"); - print $this->wsdl->serialize($this->debug_flag); - if ($this->debug_flag) { - $this->debug('wsdl:'); - $this->appendDebug($this->varDump($this->wsdl)); - print $this->getDebugAsXMLComment(); - } - } else { - $this->debug("In service, there is no WSDL"); - header("Content-Type: text/html; charset=ISO-8859-1\r\n"); - print "This service does not provide WSDL"; - } - } elseif ($this->wsdl) { - $this->debug("In service, return Web description"); - print $this->wsdl->webDescription(); - } else { - $this->debug("In service, no Web description"); - header("Content-Type: text/html; charset=ISO-8859-1\r\n"); - print "This service does not provide a Web description"; - } - } - - /** - * parses HTTP request headers. - * - * The following fields are set by this function (when successful) - * - * headers - * request - * xml_encoding - * SOAPAction - * - * @access private - */ - function parse_http_headers() { - global $HTTP_SERVER_VARS; - - $this->request = ''; - $this->SOAPAction = ''; - if(function_exists('getallheaders')){ - $this->debug("In parse_http_headers, use getallheaders"); - $headers = getallheaders(); - foreach($headers as $k=>$v){ - $k = strtolower($k); - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - // get SOAPAction header - if(isset($this->headers['soapaction'])){ - $this->SOAPAction = str_replace('"','',$this->headers['soapaction']); - } - // get the character encoding of the incoming request - if(isset($this->headers['content-type']) && strpos($this->headers['content-type'],'=')){ - $enc = str_replace('"','',substr(strstr($this->headers["content-type"],'='),1)); - if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } elseif(isset($_SERVER) && is_array($_SERVER)){ - $this->debug("In parse_http_headers, use _SERVER"); - foreach ($_SERVER as $k => $v) { - if (substr($k, 0, 5) == 'HTTP_') { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); - } else { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); - } - if ($k == 'soapaction') { - // get SOAPAction header - $k = 'SOAPAction'; - $v = str_replace('"', '', $v); - $v = str_replace('\\', '', $v); - $this->SOAPAction = $v; - } else if ($k == 'content-type') { - // get the character encoding of the incoming request - if (strpos($v, '=')) { - $enc = substr(strstr($v, '='), 1); - $enc = str_replace('"', '', $enc); - $enc = str_replace('\\', '', $enc); - if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)) { - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - } elseif (is_array($HTTP_SERVER_VARS)) { - $this->debug("In parse_http_headers, use HTTP_SERVER_VARS"); - foreach ($HTTP_SERVER_VARS as $k => $v) { - if (substr($k, 0, 5) == 'HTTP_') { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); $k = strtolower(substr($k, 5)); - } else { - $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); $k = strtolower($k); - } - if ($k == 'soapaction') { - // get SOAPAction header - $k = 'SOAPAction'; - $v = str_replace('"', '', $v); - $v = str_replace('\\', '', $v); - $this->SOAPAction = $v; - } else if ($k == 'content-type') { - // get the character encoding of the incoming request - if (strpos($v, '=')) { - $enc = substr(strstr($v, '='), 1); - $enc = str_replace('"', '', $enc); - $enc = str_replace('\\', '', $enc); - if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)) { - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - } - $this->headers[$k] = $v; - $this->request .= "$k: $v\r\n"; - $this->debug("$k: $v"); - } - } else { - $this->debug("In parse_http_headers, HTTP headers not accessible"); - $this->setError("HTTP headers not accessible"); - } - } - - /** - * parses a request - * - * The following fields are set by this function (when successful) - * - * headers - * request - * xml_encoding - * SOAPAction - * request - * requestSOAP - * methodURI - * methodname - * methodparams - * requestHeaders - * document - * - * This sets the fault field on error - * - * @param string $data XML string - * @access private - */ - function parse_request($data='') { - $this->debug('entering parse_request()'); - $this->parse_http_headers(); - $this->debug('got character encoding: '.$this->xml_encoding); - // uncompress if necessary - if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') { - $this->debug('got content encoding: ' . $this->headers['content-encoding']); - if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') { - // if decoding works, use it. else assume data wasn't gzencoded - if (function_exists('gzuncompress')) { - if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { - $data = $degzdata; - } elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) { - $data = $degzdata; - } else { - $this->fault('SOAP-ENV:Client', 'Errors occurred when trying to decode the data'); - return; - } - } else { - $this->fault('SOAP-ENV:Client', 'This Server does not support compressed data'); - return; - } - } - } - $this->request .= "\r\n".$data; - $data = $this->parseRequest($this->headers, $data); - $this->requestSOAP = $data; - $this->debug('leaving parse_request'); - } - - /** - * invokes a PHP function for the requested SOAP method - * - * The following fields are set by this function (when successful) - * - * methodreturn - * - * Note that the PHP function that is called may also set the following - * fields to affect the response sent to the client - * - * responseHeaders - * outgoing_headers - * - * This sets the fault field on error - * - * @access private - */ - function invoke_method() { - $this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction); - - // - // if you are debugging in this area of the code, your service uses a class to implement methods, - // you use SOAP RPC, and the client is .NET, please be aware of the following... - // when the .NET wsdl.exe utility generates a proxy, it will remove the '.' or '..' from the - // method name. that is fine for naming the .NET methods. it is not fine for properly constructing - // the XML request and reading the XML response. you need to add the RequestElementName and - // ResponseElementName to the System.Web.Services.Protocols.SoapRpcMethodAttribute that wsdl.exe - // generates for the method. these parameters are used to specify the correct XML element names - // for .NET to use, i.e. the names with the '.' in them. - // - $orig_methodname = $this->methodname; - if ($this->wsdl) { - if ($this->opData = $this->wsdl->getOperationData($this->methodname)) { - $this->debug('in invoke_method, found WSDL operation=' . $this->methodname); - $this->appendDebug('opData=' . $this->varDump($this->opData)); - } elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) { - // Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element - $this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']); - $this->appendDebug('opData=' . $this->varDump($this->opData)); - $this->methodname = $this->opData['name']; - } else { - $this->debug('in invoke_method, no WSDL for operation=' . $this->methodname); - $this->fault('SOAP-ENV:Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service"); - return; - } - } else { - $this->debug('in invoke_method, no WSDL to validate method'); - } - - // if a . is present in $this->methodname, we see if there is a class in scope, - // which could be referred to. We will also distinguish between two deliminators, - // to allow methods to be called a the class or an instance - if (strpos($this->methodname, '..') > 0) { - $delim = '..'; - } else if (strpos($this->methodname, '.') > 0) { - $delim = '.'; - } else { - $delim = ''; - } - $this->debug("in invoke_method, delim=$delim"); - - $class = ''; - $method = ''; - if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1) { - $try_class = substr($this->methodname, 0, strpos($this->methodname, $delim)); - if (class_exists($try_class)) { - // get the class and method name - $class = $try_class; - $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim)); - $this->debug("in invoke_method, class=$class method=$method delim=$delim"); - } else { - $this->debug("in invoke_method, class=$try_class not found"); - } - } else { - $try_class = ''; - $this->debug("in invoke_method, no class to try"); - } - - // does method exist? - if ($class == '') { - if (!function_exists($this->methodname)) { - $this->debug("in invoke_method, function '$this->methodname' not found!"); - $this->result = 'fault: method not found'; - $this->fault('SOAP-ENV:Client',"method '$this->methodname'('$orig_methodname') not defined in service('$try_class' '$delim')"); - return; - } - } else { - $method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method; - if (!in_array($method_to_compare, get_class_methods($class))) { - $this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!"); - $this->result = 'fault: method not found'; - $this->fault('SOAP-ENV:Client',"method '$this->methodname'/'$method_to_compare'('$orig_methodname') not defined in service/'$class'('$try_class' '$delim')"); - return; - } - } - - // evaluate message, getting back parameters - // verify that request parameters match the method's signature - if(! $this->verify_method($this->methodname,$this->methodparams)){ - // debug - $this->debug('ERROR: request not verified against method signature'); - $this->result = 'fault: request failed validation against method signature'; - // return fault - $this->fault('SOAP-ENV:Client',"Operation '$this->methodname' not defined in service."); - return; - } - - // if there are parameters to pass - $this->debug('in invoke_method, params:'); - $this->appendDebug($this->varDump($this->methodparams)); - $this->debug("in invoke_method, calling '$this->methodname'"); - if (!function_exists('call_user_func_array')) { - if ($class == '') { - $this->debug('in invoke_method, calling function using eval()'); - $funcCall = "\$this->methodreturn = $this->methodname("; - } else { - if ($delim == '..') { - $this->debug('in invoke_method, calling class method using eval()'); - $funcCall = "\$this->methodreturn = ".$class."::".$method."("; - } else { - $this->debug('in invoke_method, calling instance method using eval()'); - // generate unique instance name - $instname = "\$inst_".time(); - $funcCall = $instname." = new ".$class."(); "; - $funcCall .= "\$this->methodreturn = ".$instname."->".$method."("; - } - } - if ($this->methodparams) { - foreach ($this->methodparams as $param) { - if (is_array($param) || is_object($param)) { - $this->fault('SOAP-ENV:Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available'); - return; - } - $funcCall .= "\"$param\","; - } - $funcCall = substr($funcCall, 0, -1); - } - $funcCall .= ');'; - $this->debug('in invoke_method, function call: '.$funcCall); - @eval($funcCall); - } else { - if ($class == '') { - $this->debug('in invoke_method, calling function using call_user_func_array()'); - $call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array() - } elseif ($delim == '..') { - $this->debug('in invoke_method, calling class method using call_user_func_array()'); - $call_arg = array ($class, $method); - } else { - $this->debug('in invoke_method, calling instance method using call_user_func_array()'); - $instance = new $class (); - $call_arg = array(&$instance, $method); - } - if (is_array($this->methodparams)) { - $this->methodreturn = call_user_func_array($call_arg, array_values($this->methodparams)); - } else { - $this->methodreturn = call_user_func_array($call_arg, array()); - } - } - $this->debug('in invoke_method, methodreturn:'); - $this->appendDebug($this->varDump($this->methodreturn)); - $this->debug("in invoke_method, called method $this->methodname, received data of type ".gettype($this->methodreturn)); - } - - /** - * serializes the return value from a PHP function into a full SOAP Envelope - * - * The following fields are set by this function (when successful) - * - * responseSOAP - * - * This sets the fault field on error - * - * @access private - */ - function serialize_return() { - $this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI); - // if fault - if (isset($this->methodreturn) && is_object($this->methodreturn) && ((get_class($this->methodreturn) == 'soap_fault') || (get_class($this->methodreturn) == 'nusoap_fault'))) { - $this->debug('got a fault object from method'); - $this->fault = $this->methodreturn; - return; - } elseif ($this->methodreturnisliteralxml) { - $return_val = $this->methodreturn; - // returned value(s) - } else { - $this->debug('got a(n) '.gettype($this->methodreturn).' from method'); - $this->debug('serializing return value'); - if($this->wsdl){ - if (sizeof($this->opData['output']['parts']) > 1) { - $this->debug('more than one output part, so use the method return unchanged'); - $opParams = $this->methodreturn; - } elseif (sizeof($this->opData['output']['parts']) == 1) { - $this->debug('exactly one output part, so wrap the method return in a simple array'); - // TODO: verify that it is not already wrapped! - //foreach ($this->opData['output']['parts'] as $name => $type) { - // $this->debug('wrap in element named ' . $name); - //} - $opParams = array($this->methodreturn); - } - $return_val = $this->wsdl->serializeRPCParameters($this->methodname,'output',$opParams); - $this->appendDebug($this->wsdl->getDebug()); - $this->wsdl->clearDebug(); - if($errstr = $this->wsdl->getError()){ - $this->debug('got wsdl error: '.$errstr); - $this->fault('SOAP-ENV:Server', 'unable to serialize result'); - return; - } - } else { - if (isset($this->methodreturn)) { - $return_val = $this->serialize_val($this->methodreturn, 'return'); - } else { - $return_val = ''; - $this->debug('in absence of WSDL, assume void return for backward compatibility'); - } - } - } - $this->debug('return value:'); - $this->appendDebug($this->varDump($return_val)); - - $this->debug('serializing response'); - if ($this->wsdl) { - $this->debug('have WSDL for serialization: style is ' . $this->opData['style']); - if ($this->opData['style'] == 'rpc') { - $this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']); - if ($this->opData['output']['use'] == 'literal') { - // http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html R2735 says rpc/literal accessor elements should not be in a namespace - if ($this->methodURI) { - $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } else { - $payload = '<'.$this->methodname.'Response>'.$return_val.'methodname.'Response>'; - } - } else { - if ($this->methodURI) { - $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } else { - $payload = '<'.$this->methodname.'Response>'.$return_val.'methodname.'Response>'; - } - } - } else { - $this->debug('style is not rpc for serialization: assume document'); - $payload = $return_val; - } - } else { - $this->debug('do not have WSDL for serialization: assume rpc/encoded'); - $payload = 'methodname.'Response xmlns:ns1="'.$this->methodURI.'">'.$return_val.'methodname."Response>"; - } - $this->result = 'successful'; - if($this->wsdl){ - //if($this->debug_flag){ - $this->appendDebug($this->wsdl->getDebug()); - // } - if (isset($this->opData['output']['encodingStyle'])) { - $encodingStyle = $this->opData['output']['encodingStyle']; - } else { - $encodingStyle = ''; - } - // Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces. - $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders,$this->wsdl->usedNamespaces,$this->opData['style'],$this->opData['output']['use'],$encodingStyle); - } else { - $this->responseSOAP = $this->serializeEnvelope($payload,$this->responseHeaders); - } - $this->debug("Leaving serialize_return"); - } - - /** - * sends an HTTP response - * - * The following fields are set by this function (when successful) - * - * outgoing_headers - * response - * - * @access private - */ - function send_response() { - $this->debug('Enter send_response'); - if ($this->fault) { - $payload = $this->fault->serialize(); - $this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error"; - $this->outgoing_headers[] = "Status: 500 Internal Server Error"; - } else { - $payload = $this->responseSOAP; - // Some combinations of PHP+Web server allow the Status - // to come through as a header. Since OK is the default - // just do nothing. - // $this->outgoing_headers[] = "HTTP/1.0 200 OK"; - // $this->outgoing_headers[] = "Status: 200 OK"; - } - // add debug data if in debug mode - if(isset($this->debug_flag) && $this->debug_flag){ - $payload .= $this->getDebugAsXMLComment(); - } - $this->outgoing_headers[] = "Server: $this->title Server v$this->version"; - // @CHANGE Fix for php8 - $rev = array(); - preg_match('/\$Revision: ([^ ]+)/', $this->revision, $rev); - $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (".(isset($rev[1]) ? $rev[1] : '').")"; - // Let the Web server decide about this - //$this->outgoing_headers[] = "Connection: Close\r\n"; - $payload = $this->getHTTPBody($payload); - $type = $this->getHTTPContentType(); - $charset = $this->getHTTPContentTypeCharset(); - $this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : ''); - //begin code to compress payload - by John - // NOTE: there is no way to know whether the Web server will also compress - // this data. - if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) { - if (strstr($this->headers['accept-encoding'], 'gzip')) { - if (function_exists('gzencode')) { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - $this->outgoing_headers[] = "Content-Encoding: gzip"; - $payload = gzencode($payload); - } else { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - } - } elseif (strstr($this->headers['accept-encoding'], 'deflate')) { - // Note: MSIE requires gzdeflate output (no Zlib header and checksum), - // instead of gzcompress output, - // which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5) - if (function_exists('gzdeflate')) { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - $this->outgoing_headers[] = "Content-Encoding: deflate"; - $payload = gzdeflate($payload); - } else { - if (isset($this->debug_flag) && $this->debug_flag) { - $payload .= ""; - } - } - } - } - //end code - $this->outgoing_headers[] = "Content-Length: ".strlen($payload); - reset($this->outgoing_headers); - foreach($this->outgoing_headers as $hdr){ - header($hdr, false); - } - print $payload; - $this->response = join("\r\n",$this->outgoing_headers)."\r\n\r\n".$payload; - } - - /** - * takes the value that was created by parsing the request - * and compares to the method's signature, if available. - * - * @param string $operation The operation to be invoked - * @param array $request The array of parameter values - * @return boolean Whether the operation was found - * @access private - */ - function verify_method($operation,$request){ - if(isset($this->wsdl) && is_object($this->wsdl)){ - if($this->wsdl->getOperationData($operation)){ - return true; - } - } elseif(isset($this->operations[$operation])){ - return true; - } - return false; - } - - /** - * processes SOAP message received from client - * - * @param array $headers The HTTP headers - * @param string $data unprocessed request data from client - * @return mixed value of the message, decoded into a PHP type - * @access private - */ - function parseRequest($headers, $data) { - $this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' headers:'); - $this->appendDebug($this->varDump($headers)); - if (!isset($headers['content-type'])) { - $this->setError('Request not of type text/xml (no content-type header)'); - return false; - } - if (!strstr($headers['content-type'], 'text/xml')) { - $this->setError('Request not of type text/xml'); - return false; - } - if (strpos($headers['content-type'], '=')) { - $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1)); - $this->debug('Got response encoding: ' . $enc); - if(preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i',$enc)){ - $this->xml_encoding = strtoupper($enc); - } else { - $this->xml_encoding = 'US-ASCII'; - } - } else { - // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 - $this->xml_encoding = 'ISO-8859-1'; - } - $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser'); - // parse response, get soap parser obj - $parser = new nusoap_parser($data,$this->xml_encoding,'',$this->decode_utf8); - // parser debug - $this->debug("parser debug: \n".$parser->getDebug()); - // if fault occurred during message parsing - if($err = $parser->getError()){ - $this->result = 'fault: error in msg parsing: '.$err; - $this->fault('SOAP-ENV:Client',"error in msg parsing:\n".$err); - // else successfully parsed request into soapval object - } else { - // get/set methodname - $this->methodURI = $parser->root_struct_namespace; - $this->methodname = $parser->root_struct_name; - $this->debug('methodname: '.$this->methodname.' methodURI: '.$this->methodURI); - $this->debug('calling parser->get_soapbody()'); - $this->methodparams = $parser->get_soapbody(); - // get SOAP headers - $this->requestHeaders = $parser->getHeaders(); - // get SOAP Header - $this->requestHeader = $parser->get_soapheader(); - // add document for doclit support - $this->document = $parser->document; - } - } - - /** - * gets the HTTP body for the current response. - * - * @param string $soapmsg The SOAP payload - * @return string The HTTP body, which includes the SOAP payload - * @access private - */ - function getHTTPBody($soapmsg) { - return $soapmsg; - } - - /** - * gets the HTTP content type for the current response. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type for the current response. - * @access private - */ - function getHTTPContentType() { - return 'text/xml'; - } - - /** - * gets the HTTP content type charset for the current response. - * returns false for non-text content types. - * - * Note: getHTTPBody must be called before this. - * - * @return string the HTTP content type charset for the current response. - * @access private - */ - function getHTTPContentTypeCharset() { - return $this->soap_defencoding; - } - - /** - * add a method to the dispatch map (this has been replaced by the register method) - * - * @param string $methodname - * @param string $in array of input values - * @param string $out array of output values - * @access public - * @deprecated - */ - function add_to_map($methodname,$in,$out){ - $this->operations[$methodname] = array('name' => $methodname,'in' => $in,'out' => $out); - } - - /** - * register a service function with the server - * - * @param string $name the name of the PHP function, class.method or class..method - * @param array $in assoc array of input values: key = param name, value = param type - * @param array $out assoc array of output values: key = param name, value = param type - * @param mixed $namespace the element namespace for the method or false - * @param mixed $soapaction the soapaction for the method or false - * @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically - * @param mixed $use optional (encoded|literal) or false - * @param string $documentation optional Description to include in WSDL - * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) - * @access public - */ - function register($name,$in=array(),$out=array(),$namespace=false,$soapaction=false,$style=false,$use=false,$documentation='',$encodingStyle=''){ - global $HTTP_SERVER_VARS; - - if($this->externalWSDLURL){ - die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.'); - } - if (! $name) { - die('You must specify a name when you register an operation'); - } - if (!is_array($in)) { - die('You must provide an array for operation inputs'); - } - if (!is_array($out)) { - die('You must provide an array for operation outputs'); - } - if(false == $namespace) { - } - if(false == $soapaction) { - if (isset($_SERVER)) { - $SERVER_NAME = $_SERVER['SERVER_NAME']; - $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; - $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'); - } elseif (isset($HTTP_SERVER_VARS)) { - $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; - $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME']; - $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } - if ($HTTPS == '1' || $HTTPS == 'on') { - $SCHEME = 'https'; - } else { - $SCHEME = 'http'; - } - $soapaction = "$SCHEME://$SERVER_NAME$SCRIPT_NAME/$name"; - } - if(false == $style) { - $style = "rpc"; - } - if(false == $use) { - $use = "encoded"; - } - if ($use == 'encoded' && $encodingStyle == '') { - $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; - } - - $this->operations[$name] = array( - 'name' => $name, - 'in' => $in, - 'out' => $out, - 'namespace' => $namespace, - 'soapaction' => $soapaction, - 'style' => $style); - if($this->wsdl){ - $this->wsdl->addOperation($name,$in,$out,$namespace,$soapaction,$style,$use,$documentation,$encodingStyle); - } - return true; - } - - /** - * Specify a fault to be returned to the client. - * This also acts as a flag to the server that a fault has occured. - * - * @param string $faultcode - * @param string $faultstring - * @param string $faultactor - * @param string $faultdetail - * @access public - */ - function fault($faultcode,$faultstring,$faultactor='',$faultdetail=''){ - if ($faultdetail == '' && $this->debug_flag) { - $faultdetail = $this->getDebug(); - } - $this->fault = new nusoap_fault($faultcode,$faultactor,$faultstring,$faultdetail); - $this->fault->soap_defencoding = $this->soap_defencoding; - } + /** + * HTTP headers of response + * + * @var array + * @access public + */ + var $outgoing_headers = array(); + /** + * HTTP response + * + * @var string + * @access private + */ + var $response = ''; + /** + * SOAP headers for response (text or array of soapval or associative array) + * + * @var mixed + * @access public + */ + var $responseHeaders = ''; + /** + * SOAP payload for response (text) + * + * @var string + * @access private + */ + var $responseSOAP = ''; + /** + * SOAP attachments in response + * + * @var string + * @access private + */ + var $attachments= ''; + /** + * method return value to place in response + * + * @var mixed + * @access private + */ + var $methodreturn = false; + /** + * whether $methodreturn is a string of literal XML + * + * @var boolean + * @access public + */ + var $methodreturnisliteralxml = false; + /** + * SOAP fault for response (or false) + * + * @var mixed + * @access private + */ + var $fault = false; + /** + * text indication of result (for debugging) + * + * @var string + * @access private + */ + var $result = 'successful'; /** - * Sets up wsdl object. - * Acts as a flag to enable internal WSDL generation - * - * @param string $serviceName, name of the service - * @param mixed $namespace optional 'tns' service namespace or false - * @param mixed $endpoint optional URL of service endpoint or false - * @param string $style optional (rpc|document) WSDL style (also specified by operation) - * @param string $transport optional SOAP transport - * @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false - */ - function configureWSDL($serviceName,$namespace = false,$endpoint = false,$style='rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false) - { - global $HTTP_SERVER_VARS; + * assoc array of operations => opData; operations are added by the register() + * method or by parsing an external WSDL definition + * + * @var array + * @access private + */ + var $operations = array(); + /** + * wsdl instance (if one) + * + * @var mixed + * @access private + */ + var $wsdl = false; + /** + * URL for WSDL (if one) + * + * @var mixed + * @access private + */ + var $externalWSDLURL = false; + /** + * whether to append debug to response as XML comment + * + * @var boolean + * @access public + */ + var $debug_flag = false; - if (isset($_SERVER)) { - $SERVER_NAME = $_SERVER['SERVER_NAME']; - $SERVER_PORT = $_SERVER['SERVER_PORT']; - $SCRIPT_NAME = isset($_SERVER['PHP_SELF']) ? $_SERVER['PHP_SELF'] : $_SERVER['SCRIPT_NAME']; - $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'); - } elseif (isset($HTTP_SERVER_VARS)) { - $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; - $SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT']; - $SCRIPT_NAME = isset($HTTP_SERVER_VARS['PHP_SELF']) ? $HTTP_SERVER_VARS['PHP_SELF'] : $HTTP_SERVER_VARS['SCRIPT_NAME']; - $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } - // If server name has port number attached then strip it (else port number gets duplicated in WSDL output) (occurred using lighttpd and FastCGI) - $colon = strpos($SERVER_NAME,":"); - if ($colon) { - $SERVER_NAME = substr($SERVER_NAME, 0, $colon); - } - if ($SERVER_PORT == 80) { - $SERVER_PORT = ''; - } else { - $SERVER_PORT = ':' . $SERVER_PORT; - } - if(false == $namespace) { + /** @var array */ + var $opData; + + + /** + * constructor + * the optional parameter is a path to a WSDL file that you'd like to bind the server instance to. + * + * @param mixed $wsdl file path or URL (string), or wsdl instance (object) + * @access public + */ + function __construct($wsdl = false) + { + parent::__construct(); + // turn on debugging? + global $debug; + global $HTTP_SERVER_VARS; + + if (isset($_SERVER)) { + $this->debug("_SERVER is defined:"); + $this->appendDebug($this->varDump($_SERVER)); + } elseif (isset($HTTP_SERVER_VARS)) { + $this->debug("HTTP_SERVER_VARS is defined:"); + $this->appendDebug($this->varDump($HTTP_SERVER_VARS)); + } else { + $this->debug("Neither _SERVER nor HTTP_SERVER_VARS is defined."); + } + + if (isset($debug)) { + $this->debug("In nusoap_server, set debug_flag=$debug based on global flag"); + $this->debug_flag = $debug; + } elseif (isset($_SERVER['QUERY_STRING'])) { + $qs = explode('&', $_SERVER['QUERY_STRING']); + foreach ($qs as $v) { + if (substr($v, 0, 6) == 'debug=') { + $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #1"); + $this->debug_flag = substr($v, 6); + } + } + } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { + $qs = explode('&', $HTTP_SERVER_VARS['QUERY_STRING']); + foreach ($qs as $v) { + if (substr($v, 0, 6) == 'debug=') { + $this->debug("In nusoap_server, set debug_flag=" . substr($v, 6) . " based on query string #2"); + $this->debug_flag = substr($v, 6); + } + } + } + + // wsdl + if ($wsdl) { + $this->debug("In nusoap_server, WSDL is specified"); + if (is_object($wsdl) && (get_class($wsdl) == 'wsdl')) { + $this->wsdl = $wsdl; + $this->externalWSDLURL = $this->wsdl->wsdl; + $this->debug('Use existing wsdl instance from ' . $this->externalWSDLURL); + } else { + $this->debug('Create wsdl from ' . $wsdl); + $this->wsdl = new wsdl($wsdl); + $this->externalWSDLURL = $wsdl; + } + $this->appendDebug($this->wsdl->getDebug()); + $this->wsdl->clearDebug(); + if ($err = $this->wsdl->getError()) { + die('WSDL ERROR: ' . $err); + } + } + } + + /** + * processes request and returns response + * + * @param string $data usually is the value of $HTTP_RAW_POST_DATA + * @access public + */ + function service($data) + { + global $HTTP_SERVER_VARS; + + if (isset($_SERVER['REQUEST_METHOD'])) { + $rm = $_SERVER['REQUEST_METHOD']; + } elseif (isset($HTTP_SERVER_VARS['REQUEST_METHOD'])) { + $rm = $HTTP_SERVER_VARS['REQUEST_METHOD']; + } else { + $rm = ''; + } + + if (isset($_SERVER['QUERY_STRING'])) { + $qs = $_SERVER['QUERY_STRING']; + } elseif (isset($HTTP_SERVER_VARS['QUERY_STRING'])) { + $qs = $HTTP_SERVER_VARS['QUERY_STRING']; + } else { + $qs = ''; + } + $this->debug("In service, request method=$rm query string=$qs strlen(\$data)=" . strlen($data)); + + if ($rm == 'POST') { + $this->debug("In service, invoke the request"); + $this->parse_request($data); + if (!$this->fault) { + $this->invoke_method(); + } + if (!$this->fault) { + $this->serialize_return(); + } + $this->send_response(); + } elseif (preg_match('/wsdl/', $qs)) { + $this->debug("In service, this is a request for WSDL"); + if ($this->externalWSDLURL) { + if (strpos($this->externalWSDLURL, "http://") !== false) { // assume URL + $this->debug("In service, re-direct for WSDL"); + header('Location: ' . $this->externalWSDLURL); + } else { // assume file + $this->debug("In service, use file passthru for WSDL"); + header("Content-Type: text/xml\r\n"); + $fp = fopen($this->externalWSDLURL, 'r'); + fpassthru($fp); + } + } elseif ($this->wsdl) { + $this->debug("In service, serialize WSDL"); + header("Content-Type: text/xml; charset=ISO-8859-1\r\n"); + print $this->wsdl->serialize($this->debug_flag); + if ($this->debug_flag) { + $this->debug('wsdl:'); + $this->appendDebug($this->varDump($this->wsdl)); + print $this->getDebugAsXMLComment(); + } + } else { + $this->debug("In service, there is no WSDL"); + header("Content-Type: text/html; charset=ISO-8859-1\r\n"); + print "This service does not provide WSDL"; + } + } elseif ($this->wsdl) { + $this->debug("In service, return Web description"); + print $this->wsdl->webDescription(); + } else { + $this->debug("In service, no Web description"); + header("Content-Type: text/html; charset=ISO-8859-1\r\n"); + print "This service does not provide a Web description"; + } + } + + /** + * parses HTTP request headers. + * + * The following fields are set by this function (when successful) + * + * headers + * request + * xml_encoding + * SOAPAction + * + * @access private + */ + function parse_http_headers() + { + global $HTTP_SERVER_VARS; + + $this->request = ''; + $this->SOAPAction = ''; + if (function_exists('getallheaders')) { + $this->debug("In parse_http_headers, use getallheaders"); + $headers = getallheaders(); + foreach ($headers as $k => $v) { + $k = strtolower($k); + $this->headers[$k] = $v; + $this->request .= "$k: $v\r\n"; + $this->debug("$k: $v"); + } + // get SOAPAction header + if (isset($this->headers['soapaction'])) { + $this->SOAPAction = str_replace('"', '', $this->headers['soapaction']); + } + // get the character encoding of the incoming request + if (isset($this->headers['content-type']) && strpos($this->headers['content-type'], '=')) { + $enc = str_replace('"', '', substr(strstr($this->headers["content-type"], '='), 1)); + if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i', $enc)) { + $this->xml_encoding = strtoupper($enc); + } else { + $this->xml_encoding = 'US-ASCII'; + } + } else { + // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 + $this->xml_encoding = 'ISO-8859-1'; + } + } elseif (isset($_SERVER) && is_array($_SERVER)) { + $this->debug("In parse_http_headers, use _SERVER"); + foreach ($_SERVER as $k => $v) { + if (substr($k, 0, 5) == 'HTTP_') { + $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); + } else { + $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); + } + if ($k == 'soapaction') { + // get SOAPAction header + $k = 'SOAPAction'; + $v = str_replace('"', '', $v); + $v = str_replace('\\', '', $v); + $this->SOAPAction = $v; + } elseif ($k == 'content-type') { + // get the character encoding of the incoming request + if (strpos($v, '=')) { + $enc = substr(strstr($v, '='), 1); + $enc = str_replace('"', '', $enc); + $enc = str_replace('\\', '', $enc); + if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i', $enc)) { + $this->xml_encoding = strtoupper($enc); + } else { + $this->xml_encoding = 'US-ASCII'; + } + } else { + // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 + $this->xml_encoding = 'ISO-8859-1'; + } + } + $this->headers[$k] = $v; + if (is_array($v)) { + $this->request .= "$k: " . json_encode($v) . "\r\n"; + $this->debug("$k: " . json_encode($v)); + } else { + $this->request .= "$k: $v\r\n"; + $this->debug("$k: $v"); + } + } + } elseif (is_array($HTTP_SERVER_VARS)) { + $this->debug("In parse_http_headers, use HTTP_SERVER_VARS"); + foreach ($HTTP_SERVER_VARS as $k => $v) { + if (substr($k, 0, 5) == 'HTTP_') { + $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', substr($k, 5)))); + $k = strtolower(substr($k, 5)); + } else { + $k = str_replace(' ', '-', strtolower(str_replace('_', ' ', $k))); + $k = strtolower($k); + } + if ($k == 'soapaction') { + // get SOAPAction header + $k = 'SOAPAction'; + $v = str_replace('"', '', $v); + $v = str_replace('\\', '', $v); + $this->SOAPAction = $v; + } elseif ($k == 'content-type') { + // get the character encoding of the incoming request + if (strpos($v, '=')) { + $enc = substr(strstr($v, '='), 1); + $enc = str_replace('"', '', $enc); + $enc = str_replace('\\', '', $enc); + if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i', $enc)) { + $this->xml_encoding = strtoupper($enc); + } else { + $this->xml_encoding = 'US-ASCII'; + } + } else { + // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 + $this->xml_encoding = 'ISO-8859-1'; + } + } + $this->headers[$k] = $v; + $this->request .= "$k: $v\r\n"; + $this->debug("$k: $v"); + } + } else { + $this->debug("In parse_http_headers, HTTP headers not accessible"); + $this->setError("HTTP headers not accessible"); + } + } + + /** + * parses a request + * + * The following fields are set by this function (when successful) + * + * headers + * request + * xml_encoding + * SOAPAction + * request + * requestSOAP + * methodURI + * methodname + * methodparams + * requestHeaders + * document + * + * This sets the fault field on error + * + * @param string $data XML string + * @access private + */ + function parse_request($data = '') + { + $this->debug('entering parse_request()'); + $this->parse_http_headers(); + $this->debug('got character encoding: ' . $this->xml_encoding); + // uncompress if necessary + if (isset($this->headers['content-encoding']) && $this->headers['content-encoding'] != '') { + $this->debug('got content encoding: ' . $this->headers['content-encoding']); + if ($this->headers['content-encoding'] == 'deflate' || $this->headers['content-encoding'] == 'gzip') { + // if decoding works, use it. else assume data wasn't gzencoded + if (function_exists('gzuncompress')) { + if ($this->headers['content-encoding'] == 'deflate' && $degzdata = @gzuncompress($data)) { + $data = $degzdata; + } elseif ($this->headers['content-encoding'] == 'gzip' && $degzdata = gzinflate(substr($data, 10))) { + $data = $degzdata; + } else { + $this->fault('SOAP-ENV:Client', 'Errors occurred when trying to decode the data'); + return; + } + } else { + $this->fault('SOAP-ENV:Client', 'This Server does not support compressed data'); + return; + } + } + } + $this->request .= "\r\n" . $data; + $data = $this->parseRequest($this->headers, $data); + $this->requestSOAP = $data; + $this->debug('leaving parse_request'); + } + + /** + * invokes a PHP function for the requested SOAP method + * + * The following fields are set by this function (when successful) + * + * methodreturn + * + * Note that the PHP function that is called may also set the following + * fields to affect the response sent to the client + * + * responseHeaders + * outgoing_headers + * + * This sets the fault field on error + * + * @access private + */ + function invoke_method() + { + $this->debug('in invoke_method, methodname=' . $this->methodname . ' methodURI=' . $this->methodURI . ' SOAPAction=' . $this->SOAPAction); + + // + // if you are debugging in this area of the code, your service uses a class to implement methods, + // you use SOAP RPC, and the client is .NET, please be aware of the following... + // when the .NET wsdl.exe utility generates a proxy, it will remove the '.' or '..' from the + // method name. that is fine for naming the .NET methods. it is not fine for properly constructing + // the XML request and reading the XML response. you need to add the RequestElementName and + // ResponseElementName to the System.Web.Services.Protocols.SoapRpcMethodAttribute that wsdl.exe + // generates for the method. these parameters are used to specify the correct XML element names + // for .NET to use, i.e. the names with the '.' in them. + // + $orig_methodname = $this->methodname; + if ($this->wsdl) { + if ($this->opData = $this->wsdl->getOperationData($this->methodname)) { + $this->debug('in invoke_method, found WSDL operation=' . $this->methodname); + $this->appendDebug('opData=' . $this->varDump($this->opData)); + } elseif ($this->opData = $this->wsdl->getOperationDataForSoapAction($this->SOAPAction)) { + // Note: hopefully this case will only be used for doc/lit, since rpc services should have wrapper element + $this->debug('in invoke_method, found WSDL soapAction=' . $this->SOAPAction . ' for operation=' . $this->opData['name']); + $this->appendDebug('opData=' . $this->varDump($this->opData)); + $this->methodname = $this->opData['name']; + } else { + $this->debug('in invoke_method, no WSDL for operation=' . $this->methodname); + $this->fault('SOAP-ENV:Client', "Operation '" . $this->methodname . "' is not defined in the WSDL for this service"); + return; + } + } else { + $this->debug('in invoke_method, no WSDL to validate method'); + } + + // if a . is present in $this->methodname, we see if there is a class in scope, + // which could be referred to. We will also distinguish between two deliminators, + // to allow methods to be called a the class or an instance + if (strpos($this->methodname, '..') > 0) { + $delim = '..'; + } elseif (strpos($this->methodname, '.') > 0) { + $delim = '.'; + } else { + $delim = ''; + } + $this->debug("in invoke_method, delim=$delim"); + + $class = ''; + $method = ''; + $try_class = ''; + if (strlen($delim) > 0 && substr_count($this->methodname, $delim) == 1) { + $try_class = substr($this->methodname, 0, strpos($this->methodname, $delim)); + if (class_exists($try_class)) { + // get the class and method name + $class = $try_class; + $method = substr($this->methodname, strpos($this->methodname, $delim) + strlen($delim)); + $this->debug("in invoke_method, class=$class method=$method delim=$delim"); + } else { + $this->debug("in invoke_method, class=$try_class not found"); + } + } elseif (strlen($delim) > 0 && substr_count($this->methodname, $delim) > 1) { + $split = explode($delim, $this->methodname); + $method = array_pop($split); + $class = implode('\\', $split); + } else { + $this->debug("in invoke_method, no class to try"); + } + + // does method exist? + if ($class == '') { + if (!function_exists($this->methodname)) { + $this->debug("in invoke_method, function '$this->methodname' not found!"); + $this->result = 'fault: method not found'; + $this->fault('SOAP-ENV:Client', "method '$this->methodname'('$orig_methodname') not defined in service('$try_class' '$delim')"); + return; + } + } else { + $method_to_compare = (substr(phpversion(), 0, 2) == '4.') ? strtolower($method) : $method; + if (!in_array($method_to_compare, get_class_methods($class))) { + $this->debug("in invoke_method, method '$this->methodname' not found in class '$class'!"); + $this->result = 'fault: method not found'; + $this->fault('SOAP-ENV:Client', "method '$this->methodname'/'$method_to_compare'('$orig_methodname') not defined in service/'$class'('$try_class' '$delim')"); + return; + } + } + + // evaluate message, getting back parameters + // verify that request parameters match the method's signature + if (!$this->verify_method($this->methodname, $this->methodparams)) { + // debug + $this->debug('ERROR: request not verified against method signature'); + $this->result = 'fault: request failed validation against method signature'; + // return fault + $this->fault('SOAP-ENV:Client', "Operation '$this->methodname' not defined in service."); + return; + } + + // if there are parameters to pass + $this->debug('in invoke_method, params:'); + $this->appendDebug($this->varDump($this->methodparams)); + $this->debug("in invoke_method, calling '$this->methodname'"); + if (!function_exists('call_user_func_array')) { + if ($class == '') { + $this->debug('in invoke_method, calling function using eval()'); + $funcCall = "\$this->methodreturn = $this->methodname("; + } else { + if ($delim == '..') { + $this->debug('in invoke_method, calling class method using eval()'); + $funcCall = "\$this->methodreturn = " . $class . "::" . $method . "("; + } else { + $this->debug('in invoke_method, calling instance method using eval()'); + // generate unique instance name + $instname = "\$inst_" . time(); + $funcCall = $instname . " = new " . $class . "(); "; + $funcCall .= "\$this->methodreturn = " . $instname . "->" . $method . "("; + } + } + if ($this->methodparams) { + foreach ($this->methodparams as $param) { + if (is_array($param) || is_object($param)) { + $this->fault('SOAP-ENV:Client', 'NuSOAP does not handle complexType parameters correctly when using eval; call_user_func_array must be available'); + return; + } + $funcCall .= "\"$param\","; + } + $funcCall = substr($funcCall, 0, -1); + } + $funcCall .= ');'; + $this->debug('in invoke_method, function call: ' . $funcCall); + @eval($funcCall); + } else { + if ($class == '') { + $this->debug('in invoke_method, calling function using call_user_func_array()'); + $call_arg = "$this->methodname"; // straight assignment changes $this->methodname to lower case after call_user_func_array() + } elseif ($delim == '..') { + $this->debug('in invoke_method, calling class method using call_user_func_array()'); + $call_arg = array($class, $method); + } else { + $this->debug('in invoke_method, calling instance method using call_user_func_array()'); + $instance = new $class (); + $call_arg = array(&$instance, $method); + } + if (is_array($this->methodparams)) { + $this->methodreturn = call_user_func_array($call_arg, array_values($this->methodparams)); + } else { + $this->methodreturn = call_user_func_array($call_arg, array()); + } + } + $this->debug('in invoke_method, methodreturn:'); + $this->appendDebug($this->varDump($this->methodreturn)); + $this->debug("in invoke_method, called method $this->methodname, received data of type " . gettype($this->methodreturn)); + } + + /** + * serializes the return value from a PHP function into a full SOAP Envelope + * + * The following fields are set by this function (when successful) + * + * responseSOAP + * + * This sets the fault field on error + * + * @access private + */ + function serialize_return() + { + $this->debug('Entering serialize_return methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI); + // if fault + if (isset($this->methodreturn) && is_object($this->methodreturn) && ((get_class($this->methodreturn) == 'soap_fault') || (get_class($this->methodreturn) == 'nusoap_fault'))) { + $this->debug('got a fault object from method'); + $this->fault = $this->methodreturn; + return; + } elseif ($this->methodreturnisliteralxml) { + $return_val = $this->methodreturn; + // returned value(s) + } else { + $this->debug('got a(n) ' . gettype($this->methodreturn) . ' from method'); + $this->debug('serializing return value'); + if ($this->wsdl) { + if (sizeof($this->opData['output']['parts']) > 1) { + $this->debug('more than one output part, so use the method return unchanged'); + $opParams = $this->methodreturn; + } elseif (sizeof($this->opData['output']['parts']) == 1) { + $this->debug('exactly one output part, so wrap the method return in a simple array'); + // TODO: verify that it is not already wrapped! + //foreach ($this->opData['output']['parts'] as $name => $type) { + // $this->debug('wrap in element named ' . $name); + //} + $opParams = array($this->methodreturn); + } + $opParams = isset($opParams) ? $opParams : []; + $return_val = $this->wsdl->serializeRPCParameters($this->methodname, 'output', $opParams); + $this->appendDebug($this->wsdl->getDebug()); + $this->wsdl->clearDebug(); + if ($errstr = $this->wsdl->getError()) { + $this->debug('got wsdl error: ' . $errstr); + $this->fault('SOAP-ENV:Server', 'unable to serialize result'); + return; + } + } else { + if (isset($this->methodreturn)) { + $return_val = $this->serialize_val($this->methodreturn, 'return'); + } else { + $return_val = ''; + $this->debug('in absence of WSDL, assume void return for backward compatibility'); + } + } + } + $this->debug('return value:'); + $this->appendDebug($this->varDump($return_val)); + + $this->debug('serializing response'); + if ($this->wsdl) { + $this->debug('have WSDL for serialization: style is ' . $this->opData['style']); + if ($this->opData['style'] == 'rpc') { + $this->debug('style is rpc for serialization: use is ' . $this->opData['output']['use']); + if ($this->opData['output']['use'] == 'literal') { + // http://www.ws-i.org/Profiles/BasicProfile-1.1-2004-08-24.html R2735 says rpc/literal accessor elements should not be in a namespace + if ($this->methodURI) { + $payload = 'responseTagName . ' xmlns:ns1="' . $this->methodURI . '">' . $return_val . 'responseTagName . ">"; + } else { + $payload = '<' . $this->responseTagName . '>' . $return_val . 'responseTagName . 'Response>'; + } + } else { + if ($this->methodURI) { + $payload = 'responseTagName . ' xmlns:ns1="' . $this->methodURI . '">' . $return_val . 'responseTagName . ">"; + } else { + $payload = '<' . $this->responseTagName . '>' . $return_val . 'responseTagName . '>'; + } + } + } else { + $this->debug('style is not rpc for serialization: assume document'); + $payload = $return_val; + } + } else { + $this->debug('do not have WSDL for serialization: assume rpc/encoded'); + $payload = 'responseTagName . ' xmlns:ns1="' . $this->methodURI . '">' . $return_val . 'responseTagName . ">"; + } + $this->result = 'successful'; + if ($this->wsdl) { + //if($this->debug_flag){ + $this->appendDebug($this->wsdl->getDebug()); + // } + if (isset($this->opData['output']['encodingStyle'])) { + $encodingStyle = $this->opData['output']['encodingStyle']; + } else { + $encodingStyle = ''; + } + // Added: In case we use a WSDL, return a serialized env. WITH the usedNamespaces. + $this->responseSOAP = $this->serializeEnvelope($payload, $this->responseHeaders, $this->wsdl->usedNamespaces, $this->opData['style'], $this->opData['output']['use'], $encodingStyle); + } else { + $this->responseSOAP = $this->serializeEnvelope($payload, $this->responseHeaders); + } + $this->debug("Leaving serialize_return"); + } + + /** + * sends an HTTP response + * + * The following fields are set by this function (when successful) + * + * outgoing_headers + * response + * + * @access private + */ + function send_response() + { + $this->debug('Enter send_response'); + if ($this->fault) { + $payload = $this->fault->serialize(); + $this->outgoing_headers[] = "HTTP/1.0 500 Internal Server Error"; + $this->outgoing_headers[] = "Status: 500 Internal Server Error"; + } else { + $payload = $this->responseSOAP; + // Some combinations of PHP+Web server allow the Status + // to come through as a header. Since OK is the default + // just do nothing. + // $this->outgoing_headers[] = "HTTP/1.0 200 OK"; + // $this->outgoing_headers[] = "Status: 200 OK"; + } + // add debug data if in debug mode + if (isset($this->debug_flag) && $this->debug_flag) { + $payload .= $this->getDebugAsXMLComment(); + } + $this->outgoing_headers[] = "Server: $this->title Server v$this->version"; + $rev = array(); + preg_match('/\$Revisio' . 'n: ([^ ]+)/', $this->revision, $rev); + $this->outgoing_headers[] = "X-SOAP-Server: $this->title/$this->version (" . (isset($rev[1]) ? $rev[1] : '') . ")"; + // Let the Web server decide about this + //$this->outgoing_headers[] = "Connection: Close\r\n"; + $payload = $this->getHTTPBody($payload); + $type = $this->getHTTPContentType(); + $charset = $this->getHTTPContentTypeCharset(); + $this->outgoing_headers[] = "Content-Type: $type" . ($charset ? '; charset=' . $charset : ''); + //begin code to compress payload - by John + // NOTE: there is no way to know whether the Web server will also compress + // this data. + if (strlen($payload) > 1024 && isset($this->headers) && isset($this->headers['accept-encoding'])) { + if (strstr($this->headers['accept-encoding'], 'gzip')) { + if (function_exists('gzencode')) { + if (isset($this->debug_flag) && $this->debug_flag) { + $payload .= ""; + } + $this->outgoing_headers[] = "Content-Encoding: gzip"; + $payload = gzencode($payload); + } else { + if (isset($this->debug_flag) && $this->debug_flag) { + $payload .= ""; + } + } + } elseif (strstr($this->headers['accept-encoding'], 'deflate')) { + // Note: MSIE requires gzdeflate output (no Zlib header and checksum), + // instead of gzcompress output, + // which conflicts with HTTP 1.1 spec (http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.5) + if (function_exists('gzdeflate')) { + if (isset($this->debug_flag) && $this->debug_flag) { + $payload .= ""; + } + $this->outgoing_headers[] = "Content-Encoding: deflate"; + $payload = gzdeflate($payload); + } else { + if (isset($this->debug_flag) && $this->debug_flag) { + $payload .= ""; + } + } + } + } + //end code + $this->outgoing_headers[] = "Content-Length: " . strlen($payload); + reset($this->outgoing_headers); + foreach ($this->outgoing_headers as $hdr) { + header($hdr, false); + } + print $payload; + $this->response = join("\r\n", $this->outgoing_headers) . "\r\n\r\n" . $payload; + } + + /** + * takes the value that was created by parsing the request + * and compares to the method's signature, if available. + * + * @param string $operation The operation to be invoked + * @param array $request The array of parameter values + * @return boolean Whether the operation was found + * @access private + */ + function verify_method($operation, $request) + { + if (isset($this->wsdl) && is_object($this->wsdl)) { + if ($this->wsdl->getOperationData($operation)) { + return true; + } + } elseif (isset($this->operations[$operation])) { + return true; + } + return false; + } + + /** + * processes SOAP message received from client + * + * @param array $headers The HTTP headers + * @param string $data unprocessed request data from client + * @return false|void void or false on error + * @access private + */ + function parseRequest($headers, $data) + { + $this->debug('Entering parseRequest() for data of length ' . strlen($data) . ' headers:'); + $this->appendDebug($this->varDump($headers)); + if (!isset($headers['content-type'])) { + $this->setError('Request not of type '.$this->contentType.' (no content-type header)'); + return false; + } + if (!strstr($headers['content-type'], $this->contentType)) { + $this->setError('Request not of type '.$this->contentType.': ' . $headers['content-type']); + return false; + } + if (strpos($headers['content-type'], '=')) { + $enc = str_replace('"', '', substr(strstr($headers["content-type"], '='), 1)); + $this->debug('Got response encoding: ' . $enc); + if (preg_match('/^(ISO-8859-1|US-ASCII|UTF-8)$/i', $enc)) { + $this->xml_encoding = strtoupper($enc); + } else { + $this->xml_encoding = 'US-ASCII'; + } + } else { + // should be US-ASCII for HTTP 1.0 or ISO-8859-1 for HTTP 1.1 + $this->xml_encoding = 'ISO-8859-1'; + } + $this->debug('Use encoding: ' . $this->xml_encoding . ' when creating nusoap_parser'); + // parse response, get soap parser obj + $parser = new nusoap_parser($data, $this->xml_encoding, '', $this->decode_utf8); + // parser debug + $this->debug("parser debug: \n" . $parser->getDebug()); + // if fault occurred during message parsing + if ($err = $parser->getError()) { + $this->result = 'fault: error in msg parsing: ' . $err; + $this->fault('SOAP-ENV:Client', "error in msg parsing:\n" . $err); + // else successfully parsed request into soapval object + } else { + // get/set methodname + $this->methodURI = $parser->root_struct_namespace; + $this->methodname = $parser->root_struct_name; + $this->debug('methodname: ' . $this->methodname . ' methodURI: ' . $this->methodURI); + + // get/set custom response tag name + $outputMessage = $this->wsdl->getOperationData($this->methodname)['output']['message']; + $this->responseTagName = $outputMessage; + $this->debug('responseTagName: ' . $this->responseTagName . ' methodURI: ' . $this->methodURI); + + $this->debug('calling parser->get_soapbody()'); + $this->methodparams = $parser->get_soapbody(); + // get SOAP headers + $this->requestHeaders = $parser->getHeaders(); + // get SOAP Header + $this->requestHeader = $parser->get_soapheader(); + // add document for doclit support + $this->document = $parser->document; + } + } + + /** + * gets the HTTP body for the current response. + * + * @param string $soapmsg The SOAP payload + * @return string The HTTP body, which includes the SOAP payload + * @access private + */ + function getHTTPBody($soapmsg) + { + return $soapmsg; + } + + /** + * gets the HTTP content type for the current response. + * + * Note: getHTTPBody must be called before this. + * + * @return string the HTTP content type for the current response. + * @access private + */ + function getHTTPContentType() + { + return 'text/xml'; + } + + /** + * gets the HTTP content type charset for the current response. + * returns false for non-text content types. + * + * Note: getHTTPBody must be called before this. + * + * @return string the HTTP content type charset for the current response. + * @access private + */ + function getHTTPContentTypeCharset() + { + return $this->soap_defencoding; + } + + /** + * add a method to the dispatch map (this has been replaced by the register method) + * + * @param string $methodname + * @param string $in array of input values + * @param string $out array of output values + * @access public + * @deprecated + */ + function add_to_map($methodname, $in, $out) + { + $this->operations[$methodname] = array('name' => $methodname, 'in' => $in, 'out' => $out); + } + + /** + * register a service function with the server + * + * @param string $name the name of the PHP function, class.method or class..method + * @param array $in assoc array of input values: key = param name, value = param type + * @param array $out assoc array of output values: key = param name, value = param type + * @param mixed $namespace the element namespace for the method or false + * @param mixed $soapaction the soapaction for the method or false + * @param mixed $style optional (rpc|document) or false Note: when 'document' is specified, parameter and return wrappers are created for you automatically + * @param mixed $use optional (encoded|literal) or false + * @param string $documentation optional Description to include in WSDL + * @param string $encodingStyle optional (usually 'http://schemas.xmlsoap.org/soap/encoding/' for encoded) + * @param string $customResponseTagName optional Name of the outgoing response, default $name . 'Response' + * @access public + */ + function register($name, $in = array(), $out = array(), $namespace = false, $soapaction = false, $style = false, $use = false, $documentation = '', $encodingStyle = '', $customResponseTagName = '') + { + global $HTTP_SERVER_VARS; + + if ($this->externalWSDLURL) { + die('You cannot bind to an external WSDL file, and register methods outside of it! Please choose either WSDL or no WSDL.'); + } + if (!$name) { + die('You must specify a name when you register an operation'); + } + if (!is_array($in)) { + die('You must provide an array for operation inputs'); + } + if (!is_array($out)) { + die('You must provide an array for operation outputs'); + } + if (!$soapaction) { + if (isset($_SERVER)) { + $SERVER_NAME = $_SERVER['SERVER_NAME']; + $SCRIPT_NAME = $_SERVER['SCRIPT_NAME']; + $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'); + } elseif (isset($HTTP_SERVER_VARS)) { + $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; + $SCRIPT_NAME = $HTTP_SERVER_VARS['SCRIPT_NAME']; + $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'; + } else { + $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); + $HTTPS = ''; + $SERVER_NAME = ''; + $SCRIPT_NAME = ''; + } + if ($HTTPS == '1' || $HTTPS == 'on') { + $SCHEME = 'https'; + } else { + $SCHEME = 'http'; + } + $soapaction = "$SCHEME://$SERVER_NAME$SCRIPT_NAME/$name"; + } + if (!$style) { + $style = "rpc"; + } + if (!$use) { + $use = "encoded"; + } + if ($use == 'encoded' && $encodingStyle == '') { + $encodingStyle = 'http://schemas.xmlsoap.org/soap/encoding/'; + } + if (!$customResponseTagName) { + $customResponseTagName = $name . 'Response'; + } + + $this->operations[$name] = array( + 'name' => $name, + 'in' => $in, + 'out' => $out, + 'namespace' => $namespace, + 'soapaction' => $soapaction, + 'style' => $style, + 'outputMessage' => $customResponseTagName, + ); + if ($this->wsdl) { + $this->wsdl->addOperation($name, $in, $out, $namespace, $soapaction, $style, $use, $documentation, $encodingStyle, $customResponseTagName); + } + return true; + } + + /** + * Specify a fault to be returned to the client. + * This also acts as a flag to the server that a fault has occured. + * + * @param string $faultcode + * @param string $faultstring + * @param string $faultactor + * @param string $faultdetail + * @access public + */ + function fault($faultcode, $faultstring, $faultactor = '', $faultdetail = '') + { + if ($faultdetail == '' && $this->debug_flag) { + $faultdetail = $this->getDebug(); + } + $this->fault = new nusoap_fault($faultcode, $faultactor, $faultstring, $faultdetail); + $this->fault->soap_defencoding = $this->soap_defencoding; + } + + /** + * Sets up wsdl object. + * Acts as a flag to enable internal WSDL generation + * + * @param string $serviceName , name of the service + * @param mixed $namespace optional 'tns' service namespace or false + * @param mixed $endpoint optional URL of service endpoint or false + * @param string $style optional (rpc|document) WSDL style (also specified by operation) + * @param string $transport optional SOAP transport + * @param mixed $schemaTargetNamespace optional 'types' targetNamespace for service schema or false + */ + function configureWSDL($serviceName, $namespace = false, $endpoint = false, $style = 'rpc', $transport = 'http://schemas.xmlsoap.org/soap/http', $schemaTargetNamespace = false) + { + global $HTTP_SERVER_VARS; + + if (isset($_SERVER)) { + $SERVER_NAME = $_SERVER['SERVER_NAME']; + $SERVER_PORT = $_SERVER['SERVER_PORT']; + $SCRIPT_NAME = $_SERVER['SCRIPT_NAME']; + $HTTPS = isset($_SERVER['HTTPS']) ? $_SERVER['HTTPS'] : (isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'); + } elseif (isset($HTTP_SERVER_VARS)) { + $SERVER_NAME = $HTTP_SERVER_VARS['SERVER_NAME']; + $SERVER_PORT = $HTTP_SERVER_VARS['SERVER_PORT']; + $SCRIPT_NAME = $HTTP_SERVER_VARS['SCRIPT_NAME']; + $HTTPS = isset($HTTP_SERVER_VARS['HTTPS']) ? $HTTP_SERVER_VARS['HTTPS'] : 'off'; + } else { + $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); + $SERVER_PORT = ''; + $SERVER_NAME = ''; + $SCRIPT_NAME = ''; + $HTTPS = ''; + } + // If server name has port number attached then strip it (else port number gets duplicated in WSDL output) (occurred using lighttpd and FastCGI) + $colon = strpos($SERVER_NAME, ":"); + if ($colon) { + $SERVER_NAME = substr($SERVER_NAME, 0, $colon); + } + if ($SERVER_PORT == 80) { + $SERVER_PORT = ''; + } else { + $SERVER_PORT = ':' . $SERVER_PORT; + } + if (!$namespace) { $namespace = "http://$SERVER_NAME/soap/$serviceName"; } - if(false == $endpoint) { - if ($HTTPS == '1' || $HTTPS == 'on') { - $SCHEME = 'https'; - } else { - $SCHEME = 'http'; - } + if (!$endpoint) { + if ($HTTPS == '1' || $HTTPS == 'on') { + $SCHEME = 'https'; + } else { + $SCHEME = 'http'; + } $endpoint = "$SCHEME://$SERVER_NAME$SERVER_PORT$SCRIPT_NAME"; } - if(false == $schemaTargetNamespace) { + if (!$schemaTargetNamespace) { $schemaTargetNamespace = $namespace; } - $this->wsdl = new wsdl; - $this->wsdl->serviceName = $serviceName; + $this->wsdl = new wsdl; + $this->wsdl->serviceName = $serviceName; $this->wsdl->endpoint = $endpoint; - $this->wsdl->namespaces['tns'] = $namespace; - $this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/'; - $this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/'; - if ($schemaTargetNamespace != $namespace) { - $this->wsdl->namespaces['types'] = $schemaTargetNamespace; - } + $this->wsdl->namespaces['tns'] = $namespace; + $this->wsdl->namespaces['soap'] = 'http://schemas.xmlsoap.org/wsdl/soap/'; + $this->wsdl->namespaces['wsdl'] = 'http://schemas.xmlsoap.org/wsdl/'; + if ($schemaTargetNamespace != $namespace) { + $this->wsdl->namespaces['types'] = $schemaTargetNamespace; + } $this->wsdl->schemas[$schemaTargetNamespace][0] = new nusoap_xmlschema('', '', $this->wsdl->namespaces); if ($style == 'document') { - $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaInfo['elementFormDefault'] = 'qualified'; + $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaInfo['elementFormDefault'] = 'qualified'; } $this->wsdl->schemas[$schemaTargetNamespace][0]->schemaTargetNamespace = $schemaTargetNamespace; $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/soap/encoding/'][0] = array('location' => '', 'loaded' => true); $this->wsdl->schemas[$schemaTargetNamespace][0]->imports['http://schemas.xmlsoap.org/wsdl/'][0] = array('location' => '', 'loaded' => true); - $this->wsdl->bindings[$serviceName.'Binding'] = array( - 'name'=>$serviceName.'Binding', - 'style'=>$style, - 'transport'=>$transport, - 'portType'=>$serviceName.'PortType'); - $this->wsdl->ports[$serviceName.'Port'] = array( - 'binding'=>$serviceName.'Binding', - 'location'=>$endpoint, - 'bindingType'=>'http://schemas.xmlsoap.org/wsdl/soap/'); + $this->wsdl->bindings[$serviceName . 'Binding'] = array( + 'name' => $serviceName . 'Binding', + 'style' => $style, + 'transport' => $transport, + 'portType' => $serviceName . 'PortType'); + $this->wsdl->ports[$serviceName . 'Port'] = array( + 'binding' => $serviceName . 'Binding', + 'location' => $endpoint, + 'bindingType' => 'http://schemas.xmlsoap.org/wsdl/soap/'); } } /** * Backward compatibility */ -class soap_server extends nusoap_server { +class soap_server extends nusoap_server +{ } -?> -* @author Scott Nichol -* @access public -*/ -class wsdl extends nusoap_base { - // URL or filename of the root of this WSDL + * parses a WSDL file, allows access to it's data, other utility methods. + * also builds WSDL structures programmatically. + * + * @author Dietrich Ayala + * @author Scott Nichol + * @version $Id: nusoap.php,v 1.123 2010/04/26 20:15:08 snichol Exp $ + * @access public + */ +class wsdl extends nusoap_base +{ + // URL or filename of the root of this WSDL var $wsdl; // define internal arrays of bindings, ports, operations, messages, etc. var $schemas = array(); @@ -4618,151 +4767,162 @@ class wsdl extends nusoap_base { var $position = 0; var $depth = 0; var $depth_array = array(); - // for getting wsdl - var $proxyhost = ''; + // for getting wsdl + var $proxyhost = ''; var $proxyport = ''; - var $proxyusername = ''; - var $proxypassword = ''; - var $timeout = 0; - var $response_timeout = 30; - var $curl_options = array(); // User-specified cURL options - var $use_curl = false; // whether to always try to use cURL - // for HTTP authentication - var $username = ''; // Username for HTTP authentication - var $password = ''; // Password for HTTP authentication - var $authtype = ''; // Type of HTTP authentication - var $certRequest = array(); // Certificate for HTTP SSL authentication + var $proxyusername = ''; + var $proxypassword = ''; + var $timeout = 0; + var $response_timeout = 30; + var $curl_options = array(); // User-specified cURL options + var $use_curl = false; // whether to always try to use cURL + // for HTTP authentication + var $username = ''; // Username for HTTP authentication + var $password = ''; // Password for HTTP authentication + var $authtype = ''; // Type of HTTP authentication + var $certRequest = array(); // Certificate for HTTP SSL authentication + + /** @var mixed */ + var $currentPortOperation; + /** @var string */ + var $opStatus; + /** @var mixed */ + var $serviceName; + var $wsdl_info; /** * constructor * * @param string $wsdl WSDL document URL - * @param string $proxyhost - * @param string $proxyport - * @param string $proxyusername - * @param string $proxypassword - * @param integer $timeout set the connection timeout - * @param integer $response_timeout set the response timeout - * @param array $curl_options user-specified cURL options - * @param boolean $use_curl try to use cURL + * @param string $proxyhost + * @param string $proxyport + * @param string $proxyusername + * @param string $proxypassword + * @param integer $timeout set the connection timeout + * @param integer $response_timeout set the response timeout + * @param array $curl_options user-specified cURL options + * @param boolean $use_curl try to use cURL * @access public */ - function __construct($wsdl = '',$proxyhost=false,$proxyport=false,$proxyusername=false,$proxypassword=false,$timeout=0,$response_timeout=30,$curl_options=null,$use_curl=false){ - parent::__construct(); - $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout"); + function __construct($wsdl = '', $proxyhost = false, $proxyport = false, $proxyusername = false, $proxypassword = false, $timeout = 0, $response_timeout = 30, $curl_options = null, $use_curl = false) + { + parent::__construct(); + $this->debug("ctor wsdl=$wsdl timeout=$timeout response_timeout=$response_timeout"); $this->proxyhost = $proxyhost; $this->proxyport = $proxyport; - $this->proxyusername = $proxyusername; - $this->proxypassword = $proxypassword; - $this->timeout = $timeout; - $this->response_timeout = $response_timeout; - if (is_array($curl_options)) - $this->curl_options = $curl_options; - $this->use_curl = $use_curl; - $this->fetchWSDL($wsdl); + $this->proxyusername = $proxyusername; + $this->proxypassword = $proxypassword; + $this->timeout = $timeout; + $this->response_timeout = $response_timeout; + if (is_array($curl_options)) { + $this->curl_options = $curl_options; + } + $this->use_curl = $use_curl; + $this->fetchWSDL($wsdl); } - /** - * fetches the WSDL document and parses it - * - * @access public - */ - function fetchWSDL($wsdl) { - $this->debug("parse and process WSDL path=$wsdl"); - $this->wsdl = $wsdl; + /** + * fetches the WSDL document and parses it + * + * @access public + */ + function fetchWSDL($wsdl) + { + $this->debug("parse and process WSDL path=$wsdl"); + $this->wsdl = $wsdl; // parse wsdl file if ($this->wsdl != "") { $this->parseWSDL($this->wsdl); } // imports // TODO: handle imports more properly, grabbing them in-line and nesting them - $imported_urls = array(); - $imported = 1; - while ($imported > 0) { - $imported = 0; - // Schema imports - foreach ($this->schemas as $ns => $list) { - foreach ($list as $xs) { - $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! - foreach ($xs->imports as $ns2 => $list2) { - for ($ii = 0; $ii < count($list2); $ii++) { - if (! $list2[$ii]['loaded']) { - $this->schemas[$ns]->imports[$ns2][$ii]['loaded'] = true; - $url = $list2[$ii]['location']; - if ($url != '') { - $urlparts = parse_url($url); - if (!isset($urlparts['host'])) { - $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' .$wsdlparts['port'] : '') . - substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path']; - } - if (! in_array($url, $imported_urls)) { - $this->parseWSDL($url); - $imported++; - $imported_urls[] = $url; - } - } else { - $this->debug("Unexpected scenario: empty URL for unloaded import"); - } - } - } - } - } - } - // WSDL imports - $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! + $imported_urls = array(); + $imported = 1; + while ($imported > 0) { + $imported = 0; + // Schema imports + foreach ($this->schemas as $ns => $list) { + foreach ($list as $xsKey => $xs) { + $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! + foreach ($xs->imports as $ns2 => $list2) { + for ($ii = 0; $ii < count($list2); $ii++) { + if (array_key_exists($ii, $list2) && (!isset($list2[$ii]['loaded']) || !$list2[$ii]['loaded'])) { + @$this->schemas[$ns][$xsKey]->imports[$ns2][$ii]['loaded'] = true; + $url = $list2[$ii]['location']; + if ($url != '') { + $urlparts = parse_url($url); + if (!isset($urlparts['host'])) { + $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') . + substr($wsdlparts['path'], 0, strrpos($wsdlparts['path'], '/') + 1) . $urlparts['path']; + } + if (!in_array($url, $imported_urls)) { + $this->parseWSDL($url); + $imported++; + $imported_urls[] = $url; + } + } else { + $this->debug("Unexpected scenario: empty URL for unloaded import"); + } + } + } + } + } + } + // WSDL imports + $wsdlparts = parse_url($this->wsdl); // this is bogusly simple! foreach ($this->import as $ns => $list) { for ($ii = 0; $ii < count($list); $ii++) { - if (! $list[$ii]['loaded']) { - $this->import[$ns][$ii]['loaded'] = true; - $url = $list[$ii]['location']; - if ($url != '') { - $urlparts = parse_url($url); - if (!isset($urlparts['host'])) { - $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') . - substr($wsdlparts['path'],0,strrpos($wsdlparts['path'],'/') + 1) .$urlparts['path']; - } - if (! in_array($url, $imported_urls)) { - $this->parseWSDL($url); - $imported++; - $imported_urls[] = $url; - } - } else { - $this->debug("Unexpected scenario: empty URL for unloaded import"); - } - } - } + if (!$list[$ii]['loaded']) { + $this->import[$ns][$ii]['loaded'] = true; + $url = $list[$ii]['location']; + if ($url != '') { + $urlparts = parse_url($url); + if (!isset($urlparts['host'])) { + $url = $wsdlparts['scheme'] . '://' . $wsdlparts['host'] . (isset($wsdlparts['port']) ? ':' . $wsdlparts['port'] : '') . + substr($wsdlparts['path'], 0, strrpos($wsdlparts['path'], '/') + 1) . $urlparts['path']; + } + if (!in_array($url, $imported_urls)) { + $this->parseWSDL($url); + $imported++; + $imported_urls[] = $url; + } + } else { + $this->debug("Unexpected scenario: empty URL for unloaded import"); + } + } + } } - } + } // add new data to operation data - foreach($this->bindings as $binding => $bindingData) { + foreach ($this->bindings as $binding => $bindingData) { if (isset($bindingData['operations']) && is_array($bindingData['operations'])) { - foreach($bindingData['operations'] as $operation => $data) { + foreach ($bindingData['operations'] as $operation => $data) { $this->debug('post-parse data gathering for ' . $operation); $this->bindings[$binding]['operations'][$operation]['input'] = - isset($this->bindings[$binding]['operations'][$operation]['input']) ? - array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[ $bindingData['portType'] ][$operation]['input']) : - $this->portTypes[ $bindingData['portType'] ][$operation]['input']; + isset($this->bindings[$binding]['operations'][$operation]['input']) ? + array_merge($this->bindings[$binding]['operations'][$operation]['input'], $this->portTypes[$bindingData['portType']][$operation]['input']) : + $this->portTypes[$bindingData['portType']][$operation]['input']; $this->bindings[$binding]['operations'][$operation]['output'] = - isset($this->bindings[$binding]['operations'][$operation]['output']) ? - array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[ $bindingData['portType'] ][$operation]['output']) : - $this->portTypes[ $bindingData['portType'] ][$operation]['output']; - if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ])){ - $this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['input']['message'] ]; - } - if(isset($this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ])){ - $this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[ $this->bindings[$binding]['operations'][$operation]['output']['message'] ]; + isset($this->bindings[$binding]['operations'][$operation]['output']) ? + array_merge($this->bindings[$binding]['operations'][$operation]['output'], $this->portTypes[$bindingData['portType']][$operation]['output']) : + $this->portTypes[$bindingData['portType']][$operation]['output']; + if (isset($this->messages[$this->bindings[$binding]['operations'][$operation]['input']['message']])) { + $this->bindings[$binding]['operations'][$operation]['input']['parts'] = $this->messages[$this->bindings[$binding]['operations'][$operation]['input']['message']]; + } + if (isset($this->messages[$this->bindings[$binding]['operations'][$operation]['output']['message']])) { + $this->bindings[$binding]['operations'][$operation]['output']['parts'] = $this->messages[$this->bindings[$binding]['operations'][$operation]['output']['message']]; } // Set operation style if necessary, but do not override one already provided - if (isset($bindingData['style']) && !isset($this->bindings[$binding]['operations'][$operation]['style'])) { + if (isset($bindingData['style']) && !isset($this->bindings[$binding]['operations'][$operation]['style'])) { $this->bindings[$binding]['operations'][$operation]['style'] = $bindingData['style']; } $this->bindings[$binding]['operations'][$operation]['transport'] = isset($bindingData['transport']) ? $bindingData['transport'] : ''; - $this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[ $bindingData['portType'] ][$operation]['documentation']) ? $this->portTypes[ $bindingData['portType'] ][$operation]['documentation'] : ''; + $this->bindings[$binding]['operations'][$operation]['documentation'] = isset($this->portTypes[$bindingData['portType']][$operation]['documentation']) ? $this->portTypes[$bindingData['portType']][$operation]['documentation'] : ''; $this->bindings[$binding]['operations'][$operation]['endpoint'] = isset($bindingData['endpoint']) ? $bindingData['endpoint'] : ''; } } } - } + } /** * parses the wsdl document @@ -4770,8 +4930,9 @@ class wsdl extends nusoap_base { * @param string $wsdl path or URL * @access private */ - function parseWSDL($wsdl = '') { - $this->debug("parse WSDL at path=$wsdl"); + function parseWSDL($wsdl = '') + { + $this->debug("parse WSDL at path=$wsdl"); if ($wsdl == '') { $this->debug('no wsdl passed to parseWSDL()!!'); @@ -4784,38 +4945,38 @@ class wsdl extends nusoap_base { if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'http' || $wsdl_props['scheme'] == 'https')) { $this->debug('getting WSDL http(s) URL ' . $wsdl); - // get wsdl - $tr = new soap_transport_http($wsdl, $this->curl_options, $this->use_curl); - $tr->request_method = 'GET'; - $tr->useSOAPAction = false; - if($this->proxyhost && $this->proxyport){ - $tr->setProxy($this->proxyhost,$this->proxyport,$this->proxyusername,$this->proxypassword); - } - if ($this->authtype != '') { - $tr->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest); - } - $tr->setEncoding('gzip, deflate'); - $wsdl_string = $tr->send('', $this->timeout, $this->response_timeout); - //$this->debug("WSDL request\n" . $tr->outgoing_payload); - //$this->debug("WSDL response\n" . $tr->incoming_payload); - $this->appendDebug($tr->getDebug()); - // catch errors - if($err = $tr->getError() ){ - $errstr = 'Getting ' . $wsdl . ' - HTTP ERROR: '.$err; - $this->debug($errstr); - $this->setError($errstr); - unset($tr); - return false; - } - unset($tr); - $this->debug("got WSDL URL"); + // get wsdl + $tr = new soap_transport_http($wsdl, $this->curl_options, $this->use_curl); + $tr->request_method = 'GET'; + $tr->useSOAPAction = false; + if ($this->proxyhost && $this->proxyport) { + $tr->setProxy($this->proxyhost, $this->proxyport, $this->proxyusername, $this->proxypassword); + } + if ($this->authtype != '') { + $tr->setCredentials($this->username, $this->password, $this->authtype, array(), $this->certRequest); + } + $tr->setEncoding(); + $wsdl_string = $tr->send('', $this->timeout, $this->response_timeout); + //$this->debug("WSDL request\n" . $tr->outgoing_payload); + //$this->debug("WSDL response\n" . $tr->incoming_payload); + $this->appendDebug($tr->getDebug()); + // catch errors + if ($err = $tr->getError()) { + $errstr = 'Getting ' . $wsdl . ' - HTTP ERROR: ' . $err; + $this->debug($errstr); + $this->setError($errstr); + unset($tr); + return false; + } + unset($tr); + $this->debug("got WSDL URL"); } else { // $wsdl is not http(s), so treat it as a file URL or plain file path - if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) { - $path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path']; - } else { - $path = $wsdl; - } + if (isset($wsdl_props['scheme']) && ($wsdl_props['scheme'] == 'file') && isset($wsdl_props['path'])) { + $path = isset($wsdl_props['host']) ? ($wsdl_props['host'] . ':' . $wsdl_props['path']) : $wsdl_props['path']; + } else { + $path = $wsdl; + } $this->debug('getting WSDL file ' . $path); if ($fp = @fopen($path, 'r')) { $wsdl_string = ''; @@ -4824,8 +4985,8 @@ class wsdl extends nusoap_base { } fclose($fp); } else { - $errstr = "Bad path to WSDL file $path"; - $this->debug($errstr); + $errstr = "Bad path to WSDL file $path"; + $this->debug($errstr); $this->setError($errstr); return false; } @@ -4846,23 +5007,26 @@ class wsdl extends nusoap_base { if (!xml_parse($this->parser, $wsdl_string, true)) { // Display an error message. $errstr = sprintf( - 'XML error parsing WSDL from %s on line %d: %s', - $wsdl, + 'XML error parsing WSDL from %s on line %d: %s', + $wsdl, xml_get_current_line_number($this->parser), xml_error_string(xml_get_error_code($this->parser)) - ); + ); $this->debug($errstr); - $this->debug("XML payload:\n" . $wsdl_string); + $this->debug("XML payload:\n" . $wsdl_string); $this->setError($errstr); + xml_parser_free($this->parser); + unset($this->parser); return false; } - // free the parser + // free the parser xml_parser_free($this->parser); + unset($this->parser); $this->debug('Parsing WSDL done'); - // catch wsdl parse errors - if($this->getError()){ - return false; - } + // catch wsdl parse errors + if ($this->getError()) { + return false; + } return true; } @@ -4871,7 +5035,7 @@ class wsdl extends nusoap_base { * * @param string $parser XML parser object * @param string $name element name - * @param string $attrs associative array of attributes + * @param array $attrs associative array of attributes * @access private */ function start_element($parser, $name, $attrs) @@ -4881,7 +5045,7 @@ class wsdl extends nusoap_base { $this->appendDebug($this->currentSchema->getDebug()); $this->currentSchema->clearDebug(); } elseif (preg_match('/schema$/', $name)) { - $this->debug('Parsing WSDL schema'); + $this->debug('Parsing WSDL schema'); // $this->debug("startElement for $name ($attrs[name]). status = $this->status (".$this->getLocalPart($name).")"); $this->status = 'schema'; $this->currentSchema = new nusoap_xmlschema('', '', $this->namespaces); @@ -4897,9 +5061,9 @@ class wsdl extends nusoap_base { $this->message[$pos] = array('cdata' => ''); // process attributes if (count($attrs) > 0) { - // register namespace declarations - foreach($attrs as $k => $v) { - if (preg_match('/^xmlns/',$k)) { + // register namespace declarations + foreach ($attrs as $k => $v) { + if (preg_match('/^xmlns/', $k)) { if ($ns_prefix = substr(strrchr($k, ':'), 1)) { $this->namespaces[$ns_prefix] = $v; } else { @@ -4912,7 +5076,8 @@ class wsdl extends nusoap_base { } } // expand each attribute prefix to its namespace - foreach($attrs as $k => $v) { + $eAttrs = array (); + foreach ($attrs as $k => $v) { $k = strpos($k, ':') ? $this->expandQname($k) : $k; if ($k != 'location' && $k != 'soapAction' && $k != 'namespace') { $v = strpos($v, ':') ? $this->expandQname($v) : $v; @@ -4923,6 +5088,10 @@ class wsdl extends nusoap_base { } else { $attrs = array(); } + // Set default prefix and namespace + // to prevent error Undefined variable $prefix and $namespace if (preg_match('/:/', $name)) return 0 or FALSE + $prefix = ''; + $namespace = ''; // get element prefix, namespace and name if (preg_match('/:/', $name)) { // get ns prefix @@ -4932,418 +5101,427 @@ class wsdl extends nusoap_base { // get unqualified name $name = substr(strstr($name, ':'), 1); } - // process attributes, expanding any prefixes to namespaces + // process attributes, expanding any prefixes to namespaces // find status, register data switch ($this->status) { case 'message': if ($name == 'part') { - if (isset($attrs['type'])) { - $this->debug("msg " . $this->currentMessage . ": found part (with type) $attrs[name]: " . implode(',', $attrs)); - $this->messages[$this->currentMessage][$attrs['name']] = $attrs['type']; - } - if (isset($attrs['element'])) { - $this->debug("msg " . $this->currentMessage . ": found part (with element) $attrs[name]: " . implode(',', $attrs)); - $this->messages[$this->currentMessage][$attrs['name']] = $attrs['element'] . '^'; - } - } - break; - case 'portType': - switch ($name) { - case 'operation': - $this->currentPortOperation = $attrs['name']; - $this->debug("portType $this->currentPortType operation: $this->currentPortOperation"); - if (isset($attrs['parameterOrder'])) { - $this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder']; - } - break; - case 'documentation': - $this->documentation = true; - break; - // merge input/output data - default: - $m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : ''; - $this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m; - break; - } - break; - case 'binding': - switch ($name) { - case 'binding': - // get ns prefix - if (isset($attrs['style'])) { - $this->bindings[$this->currentBinding]['prefix'] = $prefix; - } - $this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs); - break; - case 'header': - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs; - break; - case 'operation': - if (isset($attrs['soapAction'])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction']; - } - if (isset($attrs['style'])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style']; - } - if (isset($attrs['name'])) { - $this->currentOperation = $attrs['name']; - $this->debug("current binding operation: $this->currentOperation"); - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name']; - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding; - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : ''; - } - break; - case 'input': - $this->opStatus = 'input'; - break; - case 'output': - $this->opStatus = 'output'; - break; - case 'body': - if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs); - } else { - $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs; - } - break; - } - break; - case 'service': - switch ($name) { - case 'port': - $this->currentPort = $attrs['name']; - $this->debug('current port: ' . $this->currentPort); - $this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']); + if (isset($attrs['type'])) { + $this->debug("msg " . $this->currentMessage . ": found part (with type) $attrs[name]: " . implode(',', $attrs)); + $this->messages[$this->currentMessage][$attrs['name']] = $attrs['type']; + } + if (isset($attrs['element'])) { + $this->debug("msg " . $this->currentMessage . ": found part (with element) $attrs[name]: " . implode(',', $attrs)); + $this->messages[$this->currentMessage][$attrs['name']] = $attrs['element'] . '^'; + } + } + break; + case 'portType': + switch ($name) { + case 'operation': + $this->currentPortOperation = $attrs['name']; + $this->debug("portType $this->currentPortType operation: $this->currentPortOperation"); + if (isset($attrs['parameterOrder'])) { + $this->portTypes[$this->currentPortType][$attrs['name']]['parameterOrder'] = $attrs['parameterOrder']; + } + break; + case 'documentation': + $this->documentation = true; + break; + // merge input/output data + default: + $m = isset($attrs['message']) ? $this->getLocalPart($attrs['message']) : ''; + $this->portTypes[$this->currentPortType][$this->currentPortOperation][$name]['message'] = $m; + break; + } + break; + case 'binding': + switch ($name) { + case 'binding': + // get ns prefix + if (isset($attrs['style'])) { + $this->bindings[$this->currentBinding]['prefix'] = $prefix; + } + $this->bindings[$this->currentBinding] = array_merge($this->bindings[$this->currentBinding], $attrs); + break; + case 'header': + $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus]['headers'][] = $attrs; + break; + case 'operation': + if (isset($attrs['soapAction'])) { + $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['soapAction'] = $attrs['soapAction']; + } + if (isset($attrs['style'])) { + $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['style'] = $attrs['style']; + } + if (isset($attrs['name'])) { + $this->currentOperation = $attrs['name']; + $this->debug("current binding operation: $this->currentOperation"); + $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['name'] = $attrs['name']; + $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['binding'] = $this->currentBinding; + $this->bindings[$this->currentBinding]['operations'][$this->currentOperation]['endpoint'] = isset($this->bindings[$this->currentBinding]['endpoint']) ? $this->bindings[$this->currentBinding]['endpoint'] : ''; + } + break; + case 'input': + $this->opStatus = 'input'; + break; + case 'output': + $this->opStatus = 'output'; + break; + case 'body': + if (isset($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus])) { + $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = array_merge($this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus], $attrs); + } else { + $this->bindings[$this->currentBinding]['operations'][$this->currentOperation][$this->opStatus] = $attrs; + } + break; + } + break; + case 'service': + switch ($name) { + case 'port': + $this->currentPort = $attrs['name']; + $this->debug('current port: ' . $this->currentPort); + $this->ports[$this->currentPort]['binding'] = $this->getLocalPart($attrs['binding']); - break; - case 'address': - $this->ports[$this->currentPort]['location'] = $attrs['location']; - $this->ports[$this->currentPort]['bindingType'] = $namespace; - $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['bindingType'] = $namespace; - $this->bindings[ $this->ports[$this->currentPort]['binding'] ]['endpoint'] = $attrs['location']; - break; - } - break; - } - // set status - switch ($name) { - case 'import': - if (isset($attrs['location'])) { - $this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false); - $this->debug('parsing import ' . $attrs['namespace']. ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]).')'); - } else { - $this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true); - if (! $this->getPrefixFromNamespace($attrs['namespace'])) { - $this->namespaces['ns'.(count($this->namespaces)+1)] = $attrs['namespace']; - } - $this->debug('parsing import ' . $attrs['namespace']. ' - [no location] (' . count($this->import[$attrs['namespace']]).')'); - } - break; - //wait for schema - //case 'types': - // $this->status = 'schema'; - // break; - case 'message': - $this->status = 'message'; - $this->messages[$attrs['name']] = array(); - $this->currentMessage = $attrs['name']; - break; - case 'portType': - $this->status = 'portType'; - $this->portTypes[$attrs['name']] = array(); - $this->currentPortType = $attrs['name']; - break; - case "binding": - if (isset($attrs['name'])) { - // get binding name - if (strpos($attrs['name'], ':')) { - $this->currentBinding = $this->getLocalPart($attrs['name']); - } else { - $this->currentBinding = $attrs['name']; - } - $this->status = 'binding'; - $this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']); - $this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']); - } - break; - case 'service': - $this->serviceName = $attrs['name']; - $this->status = 'service'; - $this->debug('current service: ' . $this->serviceName); - break; - case 'definitions': - foreach ($attrs as $name => $value) { - $this->wsdl_info[$name] = $value; - } - break; - } - } - } - - /** - * end-element handler - * - * @param string $parser XML parser object - * @param string $name element name - * @access private - */ - function end_element($parser, $name){ - // unset schema status - if (/*preg_match('/types$/', $name) ||*/ preg_match('/schema$/', $name)) { - $this->status = ""; - $this->appendDebug($this->currentSchema->getDebug()); - $this->currentSchema->clearDebug(); - $this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema; - $this->debug('Parsing WSDL schema done'); - } - if ($this->status == 'schema') { - $this->currentSchema->schemaEndElement($parser, $name); - } else { - // bring depth down a notch - $this->depth--; - } - // end documentation - if ($this->documentation) { - //TODO: track the node to which documentation should be assigned; it can be a part, message, etc. - //$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation; - $this->documentation = false; - } - } - - /** - * element content handler - * - * @param string $parser XML parser object - * @param string $data element content - * @access private - */ - function character_data($parser, $data) - { - $pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0; - if (isset($this->message[$pos]['cdata'])) { - $this->message[$pos]['cdata'] .= $data; - } - if ($this->documentation) { - $this->documentation .= $data; - } - } - - /** - * if authenticating, set user credentials here - * - * @param string $username - * @param string $password - * @param string $authtype (basic|digest|certificate|ntlm) - * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) - * @access public - */ - function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) { - $this->debug("setCredentials username=$username authtype=$authtype certRequest="); - $this->appendDebug($this->varDump($certRequest)); - $this->username = $username; - $this->password = $password; - $this->authtype = $authtype; - $this->certRequest = $certRequest; - } - - function getBindingData($binding) - { - if (is_array($this->bindings[$binding])) { - return $this->bindings[$binding]; - } - } - - /** - * returns an assoc array of operation names => operation data - * - * @param string $portName WSDL port name - * @param string $bindingType eg: soap, smtp, dime (only soap and soap12 are currently supported) - * @return array - * @access public - */ - function getOperations($portName = '', $bindingType = 'soap') { - $ops = array(); - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } elseif ($bindingType == 'soap12') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/'; - } else { - $this->debug("getOperations bindingType $bindingType may not be supported"); - } - $this->debug("getOperations for port '$portName' bindingType $bindingType"); - // loop thru ports - foreach($this->ports as $port => $portData) { - $this->debug("getOperations checking port $port bindingType " . $portData['bindingType']); - if ($portName == '' || $port == $portName) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - $this->debug("getOperations found port $port bindingType $bindingType"); - //$this->debug("port data: " . $this->varDump($portData)); - //$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ])); - // merge bindings - if (isset($this->bindings[ $portData['binding'] ]['operations'])) { - $ops = array_merge ($ops, $this->bindings[ $portData['binding'] ]['operations']); - } - } - } - } - if (count($ops) == 0) { - $this->debug("getOperations found no operations for port '$portName' bindingType $bindingType"); - } - return $ops; - } - - /** - * returns an associative array of data necessary for calling an operation - * - * @param string $operation name of operation - * @param string $bindingType type of binding eg: soap, soap12 - * @return array - * @access public - */ - function getOperationData($operation, $bindingType = 'soap') - { - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } elseif ($bindingType == 'soap12') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/'; - } - // loop thru ports - foreach($this->ports as $port => $portData) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - // get binding - //foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) { - foreach(array_keys($this->bindings[ $portData['binding'] ]['operations']) as $bOperation) { - // note that we could/should also check the namespace here - if ($operation == $bOperation) { - $opData = $this->bindings[ $portData['binding'] ]['operations'][$operation]; - return $opData; - } - } - } - } - } - - /** - * returns an associative array of data necessary for calling an operation - * - * @param string $soapAction soapAction for operation - * @param string $bindingType type of binding eg: soap, soap12 - * @return array - * @access public - */ - function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') { - if ($bindingType == 'soap') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; - } elseif ($bindingType == 'soap12') { - $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/'; - } - // loop thru ports - foreach($this->ports as $port => $portData) { - // binding type of port matches parameter - if ($portData['bindingType'] == $bindingType) { - // loop through operations for the binding - foreach ($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) { - if ($opData['soapAction'] == $soapAction) { - return $opData; - } - } - } - } - } - - /** - * returns an array of information about a given type - * returns false if no type exists by the given name - * - * typeDef = array( - * 'elements' => array(), // refs to elements array - * 'restrictionBase' => '', - * 'phpType' => '', - * 'order' => '(sequence|all)', - * 'attrs' => array() // refs to attributes array - * ) - * - * @param string $type the type - * @param string $ns namespace (not prefix) of the type - * @return mixed - * @access public - * @see nusoap_xmlschema - */ - function getTypeDef($type, $ns) { - $this->debug("in getTypeDef: type=$type, ns=$ns"); - if ((! $ns) && isset($this->namespaces['tns'])) { - $ns = $this->namespaces['tns']; - $this->debug("in getTypeDef: type namespace forced to $ns"); - } - if (!isset($this->schemas[$ns])) { - foreach ($this->schemas as $ns0 => $schema0) { - if (strcasecmp($ns, $ns0) == 0) { - $this->debug("in getTypeDef: replacing schema namespace $ns with $ns0"); - $ns = $ns0; - break; - } - } - } - if (isset($this->schemas[$ns])) { - $this->debug("in getTypeDef: have schema for namespace $ns"); - for ($i = 0; $i < count($this->schemas[$ns]); $i++) { - $xs = &$this->schemas[$ns][$i]; - $t = $xs->getTypeDef($type); - $this->appendDebug($xs->getDebug()); - $xs->clearDebug(); - if ($t) { - $this->debug("in getTypeDef: found type $type"); - if (!isset($t['phpType'])) { - // get info for type to tack onto the element - $uqType = substr($t['type'], strrpos($t['type'], ':') + 1); - $ns = substr($t['type'], 0, strrpos($t['type'], ':')); - $etype = $this->getTypeDef($uqType, $ns); - if ($etype) { - $this->debug("found type for [element] $type:"); - $this->debug($this->varDump($etype)); - if (isset($etype['phpType'])) { - $t['phpType'] = $etype['phpType']; - } - if (isset($etype['elements'])) { - $t['elements'] = $etype['elements']; - } - if (isset($etype['attrs'])) { - $t['attrs'] = $etype['attrs']; - } - } else { - $this->debug("did not find type for [element] $type"); - } - } - return $t; - } - } - $this->debug("in getTypeDef: did not find type $type"); - } else { - $this->debug("in getTypeDef: do not have schema for namespace $ns"); - } - return false; - } + break; + case 'address': + $this->ports[$this->currentPort]['location'] = $attrs['location']; + $this->ports[$this->currentPort]['bindingType'] = $namespace; + $this->bindings[$this->ports[$this->currentPort]['binding']]['bindingType'] = $namespace; + $this->bindings[$this->ports[$this->currentPort]['binding']]['endpoint'] = $attrs['location']; + break; + } + break; + } + // set status + switch ($name) { + case 'import': + if (isset($attrs['location'])) { + $this->import[$attrs['namespace']][] = array('location' => $attrs['location'], 'loaded' => false); + $this->debug('parsing import ' . $attrs['namespace'] . ' - ' . $attrs['location'] . ' (' . count($this->import[$attrs['namespace']]) . ')'); + } else { + $this->import[$attrs['namespace']][] = array('location' => '', 'loaded' => true); + if (!$this->getPrefixFromNamespace($attrs['namespace'])) { + $this->namespaces['ns' . (count($this->namespaces) + 1)] = $attrs['namespace']; + } + $this->debug('parsing import ' . $attrs['namespace'] . ' - [no location] (' . count($this->import[$attrs['namespace']]) . ')'); + } + break; + //wait for schema + //case 'types': + // $this->status = 'schema'; + // break; + case 'message': + $this->status = 'message'; + $this->messages[$attrs['name']] = array(); + $this->currentMessage = $attrs['name']; + break; + case 'portType': + $this->status = 'portType'; + $this->portTypes[$attrs['name']] = array(); + $this->currentPortType = $attrs['name']; + break; + case "binding": + if (isset($attrs['name'])) { + // get binding name + if (strpos($attrs['name'], ':')) { + $this->currentBinding = $this->getLocalPart($attrs['name']); + } else { + $this->currentBinding = $attrs['name']; + } + $this->status = 'binding'; + $this->bindings[$this->currentBinding]['portType'] = $this->getLocalPart($attrs['type']); + $this->debug("current binding: $this->currentBinding of portType: " . $attrs['type']); + } + break; + case 'service': + $this->serviceName = $attrs['name']; + $this->status = 'service'; + $this->debug('current service: ' . $this->serviceName); + break; + case 'definitions': + foreach ($attrs as $name => $value) { + $this->wsdl_info[$name] = $value; + } + break; + } + } + } /** - * prints html description of services - * - * @access private - */ - function webDescription(){ - global $HTTP_SERVER_VARS; + * end-element handler + * + * @param string $parser XML parser object + * @param string $name element name + * @access private + */ + function end_element($parser, $name) + { + // unset schema status + if (/*preg_match('/types$/', $name) ||*/ + preg_match('/schema$/', $name) + ) { + $this->status = ""; + $this->appendDebug($this->currentSchema->getDebug()); + $this->currentSchema->clearDebug(); + $this->schemas[$this->currentSchema->schemaTargetNamespace][] = $this->currentSchema; + $this->debug('Parsing WSDL schema done'); + } + if ($this->status == 'schema') { + $this->currentSchema->schemaEndElement($parser, $name); + } else { + // bring depth down a notch + $this->depth--; + } + // end documentation + if ($this->documentation) { + //TODO: track the node to which documentation should be assigned; it can be a part, message, etc. + //$this->portTypes[$this->currentPortType][$this->currentPortOperation]['documentation'] = $this->documentation; + $this->documentation = false; + } + } - if (isset($_SERVER)) { - $PHP_SELF = $_SERVER['PHP_SELF']; - } elseif (isset($HTTP_SERVER_VARS)) { - $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF']; - } else { - $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); - } + /** + * element content handler + * + * @param string $parser XML parser object + * @param string $data element content + * @access private + */ + function character_data($parser, $data) + { + $pos = isset($this->depth_array[$this->depth]) ? $this->depth_array[$this->depth] : 0; + if (isset($this->message[$pos]['cdata'])) { + $this->message[$pos]['cdata'] .= $data; + } + if ($this->documentation) { + $this->documentation .= $data; + } + } - $b = ' - NuSOAP: '.$this->serviceName.' + /** + * if authenticating, set user credentials here + * + * @param string $username + * @param string $password + * @param string $authtype (basic|digest|certificate|ntlm) + * @param array $certRequest (keys must be cainfofile (optional), sslcertfile, sslkeyfile, passphrase, certpassword (optional), verifypeer (optional), verifyhost (optional): see corresponding options in cURL docs) + * @access public + */ + function setCredentials($username, $password, $authtype = 'basic', $certRequest = array()) + { + $this->debug("setCredentials username=$username authtype=$authtype certRequest="); + $this->appendDebug($this->varDump($certRequest)); + $this->username = $username; + $this->password = $password; + $this->authtype = $authtype; + $this->certRequest = $certRequest; + } + + function getBindingData($binding) + { + if (is_array($this->bindings[$binding])) { + return $this->bindings[$binding]; + } + return false; + } + + /** + * returns an assoc array of operation names => operation data + * + * @param string $portName WSDL port name + * @param string $bindingType eg: soap, smtp, dime (only soap and soap12 are currently supported) + * @return array + * @access public + */ + function getOperations($portName = '', $bindingType = 'soap') + { + $ops = array(); + if ($bindingType == 'soap') { + $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; + } elseif ($bindingType == 'soap12') { + $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/'; + } else { + $this->debug("getOperations bindingType $bindingType may not be supported"); + } + $this->debug("getOperations for port '$portName' bindingType $bindingType"); + // loop thru ports + foreach ($this->ports as $port => $portData) { + $this->debug("getOperations checking port $port bindingType " . $portData['bindingType']); + if ($portName == '' || $port == $portName) { + // binding type of port matches parameter + if ($portData['bindingType'] == $bindingType) { + $this->debug("getOperations found port $port bindingType $bindingType"); + //$this->debug("port data: " . $this->varDump($portData)); + //$this->debug("bindings: " . $this->varDump($this->bindings[ $portData['binding'] ])); + // merge bindings + if (isset($this->bindings[$portData['binding']]['operations'])) { + $ops = array_merge($ops, $this->bindings[$portData['binding']]['operations']); + } + } + } + } + if (count($ops) == 0) { + $this->debug("getOperations found no operations for port '$portName' bindingType $bindingType"); + } + return $ops; + } + + /** + * returns an associative array of data necessary for calling an operation + * + * @param string $operation name of operation + * @param string $bindingType type of binding eg: soap, soap12 + * @return array + * @access public + */ + function getOperationData($operation, $bindingType = 'soap') + { + if ($bindingType == 'soap') { + $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; + } elseif ($bindingType == 'soap12') { + $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/'; + } + // loop thru ports + foreach ($this->ports as $portData) { + // binding type of port matches parameter + if ($portData['bindingType'] == $bindingType) { + // get binding + //foreach($this->bindings[ $portData['binding'] ]['operations'] as $bOperation => $opData) { + // note that we could/should also check the namespace here + if (in_array ($operation, array_keys ($this->bindings[$portData['binding']]['operations']))) + { + return $this->bindings[$portData['binding']]['operations'][$operation]; + } + } + } + return array (); + } + + /** + * returns an associative array of data necessary for calling an operation + * + * @param string $soapAction soapAction for operation + * @param string $bindingType type of binding eg: soap, soap12 + * @return array + * @access public + */ + function getOperationDataForSoapAction($soapAction, $bindingType = 'soap') + { + if ($bindingType == 'soap') { + $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap/'; + } elseif ($bindingType == 'soap12') { + $bindingType = 'http://schemas.xmlsoap.org/wsdl/soap12/'; + } + // loop thru ports + foreach ($this->ports as $portData) { + // binding type of port matches parameter + if ($portData['bindingType'] == $bindingType) { + // loop through operations for the binding + foreach ($this->bindings[$portData['binding']]['operations'] as $opData) { + if ($opData['soapAction'] == $soapAction) { + return $opData; + } + } + } + } + return array (); + } + + /** + * returns an array of information about a given type + * returns false if no type exists by the given name + * typeDef = array( + * 'elements' => array(), // refs to elements array + * 'restrictionBase' => '', + * 'phpType' => '', + * 'order' => '(sequence|all)', + * 'attrs' => array() // refs to attributes array + * ) + * + * @param string $type the type + * @param string $ns namespace (not prefix) of the type + * @return false + * @access public + * @see nusoap_xmlschema + */ + function getTypeDef($type, $ns) + { + $this->debug("in getTypeDef: type=$type, ns=$ns"); + if ((!$ns) && isset($this->namespaces['tns'])) { + $ns = $this->namespaces['tns']; + $this->debug("in getTypeDef: type namespace forced to $ns"); + } + if (!isset($this->schemas[$ns])) { + foreach ($this->schemas as $ns0 => $schema0) { + if (strcasecmp($ns, $ns0) == 0) { + $this->debug("in getTypeDef: replacing schema namespace $ns with $ns0"); + $ns = $ns0; + break; + } + } + } + if (isset($this->schemas[$ns])) { + $this->debug("in getTypeDef: have schema for namespace $ns"); + for ($i = 0; $i < count($this->schemas[$ns]); $i++) { + $xs = &$this->schemas[$ns][$i]; + $t = $xs->getTypeDef($type); + $this->appendDebug($xs->getDebug()); + $xs->clearDebug(); + if ($t) { + $this->debug("in getTypeDef: found type $type"); + if (!isset($t['phpType'])) { + // get info for type to tack onto the element + $uqType = substr($t['type'], strrpos($t['type'], ':') + 1); + $ns = substr($t['type'], 0, strrpos($t['type'], ':')); + $etype = $this->getTypeDef($uqType, $ns); + if ($etype) { + $this->debug("found type for [element] $type:"); + $this->debug($this->varDump($etype)); + if (isset($etype['phpType'])) { + $t['phpType'] = $etype['phpType']; + } + if (isset($etype['elements'])) { + $t['elements'] = $etype['elements']; + } + if (isset($etype['attrs'])) { + $t['attrs'] = $etype['attrs']; + } + } else { + $this->debug("did not find type for [element] $type"); + } + } + return $t; + } + } + $this->debug("in getTypeDef: did not find type $type"); + } else { + $this->debug("in getTypeDef: do not have schema for namespace $ns"); + } + return false; + } + + /** + * prints html description of services + * + * @access private + */ + function webDescription() + { + global $HTTP_SERVER_VARS; + + if (isset($_SERVER)) { + $PHP_SELF = $_SERVER['PHP_SELF']; + } elseif (isset($HTTP_SERVER_VARS)) { + $PHP_SELF = $HTTP_SERVER_VARS['PHP_SELF']; + } else { + $this->setError("Neither _SERVER nor HTTP_SERVER_VARS is available"); + $PHP_SELF = ''; + } + + $b = ' + NuSOAP: ' . $this->serviceName . '