diff --git a/.php-cs-fixer.dist.php b/.php-cs-fixer.dist.php index dfe3fa53994..e6bcc7ad12e 100644 --- a/.php-cs-fixer.dist.php +++ b/.php-cs-fixer.dist.php @@ -8,6 +8,8 @@ $finder = (new PhpCsFixer\Finder()) 'custom', 'documents', 'doctemplates', + 'vendor', + 'install/doctemplates', 'htdocs/custom', 'htdocs/includes', 'htdocs/install/doctemplates', @@ -41,6 +43,8 @@ return (new PhpCsFixer\Config()) // So we use target PHP70 for the moment. '@PHP70Migration' => true, //'@PHP71Migration' => true, + // Avoid adding public to const (incompatible with PHP 7.0): + 'visibility_required' => ['elements'=>['property', 'method']], //'strict_param' => true, //'array_syntax' => ['syntax' => 'short'], 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 31b7f47434e..0bb5937497d 100644 --- a/COPYRIGHT +++ b/COPYRIGHT @@ -26,9 +26,9 @@ PHP libraries: EvalMath 1.0 BSD Yes Safe math expressions evaluation. Used by dynamic price only. TODO Replace with dol_eval ? Escpos-php 3.0 MIT License Yes Thermal receipt printer library, for use with ESC/POS compatible printers 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 +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 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/SECURITY.md b/SECURITY.md index 953059e625f..f004cea7c86 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -82,18 +82,17 @@ Scope is the web application (backoffice) and the APIs. ## Examples of vulnerabilities that are Non-qualified for reporting. * "Self" XSS -* SSL/TLS best practices -* Denial of Service attacks * Clickjacking/UI redressing -* Physical or social engineering attempts or issues that require physical access to a victim’s computer/device * Presence of autocomplete attribute on web forms -* Vulnerabilities affecting outdated browsers or platforms, or vulnerabilities inside browsers themself. * Logout and other instances of low-severity Cross-Site Request Forgery -* Missing security-related HTTP headers which do not lead directly to a vulnerability * Reports from automated web vulnerability scanners (Acunetix, Vega, etc.) that have not been validated -* Invalid or missing SPF (Sender Policy Framework) records (Incomplete or missing SPF/DKIM/DMARC) -* Reports on features flagged as "experimental" or "development" -* Software version or private IP disclosure when logged-in user is admin +* Reports on features on modules flagged as "deprecated", "experimental" or "development" if the module needs to be enabled for that (this is not the case on production). +* Software or libraries versions or private IP disclosure when logged-in user is admin * Stack traces or path disclosure when logged-in user is admin * Any vulnerabilities due to a configuration different than the one defined in chapter "Scope for qualified vulnerabilities". -* Brute force attacks on login page, password forgotten page or any public pages (/public/*) are not qualified if the fail2ban recommended fail2ban rules were not installed. +* Vulnerabilities affecting outdated browsers or platforms, or vulnerabilities inside browsers themself. +* Brute force attacks on login page, password forgotten page or any public pages (/public/*) are not qualified if the recommended fail2ban rules were not installed. +* SSL/TLS best practices +* Denial of Service attacks +* Invalid or missing SPF (Sender Policy Framework) records (Incomplete or missing SPF/DKIM/DMARC) +* Physical or social engineering attempts or issues that require physical access to a victim’s computer/device 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..e8af4cd420d 100644 --- a/dev/dolibarr_changes.txt +++ b/dev/dolibarr_changes.txt @@ -44,23 +44,22 @@ 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) { diff --git a/dev/examples/stripe/webhook_ipn_paymentintent_failed_sepa.txt b/dev/examples/stripe/webhook_ipn_paymentintent_failed_sepa.txt new file mode 100644 index 00000000000..d85bedd9528 --- /dev/null +++ b/dev/examples/stripe/webhook_ipn_paymentintent_failed_sepa.txt @@ -0,0 +1,124 @@ +{ + "id": "evt_123456789", + "object": "event", + "api_version": "2023-10-16", + "created": 1702053463, + "data": { + "object": { + "id": "pi_123456789", + "object": "payment_intent", + "amount": 60, + "amount_capturable": 0, + "amount_details": { + "tip": { + } + }, + "amount_received": 0, + "application": null, + "application_fee_amount": null, + "automatic_payment_methods": null, + "canceled_at": null, + "cancellation_reason": null, + "capture_method": "automatic", + "client_secret": "pi_123456789_secret_123456789", + "confirmation_method": "automatic", + "created": 1702053448, + "currency": "eur", + "customer": "cus_123456789", + "description": "Stripe payment from makeStripeSepaRequest: DID=31262-INV=123-CUS=123 did=123 ref=FA2312-123", + "invoice": null, + "last_payment_error": { + "code": "", + "decline_code": "generic_decline", + "message": "The transaction can't be processed because your customer's account information is missing or incorrect. Collect a new mandate and ask your customer to provide their name and address exactly as it appears on their bank account. After this, you can attempt the transaction again.", + "payment_method": { + "id": "pm_123456789", + "object": "payment_method", + "billing_details": { + "address": { + "city": null, + "country": "FR", + "line1": null, + "line2": null, + "postal_code": null, + "state": null + }, + "email": "email@example.com", + "name": "Test example", + "phone": null + }, + "created": 1692688898, + "customer": "cus_123456789", + "livemode": false, + "metadata": { + "dol_version": "19.0.0-dev", + "dol_thirdparty_id": "123", + "ipaddress": "1.2.3.4", + "dol_id": "123", + "dol_type": "companypaymentmode", + "dol_entity": "1" + }, + "sepa_debit": { + "bank_code": "123", + "branch_code": "", + "country": "AT", + "fingerprint": "123456789", + "generated_from": { + "charge": null, + "setup_attempt": null + }, + "last4": "3202" + }, + "type": "sepa_debit" + }, + "type": "card_error" + }, + "latest_charge": "py_123456789", + "livemode": false, + "metadata": { + "dol_version": "19.0.0-beta", + "dol_thirdparty_id": "123", + "ipaddress": "1.2.3.4", + "dol_id": "123", + "dol_type": "facture", + "dol_entity": "1" + }, + "next_action": null, + "on_behalf_of": null, + "payment_method": null, + "payment_method_configuration_details": null, + "payment_method_options": { + "card": { + "installments": null, + "mandate_options": null, + "network": null, + "request_three_d_secure": "automatic" + }, + "sepa_debit": { + } + }, + "payment_method_types": [ + "card", + "sepa_debit" + ], + "processing": null, + "receipt_email": null, + "review": null, + "setup_future_usage": null, + "shipping": null, + "source": null, + "statement_descriptor": "DID=123-", + "statement_descriptor_suffix": "DID=123-", + "status": "requires_payment_method", + "transfer_data": null, + "transfer_group": null + } + }, + "livemode": false, + "pending_webhooks": 1, + "request": { + "id": null, + "idempotency_key": null + }, + "type": "payment_intent.payment_failed" +} 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/apstats.php b/dev/tools/apstats.php index e15c8b5ace2..80e026bb600 100755 --- a/dev/tools/apstats.php +++ b/dev/tools/apstats.php @@ -38,6 +38,8 @@ error_reporting(E_ALL & ~E_DEPRECATED); define('PRODUCT', "apstats"); define('VERSION', "1.0"); +$phpstanlevel = 2; + print '***** '.constant('PRODUCT').' - '.constant('VERSION').' *****'."\n"; if (empty($argv[1])) { @@ -71,6 +73,7 @@ while ($i < $argc) { $i++; } +$timestart = time(); // Count lines of code of Dolibarr itself /* @@ -86,7 +89,7 @@ $resexec = (int) (empty($resexec) ? 0 : trim($resexec)); */ // Count lines of code of application -$commandcheck = ($dirscc ? $dirscc.'/' : '').'scc . --exclude-dir=includes,custom'; +$commandcheck = ($dirscc ? $dirscc.'/' : '').'scc . --exclude-dir=htdocs/includes,htdocs/custom,htdocs/theme/common/fontawesome-5,htdocs/theme/common/octicons'; print 'Execute SCC to count lines of code in project: '.$commandcheck."\n"; $output_arrproj = array(); $resexecproj = 0; @@ -94,7 +97,7 @@ exec($commandcheck, $output_arrproj, $resexecproj); // Count lines of code of dependencies -$commandcheck = ($dirscc ? $dirscc.'/' : '').'scc htdocs/includes'; +$commandcheck = ($dirscc ? $dirscc.'/' : '').'scc htdocs/includes htdocs/theme/common/fontawesome-5 htdocs/theme/common/octicons'; print 'Execute SCC to count lines of code in dependencies: '.$commandcheck."\n"; $output_arrdep = array(); $resexecdep = 0; @@ -102,7 +105,7 @@ exec($commandcheck, $output_arrdep, $resexecdep); // Get technical debt -$commandcheck = ($dirphpstan ? $dirphpstan.'/' : '').'phpstan -v analyze -a build/phpstan/bootstrap.php --memory-limit 5G --error-format=github'; +$commandcheck = ($dirphpstan ? $dirphpstan.'/' : '').'phpstan --level='.$phpstanlevel.' -v analyze -a build/phpstan/bootstrap.php --memory-limit 5G --error-format=github'; print 'Execute PHPStan to get the technical debt: '.$commandcheck."\n"; $output_arrtd = array(); $resexectd = 0; @@ -169,6 +172,8 @@ foreach (array('proj', 'dep') as $source) { } } +$timeend = time(); + /* * View @@ -224,7 +229,7 @@ th,td { .nowrap { white-space: nowrap; } -.opacity { +.opacitymedium { opacity: 0.5; } .centpercent { @@ -238,6 +243,7 @@ th,td { } .seedetail { color: #000088; + cursor: pointer; } .box { padding: 20px; @@ -293,7 +299,7 @@ $html .= ''."\n"; $html .= '
'."\n"; $html .= '

Advanced Project Statistics

'."\n"; $currentDate = date("Y-m-d H:i:s"); // Format: Year-Month-Day Hour:Minute:Second -$html .= 'Generated on '.$currentDate.''."\n"; +$html .= 'Generated on '.$currentDate.' in '.($timeend - $timestart).' seconds'."\n"; $html .= '
'."\n"; $html .= '
'."\n"; @@ -314,9 +320,9 @@ $html .= ''; foreach (array('proj', 'dep') as $source) { $html .= ''; if ($source == 'proj') { - $html .= 'All files from project only'; + $html .= 'All files without dependencies'; } elseif ($source == 'dep') { - $html .= 'All files from dependencies'; + $html .= 'All files of dependencies only'; } $html .= '     (See detail per file type...)'; $html .= ''.formatNumber($arrayofmetrics[$source]['Bytes']).''; @@ -372,19 +378,24 @@ $html .= ''.formatNumber($arraycocomo['proj']['people'] * $arraycocomo['proj' $html .= ' monthes people
'; $html .= '
'."\n"; -$html .= '
'."\n"; -$html .= '

Technical debt ('.count($output_arrtd).')


'."\n"; -$html .= '
'."\n"; -$html .= ''."\n"; -$html .= ''."\n"; +$tmp = ''; +$nblines = 0; foreach ($output_arrtd as $line) { $reg = array(); //print $line."\n"; preg_match('/^::error file=(.*),line=(\d+),col=(\d+)::(.*)$/', $line, $reg); if (!empty($reg[1])) { - $html .= ''."\n"; + $tmp .= ''."\n"; + $nblines++; } } + +$html .= '
'."\n"; +$html .= '

Technical debt (PHPStan level '.$phpstanlevel.' -> '.$nblines.' warnings)


'."\n"; +$html .= '
'."\n"; +$html .= '
FileLineType
'.$reg[1].''.$reg[2].''.$reg[4].'
'.$reg[1].''.$reg[2].''.$reg[4].'
'."\n"; +$html .= ''."\n"; +$html .= $tmp; $html .= '
FileLineType
'; $html .= '
'; $html .= '
'."\n"; diff --git a/dev/tools/php-cs-fixer/run-php-cs-fixer.sh b/dev/tools/php-cs-fixer/run-php-cs-fixer.sh index b62befcf011..d8c9d4ae6bb 100755 --- a/dev/tools/php-cs-fixer/run-php-cs-fixer.sh +++ b/dev/tools/php-cs-fixer/run-php-cs-fixer.sh @@ -36,7 +36,7 @@ MINPHPVERSION="7.0" echo "***** run-php-cs-fixer.sh *****" if [ "x$1" = "x" ]; then - echo "Syntax: run-php-cs-fixer.sh check|fix [path]" + echo "Syntax: run-php-cs-fixer.sh check|fix [path_from_root_project]" exit 1; fi diff --git a/dev/tools/rector/src/Renaming/GlobalToFunction.php b/dev/tools/rector/src/Renaming/GlobalToFunction.php index d20c2867cdb..f81f2ee34c1 100644 --- a/dev/tools/rector/src/Renaming/GlobalToFunction.php +++ b/dev/tools/rector/src/Renaming/GlobalToFunction.php @@ -21,10 +21,12 @@ use Rector\Php71\ValueObject\TwoNodeMatch; use Symplify\RuleDocGenerator\Exception\PoorDocumentationException; use Symplify\RuleDocGenerator\ValueObject\CodeSample\CodeSample; use Symplify\RuleDocGenerator\ValueObject\RuleDefinition; +use PhpParser\Node\Expr\BinaryOp\NotEqual; use PhpParser\Node\Expr\BinaryOp\Greater; use PhpParser\Node\Expr\BinaryOp\GreaterOrEqual; use PhpParser\Node\Expr\BinaryOp\Smaller; use PhpParser\Node\Expr\BinaryOp\SmallerOrEqual; +use PhpParser\Node\Expr\BinaryOp\NotIdentical; /** * Class with Rector custom rule to fix code @@ -55,7 +57,7 @@ class GlobalToFunction extends AbstractRector public function getRuleDefinition(): RuleDefinition { return new RuleDefinition( - 'Change $conf->global to getDolGlobal', + 'Change $conf->global to getDolGlobal in context (1) conf->global Operator Value or (2) function(conf->global...)', [new CodeSample( '$conf->global->CONSTANT', 'getDolGlobalInt(\'CONSTANT\')' @@ -70,14 +72,15 @@ class GlobalToFunction extends AbstractRector */ public function getNodeTypes(): array { - return [Equal::class, Greater::class, GreaterOrEqual::class, Smaller::class, SmallerOrEqual::class, BooleanAnd::class, Concat::class, ArrayDimFetch::class]; + return [FuncCall::class, Equal::class, NotEqual::class, Greater::class, GreaterOrEqual::class, Smaller::class, SmallerOrEqual::class, NotIdentical::class, BooleanAnd::class, Concat::class, ArrayDimFetch::class]; } /** * refactor * * @param Node $node A node - * @return Equal|Concat|ArrayDimFetch|void + * @return FuncCall|Equal|Concat|ArrayDimFetch|void + * return $node unchanged or void to do nothing */ public function refactor(Node $node) { @@ -97,6 +100,36 @@ class GlobalToFunction extends AbstractRector } return $node; } + + if ($node instanceof FuncCall) { + $tmpfunctionname = $this->getName($node); + // If function is ok(we must avoid a lot of cases like isset, empty) + if (in_array($tmpfunctionname, array('dol_escape_htmltag', 'make_substitutions', 'min', 'max', 'explode'))) { + $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 FuncCall(new Name($tmpfunctionname), $tmpargs); + return $r; + } + } + } + } + return $node; + } + if ($node instanceof Concat) { if ($this->isGlobalVar($node->left)) { $constName = $this->getConstName($node->left); @@ -125,6 +158,7 @@ class GlobalToFunction extends AbstractRector } return new Concat($leftConcat, $rightConcat); } + if ($node instanceof BooleanAnd) { $nodes = $this->resolveTwoNodeMatch($node); if (!isset($nodes)) { @@ -135,10 +169,16 @@ class GlobalToFunction extends AbstractRector $node = $nodes->getFirstExpr(); } + // Now process all comparison like: + // $conf->global->... Operator Value + $typeofcomparison = ''; if ($node instanceof Equal) { $typeofcomparison = 'Equal'; } + if ($node instanceof NotEqual) { + $typeofcomparison = 'NotEqual'; + } if ($node instanceof Greater) { $typeofcomparison = 'Greater'; } @@ -151,6 +191,10 @@ class GlobalToFunction extends AbstractRector if ($node instanceof SmallerOrEqual) { $typeofcomparison = 'SmallerOrEqual'; } + if ($node instanceof NotIdentical) { + $typeofcomparison = 'NotIdentical'; + //var_dump($node->left); + } if (empty($typeofcomparison)) { return; } @@ -160,7 +204,8 @@ class GlobalToFunction extends AbstractRector } // Test the type after the comparison conf->global->xxx to know the name of function - switch ($node->right->getType()) { + $typeright = $node->right->getType(); + switch ($typeright) { case 'Scalar_LNumber': $funcName = 'getDolGlobalInt'; break; @@ -185,6 +230,15 @@ class GlobalToFunction extends AbstractRector $node->right ); } + if ($typeofcomparison == 'NotEqual') { + return new NotEqual( + new FuncCall( + new Name($funcName), + [new Arg($constName)] + ), + $node->right + ); + } if ($typeofcomparison == 'Greater') { return new Greater( new FuncCall( @@ -221,6 +275,15 @@ class GlobalToFunction extends AbstractRector $node->right ); } + if ($typeofcomparison == 'NotIdentical') { + return new NotIdentical( + new FuncCall( + new Name($funcName), + [new Arg($constName)] + ), + $node->right + ); + } } /** @@ -233,7 +296,7 @@ class GlobalToFunction extends AbstractRector { return $this->binaryOpManipulator->matchFirstAndSecondConditionNode( $booleanAnd, - // $conf->global == $value + // Function to check if we are in the case $conf->global->... == $value function (Node $node): bool { if (!$node instanceof Equal) { return \false; @@ -257,7 +320,7 @@ class GlobalToFunction extends AbstractRector * Check if node is a global access with format conf->global->XXX * * @param Node $node A node - * @return bool Return true if noe is conf->global->XXX + * @return bool Return true if node is conf->global->XXX */ private function isGlobalVar($node) { diff --git a/scripts/invoices/facturex-pdfextractxml.py b/dev/tools/test/facturex-pdfextractxml.py similarity index 100% rename from scripts/invoices/facturex-pdfextractxml.py rename to dev/tools/test/facturex-pdfextractxml.py diff --git a/htdocs/accountancy/admin/accountmodel.php b/htdocs/accountancy/admin/accountmodel.php index 29cb1300f4c..5a2b7aa5e21 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); @@ -740,9 +742,8 @@ $db->close(); */ function fieldListAccountModel($fieldlist, $obj = '', $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..35126c5d464 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; } @@ -994,8 +998,11 @@ function fieldListAccountingCategories($fieldlist, $obj = '', $tabname = '', $co } else { print ''; print ''; print ''; print ''; // Accounting groups used for the income statement print ''; print ''; print ''; 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/closure.php b/htdocs/accountancy/admin/closure.php index d1b0d10e262..faf5360c984 100644 --- a/htdocs/accountancy/admin/closure.php +++ b/htdocs/accountancy/admin/closure.php @@ -145,14 +145,14 @@ print '
'.$langs->trans("ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_BALANCE_SHEET_ACCOUNT").''; -print ''; +print ''; print '
'.$langs->trans("ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_INCOME_STATEMENT").''; -print ''; +print ''; print '
\n"; 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/bookkeeping/balance.php b/htdocs/accountancy/bookkeeping/balance.php index a1881cf212d..aaba332d2ef 100644 --- a/htdocs/accountancy/bookkeeping/balance.php +++ b/htdocs/accountancy/bookkeeping/balance.php @@ -100,7 +100,7 @@ if (empty($search_date_start) && !GETPOSTISSET('formfilteraction')) { $search_date_start = strtotime($fiscalYear->date_start); $search_date_end = strtotime($fiscalYear->date_end); } else { - $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); $year_start = dol_print_date(dol_now(), '%Y'); if (dol_print_date(dol_now(), '%m') < $month_start) { $year_start--; // If current month is lower that starting fiscal month, we start last year diff --git a/htdocs/accountancy/bookkeeping/export.php b/htdocs/accountancy/bookkeeping/export.php index 5323c3c9cce..b6f21694a4f 100644 --- a/htdocs/accountancy/bookkeeping/export.php +++ b/htdocs/accountancy/bookkeeping/export.php @@ -170,7 +170,7 @@ if (!in_array($action, array('export_file', 'delmouv', 'delmouvconfirm')) && !GE $search_date_start = strtotime($fiscalYear->date_start); $search_date_end = strtotime($fiscalYear->date_end); } else { - $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); $year_start = dol_print_date(dol_now(), '%Y'); if (dol_print_date(dol_now(), '%m') < $month_start) { $year_start--; // If current month is lower that starting fiscal month, we start last year diff --git a/htdocs/accountancy/bookkeeping/list.php b/htdocs/accountancy/bookkeeping/list.php index f722e32df08..4efa16fcbde 100644 --- a/htdocs/accountancy/bookkeeping/list.php +++ b/htdocs/accountancy/bookkeeping/list.php @@ -165,7 +165,7 @@ if (!in_array($action, array('delmouv', 'delmouvconfirm')) && !GETPOSTISSET('beg $search_date_start = strtotime($fiscalYear->date_start); $search_date_end = strtotime($fiscalYear->date_end); } else { - $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); $year_start = dol_print_date(dol_now(), '%Y'); if (dol_print_date(dol_now(), '%m') < $month_start) { $year_start--; // If current month is lower that starting fiscal month, we start last year @@ -1198,7 +1198,7 @@ while ($i < min($num, $limit)) { $labeltoshowalt .= $line->doc_ref; } - print ''; + print ''; print $labeltoshow; print "\n"; if (!$i) { diff --git a/htdocs/accountancy/bookkeeping/listbyaccount.php b/htdocs/accountancy/bookkeeping/listbyaccount.php index 864508e99d8..8143cee2434 100644 --- a/htdocs/accountancy/bookkeeping/listbyaccount.php +++ b/htdocs/accountancy/bookkeeping/listbyaccount.php @@ -141,7 +141,7 @@ if (empty($search_date_start) && empty($search_date_end) && !GETPOSTISSET('searc $search_date_start = strtotime($fiscalYear->date_start); $search_date_end = strtotime($fiscalYear->date_end); } else { - $month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); $year_start = dol_print_date(dol_now(), '%Y'); if (dol_print_date(dol_now(), '%m') < $month_start) { $year_start--; // If current month is lower that starting fiscal month, we start last year @@ -1200,12 +1200,9 @@ while ($i < min($num, $limit)) { // Other type } - 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 "\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 ? ''.$line->label_operation.'' : ''.$line->label_operation.'
('.length_accounta($line->subledger_account).')'; + if (strlen(length_accounta($line->subledger_account)) == 0) { + print ''.dol_escape_htmltag($line->label_operation).''; + } else { + print '('.length_accounta($line->subledger_account).')').'">'.dol_escape_htmltag($line->label_operation).($line->label_operation?'
':'').'('.dol_escape_htmltag(length_accounta($line->subledger_account)).')'; + } if (!$i) { $totalarray['nbfield']++; } @@ -1236,7 +1236,7 @@ while ($i < min($num, $limit)) { // Lettering code if (!empty($arrayfields['t.lettering_code']['checked'])) { - print ''.$line->lettering_code.''; + print ''.dol_escape_htmltag($line->lettering_code).''; if (!$i) { $totalarray['nbfield']++; } @@ -1295,7 +1295,7 @@ while ($i < min($num, $limit)) { } if (!empty($arrayfields['t.import_key']['checked'])) { - print ''.$line->import_key."\n"; + print ''.dol_escape_htmltag($line->import_key)."\n"; if (!$i) { $totalarray['nbfield']++; } diff --git a/htdocs/accountancy/class/accountingjournal.class.php b/htdocs/accountancy/class/accountingjournal.class.php index 8456732a2a1..1d475b67527 100644 --- a/htdocs/accountancy/class/accountingjournal.class.php +++ b/htdocs/accountancy/class/accountingjournal.class.php @@ -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( diff --git a/htdocs/accountancy/class/bookkeeping.class.php b/htdocs/accountancy/class/bookkeeping.class.php index 8759890a020..ffda82c2174 100644 --- a/htdocs/accountancy/class/bookkeeping.class.php +++ b/htdocs/accountancy/class/bookkeeping.class.php @@ -367,7 +367,7 @@ class BookKeeping extends CommonObject $this->piece_num = $objnum->piece_num; } - dol_syslog(get_class($this).":: create this->piece_num=".$this->piece_num, LOG_DEBUG); + dol_syslog(get_class($this)."::create this->piece_num=".$this->piece_num, LOG_DEBUG); if (empty($this->piece_num)) { $sqlnum = "SELECT MAX(piece_num)+1 as maxpiecenum"; $sqlnum .= " FROM ".MAIN_DB_PREFIX.$this->table_element; diff --git a/htdocs/accountancy/closure/index.php b/htdocs/accountancy/closure/index.php index 3920cd1ef54..085c8a65e80 100644 --- a/htdocs/accountancy/closure/index.php +++ b/htdocs/accountancy/closure/index.php @@ -87,8 +87,8 @@ if (is_array($fiscal_periods)) { } } -$accounting_groups_used_for_balance_sheet_account = array_filter(array_map('trim', explode(',', $conf->global->ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_BALANCE_SHEET_ACCOUNT)), 'strlen'); -$accounting_groups_used_for_income_statement = array_filter(array_map('trim', explode(',', $conf->global->ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_INCOME_STATEMENT)), 'strlen'); +$accounting_groups_used_for_balance_sheet_account = array_filter(array_map('trim', explode(',', getDolGlobalString('ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_BALANCE_SHEET_ACCOUNT'))), 'strlen'); +$accounting_groups_used_for_income_statement = array_filter(array_map('trim', explode(',', getDolGlobalString('ACCOUNTING_CLOSURE_ACCOUNTING_GROUPS_USED_FOR_INCOME_STATEMENT'))), 'strlen'); /* @@ -263,6 +263,7 @@ if (isset($current_fiscal_period)) { 'label' => $langs->trans('DateEnd'), 'value' => $current_fiscal_period['date_end'] ); + $formconfirm = $form->formconfirm( $_SERVER["PHP_SELF"] . '?fiscal_period_id=' . $current_fiscal_period['id'], $langs->trans('AccountancyClosureAccountingReversal'), diff --git a/htdocs/accountancy/customer/index.php b/htdocs/accountancy/customer/index.php index 14e69593c02..0551a3fe95a 100644 --- a/htdocs/accountancy/customer/index.php +++ b/htdocs/accountancy/customer/index.php @@ -53,7 +53,7 @@ if (!$user->hasRight('accounting', 'bind', 'write')) { $accountingAccount = new AccountingAccount($db); -$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); +$month_start = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); if (GETPOST("year", 'int')) { $year_start = GETPOST("year", 'int'); } else { diff --git a/htdocs/accountancy/expensereport/index.php b/htdocs/accountancy/expensereport/index.php index 0f0b5ec146c..1382eaf5ac6 100644 --- a/htdocs/accountancy/expensereport/index.php +++ b/htdocs/accountancy/expensereport/index.php @@ -36,7 +36,7 @@ $langs->loadLangs(array("compta", "bills", "other", "accountancy")); $validatemonth = GETPOST('validatemonth', 'int'); $validateyear = GETPOST('validateyear', 'int'); -$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); +$month_start = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); if (GETPOST("year", 'int')) { $year_start = GETPOST("year", 'int'); } else { 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 e9cb8de0705..5d80232d51d 100644 --- a/htdocs/accountancy/journal/bankjournal.php +++ b/htdocs/accountancy/journal/bankjournal.php @@ -104,10 +104,16 @@ $error = 0; $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); -if (empty($date_startmonth) || empty($date_endmonth)) { +if (empty($date_startmonth)) { // Period by default on transfer $dates = getDefaultDatesForTransfer(); $date_start = $dates['date_start']; + $pastmonthyear = $dates['pastmonthyear']; + $pastmonth = $dates['pastmonth']; +} +if (empty($date_endmonth)) { + // Period by default on transfer + $dates = getDefaultDatesForTransfer(); $date_end = $dates['date_end']; $pastmonthyear = $dates['pastmonthyear']; $pastmonth = $dates['pastmonth']; @@ -306,16 +312,28 @@ if ($result) { // get_url may return -1 which is not traversable if (is_array($links) && count($links) > 0) { + // Test if entry is for a social contribution, salary or expense report. + // In such a case, we will ignore the bank url line for user $is_sc = false; + $is_salary = false; + $is_expensereport = false; foreach ($links as $v) { if ($v['type'] == 'sc') { $is_sc = true; break; } + if ($v['type'] == 'payment_salary') { + $is_salary = true; + break; + } + if ($v['type'] == 'payment_expensereport') { + $is_expensereport = true; + break; + } } // Now loop on each link of record in bank (code similar to bankentries_list.php) foreach ($links as $key => $val) { - if ($links[$key]['type'] == 'user' && !$is_sc) { + if ($links[$key]['type'] == 'user' && !$is_sc && !$is_salary && !$is_expensereport) { continue; } if (in_array($links[$key]['type'], array('sc', 'payment_sc', 'payment', 'payment_supplier', 'payment_vat', 'payment_expensereport', 'banktransfert', 'payment_donation', 'member', 'payment_loan', 'payment_salary', 'payment_various'))) { @@ -365,6 +383,7 @@ if ($result) { $userstatic->firstname = $tabuser[$obj->rowid]['firstname']; $userstatic->lastname = $tabuser[$obj->rowid]['lastname']; $userstatic->statut = $tabuser[$obj->rowid]['status']; + $userstatic->status = $tabuser[$obj->rowid]['status']; $userstatic->accountancy_code = $tabuser[$obj->rowid]['accountancy_code']; if ($userstatic->id > 0) { $tabpay[$obj->rowid]["soclib"] = $userstatic->getNomUrl(1, 'accountancy', 0); diff --git a/htdocs/accountancy/journal/expensereportsjournal.php b/htdocs/accountancy/journal/expensereportsjournal.php index 39fa8d8e050..fb86cdc3505 100644 --- a/htdocs/accountancy/journal/expensereportsjournal.php +++ b/htdocs/accountancy/journal/expensereportsjournal.php @@ -90,10 +90,16 @@ $journal_label = $accountingjournalstatic->label; $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); -if (empty($date_startmonth) || empty($date_endmonth)) { +if (empty($date_startmonth)) { // Period by default on transfer $dates = getDefaultDatesForTransfer(); $date_start = $dates['date_start']; + $pastmonthyear = $dates['pastmonthyear']; + $pastmonth = $dates['pastmonth']; +} +if (empty($date_endmonth)) { + // Period by default on transfer + $dates = getDefaultDatesForTransfer(); $date_end = $dates['date_end']; $pastmonthyear = $dates['pastmonthyear']; $pastmonth = $dates['pastmonth']; diff --git a/htdocs/accountancy/journal/purchasesjournal.php b/htdocs/accountancy/journal/purchasesjournal.php index ed03d708b79..8439ff5ec99 100644 --- a/htdocs/accountancy/journal/purchasesjournal.php +++ b/htdocs/accountancy/journal/purchasesjournal.php @@ -92,10 +92,16 @@ $journal_label = $accountingjournalstatic->label; $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); -if (empty($date_startmonth) || empty($date_endmonth)) { +if (empty($date_startmonth)) { // Period by default on transfer $dates = getDefaultDatesForTransfer(); $date_start = $dates['date_start']; + $pastmonthyear = $dates['pastmonthyear']; + $pastmonth = $dates['pastmonth']; +} +if (empty($date_endmonth)) { + // Period by default on transfer + $dates = getDefaultDatesForTransfer(); $date_end = $dates['date_end']; $pastmonthyear = $dates['pastmonthyear']; $pastmonth = $dates['pastmonth']; diff --git a/htdocs/accountancy/journal/sellsjournal.php b/htdocs/accountancy/journal/sellsjournal.php index 5ca5c164007..b91a7393572 100644 --- a/htdocs/accountancy/journal/sellsjournal.php +++ b/htdocs/accountancy/journal/sellsjournal.php @@ -94,10 +94,16 @@ $journal_label = $accountingjournalstatic->label; $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); -if (empty($date_startmonth) || empty($date_endmonth)) { +if (empty($date_startmonth)) { // Period by default on transfer $dates = getDefaultDatesForTransfer(); $date_start = $dates['date_start']; + $pastmonthyear = $dates['pastmonthyear']; + $pastmonth = $dates['pastmonth']; +} +if (empty($date_endmonth)) { + // Period by default on transfer + $dates = getDefaultDatesForTransfer(); $date_end = $dates['date_end']; $pastmonthyear = $dates['pastmonthyear']; $pastmonth = $dates['pastmonth']; @@ -464,7 +470,7 @@ if ($action == 'writebookkeeping' && !$error) { // Warranty if (!$errorforline) { - if (is_iterable($tabwarranty[$key])) { + if (is_array($tabwarranty[$key])) { foreach ($tabwarranty[$key] as $k => $mt) { $bookkeeping = new BookKeeping($db); $bookkeeping->doc_date = $val["date"]; @@ -706,7 +712,7 @@ if ($action == 'writebookkeeping' && !$error) { // Revenue stamp if (!$errorforline) { - if (is_iterable($tabrevenuestamp[$key])) { + if (is_array($tabrevenuestamp[$key])) { foreach ($tabrevenuestamp[$key] as $k => $mt) { if ($mt) { $accountingaccount->fetch(null, $k, true); // TODO Use a cache for label @@ -1144,7 +1150,7 @@ if (empty($action) || $action == 'view') { } // Warranty - if (is_iterable($tabwarranty[$key])) { + if (is_array($tabwarranty[$key])) { foreach ($tabwarranty[$key] as $k => $mt) { print ''; print ""; @@ -1292,7 +1298,7 @@ if (empty($action) || $action == 'view') { } // Revenue stamp - if (is_iterable($tabrevenuestamp[$key])) { + if (is_array($tabrevenuestamp[$key])) { foreach ($tabrevenuestamp[$key] as $k => $mt) { print ''; print ""; diff --git a/htdocs/accountancy/journal/variousjournal.php b/htdocs/accountancy/journal/variousjournal.php index 7d496cee5a0..0906f7c4754 100644 --- a/htdocs/accountancy/journal/variousjournal.php +++ b/htdocs/accountancy/journal/variousjournal.php @@ -61,10 +61,16 @@ $parameters = array(); $date_start = dol_mktime(0, 0, 0, $date_startmonth, $date_startday, $date_startyear); $date_end = dol_mktime(23, 59, 59, $date_endmonth, $date_endday, $date_endyear); -if (empty($date_startmonth) || empty($date_endmonth)) { +if (empty($date_startmonth)) { // Period by default on transfer $dates = getDefaultDatesForTransfer(); $date_start = $dates['date_start']; + $pastmonthyear = $dates['pastmonthyear']; + $pastmonth = $dates['pastmonth']; +} +if (empty($date_endmonth)) { + // Period by default on transfer + $dates = getDefaultDatesForTransfer(); $date_end = $dates['date_end']; $pastmonthyear = $dates['pastmonthyear']; $pastmonth = $dates['pastmonth']; diff --git a/htdocs/accountancy/supplier/index.php b/htdocs/accountancy/supplier/index.php index fd07ac82704..a8181885c3a 100644 --- a/htdocs/accountancy/supplier/index.php +++ b/htdocs/accountancy/supplier/index.php @@ -51,7 +51,7 @@ if (!$user->hasRight('accounting', 'bind', 'write')) { $accountingAccount = new AccountingAccount($db); -$month_start = ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); +$month_start = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); if (GETPOST("year", 'int')) { $year_start = GETPOST("year", 'int'); } else { diff --git a/htdocs/accountancy/tpl/export_journal.tpl.php b/htdocs/accountancy/tpl/export_journal.tpl.php index 0a87cf13b4a..9853dd08bf1 100644 --- a/htdocs/accountancy/tpl/export_journal.tpl.php +++ b/htdocs/accountancy/tpl/export_journal.tpl.php @@ -53,7 +53,7 @@ if (($accountancyexport->getFormatCode($formatexportset) == 'fec' || $accountanc } $datetouseforfilename = $search_date_end; $tmparray = dol_getdate($datetouseforfilename); - $fiscalmonth = !getDolGlobalString('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START; + $fiscalmonth = getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); // Define end of month to use if ($tmparray['mon'] < $fiscalmonth || $fiscalmonth == 1) { $tmparray['mon'] = $fiscalmonth == 1 ? 12 : $fiscalmonth - 1; diff --git a/htdocs/adherents/admin/member.php b/htdocs/adherents/admin/member.php index 06cd83397c4..b78cd367c9d 100644 --- a/htdocs/adherents/admin/member.php +++ b/htdocs/adherents/admin/member.php @@ -353,12 +353,12 @@ print "\n"; print ''; print $langs->trans("MemberSubscriptionStartAfter"); print ''; -print ''; +print ''; print "\n"; // Mail required for members print ''.$langs->trans("AdherentMailRequired").''; -print $form->selectyesno('ADHERENT_MAIL_REQUIRED', (getDolGlobalString('ADHERENT_MAIL_REQUIRED') ? $conf->global->ADHERENT_MAIL_REQUIRED : 0), 1); +print $form->selectyesno('ADHERENT_MAIL_REQUIRED', getDolGlobalInt('ADHERENT_MAIL_REQUIRED'), 1); print "\n"; // Login/Pass required for members @@ -370,24 +370,24 @@ print "\n"; // Send mail information is on by default print ''.$langs->trans("MemberSendInformationByMailByDefault").''; -print $form->selectyesno('ADHERENT_DEFAULT_SENDINFOBYMAIL', (getDolGlobalString('ADHERENT_DEFAULT_SENDINFOBYMAIL') ? $conf->global->ADHERENT_DEFAULT_SENDINFOBYMAIL : 0), 1); +print $form->selectyesno('ADHERENT_DEFAULT_SENDINFOBYMAIL', getDolGlobalInt('ADHERENT_DEFAULT_SENDINFOBYMAIL', 0), 1); print "\n"; // Create an external user login for each new member subscription validated print ''.$langs->trans("MemberCreateAnExternalUserForSubscriptionValidated").''; -print $form->selectyesno('ADHERENT_CREATE_EXTERNAL_USER_LOGIN', (getDolGlobalString('ADHERENT_CREATE_EXTERNAL_USER_LOGIN') ? $conf->global->ADHERENT_CREATE_EXTERNAL_USER_LOGIN : 0), 1); +print $form->selectyesno('ADHERENT_CREATE_EXTERNAL_USER_LOGIN', getDolGlobalInt('ADHERENT_CREATE_EXTERNAL_USER_LOGIN', 0), 1); print "\n"; // Create an external user login for each new member subscription validated -$linkofpubliclist = DOL_MAIN_URL_ROOT.'/public/members/public_list.php'.((isModEnabled('multicompany')) ? '?entity='.$conf->entity : ''); +$linkofpubliclist = DOL_MAIN_URL_ROOT.'/public/members/public_list.php'.((isModEnabled('multicompany')) ? '?entity='.((int) $conf->entity) : ''); print ''.$langs->trans("Public", getDolGlobalString('MAIN_INFO_SOCIETE_NOM'), $linkofpubliclist).''; -print $form->selectyesno('MEMBER_PUBLIC_ENABLED', (getDolGlobalString('MEMBER_PUBLIC_ENABLED') ? $conf->global->MEMBER_PUBLIC_ENABLED : 0), 1); +print $form->selectyesno('MEMBER_PUBLIC_ENABLED', getDolGlobalInt('MEMBER_PUBLIC_ENABLED', 0), 1); print "\n"; // Allow members to change type on renewal forms /* To test during next beta print ''.$langs->trans("MemberAllowchangeOfType").''; -print $form->selectyesno('MEMBER_ALLOW_CHANGE_OF_TYPE', (!empty($conf->global->MEMBER_ALLOW_CHANGE_OF_TYPE) ? 0 : 1), 1); +print $form->selectyesno('MEMBER_ALLOW_CHANGE_OF_TYPE', (getDolGlobalInt('MEMBER_ALLOW_CHANGE_OF_TYPE') ? 0 : 1), 1); print "\n"; */ @@ -416,7 +416,7 @@ if (isModEnabled('facture')) { print ''.$langs->trans("VATToUseForSubscriptions").''; if (isModEnabled("banque")) { print ''; - print $form->selectarray('ADHERENT_VAT_FOR_SUBSCRIPTIONS', array('0'=>$langs->trans("NoVatOnSubscription"), 'defaultforfoundationcountry'=>$langs->trans("Default")), (!getDolGlobalString('ADHERENT_VAT_FOR_SUBSCRIPTIONS') ? '0' : $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS), 0); + print $form->selectarray('ADHERENT_VAT_FOR_SUBSCRIPTIONS', array('0'=>$langs->trans("NoVatOnSubscription"), 'defaultforfoundationcountry'=>$langs->trans("Default")), getDolGlobalString('ADHERENT_VAT_FOR_SUBSCRIPTIONS', '0'), 0); print ''; } else { print ''; @@ -428,7 +428,7 @@ if (isModEnabled('facture')) { if (isModEnabled("product") || isModEnabled("service")) { print ''.$langs->trans("ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS").''; print ''; - $selected = (!getDolGlobalString('ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS') ? '' : $conf->global->ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS); + $selected = getDolGlobalString('ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS'); print img_picto('', 'product', 'class="pictofixedwidth"'); $form->select_produits($selected, 'ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS', '', 0); print ''; diff --git a/htdocs/adherents/admin/website.php b/htdocs/adherents/admin/website.php index 4a9ba7ee1c7..8ac296f9449 100644 --- a/htdocs/adherents/admin/website.php +++ b/htdocs/adherents/admin/website.php @@ -215,7 +215,7 @@ if (getDolGlobalString('MEMBER_ENABLE_PUBLIC')) { print ''; $listofval = array(); $listofval += $adht->liste_array(1); - $forcetype = !getDolGlobalString('MEMBER_NEWFORM_FORCETYPE') ? -1 : $conf->global->MEMBER_NEWFORM_FORCETYPE; + $forcetype = getDolGlobalInt('MEMBER_NEWFORM_FORCETYPE', -1); print $form->selectarray("MEMBER_NEWFORM_FORCETYPE", $listofval, $forcetype, count($listofval) > 1 ? 1 : 0); print "\n"; @@ -225,7 +225,7 @@ if (getDolGlobalString('MEMBER_ENABLE_PUBLIC')) { print ''; print $langs->trans("ForceMemberNature"); print ''; - $forcenature = !getDolGlobalString('MEMBER_NEWFORM_FORCEMORPHY') ? 0 : $conf->global->MEMBER_NEWFORM_FORCEMORPHY; + $forcenature = getDolGlobalInt('MEMBER_NEWFORM_FORCEMORPHY', 0); print $form->selectarray("MEMBER_NEWFORM_FORCEMORPHY", $morphys, $forcenature, 1); print "\n"; @@ -233,25 +233,25 @@ if (getDolGlobalString('MEMBER_ENABLE_PUBLIC')) { print ''; print $langs->trans("DefaultAmount"); print ''; - print ''; + print ''; print "\n"; // Min amount print ''; print $langs->trans("MinimumAmount"); print ''; - print ''; + print ''; print "\n"; // SHow counter of validated members publicly print ''; print $langs->trans("MemberCountersArePublic"); print ''; - print $form->selectyesno("MEMBER_COUNTERS_ARE_PUBLIC", (getDolGlobalString('MEMBER_COUNTERS_ARE_PUBLIC') ? $conf->global->MEMBER_COUNTERS_ARE_PUBLIC : 0), 1); + print $form->selectyesno("MEMBER_COUNTERS_ARE_PUBLIC", getDolGlobalInt('MEMBER_COUNTERS_ARE_PUBLIC'), 1); print "\n"; // Show the table of all available membership types. If not, show a form (as the default was for Dolibarr <=16.0) - $skiptable = (getDolGlobalString('MEMBER_SKIP_TABLE') ? $conf->global->MEMBER_SKIP_TABLE : 0); + $skiptable = getDolGlobalInt('MEMBER_SKIP_TABLE'); print ''; print $langs->trans("MembersShowMembershipTypesTable"); print ''; @@ -259,7 +259,7 @@ if (getDolGlobalString('MEMBER_ENABLE_PUBLIC')) { print "\n"; // Show "vote allowed" setting for membership types - $hidevoteallowed = (getDolGlobalString('MEMBER_HIDE_VOTE_ALLOWED') ? $conf->global->MEMBER_HIDE_VOTE_ALLOWED : 0); + $hidevoteallowed = getDolGlobalInt('MEMBER_HIDE_VOTE_ALLOWED'); print ''; print $langs->trans("MembersShowVotesAllowed"); print ''; @@ -282,7 +282,7 @@ if (getDolGlobalString('MEMBER_ENABLE_PUBLIC')) { if (isModEnabled('stripe')) { $listofval['stripe'] = 'Stripe'; } - print $form->selectarray("MEMBER_NEWFORM_PAYONLINE", $listofval, (getDolGlobalString('MEMBER_NEWFORM_PAYONLINE') ? $conf->global->MEMBER_NEWFORM_PAYONLINE : ''), 0); + print $form->selectarray("MEMBER_NEWFORM_PAYONLINE", $listofval, getDolGlobalString('MEMBER_NEWFORM_PAYONLINE'), 0); print "\n"; print ''; diff --git a/htdocs/adherents/cartes/carte.php b/htdocs/adherents/cartes/carte.php index fcfe87209c0..c47e745c8b8 100644 --- a/htdocs/adherents/cartes/carte.php +++ b/htdocs/adherents/cartes/carte.php @@ -150,10 +150,10 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { // For business cards if (empty($mode) || $mode == 'card' || $mode == 'cardlogin') { - $textleft = make_substitutions($conf->global->ADHERENT_CARD_TEXT, $substitutionarray); - $textheader = make_substitutions($conf->global->ADHERENT_CARD_HEADER_TEXT, $substitutionarray); - $textfooter = make_substitutions($conf->global->ADHERENT_CARD_FOOTER_TEXT, $substitutionarray); - $textright = make_substitutions($conf->global->ADHERENT_CARD_TEXT_RIGHT, $substitutionarray); + $textleft = make_substitutions(getDolGlobalString('ADHERENT_CARD_TEXT'), $substitutionarray); + $textheader = make_substitutions(getDolGlobalString('ADHERENT_CARD_HEADER_TEXT'), $substitutionarray); + $textfooter = make_substitutions(getDolGlobalString('ADHERENT_CARD_FOOTER_TEXT'), $substitutionarray); + $textright = make_substitutions(getDolGlobalString('ADHERENT_CARD_TEXT_RIGHT'), $substitutionarray); if (is_numeric($foruserid) || $foruserlogin) { $nb = $_Avery_Labels[$model]['NX'] * $_Avery_Labels[$model]['NY']; // $_Avery_Labels is defined into an include @@ -190,7 +190,7 @@ if ((!empty($foruserid) || !empty($foruserlogin) || !empty($mode)) && !$mesg) { if (!getDolGlobalString('ADHERENT_ETIQUETTE_TEXT')) { $conf->global->ADHERENT_ETIQUETTE_TEXT = "__FULLNAME__\n__ADDRESS__\n__ZIP__ __TOWN__\n__COUNTRY__"; } - $textleft = make_substitutions($conf->global->ADHERENT_ETIQUETTE_TEXT, $substitutionarray); + $textleft = make_substitutions(getDolGlobalString('ADHERENT_ETIQUETTE_TEXT'), $substitutionarray); $textheader = ''; $textfooter = ''; $textright = ''; @@ -275,7 +275,7 @@ dol_htmloutput_errors($mesg); print '
'; -print img_picto('', 'card').' '.$langs->trans("DocForAllMembersCards", (getDolGlobalString('ADHERENT_CARD_TYPE') ? $conf->global->ADHERENT_CARD_TYPE : $langs->transnoentitiesnoconv("None"))).' '; +print img_picto('', 'card').' '.$langs->trans("DocForAllMembersCards", getDolGlobalString('ADHERENT_CARD_TYPE', $langs->transnoentitiesnoconv("None"))).' '; print '
'; print ''; print ''; @@ -288,13 +288,13 @@ foreach (array_keys($_Avery_Labels) as $codecards) { $arrayoflabels[$codecards] = $_Avery_Labels[$codecards]['name']; } asort($arrayoflabels); -print $form->selectarray('modelcard', $arrayoflabels, (GETPOST('modelcard') ? GETPOST('modelcard') : (!getDolGlobalString('ADHERENT_CARD_TYPE') ? '' : $conf->global->ADHERENT_CARD_TYPE)), 1, 0, 0, '', 0, 0, 0, '', '', 1); +print $form->selectarray('modelcard', $arrayoflabels, (GETPOST('modelcard') ? GETPOST('modelcard') : getDolGlobalString('ADHERENT_CARD_TYPE')), 1, 0, 0, '', 0, 0, 0, '', '', 1); print '
'; print '
'; print '

'; -print img_picto('', 'card').' '.$langs->trans("DocForOneMemberCards", (getDolGlobalString('ADHERENT_CARD_TYPE') ? $conf->global->ADHERENT_CARD_TYPE : $langs->transnoentitiesnoconv("None"))).' '; +print img_picto('', 'card').' '.$langs->trans("DocForOneMemberCards", getDolGlobalString('ADHERENT_CARD_TYPE', $langs->transnoentitiesnoconv("None"))).' '; print '
'; print ''; print ''; @@ -306,14 +306,14 @@ foreach (array_keys($_Avery_Labels) as $codecards) { $arrayoflabels[$codecards] = $_Avery_Labels[$codecards]['name']; } asort($arrayoflabels); -print $form->selectarray('model', $arrayoflabels, (GETPOST('model') ? GETPOST('model') : (!getDolGlobalString('ADHERENT_CARD_TYPE') ? '' : $conf->global->ADHERENT_CARD_TYPE)), 1, 0, 0, '', 0, 0, 0, '', '', 1); +print $form->selectarray('model', $arrayoflabels, (GETPOST('model') ? GETPOST('model') : getDolGlobalString('ADHERENT_CARD_TYPE')), 1, 0, 0, '', 0, 0, 0, '', '', 1); print '
'.$langs->trans("Login").': '; print '
'; print '
'; print '

'; -print img_picto('', 'card').' '.$langs->trans("DocForLabels", (!getDolGlobalString('ADHERENT_ETIQUETTE_TYPE') ? '' : $conf->global->ADHERENT_ETIQUETTE_TYPE)).' '; +print img_picto('', 'card').' '.$langs->trans("DocForLabels", getDolGlobalString('ADHERENT_ETIQUETTE_TYPE')).' '; print '
'; print ''; print ''; @@ -325,7 +325,7 @@ foreach (array_keys($_Avery_Labels) as $codecards) { $arrayoflabels[$codecards] = $_Avery_Labels[$codecards]['name']; } asort($arrayoflabels); -print $form->selectarray('modellabel', $arrayoflabels, (GETPOST('modellabel') ? GETPOST('modellabel') : (!getDolGlobalString('ADHERENT_ETIQUETTE_TYPE') ? '' : $conf->global->ADHERENT_ETIQUETTE_TYPE)), 1, 0, 0, '', 0, 0, 0, '', '', 1); +print $form->selectarray('modellabel', $arrayoflabels, (GETPOST('modellabel') ? GETPOST('modellabel') : getDolGlobalString('ADHERENT_ETIQUETTE_TYPE')), 1, 0, 0, '', 0, 0, 0, '', '', 1); print '
'; print '
'; diff --git a/htdocs/adherents/class/adherent.class.php b/htdocs/adherents/class/adherent.class.php index 294e0c4689d..f8aabe6867d 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) ); @@ -1151,7 +1150,6 @@ class Adherent extends CommonObject // Mise a jour $sql = "UPDATE ".MAIN_DB_PREFIX."adherent"; $sql .= " SET pass_crypted = '".$this->db->escape($password_crypted)."'"; - //if (!empty($conf->global->DATABASE_PWD_ENCRYPTED)) if ($isencrypted) { $sql .= ", pass = null"; } else { @@ -1921,7 +1919,7 @@ class Adherent extends CommonObject $outputlangs->setDefaultLang($newlang); } // Generate PDF (whatever is option MAIN_DISABLE_PDF_AUTOUPDATE) so we can include it into email - //if (empty($conf->global->MAIN_DISABLE_PDF_AUTOUPDATE)) + //if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) $invoice->generateDocument($invoice->model_pdf, $outputlangs); } @@ -2727,7 +2725,7 @@ class Adherent extends CommonObject $keymodified = false; // Object classes - $info["objectclass"] = explode(',', $conf->global->LDAP_MEMBER_OBJECT_CLASS); + $info["objectclass"] = explode(',', getDolGlobalString('LDAP_MEMBER_OBJECT_CLASS')); $this->fullname = $this->getFullName($langs); @@ -2752,7 +2750,7 @@ class Adherent extends CommonObject $info[getDolGlobalString($constname)] = $this->$varname; // Check if it is the LDAP key and if its value has been changed - if (getDolGlobalString('LDAP_KEY_MEMBERS') && $conf->global->LDAP_KEY_MEMBERS == getDolGlobalString($constname)) { + if (getDolGlobalString('LDAP_KEY_MEMBERS') && getDolGlobalString('LDAP_KEY_MEMBERS') == getDolGlobalString($constname)) { if (!empty($this->oldcopy) && $this->$varname != $this->oldcopy->$varname) { $keymodified = true; // For check if LDAP key has been modified } @@ -2821,15 +2819,15 @@ class Adherent extends CommonObject if (getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')) { $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')] = dol_hash($this->pass, 'openldap'); // Create OpenLDAP password (see LDAP_PASSWORD_HASH_TYPE) } - } elseif ($conf->global->LDAP_SERVER_PROTOCOLVERSION !== '3') { + } elseif (getDolGlobalString('LDAP_SERVER_PROTOCOLVERSION') !== '3') { // Set LDAP password if possible // If ldap key is modified and LDAPv3 we use ldap_rename function for avoid lose encrypt password - if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) { - // Just for the default MD5 ! - if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) { + if (getDolGlobalString('DATABASE_PWD_ENCRYPTED')) { // This should be on on default installation + // Just for the case we use old md5 encryption (deprecated, no more used, kept for compatibility) + if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO') || getDolGlobalString('MAIN_SECURITY_HASH_ALGO') == 'md5') { if ($this->pass_indatabase_crypted && getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')) { // Create OpenLDAP MD5 password from Dolibarr MD5 password - // Note: This suppose that "pass_indatabase_crypted" is a md5 (guaranted by the previous test if "(empty($conf->global->MAIN_SECURITY_HASH_ALGO))" + // Note: This suppose that "pass_indatabase_crypted" is a md5 (this should not happen anymore)" $info[getDolGlobalString('LDAP_MEMBER_FIELD_PASSWORD_CRYPTED')] = dolGetLdapPasswordHash($this->pass_indatabase_crypted, 'md5frommd5'); } } @@ -3261,7 +3259,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 c75ec565b35..19fdae122eb 100644 --- a/htdocs/adherents/class/adherent_type.class.php +++ b/htdocs/adherents/class/adherent_type.class.php @@ -844,7 +844,7 @@ class AdherentType extends CommonObject $dn = getDolGlobalString('LDAP_KEY_MEMBERS_TYPES') . "=".$info[getDolGlobalString('LDAP_KEY_MEMBERS_TYPES')]."," . getDolGlobalString('LDAP_MEMBER_TYPE_DN'); } if ($mode == 1) { - $dn = $conf->global->LDAP_MEMBER_TYPE_DN; + $dn = getDolGlobalString('LDAP_MEMBER_TYPE_DN'); } if ($mode == 2) { $dn = getDolGlobalString('LDAP_KEY_MEMBERS_TYPES') . "=".$info[getDolGlobalString('LDAP_KEY_MEMBERS_TYPES')]; @@ -868,7 +868,7 @@ class AdherentType extends CommonObject $info = array(); // Object classes - $info["objectclass"] = explode(',', $conf->global->LDAP_MEMBER_TYPE_OBJECT_CLASS); + $info["objectclass"] = explode(',', getDolGlobalString('LDAP_MEMBER_TYPE_OBJECT_CLASS')); if (empty($this->note_public) && !empty($this->note)) { // For backward compatibility $this->note_public = $this->note; @@ -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/api_members.class.php b/htdocs/adherents/class/api_members.class.php index f430e59f68d..4de525281b1 100644 --- a/htdocs/adherents/class/api_members.class.php +++ b/htdocs/adherents/class/api_members.class.php @@ -294,6 +294,12 @@ class Members extends DolibarrApi $member = new Adherent($this->db); foreach ($request_data as $field => $value) { + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $member->context['caller'] = $request_data['caller']; + continue; + } + $member->$field = $value; } if ($member->create(DolibarrApiAccess::$user) < 0) { @@ -329,6 +335,12 @@ class Members extends DolibarrApi if ($field == 'id') { continue; } + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $member->context['caller'] = $request_data['caller']; + continue; + } + // Process the status separately because it must be updated using // the validate(), resiliate() and exclude() methods of the class Adherent. if ($field == 'statut') { diff --git a/htdocs/adherents/class/api_memberstypes.class.php b/htdocs/adherents/class/api_memberstypes.class.php index 458af55a36b..5f1a1aec7b6 100644 --- a/htdocs/adherents/class/api_memberstypes.class.php +++ b/htdocs/adherents/class/api_memberstypes.class.php @@ -159,6 +159,12 @@ class MembersTypes extends DolibarrApi $membertype = new AdherentType($this->db); foreach ($request_data as $field => $value) { + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $membertype->context['caller'] = $request_data['caller']; + continue; + } + $membertype->$field = $value; } if ($membertype->create(DolibarrApiAccess::$user) < 0) { @@ -194,6 +200,12 @@ class MembersTypes extends DolibarrApi if ($field == 'id') { continue; } + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $membertype->context['caller'] = $request_data['caller']; + continue; + } + // Process the status separately because it must be updated using // the validate(), resiliate() and exclude() methods of the class AdherentType. $membertype->$field = $value; diff --git a/htdocs/adherents/class/api_subscriptions.class.php b/htdocs/adherents/class/api_subscriptions.class.php index 174de6d5fe9..9c051ac6a41 100644 --- a/htdocs/adherents/class/api_subscriptions.class.php +++ b/htdocs/adherents/class/api_subscriptions.class.php @@ -156,6 +156,12 @@ class Subscriptions extends DolibarrApi $subscription = new Subscription($this->db); foreach ($request_data as $field => $value) { + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $subscription->context['caller'] = $request_data['caller']; + continue; + } + $subscription->$field = $value; } if ($subscription->create(DolibarrApiAccess::$user) < 0) { @@ -187,6 +193,12 @@ class Subscriptions extends DolibarrApi if ($field == 'id') { continue; } + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $subscription->context['caller'] = $request_data['caller']; + continue; + } + $subscription->$field = $value; } 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/adherents/stats/byproperties.php b/htdocs/adherents/stats/byproperties.php index 351b7092dd8..d2cd86f7de0 100644 --- a/htdocs/adherents/stats/byproperties.php +++ b/htdocs/adherents/stats/byproperties.php @@ -41,7 +41,7 @@ if ($user->socid > 0) { $result = restrictedArea($user, 'adherent', '', '', 'cotisation'); $year = dol_print_date(dol_now('gmt'), "%Y", 'gmt'); -$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, $conf->global->MAIN_STATS_GRAPHS_SHOW_N_YEARS))); +$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS')))); $endyear = $year; // Load translation files required by the page diff --git a/htdocs/adherents/stats/geo.php b/htdocs/adherents/stats/geo.php index 4dc2f756df1..fd64e315ff1 100644 --- a/htdocs/adherents/stats/geo.php +++ b/htdocs/adherents/stats/geo.php @@ -43,7 +43,7 @@ if ($user->socid > 0) { $result = restrictedArea($user, 'adherent', '', '', 'cotisation'); $year = dol_print_date(dol_now('gmt'), "%Y", 'gmt'); -$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, $conf->global->MAIN_STATS_GRAPHS_SHOW_N_YEARS))); +$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS')))); $endyear = $year; // Load translation files required by the page diff --git a/htdocs/adherents/subscription.php b/htdocs/adherents/subscription.php index 182957bc97d..511553b9e88 100644 --- a/htdocs/adherents/subscription.php +++ b/htdocs/adherents/subscription.php @@ -1056,7 +1056,7 @@ if (($action == 'addsubscription' || $action == 'create_thirdparty') && $user->h print $langs->trans("CreateDolibarrThirdParty"); print ')'; } - if (!getDolGlobalString('ADHERENT_VAT_FOR_SUBSCRIPTIONS') || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') { + if (!getDolGlobalString('ADHERENT_VAT_FOR_SUBSCRIPTIONS') || getDolGlobalString('ADHERENT_VAT_FOR_SUBSCRIPTIONS') != 'defaultforfoundationcountry') { print '. '.$langs->trans("NoVatOnSubscription", 0).''; } if (getDolGlobalString('ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS') && (isModEnabled('product') || isModEnabled('service'))) { @@ -1086,7 +1086,7 @@ if (($action == 'addsubscription' || $action == 'create_thirdparty') && $user->h print $langs->trans("CreateDolibarrThirdParty"); print ')'; } - if (!getDolGlobalString('ADHERENT_VAT_FOR_SUBSCRIPTIONS') || $conf->global->ADHERENT_VAT_FOR_SUBSCRIPTIONS != 'defaultforfoundationcountry') { + if (!getDolGlobalString('ADHERENT_VAT_FOR_SUBSCRIPTIONS') || getDolGlobalString('ADHERENT_VAT_FOR_SUBSCRIPTIONS') != 'defaultforfoundationcountry') { print '. '.$langs->trans("NoVatOnSubscription", 0).''; } if (getDolGlobalString('ADHERENT_PRODUCT_ID_FOR_SUBSCRIPTIONS') && (isModEnabled('product')|| isModEnabled('service'))) { diff --git a/htdocs/admin/company.php b/htdocs/admin/company.php index 11590149cbb..87639008243 100644 --- a/htdocs/admin/company.php +++ b/htdocs/admin/company.php @@ -41,6 +41,7 @@ require_once DOL_DOCUMENT_ROOT.'/core/class/html.formcompany.class.php'; $action = GETPOST('action', 'aZ09'); $contextpage = GETPOST('contextpage', 'aZ') ? GETPOST('contextpage', 'aZ') : 'admincompany'; // To manage different context of search +$page_y = GETPOSTINT('page_y'); // Load translation files required by the page $langs->loadLangs(array('admin', 'companies', 'bills')); @@ -74,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']; @@ -137,7 +143,8 @@ if (($action == 'update' && !GETPOST("cancel", 'alpha')) dol_mkdir($dirforimage); } $result = dol_move_uploaded_file($_FILES[$varforimage]["tmp_name"], $dirforimage.$original_file, 1, 0, $_FILES[$varforimage]['error']); - if ($result > 0) { + + if (is_numeric($result) && $result > 0) { $constant = "MAIN_INFO_SOCIETE_LOGO"; if ($varforimage == 'logo_squarred') { $constant = "MAIN_INFO_SOCIETE_LOGO_SQUARRED"; @@ -267,7 +274,7 @@ if (($action == 'update' && !GETPOST("cancel", 'alpha')) } if ($action != 'updateedit' && !$error) { - header("Location: ".$_SERVER["PHP_SELF"]); + header("Location: ".$_SERVER["PHP_SELF"].($page_y ? '?page_y='.$page_y : '')); exit; } } @@ -426,6 +433,7 @@ if (!empty($conf->use_javascript_ajax)) { print '
'; print ''; print ''; +print ''; print ''; print ''."\n"; @@ -457,7 +465,7 @@ print ''."\n"; print ''; + print ''; print ''; } @@ -518,6 +526,9 @@ if ($maxmin > 0) { print ''; print ''; if (!empty($mysoc->logo_small)) { + print ''; if (file_exists($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_small)) { print '
'; print ''; @@ -531,9 +542,6 @@ if (!empty($mysoc->logo_small)) { print ''; print '
'; } - print ''; } elseif (!empty($mysoc->logo)) { if (file_exists($conf->mycompany->dir_output.'/logos/'.$mysoc->logo)) { print '
'; @@ -542,7 +550,7 @@ if (!empty($mysoc->logo_small)) { print ''; } else { print '
'; - print ''; + print ''; print '
'; } } @@ -560,6 +568,9 @@ if ($maxmin > 0) { print ''; print '
'; if (!empty($mysoc->logo_squarred_small)) { + print ''; if (file_exists($conf->mycompany->dir_output.'/logos/thumbs/'.$mysoc->logo_squarred_small)) { print '
'; print ''; @@ -573,7 +584,6 @@ if (!empty($mysoc->logo_squarred_small)) { print ''; print '
'; } - print ''; } elseif (!empty($mysoc->logo_squarred)) { if (file_exists($conf->mycompany->dir_output.'/logos/'.$mysoc->logo_squarred)) { print '
'; @@ -582,7 +592,7 @@ if (!empty($mysoc->logo_squarred_small)) { print ''; } else { print '
'; - print ''; + print ''; print '
'; } } @@ -596,8 +606,9 @@ print ''; print '
'.$langs->trans("CompanyInfo").'
'; $state_id = 0; if (getDolGlobalString('MAIN_INFO_SOCIETE_STATE')) { - $tmp = explode(':', $conf->global->MAIN_INFO_SOCIETE_STATE); + $tmp = explode(':', getDolGlobalString('MAIN_INFO_SOCIETE_STATE')); $state_id = $tmp[0]; } print img_picto('', 'state', 'class="pictofixedwidth"'); @@ -499,7 +507,7 @@ if (isModEnabled('barcode')) { print '
'; print ''; print ''; - print '
'; +print $form->buttonsSaveCancel("Save", '', array(), false, 'reposition'); -print '
'; +print '

'; // IDs of the company (country-specific) @@ -762,9 +773,12 @@ print ''.$langs->trans("FiscalYearInformation").'\n"; print ''; -print $formother->select_month(getDolGlobalString('SOCIETE_FISCAL_MONTH_START') ? $conf->global->SOCIETE_FISCAL_MONTH_START : '', 'SOCIETE_FISCAL_MONTH_START', 0, 1, 'maxwidth100').''; +print $formother->select_month(getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') ? $conf->global->SOCIETE_FISCAL_MONTH_START : '', 'SOCIETE_FISCAL_MONTH_START', 0, 1, 'maxwidth100').''; print ""; + +print $form->buttonsSaveCancel("Save", '', array(), false, 'reposition'); + print '
'; @@ -947,7 +961,7 @@ if ($mysoc->country_code == 'GR') { print ""; } -print $form->buttonsSaveCancel("Save", ''); +print $form->buttonsSaveCancel("Save", '', array(), false, 'reposition'); print '
'; diff --git a/htdocs/admin/company_socialnetworks.php b/htdocs/admin/company_socialnetworks.php index 426b5a8eeb3..d4784351dba 100644 --- a/htdocs/admin/company_socialnetworks.php +++ b/htdocs/admin/company_socialnetworks.php @@ -128,11 +128,11 @@ foreach ($listofnetworks as $key => $value) { $networkconstname = 'MAIN_INFO_SOCIETE_'.strtoupper($key).'_URL'; $networkconstid = 'MAIN_INFO_SOCIETE_'.strtoupper($key); print ''; - print ''; + print ''; print ''; - print ''; + print ''; print ''; - print ''.dol_print_socialnetworks((!empty($conf->global->$networkconstid) ? dol_escape_htmltag($conf->global->$networkconstid) : ''), 0, 0, $key, $listofnetworks).''; + print ''.dol_print_socialnetworks((!empty($conf->global->$networkconstid) ? dol_escape_htmltag(getDolGlobalString($networkconstid)) : ''), 0, 0, $key, $listofnetworks).''; print ''."\n"; } } diff --git a/htdocs/admin/delais.php b/htdocs/admin/delais.php index 804797237b8..8e4ae808f3e 100644 --- a/htdocs/admin/delais.php +++ b/htdocs/admin/delais.php @@ -286,7 +286,7 @@ if ($action == 'edit') { print '
'; -if (!getDolGlobalString('MAIN_DISABLE_METEO') || $conf->global->MAIN_DISABLE_METEO != 1) { +if (!getDolGlobalString('MAIN_DISABLE_METEO') || getDolGlobalInt('MAIN_DISABLE_METEO') != 1) { // Show logo for weather print ''.$langs->trans("DescWeather").' '; diff --git a/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php b/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php index 11b0d8668af..80da9f12971 100644 --- a/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php +++ b/htdocs/admin/dolistore/class/PSWebServiceLibrary.class.php @@ -43,8 +43,9 @@ class PrestaShopWebservice /** @var string PS version */ protected $version; - /** @var array compatible versions of PrestaShop Webservice */ + /** @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'; @@ -231,6 +232,8 @@ class PrestaShopWebservice if ($response != '') { libxml_clear_errors(); libxml_use_internal_errors(true); + libxml_disable_entity_loader(true); // Avoid load of external entities (security problem). Required only if LIBXML_VERSION < 20900 + if (!function_exists('simplexml_load_string')) { throw new PrestaShopWebserviceException('Method simplexml_load_string not available. Your PHP does not support xml.'); } diff --git a/htdocs/admin/external_rss.php b/htdocs/admin/external_rss.php index dca0d5c02f7..83e8c3f8dbf 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 ''; + 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 ''; @@ -262,13 +267,13 @@ if ($resql) { print ''; print ''.$langs->trans("Title").""; - print ''; + print ''; print ''."\n"; print ''; print "".$langs->trans("URL").""; - print ''; + print ''; print ''."\n"; diff --git a/htdocs/admin/mails.php b/htdocs/admin/mails.php index 0f33e1506f5..5f8afdb7fe2 100644 --- a/htdocs/admin/mails.php +++ b/htdocs/admin/mails.php @@ -707,7 +707,7 @@ if ($action == 'edit') { // SMTPS PW if (in_array(getDolGlobalString('MAIN_MAIL_SENDMODE', 'mail'), array('smtps', 'swiftmailer')) && getDolGlobalString('MAIN_MAIL_SMTPS_AUTH_TYPE') != "XOAUTH2") { - print ''.$langs->trans("MAIN_MAIL_SMTPS_PW").''.preg_replace('/./', '*', $conf->global->MAIN_MAIL_SMTPS_PW).''; + print ''.$langs->trans("MAIN_MAIL_SMTPS_PW").''.preg_replace('/./', '*', getDolGlobalString('MAIN_MAIL_SMTPS_PW')).''; } // SMTPS oauth service @@ -918,7 +918,7 @@ if ($action == 'edit') { print ''.$langs->trans("MAIN_MAIL_AUTOCOPY_TO").''; print ''; if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO')) { - $listofemail = explode(',', $conf->global->MAIN_MAIL_AUTOCOPY_TO); + $listofemail = explode(',', getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO')); $i = 0; foreach ($listofemail as $key => $val) { if ($i) { diff --git a/htdocs/admin/mails_emailing.php b/htdocs/admin/mails_emailing.php index dbb6ad27d61..eee4b71f42b 100644 --- a/htdocs/admin/mails_emailing.php +++ b/htdocs/admin/mails_emailing.php @@ -533,7 +533,7 @@ if ($action == 'edit') { } print ''; - if (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') { + if (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') && getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') != 'default') { // Host server if ($linuxlike && (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') == 'mail')) { //print ''.$langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").''; @@ -653,8 +653,8 @@ if ($action == 'edit') { print ''.$langs->trans("Modify").''; - if (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') && $conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'default') { - if ($conf->global->MAIN_MAIL_SENDMODE_EMAILING != 'mail' || !$linuxlike) { + if (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') && getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') != 'default') { + if (getDolGlobalString('MAIN_MAIL_SENDMODE_EMAILING') != 'mail' || !$linuxlike) { if (function_exists('fsockopen') && $port && $server) { print '' . $langs->trans("DoTestServerAvailability") . ''; } diff --git a/htdocs/admin/mails_ticket.php b/htdocs/admin/mails_ticket.php index 104efa16c19..1fa1cd2bb33 100644 --- a/htdocs/admin/mails_ticket.php +++ b/htdocs/admin/mails_ticket.php @@ -510,7 +510,7 @@ if ($action == 'edit') { } print ''; - if (getDolGlobalString('MAIN_MAIL_SENDMODE_TICKET') && $conf->global->MAIN_MAIL_SENDMODE_TICKET != 'default') { + if (getDolGlobalString('MAIN_MAIL_SENDMODE_TICKET') && getDolGlobalString('MAIN_MAIL_SENDMODE_TICKET') != 'default') { // Host server if ($linuxlike && (getDolGlobalString('MAIN_MAIL_SENDMODE_TICKET') == 'mail')) { //print ''.$langs->trans("MAIN_MAIL_SMTP_SERVER_NotAvailableOnLinuxLike").''.$langs->trans("SeeLocalSendMailSetup").''; @@ -615,8 +615,8 @@ if ($action == 'edit') { print ''.$langs->trans("Modify").''; - if (getDolGlobalString('MAIN_MAIL_SENDMODE_TICKET') && $conf->global->MAIN_MAIL_SENDMODE_TICKET != 'default') { - if ($conf->global->MAIN_MAIL_SENDMODE_TICKET != 'mail' || !$linuxlike) { + if (getDolGlobalString('MAIN_MAIL_SENDMODE_TICKET') && getDolGlobalString('MAIN_MAIL_SENDMODE_TICKET') != 'default') { + if (getDolGlobalString('MAIN_MAIL_SENDMODE_TICKET') != 'mail' || !$linuxlike) { if (function_exists('fsockopen') && $port && $server) { print ''.$langs->trans("DoTestServerAvailability").''; } 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/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_file.php b/htdocs/admin/security_file.php index 038a41c66bb..0c191d9ae7b 100644 --- a/htdocs/admin/security_file.php +++ b/htdocs/admin/security_file.php @@ -155,7 +155,7 @@ if (isset($max)) { } print ''; print ''; -print ' '.$langs->trans("Kb"); +print ' '.$langs->trans("Kb"); print ''; print ''; @@ -165,7 +165,7 @@ print ''; print $form->textwithpicto($langs->trans("UMask"), $langs->trans("UMaskExplanation")); print ''; print ''; -print ''; +print ''; print ''; print ''; @@ -200,7 +200,7 @@ print ''.$langs->trans("AntiVirusParam").'
'; print ''.$langs->trans("AntiVirusParamExample").''; print ''; print ''; -print ''; +print ''; if (defined('MAIN_ANTIVIRUS_PARAM')) { print '
'.$langs->trans("ValueIsForcedBySystem").''; } diff --git a/htdocs/admin/stock.php b/htdocs/admin/stock.php index bf686d3c93b..a784792ae02 100644 --- a/htdocs/admin/stock.php +++ b/htdocs/admin/stock.php @@ -776,7 +776,7 @@ if ($conf->use_javascript_ajax) { print ajax_constantonoff('STOCK_SUPPORTS_SERVICES'); } else { $arrval = array('0' => $langs->trans("No"), '1' => $langs->trans("Yes")); - print $form->selectarray("STOCK_SUPPORTS_SERVICES", $arrval, $conf->global->STOCK_SUPPORTS_SERVICES); + print $form->selectarray("STOCK_SUPPORTS_SERVICES", $arrval, getDolGlobalString('STOCK_SUPPORTS_SERVICES')); } print "\n"; print "\n"; diff --git a/htdocs/admin/syslog.php b/htdocs/admin/syslog.php index dd37a06b4da..88d590ffc35 100644 --- a/htdocs/admin/syslog.php +++ b/htdocs/admin/syslog.php @@ -186,16 +186,20 @@ if (isModEnabled('multicompany') && $user->entity) { // Output mode + +print '
'; + print load_fiche_titre($langs->trans("SyslogOutput"), '', ''); -// Mode -print ''; print ''; print ''; + +print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''; print ''; -print ''; -print ''; +print ''; +print ''; +print ''; print "\n"; foreach ($syslogModules as $moduleName) { @@ -209,9 +213,9 @@ foreach ($syslogModules as $moduleName) { print ''; - print ''; - print '
'.$langs->trans("Type").''.$langs->trans("Value").''.$langs->trans("Type").''.$langs->trans("Value").'
'; - print ' '; - print $module->getName(); + print ''; + print ' '; + print ''; if ($moduleName == 'mod_syslog_syslog') { if (!$module->isActive()) { $langs->load("errors"); @@ -235,22 +239,23 @@ foreach ($syslogModules as $moduleName) { $value = (isset($option['default']) ? $option['default'] : ''); } - print $option['name'].': '; + print ''.$option['name'].': '; if (!empty($option['example'])) { - print '
'.$langs->trans("Example").': '.$option['example']; + print '
'.$langs->trans("Example").': '.dol_escape_htmltag($option['example']); } if ($option['constant'] == 'SYSLOG_FILE' && preg_match('/^DOL_DATA_ROOT\/[^\/]*$/', $value)) { - $filelogparam = ' ('; + $filelogparam = '     '; $filelogparam .= $langs->trans('Download'); - $filelogparam .= ' '.basename($value).')'; + $filelogparam .= img_picto($langs->trans('Download').' '.basename($value), 'download', 'class="paddingleft"'); + $filelogparam .= ''; print $filelogparam; } } } print '
'; + print ''; if ($module->getInfo()) { print $form->textwithpicto('', $module->getInfo(), 1, 'help'); } @@ -262,42 +267,54 @@ foreach ($syslogModules as $moduleName) { } print "
\n"; +print "
\n"; + print "
\n"; + print '
'."\n\n"; -print load_fiche_titre($langs->trans("SyslogLevel"), '', ''); // Level -print '
'; + +print ''; + +print load_fiche_titre($langs->trans("SyslogLevel"), '', ''); + print ''; print ''; + +print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print ''; print ''; print ''; -print ''; +print ''; print "\n"; -print ''; -print ''; +print ''; if (!empty($conf->loghandlers['mod_syslog_file']) && isModEnabled('cron')) { - print ''; - print ''; + print ''; + print ''; } print '
'.$langs->trans("Parameter").''.$langs->trans("Value").'
'.$langs->trans("SyslogLevel").'
'.$langs->trans("SyslogLevel").''; + +print ajax_combobox("level"); print '
'.$langs->trans("SyslogFileNumberOfSaves").''; - print ' ('.$langs->trans('ConfigureCleaningCronjobToSetFrequencyOfSaves').')
'.$langs->trans("SyslogFileNumberOfSaves").''; + print '   ('.$langs->trans('ConfigureCleaningCronjobToSetFrequencyOfSaves').')
'; +print "
\n"; + print "
\n"; // End of page diff --git a/htdocs/admin/system/security.php b/htdocs/admin/system/security.php index 00d9a461048..7ad70c385b5 100644 --- a/htdocs/admin/system/security.php +++ b/htdocs/admin/system/security.php @@ -350,7 +350,7 @@ print ' -> PHP streams allowed = '; $arrayofstreams = stream_get_wrappers(); if (!empty($arrayofstreams)) { sort($arrayofstreams); - print (join(',', $arrayofstreams)).'     ('.$langs->trans("Recommended").': '.$langs->trans("TryToKeepOnly", 'file,http,https,php').')'."\n"; + print(join(',', $arrayofstreams)).'     ('.$langs->trans("Recommended").': '.$langs->trans("TryToKeepOnly", 'file,http,https,php').')'."\n"; } print '
'; @@ -627,13 +627,13 @@ print 'MAIN_SECURITY_HASH_ALGO = '.getDolGlobalString('MAIN_SEC if (!getDolGlobalString('MAIN_SECURITY_HASH_ALGO')) { print '     If unset: \'md5\''; } -if ($conf->global->MAIN_SECURITY_HASH_ALGO != 'password_hash') { +if (getDolGlobalString('MAIN_SECURITY_HASH_ALGO') != 'password_hash') { print '
MAIN_SECURITY_SALT = '.getDolGlobalString('MAIN_SECURITY_SALT', ''.$langs->trans("Undefined").'').'
'; } else { print '('.$langs->trans("Recommended").': password_hash)'; print '
'; } -if ($conf->global->MAIN_SECURITY_HASH_ALGO != 'password_hash') { +if (getDolGlobalString('MAIN_SECURITY_HASH_ALGO') != 'password_hash') { print '
The recommanded value for MAIN_SECURITY_HASH_ALGO is now \'password_hash\' but setting it now will make ALL existing passwords of all users not valid, so update is not possible.
'; print 'If you really want to switch, you must:
'; print '- Go on home - setup - other and add constant MAIN_SECURITY_HASH_ALGO to value \'password_hash\'
'; @@ -713,7 +713,9 @@ print 'MAIN_RESTRICTHTML_REMOVE_ALSO_BAD_ATTRIBUTES = '.(getDol print '   ('.$langs->trans("Recommended").": 1 - does not work on HTML5 with some old libxml libs)
"; print '
'; -print 'MAIN_DISALLOW_URL_INTO_DESCRIPTIONS = '.getDolGlobalString('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS', ''.$langs->trans("Undefined").'   ('.$langs->trans("Recommended").': 1)')."
"; +// MAIN_DISALLOW_URL_INTO_DESCRIPTIONS = 1, disallow url links except if on /medias +// MAIN_DISALLOW_URL_INTO_DESCRIPTIONS = 2, disallow all external urls link +print 'MAIN_DISALLOW_URL_INTO_DESCRIPTIONS = '.getDolGlobalString('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS', ''.$langs->trans("Undefined").'   ('.$langs->trans("Recommended").': 1=only local links allowed or 2=no links at all)')."
"; print '
'; print 'MAIN_ALLOW_SVG_FILES_AS_EXTERNAL_LINKS = '.getDolGlobalString('MAIN_ALLOW_SVG_FILES_AS_EXTERNAL_LINKS', ''.$langs->trans("Undefined").'   ('.$langs->trans("Recommended").': '.$langs->trans("Undefined").' '.$langs->trans("or").' 0)')."
"; 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/api/admin/explorer_withredoc.php b/htdocs/api/admin/explorer_withredoc.php index 387da2a06af..8c94e7a6f62 100644 --- a/htdocs/api/admin/explorer_withredoc.php +++ b/htdocs/api/admin/explorer_withredoc.php @@ -47,7 +47,7 @@ if (getDolGlobalString('API_EXPLORER_DISABLED')) { // Restrict API to some IPs if (getDolGlobalString('API_RESTRICT_ON_IP')) { - $allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP); + $allowedip = explode(' ', getDolGlobalString('API_RESTRICT_ON_IP')); $ipremote = getUserRemoteIP(); if (!in_array($ipremote, $allowedip)) { dol_syslog('Remote ip is '.$ipremote.', not into list ' . getDolGlobalString('API_RESTRICT_ON_IP')); diff --git a/htdocs/api/class/api.class.php b/htdocs/api/class/api.class.php index 868b03304e5..ffa57c6e3f8 100644 --- a/htdocs/api/class/api.class.php +++ b/htdocs/api/class/api.class.php @@ -78,18 +78,24 @@ class DolibarrApi * Display a short message an return a http code 200 * * @param string $field Field name - * @param string $value Value to check/clean + * @param mixed $value Value to check/clean * @param Object $object Object * @return string Value cleaned */ protected function _checkValForAPI($field, $value, $object) { // phpcs:enable - // TODO Use type detected in $object->fields - if (in_array($field, array('note', 'note_private', 'note_public', 'desc', 'description'))) { - return sanitizeVal($value, 'restricthtml'); + if (!is_array($value)) { + // TODO Use type detected in $object->fields if $object known and we can + if (in_array($field, array('note', 'note_private', 'note_public', 'desc', 'description'))) { + return sanitizeVal($value, 'restricthtml'); + } else { + return sanitizeVal($value, 'alphanohtml'); + } } else { - return sanitizeVal($value, 'alphanohtml'); + // TODO Recall _checkValForAPI for each element of array + + return $value; } } diff --git a/htdocs/api/class/api_setup.class.php b/htdocs/api/class/api_setup.class.php index 45b8be32763..292add085d2 100644 --- a/htdocs/api/class/api_setup.class.php +++ b/htdocs/api/class/api_setup.class.php @@ -2097,7 +2097,7 @@ class Setup extends DolibarrApi $constvalue = (empty($constvalue) ? '0' : $constvalue); // Value found $value = ''; - if ($constname && $conf->global->$constname != '') { + if ($constname && getDolGlobalString($constname) != '') { $value = $conf->global->$constname; } $valueforchecksum = (empty($value) ? '0' : $value); diff --git a/htdocs/api/index.php b/htdocs/api/index.php index da711f6f43b..b824c7b97dc 100644 --- a/htdocs/api/index.php +++ b/htdocs/api/index.php @@ -198,7 +198,7 @@ UploadFormat::$allowedMimeTypes = array('image/jpeg', 'image/png', 'text/plain', // Restrict API to some IPs if (getDolGlobalString('API_RESTRICT_ON_IP')) { - $allowedip = explode(' ', $conf->global->API_RESTRICT_ON_IP); + $allowedip = explode(' ', getDolGlobalString('API_RESTRICT_ON_IP')); $ipremote = getUserRemoteIP(); if (!in_array($ipremote, $allowedip)) { dol_syslog('Remote ip is '.$ipremote.', not into list ' . getDolGlobalString('API_RESTRICT_ON_IP')); @@ -343,7 +343,7 @@ if (!empty($reg[1]) && ($reg[1] != 'explorer' || ($reg[2] != '/swagger.json' && // Test rules on endpoints. For example: // $conf->global->API_ENDPOINT_RULES = 'endpoint1:1,endpoint2:1,...' if (getDolGlobalString('API_ENDPOINT_RULES')) { - $listofendpoints = explode(',', $conf->global->API_ENDPOINT_RULES); + $listofendpoints = explode(',', getDolGlobalString('API_ENDPOINT_RULES')); $endpointisallowed = false; foreach ($listofendpoints as $endpointrule) { diff --git a/htdocs/blockedlog/admin/blockedlog.php b/htdocs/blockedlog/admin/blockedlog.php index e73f4cb1196..75acdf7b230 100644 --- a/htdocs/blockedlog/admin/blockedlog.php +++ b/htdocs/blockedlog/admin/blockedlog.php @@ -155,7 +155,7 @@ if ($resql) { } } -$seledted = !getDolGlobalString('BLOCKEDLOG_DISABLE_NOT_ALLOWED_FOR_COUNTRY') ? array() : explode(',', $conf->global->BLOCKEDLOG_DISABLE_NOT_ALLOWED_FOR_COUNTRY); +$seledted = !getDolGlobalString('BLOCKEDLOG_DISABLE_NOT_ALLOWED_FOR_COUNTRY') ? array() : explode(',', getDolGlobalString('BLOCKEDLOG_DISABLE_NOT_ALLOWED_FOR_COUNTRY')); print $form->multiselectarray('BLOCKEDLOG_DISABLE_NOT_ALLOWED_FOR_COUNTRY', $countryArray, $seledted); print ''; diff --git a/htdocs/blockedlog/admin/blockedlog_list.php b/htdocs/blockedlog/admin/blockedlog_list.php index 70611f174e9..9874be8bebe 100644 --- a/htdocs/blockedlog/admin/blockedlog_list.php +++ b/htdocs/blockedlog/admin/blockedlog_list.php @@ -442,7 +442,6 @@ print ''; // User print ''; print $form->select_dolusers($search_fk_user, 'search_fk_user', 1, null, 0, '', '', 0, 0, 0, '', 0, '', 'maxwidth200'); - print ''; // Actions code @@ -570,7 +569,7 @@ if (is_array($blocks)) { print ''.dol_print_date($block->date_creation, 'dayhour').''; // User - print ''; + print ''; //print $block->getUser() print dol_escape_htmltag($block->user_fullname); print ''; @@ -580,7 +579,7 @@ if (is_array($blocks)) { // Ref print ''; - print $block->ref_object; + print dol_escape_htmltag($block->ref_object); print ''; // Link to source object @@ -596,7 +595,7 @@ if (is_array($blocks)) { print ''.img_info($langs->trans('ShowDetails')).''; // Fingerprint - print ''; + print ''; $texttoshow = $langs->trans("Fingerprint").' - '.$langs->trans("Saved").':
'.$block->signature; $texttoshow .= '

'.$langs->trans("Fingerprint").' - Recalculated sha256(previoushash * data):
'.$checkdetail[$block->id]['calculatedsignature']; $texttoshow .= '
'.$langs->trans("PreviousHash").'='.$checkdetail[$block->id]['previoushash'].''; diff --git a/htdocs/blockedlog/class/blockedlog.class.php b/htdocs/blockedlog/class/blockedlog.class.php index 27a05d81e0e..a69c839f369 100644 --- a/htdocs/blockedlog/class/blockedlog.class.php +++ b/htdocs/blockedlog/class/blockedlog.class.php @@ -211,7 +211,7 @@ class BlockedLog // Add more action to track from a conf variable // For example: STOCK_MOVEMENT,... if (getDolGlobalString('BLOCKEDLOG_ADD_ACTIONS_SUPPORTED')) { - $tmparrayofmoresupportedevents = explode(',', $conf->global->BLOCKEDLOG_ADD_ACTIONS_SUPPORTED); + $tmparrayofmoresupportedevents = explode(',', getDolGlobalString('BLOCKEDLOG_ADD_ACTIONS_SUPPORTED')); foreach ($tmparrayofmoresupportedevents as $val) { $this->trackedevents[$val] = 'log'.$val; } diff --git a/htdocs/bom/class/api_boms.class.php b/htdocs/bom/class/api_boms.class.php index 5188e2d4758..658543e68c3 100644 --- a/htdocs/bom/class/api_boms.class.php +++ b/htdocs/bom/class/api_boms.class.php @@ -203,6 +203,12 @@ class Boms extends DolibarrApi $result = $this->_validate($request_data); foreach ($request_data as $field => $value) { + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->bom->context['caller'] = $request_data['caller']; + continue; + } + $this->bom->$field = $value; } @@ -241,6 +247,12 @@ class Boms extends DolibarrApi if ($field == 'id') { continue; } + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->bom->context['caller'] = $request_data['caller']; + continue; + } + $this->bom->$field = $value; } @@ -547,7 +559,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..9c89778d555 100644 --- a/htdocs/bom/class/bom.class.php +++ b/htdocs/bom/class/bom.class.php @@ -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 ''; - echo ''.dol_print_date($objectlink->date_creation, 'day').''; + echo ''.dol_print_date($objectlink->date_creation, 'day').''; echo ''; if ($user->hasRight('commande', 'lire')) { $total = $total + $objectlink->total_ht; diff --git a/htdocs/bookcal/bookcalindex.php b/htdocs/bookcal/bookcalindex.php index c236815a040..c2116980254 100644 --- a/htdocs/bookcal/bookcalindex.php +++ b/htdocs/bookcal/bookcalindex.php @@ -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/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 f3a051ba703..5d2a9d0862a 100644 --- a/htdocs/categories/class/api_categories.class.php +++ b/htdocs/categories/class/api_categories.class.php @@ -204,6 +204,12 @@ class Categories extends DolibarrApi $result = $this->_validate($request_data); foreach ($request_data as $field => $value) { + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->category->context['caller'] = $request_data['caller']; + continue; + } + $this->category->$field = $value; } if ($this->category->create(DolibarrApiAccess::$user) < 0) { @@ -238,6 +244,12 @@ class Categories extends DolibarrApi if ($field == 'id') { continue; } + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->category->context['caller'] = $request_data['caller']; + continue; + } + $this->category->$field = $value; } diff --git a/htdocs/comm/action/card.php b/htdocs/comm/action/card.php index 766b440d9e9..313fefccac6 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 @@ -69,7 +69,7 @@ $p2hour = GETPOST('p2hour', 'int'); $p2min = GETPOST('p2min', 'int'); $addreminder = GETPOST('addreminder', 'alpha'); -$offsetvalue = GETPOST('offsetvalue', 'int'); +$offsetvalue = GETPOSTINT('offsetvalue'); $offsetunit = GETPOST('offsetunittype_duration', 'aZ09'); $remindertype = GETPOST('selectremindertype', 'aZ09'); $modelmail = GETPOST('actioncommsendmodel_mail', 'int'); @@ -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'; } @@ -536,7 +537,7 @@ if (empty($reshook) && $action == 'add') { if ($addreminder == 'on') { $actionCommReminder = new ActionCommReminder($db); - $dateremind = dol_time_plus_duree($datep, -$offsetvalue, $offsetunit); + $dateremind = dol_time_plus_duree($datep, -1 * $offsetvalue, $offsetunit); $actionCommReminder->dateremind = $dateremind; $actionCommReminder->typeremind = $remindertype; @@ -653,7 +654,7 @@ if (empty($reshook) && $action == 'add') { if ($addreminder == 'on') { $actionCommReminder = new ActionCommReminder($db); - $dateremind = dol_time_plus_duree($datep, -$offsetvalue, $offsetunit); + $dateremind = dol_time_plus_duree($datep, -1 * $offsetvalue, $offsetunit); $actionCommReminder->dateremind = $dateremind; $actionCommReminder->typeremind = $remindertype; @@ -981,7 +982,7 @@ if (empty($reshook) && $action == 'update') { if ($addreminder == 'on' && $object->datep > dol_now()) { $actionCommReminder = new ActionCommReminder($db); - $dateremind = dol_time_plus_duree($datep, -$offsetvalue, $offsetunit); + $dateremind = dol_time_plus_duree($datep, -1 * $offsetvalue, $offsetunit); $actionCommReminder->dateremind = $dateremind; $actionCommReminder->typeremind = $remindertype; diff --git a/htdocs/comm/action/class/api_agendaevents.class.php b/htdocs/comm/action/class/api_agendaevents.class.php index 2e816865312..5c86aa9f6b5 100644 --- a/htdocs/comm/action/class/api_agendaevents.class.php +++ b/htdocs/comm/action/class/api_agendaevents.class.php @@ -217,6 +217,12 @@ class AgendaEvents extends DolibarrApi $result = $this->_validate($request_data); foreach ($request_data as $field => $value) { + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->actioncomm->context['caller'] = $request_data['caller']; + continue; + } + $this->actioncomm->$field = $this->_checkValForAPI($field, $value, $this->actioncomm); } /*if (isset($request_data["lines"])) { @@ -269,6 +275,11 @@ class AgendaEvents extends DolibarrApi if ($field == 'id') { continue; } + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->actioncomm->context['caller'] = $request_data['caller']; + continue; + } $this->actioncomm->$field = $this->_checkValForAPI($field, $value, $this->actioncomm); } diff --git a/htdocs/comm/action/index.php b/htdocs/comm/action/index.php index 9a5d6305301..f008b84dfad 100644 --- a/htdocs/comm/action/index.php +++ b/htdocs/comm/action/index.php @@ -1683,7 +1683,7 @@ if (empty($mode) || $mode == 'show_month') { // View by month $maxnbofchar = 80; - $tmp = explode('-', $conf->global->MAIN_DEFAULT_WORKING_HOURS); + $tmp = explode('-', getDolGlobalString('MAIN_DEFAULT_WORKING_HOURS')); $minhour = round($tmp[0], 0); $maxhour = round($tmp[1], 0); if ($minhour > 23) { 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/index.php b/htdocs/comm/index.php index 27ac6154296..da07b9f9dd6 100644 --- a/htdocs/comm/index.php +++ b/htdocs/comm/index.php @@ -64,13 +64,13 @@ 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(); //restrictedArea($user, 'societe', $socid, '&societe', '', 'fk_soc', 'rowid', 0); if (!$user->hasRight('propal', 'read') && !$user->hasRight('supplier_proposal', 'read') && !$user->hasRight('commande', 'read') && !$user->hasRight('fournisseur', 'commande', 'read') - && !$user->hasRight('supplier_order', 'read') && !$user->hasRight('fichinter', 'read')) { + && !$user->hasRight('supplier_order', 'read') && !$user->hasRight('fichinter', 'read') && !$user->hasRight('contrat', 'read')) { accessforbidden(); } diff --git a/htdocs/comm/propal/class/api_proposals.class.php b/htdocs/comm/propal/class/api_proposals.class.php index 059db036436..05cb33a17df 100644 --- a/htdocs/comm/propal/class/api_proposals.class.php +++ b/htdocs/comm/propal/class/api_proposals.class.php @@ -266,6 +266,12 @@ class Proposals extends DolibarrApi $result = $this->_validate($request_data); foreach ($request_data as $field => $value) { + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->propal->context['caller'] = $request_data['caller']; + continue; + } + $this->propal->$field = $value; } /*if (isset($request_data["lines"])) { @@ -698,6 +704,12 @@ class Proposals extends DolibarrApi if ($field == 'id') { continue; } + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->propal->context['caller'] = $request_data['caller']; + continue; + } + $this->propal->$field = $value; } diff --git a/htdocs/comm/propal/class/propal.class.php b/htdocs/comm/propal/class/propal.class.php index 7ff7de223bf..d470fc8bc52 100644 --- a/htdocs/comm/propal/class/propal.class.php +++ b/htdocs/comm/propal/class/propal.class.php @@ -1512,7 +1512,7 @@ class Propal extends CommonObject $error++; } - if (!$error) { + if (!$error && !getDolGlobalInt('MAIN_IGNORE_CONTACTS_ON_CLONING')) { // copy internal contacts if ($object->copy_linked_contact($this, 'internal') < 0) { $error++; @@ -2720,7 +2720,7 @@ class Propal extends CommonObject } } - if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE')) { + if (!getDolGlobalString('MAIN_DISABLE_PDF_AUTOUPDATE') && !getDolGlobalInt('PROPAL_DISABLE_AUTOUPDATE_ON_CLOSE')) { // Define output language $outputlangs = $langs; if (getDolGlobalInt('MAIN_MULTILANGS')) { diff --git a/htdocs/comm/propal/stats/index.php b/htdocs/comm/propal/stats/index.php index 3f6f8be39c3..7c4e197bdec 100644 --- a/htdocs/comm/propal/stats/index.php +++ b/htdocs/comm/propal/stats/index.php @@ -54,7 +54,7 @@ if ($user->socid > 0) { $nowyear = dol_print_date(dol_now('gmt'), "%Y", 'gmt'); $year = GETPOST('year') > 0 ? GETPOST('year', 'int') : $nowyear; -$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, $conf->global->MAIN_STATS_GRAPHS_SHOW_N_YEARS))); +$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS')))); $endyear = $year; // Load translation files required by the page diff --git a/htdocs/commande/card.php b/htdocs/commande/card.php index 791f67fcd56..07bbd4ed74b 100644 --- a/htdocs/commande/card.php +++ b/htdocs/commande/card.php @@ -206,11 +206,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) { @@ -3037,7 +3044,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 2bbcbe94104..c5119a51f6e 100644 --- a/htdocs/commande/class/api_orders.class.php +++ b/htdocs/commande/class/api_orders.class.php @@ -282,6 +282,12 @@ class Orders extends DolibarrApi $result = $this->_validate($request_data); foreach ($request_data as $field => $value) { + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->commande->context['caller'] = $request_data['caller']; + continue; + } + $this->commande->$field = $value; } /*if (isset($request_data["lines"])) { @@ -652,6 +658,12 @@ class Orders extends DolibarrApi if ($field == 'id') { continue; } + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->commande->context['caller'] = $request_data['caller']; + continue; + } + $this->commande->$field = $value; } diff --git a/htdocs/commande/class/commande.class.php b/htdocs/commande/class/commande.class.php index 99024dca83f..5ec0a3374d1 100644 --- a/htdocs/commande/class/commande.class.php +++ b/htdocs/commande/class/commande.class.php @@ -1191,7 +1191,7 @@ class Commande extends CommonOrder return 0; } else { - dol_print_error($this->db); + $this->error = $this->db->lasterror(); $this->db->rollback(); return -1; } 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 d799b588478..d3cbb3c2367 100644 --- a/htdocs/commande/list.php +++ b/htdocs/commande/list.php @@ -10,7 +10,7 @@ * Copyright (C) 2015 Marcos García * Copyright (C) 2015 Jean-François Ferry * Copyright (C) 2016-2023 Ferran Marcet - * Copyright (C) 2018 Charlene Benke + * Copyright (C) 2018-2023 Charlene Benke * Copyright (C) 2021 Anthony Berton * * This program is free software; you can redistribute it and/or modify @@ -322,6 +322,8 @@ if (empty($reshook)) { } $uploaddir = $conf->commande->multidir_output[$conf->entity]; $triggersendname = 'ORDER_SENTBYMAIL'; + $year=""; + $month=""; include DOL_DOCUMENT_ROOT.'/core/actions_massactions.inc.php'; if ($massaction == 'confirm_createbills') { // Create bills from orders. @@ -1310,7 +1312,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"); diff --git a/htdocs/commande/list_det.php b/htdocs/commande/list_det.php index 255dd76614e..80fff860a05 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,'; @@ -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/commande/stats/index.php b/htdocs/commande/stats/index.php index a909820ae6e..702ee59d5e9 100644 --- a/htdocs/commande/stats/index.php +++ b/htdocs/commande/stats/index.php @@ -75,7 +75,7 @@ if ($user->socid > 0) { $nowyear = dol_print_date(dol_now('gmt'), "%Y", 'gmt'); $year = GETPOST('year') > 0 ? GETPOST('year') : $nowyear; -$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, $conf->global->MAIN_STATS_GRAPHS_SHOW_N_YEARS))); +$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS')))); $endyear = $year; // Load translation files required by the page diff --git a/htdocs/compta/bank/bankentries_list.php b/htdocs/compta/bank/bankentries_list.php index ce013aa89e2..038663e4dc5 100644 --- a/htdocs/compta/bank/bankentries_list.php +++ b/htdocs/compta/bank/bankentries_list.php @@ -342,7 +342,7 @@ if (GETPOST('save') && !$cancel && $user->hasRight('banque', 'modifier')) { if (price2num(GETPOST("addcredit")) > 0) { $amount = price2num(GETPOST("addcredit")); } else { - $amount = - price2num(GETPOST("adddebit")); + $amount = price2num(-1 * (float) price2num(GETPOST("adddebit"))); } $operation = GETPOST("operation", 'alpha'); @@ -1079,7 +1079,7 @@ if ($resql) { } $varpage = empty($contextpage) ? $_SERVER["PHP_SELF"] : $contextpage; - $selectedfields = ($mode != 'kanban' ? $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN', '')) : ''); // This also change content of $arrayfields + $selectedfields = ($mode != 'kanban' ? $form->multiSelectArrayWithCheckbox('selectedfields', $arrayfields, $varpage, getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) : ''); // This also change content of $arrayfields // When action is 'reconcile', we force to have the column num_releve always enabled (otherwise we can't make reconciliation). if ($action == 'reconcile') { $arrayfields['b.num_releve']['checked'] = 1; @@ -1088,12 +1088,16 @@ if ($resql) { print '
'; print ''."\n"; + // Fields title search + // -------------------------------------------------------------------- print ''; // Actions and select if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { print ''; } if (!empty($arrayfields['b.rowid']['checked'])) { @@ -1171,77 +1175,105 @@ if ($resql) { if (!empty($arrayfields['b.fk_bordereau']['checked'])) { print ''; } + // Action edit/delete and select + print ''; // Actions and select if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { print ''; } print "\n"; + $totalarray = array(); + $totalarray['nbfield'] = 0; + // Fields title print ''; // Actions and select if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { - print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch center '); + print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; + $totalarray['nbfield']++; } if (!empty($arrayfields['b.rowid']['checked'])) { print_liste_field_titre($arrayfields['b.rowid']['label'], $_SERVER['PHP_SELF'], 'b.rowid', '', $param, '', $sortfield, $sortorder); + $totalarray['nbfield']++; } if (!empty($arrayfields['b.label']['checked'])) { print_liste_field_titre($arrayfields['b.label']['label'], $_SERVER['PHP_SELF'], 'b.label', '', $param, '', $sortfield, $sortorder); + $totalarray['nbfield']++; } if (!empty($arrayfields['b.dateo']['checked'])) { print_liste_field_titre($arrayfields['b.dateo']['label'], $_SERVER['PHP_SELF'], 'b.dateo', '', $param, '', $sortfield, $sortorder, "center "); + $totalarray['nbfield']++; } if (!empty($arrayfields['b.datev']['checked'])) { print_liste_field_titre($arrayfields['b.datev']['label'], $_SERVER['PHP_SELF'], 'b.datev,b.dateo,b.rowid', '', $param, '', $sortfield, $sortorder, 'center '); + $totalarray['nbfield']++; } if (!empty($arrayfields['type']['checked'])) { print_liste_field_titre($arrayfields['type']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, 'center '); + $totalarray['nbfield']++; } if (!empty($arrayfields['b.num_chq']['checked'])) { print_liste_field_titre($arrayfields['b.num_chq']['label'], $_SERVER['PHP_SELF'], 'b.num_chq', '', $param, '', $sortfield, $sortorder, "center "); + $totalarray['nbfield']++; } if (!empty($arrayfields['bu.label']['checked'])) { print_liste_field_titre($arrayfields['bu.label']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder); + $totalarray['nbfield']++; } if (!empty($arrayfields['ba.ref']['checked'])) { print_liste_field_titre($arrayfields['ba.ref']['label'], $_SERVER['PHP_SELF'], 'ba.ref', '', $param, '', $sortfield, $sortorder); + $totalarray['nbfield']++; } if (!empty($arrayfields['b.debit']['checked'])) { print_liste_field_titre($arrayfields['b.debit']['label'], $_SERVER['PHP_SELF'], 'b.amount', '', $param, '', $sortfield, $sortorder, "right "); + $totalarray['nbfield']++; } if (!empty($arrayfields['b.credit']['checked'])) { print_liste_field_titre($arrayfields['b.credit']['label'], $_SERVER['PHP_SELF'], 'b.amount', '', $param, '', $sortfield, $sortorder, "right "); + $totalarray['nbfield']++; } if (!empty($arrayfields['balancebefore']['checked'])) { print_liste_field_titre($arrayfields['balancebefore']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, "right "); + $totalarray['nbfield']++; } if (!empty($arrayfields['balance']['checked'])) { print_liste_field_titre($arrayfields['balance']['label'], $_SERVER['PHP_SELF'], '', '', $param, '', $sortfield, $sortorder, "right "); + $totalarray['nbfield']++; } if (!empty($arrayfields['b.num_releve']['checked'])) { print_liste_field_titre($arrayfields['b.num_releve']['label'], $_SERVER['PHP_SELF'], 'b.num_releve', '', $param, '', $sortfield, $sortorder, "center "); + $totalarray['nbfield']++; } if (!empty($arrayfields['b.conciliated']['checked'])) { print_liste_field_titre($arrayfields['b.conciliated']['label'], $_SERVER['PHP_SELF'], 'b.rappro', '', $param, '', $sortfield, $sortorder, "center "); + $totalarray['nbfield']++; } if (!empty($arrayfields['b.fk_bordereau']['checked'])) { print_liste_field_titre($arrayfields['b.fk_bordereau']['label'], $_SERVER['PHP_SELF'], 'b.fk_bordereau', '', $param, '', $sortfield, $sortorder, "center "); + $totalarray['nbfield']++; } // Extra fields include DOL_DOCUMENT_ROOT.'/core/tpl/extrafields_list_search_title.tpl.php'; // Hook fields - $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder); + $parameters = array('arrayfields'=>$arrayfields, 'param'=>$param, 'sortfield'=>$sortfield, 'sortorder'=>$sortorder, 'totalarray'=>&$totalarray); $reshook = $hookmanager->executeHooks('printFieldListTitle', $parameters); // Note that $action and $object may have been modified by hook print $hookmanager->resPrint; + // Action edit/delete and select + print ''; + $totalarray['nbfield']++; // Actions and select if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { + //print getTitleFieldOfList($selectedfields, 0, $_SERVER["PHP_SELF"], '', '', '', '', $sortfield, $sortorder, 'center maxwidthsearch ')."\n"; print_liste_field_titre($selectedfields, $_SERVER["PHP_SELF"], "", '', '', '', $sortfield, $sortorder, 'maxwidthsearch center '); + $totalarray['nbfield']++; } print "\n"; @@ -1251,10 +1283,18 @@ if ($resql) { $posconciliatecol = 0; $cachebankaccount = array(); - // Loop on each record $sign = 1; - while ($i < min($num, $limit)) { + // Loop on each record + $i = 0; + $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); $links = $bankaccountstatic->get_url($objp->rowid); @@ -1364,13 +1404,17 @@ if ($resql) { '; print ''; } + + // conciliate print ''; + // Action column if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { print ''; } + print ''; } } @@ -1411,6 +1455,7 @@ if ($resql) { // Action column if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { + print ''; + if (!$i) { + $totalarray['nbfield']++; + } // Action column if (!getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { + print ''; + print ''; } print "
'; - $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); + $searchpicto = $form->showFilterButtons('left'); print $searchpicto; + //$searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); + //print $searchpicto; print ''; - $searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); + //$searchpicto = $form->showFilterAndCheckAddButtons($massactionbutton ? 1 : 0, 'checkforselect', 1); + //print $searchpicto; + $searchpicto = $form->showFilterButtons(); print $searchpicto; print '
'; print ' '; print '
'; if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; if (in_array($obj->rowid, $arrayofselected)) { @@ -1814,9 +1859,14 @@ if ($resql) { print ''; } } + print ''; if ($massactionbutton || $massaction) { // If we are in select mode (massactionbutton defined) or if we have already selected and sent an action ($massaction) defined $selected = 0; if (in_array($objp->rowid, $arrayofselected)) { @@ -1872,7 +1922,7 @@ if ($resql) { $colspan++; } } - print '
'.$langs->trans("NoRecordFound").'
'.$langs->trans("NoRecordFound").'
"; diff --git a/htdocs/compta/bank/class/account.class.php b/htdocs/compta/bank/class/account.class.php index eb82d04a190..c6ad77c7475 100644 --- a/htdocs/compta/bank/class/account.class.php +++ b/htdocs/compta/bank/class/account.class.php @@ -590,7 +590,7 @@ class Account extends CommonObject // Check parameters if (!$oper) { - $this->error = "oper not defined"; + $this->error = "Operation code not defined"; return -1; } if (!$this->id) { @@ -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; @@ -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/class/api_bankaccounts.class.php b/htdocs/compta/bank/class/api_bankaccounts.class.php index a369b2f976e..4be3f7dee2d 100644 --- a/htdocs/compta/bank/class/api_bankaccounts.class.php +++ b/htdocs/compta/bank/class/api_bankaccounts.class.php @@ -158,6 +158,12 @@ class BankAccounts extends DolibarrApi $account = new Account($this->db); foreach ($request_data as $field => $value) { + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $account->context['caller'] = $request_data['caller']; + continue; + } + $account->$field = $this->_checkValForAPI($field, $value, $account); } // Date of the initial balance (required to create an account). @@ -333,6 +339,12 @@ class BankAccounts extends DolibarrApi if ($field == 'id') { continue; } + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $account->context['caller'] = $request_data['caller']; + continue; + } + $account->$field = $this->_checkValForAPI($field, $value, $account); } diff --git a/htdocs/compta/bank/line.php b/htdocs/compta/bank/line.php index cda42de38d3..449866b5e74 100644 --- a/htdocs/compta/bank/line.php +++ b/htdocs/compta/bank/line.php @@ -258,25 +258,38 @@ if ($user->hasRight('banque', 'consolidate') && ($action == 'num_releve' || $act } $sql .= " WHERE rowid = ".((int) $rowid); - dol_syslog("line.php", LOG_DEBUG); + $updatePathFile = true; + $update_dir = true; + + dol_syslog("line.php update bank line to set the new bank receipt nuber", LOG_DEBUG); + $result = $db->query($sql); + + // We must not rename the directory of the bank receipt when we change 1 line of bank receipt. Other lines may share the same old ref. + // Renaming can be done when we rename globaly a bank receipt but not when changing 1 line from one receipt into another one. + /* if ($result) { - $oldfilepath = dol_sanitizePathName("bank/".((int) $id)."/statement/".$oldNum_rel); - $filepath = dol_sanitizePathName("bank/".((int) $id)."/statement/".$num_rel); + if ($oldNum_rel) { + if ($num_rel) { + $oldfilepath = dol_sanitizePathName("bank/".((int) $id)."/statement/".$oldNum_rel); + $filepath = dol_sanitizePathName("bank/".((int) $id)."/statement/".$num_rel); - $sql = "UPDATE ".MAIN_DB_PREFIX."ecm_files"; - $sql .= " SET filepath = '".$db->escape($filepath)."'"; - $sql .= " WHERE filepath = '".$db->escape($oldfilepath)."'"; - $updatePathFile = $db->query($sql); + $sql = "UPDATE ".MAIN_DB_PREFIX."ecm_files"; + $sql .= " SET filepath = '".$db->escape($filepath)."'"; + $sql .= " WHERE filepath = '".$db->escape($oldfilepath)."'"; + $updatePathFile = $db->query($sql); - $srcdir = dol_sanitizePathName(DOL_DATA_ROOT."/bank/".((int) $id)."/statement/".$oldNum_rel); - $destdir = dol_sanitizePathName(DOL_DATA_ROOT."/bank/".((int) $id)."/statement/".$num_rel); + $srcdir = dol_sanitizePathName(DOL_DATA_ROOT."/bank/".((int) $id)."/statement/".$oldNum_rel); + $destdir = dol_sanitizePathName(DOL_DATA_ROOT."/bank/".((int) $id)."/statement/".$num_rel); - $update_dir = true; - if (dol_is_dir($srcdir)) { - $update_dir = dol_move_dir($srcdir, $destdir, 1); + if (dol_is_dir($srcdir)) { + $update_dir = dol_move_dir($srcdir, $destdir, 1); + } + } } } + */ + if ($result && $updatePathFile && $update_dir) { setEventMessages($langs->trans("RecordSaved"), null, 'mesgs'); $db->commit(); diff --git a/htdocs/compta/cashcontrol/cashcontrol_card.php b/htdocs/compta/cashcontrol/cashcontrol_card.php index c9f4809998c..479f09dabde 100644 --- a/htdocs/compta/cashcontrol/cashcontrol_card.php +++ b/htdocs/compta/cashcontrol/cashcontrol_card.php @@ -416,7 +416,7 @@ if ($action == "create" || $action == "start" || $action == 'close') { print ''; $array = array(); - $numterminals = max(1, $conf->global->TAKEPOS_NUM_TERMINALS); + $numterminals = max(1, getDolGlobalString('TAKEPOS_NUM_TERMINALS')); for ($i = 1; $i <= $numterminals; $i++) { $array[$i] = $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/charges/index.php b/htdocs/compta/charges/index.php index 15106aaffc7..d568b0965c7 100644 --- a/htdocs/compta/charges/index.php +++ b/htdocs/compta/charges/index.php @@ -184,10 +184,11 @@ if (isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) { $resql = $db->query($sql); if ($resql) { $num = $db->num_rows($resql); - $i = 0; + $total = 0; $totalpaid = 0; + $i = 0; while ($i < min($num, $limit)) { $obj = $db->fetch_object($resql); @@ -251,15 +252,22 @@ if (isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) { $totalpaid = $totalpaid + $obj->totalpaid; $i++; } - print ''.$langs->trans("Total").''; - print ''; // A total here has no sense - print ' '; - print ' '; - print ' '; + print ''; + + print ''.$langs->trans("Total").''; + + // Total here has no sens because we can have several time the same line + //print ''.price($total).''; + print ''; + + print ' '; + print ' '; + print ' '; if (isModEnabled("banque")) { - print ''; + print ''; } print ''.price($totalpaid).""; + print ""; } else { dol_print_error($db); @@ -279,7 +287,7 @@ if (isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) { $sql .= " pct.code as payment_code,"; $sql .= " ba.rowid as bid, ba.ref as bref, ba.number as bnumber, ba.account_number, ba.fk_accountancy_journal, ba.label as blabel"; $sql .= " FROM ".MAIN_DB_PREFIX."tva as pv"; - $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_vat as ptva ON (ptva.fk_tva = pv.rowid)"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."payment_vat as ptva ON ptva.fk_tva = pv.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank as b ON (ptva.fk_bank = b.rowid)"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."bank_account as ba ON b.fk_account = ba.rowid"; $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_paiement as pct ON ptva.fk_typepaiement = pct.id"; @@ -296,8 +304,11 @@ if (isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) { $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); + $i = 0; $total = 0; + $totaltopay = 0; + print ''; print ''; print_liste_field_titre("PeriodEndDate", $_SERVER["PHP_SELF"], "pv.datev", "", $param, '', $sortfield, $sortorder, 'nowraponall '); @@ -311,14 +322,16 @@ if (isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) { } print_liste_field_titre("PayedByThisPayment", $_SERVER["PHP_SELF"], "ptva.amount", "", $param, 'class="right"', $sortfield, $sortorder); print "\n"; - $var = 1; + while ($i < $num) { $obj = $db->fetch_object($result); + $totaltopay = $totaltopay + $obj->amount_tva; $total = $total + $obj->amount; print ''; + print ''."\n"; $tva_static->id = $obj->id_tva; @@ -330,7 +343,7 @@ if (isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) { // Ref payment $ptva_static->id = $obj->rowid; $ptva_static->ref = $obj->rowid; - print '\n"; + print '\n"; // Date print '\n"; @@ -367,16 +380,28 @@ if (isModEnabled('tax') && $user->hasRight('tax', 'charges', 'lire')) { $i++; } - print ''; - print ''; - print ''; - print ''; - print ''; - print ''; - print '"; + print ''; + + print ''; + + // Total here has no sens because we can have several time the same line + //print ''; + print ''; + + print ''; + print ''; + print ''; + + if (isModEnabled("banque")) { + print ''; + } + + print '"; + print ""; print "
'.dol_print_date($db->jdate($obj->dm), 'day').''.$ptva_static->getNomUrl(1)."'.$ptva_static->getNomUrl(1)."'.dol_print_date($db->jdate($obj->date_payment), 'day')."
'.$langs->trans("Total").'     '.price($total)."
'.$langs->trans("Total").''.price($totaltopay).' '.price($total)."
"; + $db->free($result); } else { dol_print_error($db); diff --git a/htdocs/compta/deplacement/stats/index.php b/htdocs/compta/deplacement/stats/index.php index 4e41cfb8a26..381baabadae 100644 --- a/htdocs/compta/deplacement/stats/index.php +++ b/htdocs/compta/deplacement/stats/index.php @@ -64,7 +64,7 @@ if ($userid > 0) { $nowyear = dol_print_date(dol_now('gmt'), "%Y", 'gmt'); $year = GETPOST('year') > 0 ? GETPOST('year') : $nowyear; -$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, $conf->global->MAIN_STATS_GRAPHS_SHOW_N_YEARS))); +$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS')))); $endyear = $year; $mode = GETPOST("mode") ? GETPOST("mode") : 'customer'; diff --git a/htdocs/compta/facture/card.php b/htdocs/compta/facture/card.php index cdf811dd5c3..b819569d041 100644 --- a/htdocs/compta/facture/card.php +++ b/htdocs/compta/facture/card.php @@ -165,7 +165,7 @@ $permissiontoadd = $usercancreate; // Used by the include of actions_addupdatede // retained warranty invoice available type $retainedWarrantyInvoiceAvailableType = array(); if (getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')) { - $retainedWarrantyInvoiceAvailableType = explode('+', $conf->global->INVOICE_USE_RETAINED_WARRANTY); + $retainedWarrantyInvoiceAvailableType = explode('+', getDolGlobalString('INVOICE_USE_RETAINED_WARRANTY')); } // Security check @@ -1684,7 +1684,7 @@ if (empty($reshook)) { if (!isset($conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE)) { $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE = '5'; } - if ($srcobject->element == 'contrat' && in_array($lines[$i]->statut, explode(',', $conf->global->CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE))) { + if ($srcobject->element == 'contrat' && in_array($lines[$i]->statut, explode(',', getDolGlobalString('CONTRACT_EXCLUDE_SERVICES_STATUS_FOR_INVOICE')))) { continue; } diff --git a/htdocs/compta/facture/class/api_invoices.class.php b/htdocs/compta/facture/class/api_invoices.class.php index 54ff8d6621e..94de562a3c2 100644 --- a/htdocs/compta/facture/class/api_invoices.class.php +++ b/htdocs/compta/facture/class/api_invoices.class.php @@ -302,6 +302,12 @@ class Invoices extends DolibarrApi $result = $this->_validate($request_data); foreach ($request_data as $field => $value) { + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->invoice->context['caller'] = $request_data['caller']; + continue; + } + $this->invoice->$field = $value; } if (!array_key_exists('date', $request_data)) { @@ -623,6 +629,12 @@ class Invoices extends DolibarrApi if ($field == 'id') { continue; } + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->invoice->context['caller'] = $request_data['caller']; + continue; + } + $this->invoice->$field = $value; } @@ -1422,10 +1434,10 @@ class Invoices extends DolibarrApi // Clean parameters amount if payment is for a credit note if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { $resteapayer = price2num($resteapayer, 'MT'); - $amounts[$id] = -$resteapayer; + $amounts[$id] = price2num(-1 * $resteapayer, 'MT'); // Multicurrency $newvalue = price2num($this->invoice->multicurrency_total_ttc, 'MT'); - $multicurrency_amounts[$id] = -$newvalue; + $multicurrency_amounts[$id] = price2num(-1 * $newvalue, 'MT'); } else { $resteapayer = price2num($resteapayer, 'MT'); $amounts[$id] = $resteapayer; @@ -1568,7 +1580,7 @@ class Invoices extends DolibarrApi } if ($this->invoice->type == Facture::TYPE_CREDIT_NOTE) { - $amount = -$amount; + $amount = price2num(-1 * $amount, 'MT'); } if ($is_multicurrency) { diff --git a/htdocs/compta/facture/class/facture.class.php b/htdocs/compta/facture/class/facture.class.php index 9bc9d68220f..b277db0da53 100644 --- a/htdocs/compta/facture/class/facture.class.php +++ b/htdocs/compta/facture/class/facture.class.php @@ -181,8 +181,6 @@ class Facture extends CommonInvoice public $fk_facture_source; public $linked_objects = array(); - public $date_lim_reglement; - /** * @var int ID Field to store bank id to use when payment mode is withdraw */ @@ -5534,7 +5532,7 @@ class Facture extends CommonInvoice } if ($rounding < 0) { - $rounding = min($conf->global->MAIN_MAX_DECIMALS_UNIT, $conf->global->MAIN_MAX_DECIMALS_TOT); + $rounding = min(getDolGlobalString('MAIN_MAX_DECIMALS_UNIT'), $conf->global->MAIN_MAX_DECIMALS_TOT); } if ($rounding > 0) { 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 e3e7a952a6c..f66b13dca46 100644 --- a/htdocs/compta/facture/list.php +++ b/htdocs/compta/facture/list.php @@ -214,7 +214,7 @@ $arrayfields = array( 'f.subtype'=>array('label'=>"InvoiceSubtype", 'checked'=>0, 'position'=>17), 'f.date_lim_reglement'=>array('label'=>"DateDue", 'checked'=>1, 'position'=>25), 'f.date_closing'=>array('label'=>"DateClosing", 'checked'=>0, 'position'=>30), - 'p.ref'=>array('label'=>"ProjectRef", 'checked'=>1, 'enabled'=>(!isModEnabled('project') ? 0 : 1), 'position'=>40), + 'p.ref'=>array('label'=>"ProjectRef", 'langs'=>'projects', 'checked'=>1, 'enabled'=>(!isModEnabled('project') ? 0 : 1), 'position'=>40), 'p.title'=>array('label'=>"ProjectLabel", 'checked'=>0, 'enabled'=>(!isModEnabled('project') ? 0 : 1), 'position'=>41), 's.nom'=>array('label'=>"ThirdParty", 'checked'=>1, 'position'=>50), 's.name_alias'=>array('label'=>"AliasNameShort", 'checked'=>1, 'position'=>51), @@ -910,38 +910,6 @@ $parameters = array(); $reshook = $hookmanager->executeHooks('printFieldListWhere', $parameters, $object, $action); // Note that $action and $object may have been modified by hook $sql .= $hookmanager->resPrint; -// We disable this. It create a bug when searching with sall and sorting on status. Also it create performance troubles. -/* -if (!$sall) { - $sql .= ' GROUP BY f.rowid, f.ref, ref_client, f.fk_soc, f.type, f.note_private, f.note_public, f.increment, f.fk_mode_reglement, f.fk_cond_reglement, f.total_ht, f.total_tva, f.total_ttc,'; - $sql .= ' f.localtax1, f.localtax2,'; - $sql .= ' f.datef, f.date_valid, f.date_lim_reglement, f.module_source, f.pos_source,'; - $sql .= ' f.paye, f.fk_statut, f.close_code,'; - $sql .= ' f.datec, f.tms, f.date_closing,'; - $sql .= ' f.retained_warranty, f.retained_warranty_date_limit, f.situation_final, f.situation_cycle_ref, f.situation_counter,'; - $sql .= ' f.fk_user_author, f.fk_multicurrency, f.multicurrency_code, f.multicurrency_tx, f.multicurrency_total_ht,'; - $sql .= ' f.multicurrency_total_tva, f.multicurrency_total_ttc,'; - $sql .= ' s.rowid, s.nom, s.name_alias, s.email, s.phone, s.fax, s.address, s.town, s.zip, s.fk_pays, s.client, s.fournisseur, s.code_client, s.code_fournisseur, s.code_compta, s.code_compta_fournisseur,'; - $sql .= ' typent.code,'; - $sql .= ' state.code_departement, state.nom,'; - $sql .= ' country.code,'; - $sql .= " p.rowid, p.ref, p.title,"; - $sql .= " u.login, u.lastname, u.firstname, u.email, u.statut, u.entity, u.photo, u.office_phone, u.office_fax, u.user_mobile, u.job, u.gender"; - if ($search_categ_cus && $search_categ_cus != -1) { - $sql .= ", cc.fk_categorie, cc.fk_soc"; - } - // Add fields from extrafields - if (!empty($extrafields->attributes[$object->table_element]['label'])) { - foreach ($extrafields->attributes[$object->table_element]['label'] as $key => $val) { - $sql .= ($extrafields->attributes[$object->table_element]['type'][$key] != 'separate' ? ", ef.".$key : ''); - } - } - // Add GroupBy from hooks - $parameters = array('all' => !empty($all) ? $all : 0, 'fieldstosearchall' => $fieldstosearchall); - $reshook = $hookmanager->executeHooks('printFieldListGroupBy', $parameters, $object); // Note that $action and $object may have been modified by hook - $sql .= $hookmanager->resPrint; -} else { -*/ if ($sall) { $sql .= natural_search(array_keys($fieldstosearchall), $sall); } @@ -957,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); @@ -1708,6 +1677,7 @@ if (!empty($arrayfields['f.date_lim_reglement']['checked'])) { $totalarray['nbfield']++; } if (!empty($arrayfields['p.ref']['checked'])) { + $langs->load("projects"); print_liste_field_titre($arrayfields['p.ref']['label'], $_SERVER['PHP_SELF'], "p.ref", '', $param, '', $sortfield, $sortorder); $totalarray['nbfield']++; } diff --git a/htdocs/compta/facture/stats/index.php b/htdocs/compta/facture/stats/index.php index a33215086a2..54042ae0ec8 100644 --- a/htdocs/compta/facture/stats/index.php +++ b/htdocs/compta/facture/stats/index.php @@ -66,7 +66,7 @@ if ($user->socid > 0) { $nowyear = dol_print_date(dol_now('gmt'), "%Y", 'gmt'); $year = GETPOST('year') > 0 ? GETPOST('year', 'int') : $nowyear; -$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, $conf->global->MAIN_STATS_GRAPHS_SHOW_N_YEARS))); +$startyear = $year - (!getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS') ? 2 : max(1, min(10, getDolGlobalString('MAIN_STATS_GRAPHS_SHOW_N_YEARS')))); $endyear = $year; 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 4a90dd52b66..49925556725 100644 --- a/htdocs/compta/journal/purchasesjournal.php +++ b/htdocs/compta/journal/purchasesjournal.php @@ -104,7 +104,7 @@ $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '. report_header($name, '', $period, $periodlink, $description, $builddate, $exportlink); -$p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY); +$p = explode(":", getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')); $idpays = $p[0]; @@ -137,7 +137,7 @@ $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); // les variables - $cptfour = (($conf->global->ACCOUNTING_ACCOUNT_SUPPLIER != "") ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : $langs->trans("CodeNotDef")); + $cptfour = ((getDolGlobalString('ACCOUNTING_ACCOUNT_SUPPLIER') != "") ? $conf->global->ACCOUNTING_ACCOUNT_SUPPLIER : $langs->trans("CodeNotDef")); $cpttva = (getDolGlobalString('ACCOUNTING_VAT_BUY_ACCOUNT') ? $conf->global->ACCOUNTING_VAT_BUY_ACCOUNT : $langs->trans("CodeNotDef")); $tabfac = array(); diff --git a/htdocs/compta/journal/sellsjournal.php b/htdocs/compta/journal/sellsjournal.php index 9ffa49798e0..6f76ebfcedb 100644 --- a/htdocs/compta/journal/sellsjournal.php +++ b/htdocs/compta/journal/sellsjournal.php @@ -107,7 +107,7 @@ if (getDolGlobalString('FACTURE_DEPOSITS_ARE_JUST_PAYMENTS')) { $period = $form->selectDate($date_start, 'date_start', 0, 0, 0, '', 1, 0).' - '.$form->selectDate($date_end, 'date_end', 0, 0, 0, '', 1, 0); report_header($name, '', $period, $periodlink, $description, $builddate, $exportlink); -$p = explode(":", $conf->global->MAIN_INFO_SOCIETE_COUNTRY); +$p = explode(":", getDolGlobalString('MAIN_INFO_SOCIETE_COUNTRY')); $idpays = $p[0]; $sql = "SELECT f.rowid, f.ref, f.type, f.datef, f.ref_client,"; @@ -165,7 +165,7 @@ if ($result) { while ($i < $num) { $obj = $db->fetch_object($result); // les variables - $cptcli = (($conf->global->ACCOUNTING_ACCOUNT_CUSTOMER != "") ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef")); + $cptcli = ((getDolGlobalString('ACCOUNTING_ACCOUNT_CUSTOMER') != "") ? $conf->global->ACCOUNTING_ACCOUNT_CUSTOMER : $langs->trans("CodeNotDef")); $compta_soc = (!empty($obj->code_compta) ? $obj->code_compta : $cptcli); $compta_prod = $obj->accountancy_code_sell; if (empty($compta_prod)) { diff --git a/htdocs/compta/localtax/clients.php b/htdocs/compta/localtax/clients.php index d1fe6e7f2b5..fc1dbded732 100644 --- a/htdocs/compta/localtax/clients.php +++ b/htdocs/compta/localtax/clients.php @@ -55,7 +55,7 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $date_start = dol_get_first_day($year_start, GETPOST("month"), false); $date_end = dol_get_last_day($year_start, GETPOST("month"), false); } else { - $date_start = dol_get_first_day($year_start, !getDolGlobalString('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START, false); + $date_start = dol_get_first_day($year_start, !getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START, false); if (!getDolGlobalString('MAIN_INFO_VAT_RETURN') || getDolGlobalInt('MAIN_INFO_VAT_RETURN') == 2) { $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; } elseif (getDolGlobalInt('MAIN_INFO_VAT_RETURN') == 3) { diff --git a/htdocs/compta/localtax/quadri_detail.php b/htdocs/compta/localtax/quadri_detail.php index 49a448b2196..6a508abb5f8 100644 --- a/htdocs/compta/localtax/quadri_detail.php +++ b/htdocs/compta/localtax/quadri_detail.php @@ -65,7 +65,7 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $date_start = dol_get_first_day($year_start, GETPOST("month", "int"), false); $date_end = dol_get_last_day($year_start, GETPOST("month", "int"), false); } else { - $date_start = dol_get_first_day($year_start, !getDolGlobalString('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START, false); + $date_start = dol_get_first_day($year_start, !getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START, false); if (!getDolGlobalString('MAIN_INFO_VAT_RETURN') || getDolGlobalInt('MAIN_INFO_VAT_RETURN') == 2) { $date_end = dol_time_plus_duree($date_start, 3, 'm') - 1; } elseif (getDolGlobalInt('MAIN_INFO_VAT_RETURN') == 3) { diff --git a/htdocs/compta/paiement.php b/htdocs/compta/paiement.php index a5605f59873..32e05251fde 100644 --- a/htdocs/compta/paiement.php +++ b/htdocs/compta/paiement.php @@ -391,7 +391,7 @@ if ($action == 'create' || $action == 'confirm_paiement' || $action == 'add_paie } if ($(\'#fieldchqemetteur\').val() == \'\') { - var emetteur = ('.$facture->type.' == '.Facture::TYPE_CREDIT_NOTE.') ? \''.dol_escape_js(dol_escape_htmltag($conf->global->MAIN_INFO_SOCIETE_NOM)).'\' : jQuery(\'#thirdpartylabel\').val(); + var emetteur = ('.$facture->type.' == '.Facture::TYPE_CREDIT_NOTE.') ? \''.dol_escape_js(dol_escape_htmltag(getDolGlobalString('MAIN_INFO_SOCIETE_NOM'))).'\' : jQuery(\'#thirdpartylabel\').val(); $(\'#fieldchqemetteur\').val(emetteur); } } diff --git a/htdocs/compta/paymentbybanktransfer/index.php b/htdocs/compta/paymentbybanktransfer/index.php index 9a83639b3dd..9ab0d0e0aeb 100644 --- a/htdocs/compta/paymentbybanktransfer/index.php +++ b/htdocs/compta/paymentbybanktransfer/index.php @@ -92,21 +92,23 @@ $totaltoshow = 0; if (isModEnabled('supplier_invoice')) { print ''.$langs->trans("NbOfInvoiceToPayByBankTransfer").''; print ''; - print ''; + $amounttoshow = $bprev->SommeAPrelever('bank-transfer'); + print ''; print $bprev->nbOfInvoiceToPay('bank-transfer'); print ''; print ''; - $totaltoshow += $bprev->SommeAPrelever('bank-transfer'); + $totaltoshow += $amounttoshow; } if (isModEnabled('salaries')) { print ''.$langs->trans("NbOfInvoiceToPayByBankTransferForSalaries").''; print ''; - print ''; + $amounttoshow = $bprev->SommeAPrelever('bank-transfer', 'salary'); + print ''; print $bprev->nbOfInvoiceToPay('bank-transfer', 'salary'); print ''; print ''; - $totaltoshow += $bprev->SommeAPrelever('bank-transfer', 'salary'); + $totaltoshow += $amounttoshow; } print ''.$langs->trans("Total").''; @@ -116,18 +118,15 @@ print '
'; /* - * Invoices waiting for withdraw + * Invoices waiting for credit transfer */ if (isModEnabled('supplier_invoice')) { $sql = "SELECT f.ref, f.rowid, f.total_ttc, f.fk_statut, f.paye, f.type, f.datef, f.date_lim_reglement,"; $sql .= " pfd.date_demande, pfd.amount,"; $sql .= " s.nom as name, s.email, s.rowid as socid, s.tva_intra, s.siren as idprof1, s.siret as idprof2, s.ape as idprof3, s.idprof4, s.idprof5, s.idprof6"; $sql .= " FROM ".MAIN_DB_PREFIX."facture_fourn as f,"; - $sql .= " ".MAIN_DB_PREFIX."societe as s"; - if (!$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= ", ".MAIN_DB_PREFIX."societe_commerciaux as sc"; - } - $sql .= ", ".MAIN_DB_PREFIX."prelevement_demande as pfd"; + $sql .= " ".MAIN_DB_PREFIX."societe as s,"; + $sql .= " ".MAIN_DB_PREFIX."prelevement_demande as pfd"; $sql .= " WHERE s.rowid = f.fk_soc"; $sql .= " AND f.entity IN (".getEntity('supplier_invoice').")"; $sql .= " AND f.total_ttc > 0"; @@ -137,17 +136,10 @@ if (isModEnabled('supplier_invoice')) { $sql .= " AND pfd.traite = 0"; $sql .= " AND pfd.ext_payment_id IS NULL"; $sql .= " AND pfd.fk_facture_fourn = f.rowid"; - if (!$user->hasRight('societe', 'client', 'voir') && !$socid) { - $sql .= " AND s.rowid = sc.fk_soc AND sc.fk_user = ".((int) $user->id); - } if ($socid) { $sql .= " AND f.fk_soc = ".((int) $socid); } - $sqlForSalary = "SELECT * FROM ".MAIN_DB_PREFIX."salary as s, ".MAIN_DB_PREFIX."prelevement_demande as pd"; - $sqlForSalary .= " WHERE s.rowid = pd.fk_salary AND s.paye = 0 AND pd.traite = 0"; - $sqlForSalary .= " AND s.entity IN (".getEntity('salary').")"; - $resql = $db->query($sql); if ($resql) { @@ -219,6 +211,10 @@ if (isModEnabled('supplier_invoice')) { } if (isModEnabled('salaries')) { + $sqlForSalary = "SELECT * FROM ".MAIN_DB_PREFIX."salary as s, ".MAIN_DB_PREFIX."prelevement_demande as pd"; + $sqlForSalary .= " WHERE s.rowid = pd.fk_salary AND s.paye = 0 AND pd.traite = 0"; + $sqlForSalary .= " AND s.entity IN (".getEntity('salary').")"; + $resql2 = $db->query($sqlForSalary); if ($resql2) { $numRow = $db->num_rows($resql2); diff --git a/htdocs/compta/prelevement/card.php b/htdocs/compta/prelevement/card.php index a5e7c3fc17c..04b59c959ce 100644 --- a/htdocs/compta/prelevement/card.php +++ b/htdocs/compta/prelevement/card.php @@ -149,14 +149,14 @@ if (empty($reshook)) { } // Set direct debit order to credited, create payment and close invoices - if ($action == 'infocredit' && $permissiontocreditdebit) { + if ($action == 'setinfocredit' && $permissiontocreditdebit) { $dt = dol_mktime(12, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); if (($object->type != 'bank-transfer' && $object->statut == BonPrelevement::STATUS_CREDITED) || ($object->type == 'bank-transfer' && $object->statut == BonPrelevement::STATUS_DEBITED)) { $error = 1; setEventMessages('WithdrawalCantBeCreditedTwice', array(), 'errors'); } else { - $error = $object->set_infocredit($user, $dt); + $error = $object->set_infocredit($user, $dt, ($salaryBonPl ? 'salary' : '')); } if ($error) { @@ -164,6 +164,14 @@ if (empty($reshook)) { } } + if ($action == 'reopen' && $permissiontocreditdebit) { + $savtype = $object->type; + $res = $object->setStatut(BonPrelevement::STATUS_TRANSFERED); + if ($res <= 0) { + setEventMessages($object->error, $object->errors, 'errors'); + } + } + if ($action == 'confirm_delete' && $permissiontodelete) { $savtype = $object->type; $res = $object->delete($user); @@ -386,11 +394,11 @@ if ($id > 0 || $ref) { print '
'; } - if (!empty($object->date_trans) && empty($object->date_credit) && (($user->hasRight('prelevement', 'bons', 'credit') && $object->type != 'bank-transfer') || ($user->hasRight('paymentbybanktransfer', 'debit') && $object->type == 'bank-transfer')) && $action == 'setcredited') { + if ($object->status == BonPrelevement::STATUS_TRANSFERED && (($user->hasRight('prelevement', 'bons', 'credit') && $object->type != 'bank-transfer') || ($user->hasRight('paymentbybanktransfer', 'debit') && $object->type == 'bank-transfer')) && $action == 'setcredited') { $btnLabel = ($object->type == 'bank-transfer') ? $langs->trans("ClassDebited") : $langs->trans("ClassCredited"); print '
'; print ''; - print ''; + print ''; print ''; print ''; print ''; @@ -417,7 +425,8 @@ if ($id > 0 || $ref) { print dolGetButtonAction($langs->trans("SetToStatusSent"), '', 'default', 'card.php?action=settransmitted&token='.newToken().'&id='.$object->id, '', $user->hasRight('prelevement', 'bons', 'send')); } } - if (!empty($object->date_trans) && empty($object->date_credit)) { + + if ($object->status == BonPrelevement::STATUS_TRANSFERED) { if ($object->type == 'bank-transfer') { print dolGetButtonAction($langs->trans("ClassDebited"), '', 'default', 'card.php?action=setcredited&token='.newToken().'&id='.$object->id, '', $user->hasRight('paymentbybanktransfer', 'debit')); } else { @@ -425,6 +434,16 @@ if ($id > 0 || $ref) { } } + if (getDolGlobalString('BANK_CAN_REOPEN_DIRECT_DEBIT_OR_CREDIT_TRANSFER')) { + if ($object->status == BonPrelevement::STATUS_DEBITED || $object->status == BonPrelevement::STATUS_CREDITED) { + if ($object->type == 'bank-transfer') { + print dolGetButtonAction($langs->trans("ReOpen"), '', 'default', 'card.php?action=reopen&token='.newToken().'&id='.$object->id, '', $user->hasRight('paymentbybanktransfer', 'debit')); + } else { + print dolGetButtonAction($langs->trans("ReOpen"), '', 'default', 'card.php?action=reopen&token='.newToken().'&id='.$object->id, '', $user->hasRight('prelevement', 'bons', 'credit')); + } + } + } + if ($object->type == 'bank-transfer') { print dolGetButtonAction($langs->trans("Delete"), '', 'delete', 'card.php?action=delete&token='.newToken().'&id='.$object->id, '', $user->hasRight('paymentbybanktransfer', 'create')); } else { @@ -437,15 +456,21 @@ if ($id > 0 || $ref) { $ligne = new LignePrelevement($db); - /* - * Lines into withdraw request - */ + // Lines into withdraw request if ($salaryBonPl) { - $sql = "SELECT pl.rowid, pl.statut, pl.amount,pl.fk_user"; - $sql .=" FROM llx_prelevement as p, llx_prelevement_lignes as pl, llx_salary as s"; - $sql .= " WHERE pl.rowid = p.fk_prelevement_lignes"; - $sql .= " AND p.fk_salary = s.rowid"; - $sql .= " AND pl.fk_prelevement_bons = ".((int) $id); + $sql = "SELECT pl.rowid, pl.statut, pl.amount, pl.fk_user,"; + $sql .= " u.rowid as socid, u.login as name"; + $sql .=" FROM llx_prelevement_lignes as pl"; + $sql .= ", ".MAIN_DB_PREFIX."prelevement_bons as pb"; + $sql .= ", ".MAIN_DB_PREFIX."user as u"; + $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $id); + $sql .= " AND pl.fk_prelevement_bons = pb.rowid"; + $sql .= " AND pb.entity = ".((int) $conf->entity); // No sharing of entity here + $sql .= " AND pl.fk_user = u.rowid"; + if ($socid) { + $sql .= " AND u.rowid = ".((int) $socid); + } + $sql .= $db->order($sortfield, $sortorder); } else { $sql = "SELECT pl.rowid, pl.statut, pl.amount,"; $sql .= " s.rowid as socid, s.nom as name"; diff --git a/htdocs/compta/prelevement/class/bonprelevement.class.php b/htdocs/compta/prelevement/class/bonprelevement.class.php index 765431e15b6..6ec256df84f 100644 --- a/htdocs/compta/prelevement/class/bonprelevement.class.php +++ b/htdocs/compta/prelevement/class/bonprelevement.class.php @@ -35,6 +35,7 @@ require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/fournisseur.facture.class.php'; require_once DOL_DOCUMENT_ROOT.'/fourn/class/paiementfourn.class.php'; require_once DOL_DOCUMENT_ROOT.'/salaries/class/salary.class.php'; +require_once DOL_DOCUMENT_ROOT.'/salaries/class/paymentsalary.class.php'; require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; require_once DOL_DOCUMENT_ROOT.'/user/class/userbankaccount.class.php'; @@ -186,8 +187,6 @@ class BonPrelevement extends CommonObject */ public function __construct($db) { - global $conf, $langs; - $this->db = $db; $this->filename = ''; @@ -217,7 +216,7 @@ class BonPrelevement extends CommonObject /** * Add invoice to withdrawal * - * @param int $invoice_id id invoice to add + * @param int $invoice_id ID of invoice to add or ID of salary to add * @param int $client_id id invoice customer * @param string $client_nom customer name * @param int $amount amount of invoice @@ -226,7 +225,7 @@ class BonPrelevement extends CommonObject * @param string $number bank account number * @param string $number_key number key of account number * @param string $type 'debit-order' or 'bank-transfer' - * @param string $sourcetype 'salary' for invoice of salary + * @param string $sourcetype 'salary' for salary, '' for invoices * @return int >0 if OK, <0 if KO */ public function AddFacture($invoice_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key, $type = 'debit-order', $sourcetype = '') @@ -235,7 +234,7 @@ class BonPrelevement extends CommonObject $result = 0; $line_id = 0; - // Add lines + // Add lines into prelevement_lignes $result = $this->addline($line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key, $sourcetype); @@ -245,7 +244,7 @@ class BonPrelevement extends CommonObject if ($type != 'bank-transfer') { $sql .= "fk_facture"; } else { - if (!empty($sourcetype)) { + if ($sourcetype == 'salary') { $sql .= "fk_salary"; } else { $sql .= "fk_facture_fourn"; @@ -280,21 +279,21 @@ class BonPrelevement extends CommonObject /** * Add line to withdrawal * - * @param int $line_id id line to add - * @param int $client_id id invoice customer + * @param int $line_id ID of line added (returned parameter) + * @param int $client_id ID of thirdparty for invoices, ID of user for salaries * @param string $client_nom customer name * @param int $amount amount of invoice * @param string $code_banque code of bank withdrawal * @param string $code_guichet code of bank's office * @param string $number bank account number * @param string $number_key number key of account number - * @param string $sourcetype check if is salary invoice + * @param string $sourcetype 'salary' for salary, '' for invoices * @return int >0 if OK, <0 if KO */ public function addline(&$line_id, $client_id, $client_nom, $amount, $code_banque, $code_guichet, $number, $number_key, $sourcetype = '') { $result = -1; - $concat = 0; + $concat = 0; // ??? what is this for. Seems not used. if ($concat == 1) { /* @@ -303,10 +302,10 @@ class BonPrelevement extends CommonObject $sql = "SELECT rowid"; $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_lignes"; $sql .= " WHERE fk_prelevement_bons = ".((int) $this->id); - if (empty($sourcetype)) { - $sql .= " AND fk_soc =".((int) $client_id); + if ($sourcetype == 'salary') { + $sql .= " AND fk_soc = ".((int) $client_id); } else { - $sql .= " AND fk_user =".((int) $client_id); + $sql .= " AND fk_user = ".((int) $client_id); } $sql .= " AND code_banque = '".$this->db->escape($code_banque)."'"; $sql .= " AND code_guichet = '".$this->db->escape($code_guichet)."'"; @@ -331,17 +330,17 @@ class BonPrelevement extends CommonObject $sql .= ", code_guichet"; $sql .= ", number"; $sql .= ", cle_rib"; - $sql .= (!empty($sourcetype) ? ", fk_user" : ""); + $sql .= ($sourcetype == 'salary' ? ", fk_user" : ""); $sql .= ") VALUES ("; $sql .= $this->id; - $sql .= ", ".(empty($sourcetype) ? ((int) $client_id) : 0); + $sql .= ", ".(($sourcetype != 'salary') ? ((int) $client_id) : "0"); // fk_soc can't be null $sql .= ", '".$this->db->escape($client_nom)."'"; $sql .= ", ".((float) price2num($amount)); $sql .= ", '".$this->db->escape($code_banque)."'"; $sql .= ", '".$this->db->escape($code_guichet)."'"; $sql .= ", '".$this->db->escape($number)."'"; $sql .= ", '".$this->db->escape($number_key)."'"; - $sql .= (!empty($sourcetype) ? ", ". ((int) $client_id) : ''); + $sql .= (($sourcetype == 'salary') ? ", ". ((int) $client_id) : ''); $sql .= ")"; if ($this->db->query($sql)) { $line_id = $this->db->last_insert_id(MAIN_DB_PREFIX."prelevement_lignes"); @@ -451,13 +450,14 @@ class BonPrelevement extends CommonObject // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Set direct debit or credit transfer order to "paid" status. - * Then create the payment for each invoice of the prelemevement_bon. + * Then create the payment for each invoice or salary of the prelemevement_bon. * * @param User $user Id of user * @param int $date date of action + * @param string $type 'salary' for type=salary * @return int >0 if OK, <0 if KO */ - public function set_infocredit($user, $date) + public function set_infocredit($user, $date, $type = '') { // phpcs:enable global $conf, $langs; @@ -475,10 +475,10 @@ class BonPrelevement extends CommonObject $this->db->begin(); $sql = " UPDATE ".MAIN_DB_PREFIX."prelevement_bons"; - $sql .= " SET fk_user_credit = ".$user->id; + $sql .= " SET fk_user_credit = ".((int) $user->id); $sql .= ", statut = ".self::STATUS_CREDITED; $sql .= ", date_credit = '".$this->db->idate($date)."'"; - $sql .= " WHERE rowid=".((int) $this->id); + $sql .= " WHERE rowid = ".((int) $this->id); $sql .= " AND entity = ".((int) $conf->entity); $sql .= " AND statut = ".self::STATUS_TRANSFERED; @@ -498,13 +498,21 @@ class BonPrelevement extends CommonObject $amounts = array(); $amountsperthirdparty = array(); - $facs = $this->getListInvoices(1); + $facs = $this->getListInvoices(1, $type); + if ($this->error) { + $error++; + } - // Loop on each invoice. $facs=array(0=>id, 1=>amount requested) + // Loop on each invoice or salary. + // $facs should be array(0=>id, 1=>amount requested) $num = count($facs); for ($i = 0; $i < $num; $i++) { if ($this->type == 'bank-transfer') { - $fac = new FactureFournisseur($this->db); + if ($type == 'salary') { + $fac = new Salary($this->db); + } else { + $fac = new FactureFournisseur($this->db); + } } else { $fac = new Facture($this->db); } @@ -512,15 +520,34 @@ class BonPrelevement extends CommonObject $result = $fac->fetch($facs[$i][0]); $amounts[$fac->id] = $facs[$i][1]; - $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1]; + if ($this->type == 'bank-transfer') { + if ($type == 'salary') { + $amountsperthirdparty[$fac->fk_user][$fac->id] = $facs[$i][1]; + } else { + $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1]; + } + } else { + $amountsperthirdparty[$fac->socid][$fac->id] = $facs[$i][1]; + } $totalpaid = $fac->getSommePaiement(); - $totalcreditnotes = $fac->getSumCreditNotesUsed(); - $totaldeposits = $fac->getSumDepositsUsed(); + $totalcreditnotes = 0; + if (method_exists($fac, 'getSumCreditNotesUsed')) { + $totalcreditnotes = $fac->getSumCreditNotesUsed(); + } + $totaldeposits = 0; + if (method_exists($fac, 'getSumDepositsUsed')) { + $totaldeposits = $fac->getSumDepositsUsed(); + } $alreadypayed = $totalpaid + $totalcreditnotes + $totaldeposits; - // @TODO Move this after creation of payment - if (price2num($alreadypayed + $facs[$i][1], 'MT') == $fac->total_ttc) { + // Set the main document to pay with status Paid. + // @TODO Move this after creation of payments done after + $amountofdocument = $fac->total_ttc; + if ($type == 'salary') { + $amountofdocument = $fac->amount; + } + if (price2num($alreadypayed + $facs[$i][1], 'MT') == price2num($amountofdocument, 'MT')) { $result = $fac->setPaid($user); if ($result < 0) { $this->error = $fac->error; @@ -528,12 +555,15 @@ class BonPrelevement extends CommonObject } } } - //var_dump($amountsperthirdparty);exit; - // Make one payment per customer + // Make one payment per customer or employee foreach ($amountsperthirdparty as $thirdpartyid => $cursoramounts) { if ($this->type == 'bank-transfer') { - $paiement = new PaiementFourn($this->db); + if ($type == 'salary') { + $paiement = new PaymentSalary($this->db); + } else { + $paiement = new PaiementFourn($this->db); + } } else { $paiement = new Paiement($this->db); } @@ -541,8 +571,16 @@ class BonPrelevement extends CommonObject $paiement->amounts = $cursoramounts; // Array with detail of dispatching of payments for each invoice if ($this->type == 'bank-transfer') { - $paiement->paiementid = 2; - $paiement->paiementcode = 'VIR'; + if ($type == 'salary') { + $paiement->datep = $date; + + $paiement->paiementid = 2; + $paiement->fk_typepayment = 2; + $paiement->paiementcode = 'VIR'; + } else { + $paiement->paiementid = 2; + $paiement->paiementcode = 'VIR'; + } } else { $paiement->paiementid = 3; $paiement->paiementcode = 'PRE'; @@ -551,17 +589,24 @@ class BonPrelevement extends CommonObject $paiement->num_payment = $this->ref; // Set ref of direct debit note $paiement->id_prelevement = $this->id; - $paiement_id = $paiement->create($user); // This use ->paiementid, that is ID of payment mode - if ($paiement_id < 0) { + $result = $paiement->create($user); // This use ->paiementid, that is ID of payment mode + + if ($result < 0) { $error++; $this->error = $paiement->error; $this->errors = $paiement->errors; dol_syslog(get_class($this)."::set_infocredit AddPayment Error ".$this->error); } else { if ($this->type == 'bank-transfer') { - $modeforaddpayment = 'payment_supplier'; - $labelforaddpayment = '(SupplierInvoicePayment)'; - $addbankurl = 'credit-transfer'; + if ($type == 'salary') { + $modeforaddpayment = 'payment_salary'; + $labelforaddpayment = '(SalaryPayment)'; + $addbankurl = 'credit-transfer'; + } else { + $modeforaddpayment = 'payment_supplier'; + $labelforaddpayment = '(SupplierInvoicePayment)'; + $addbankurl = 'credit-transfer'; + } } else { $modeforaddpayment = 'payment'; $labelforaddpayment = '(CustomerInvoicePayment)'; @@ -569,6 +614,7 @@ class BonPrelevement extends CommonObject } $result = $paiement->addPaymentToBank($user, $modeforaddpayment, $labelforaddpayment, $fk_bank_account, '', '', 0, '', $addbankurl); + if ($result < 0) { $error++; $this->error = $paiement->error; @@ -596,12 +642,11 @@ class BonPrelevement extends CommonObject $error++; } - /* - * End of procedure - */ + // End of procedure if ($error == 0) { - $this->date_credit = $date; + $this->date_credit = $date; // date credit or debit $this->statut = self::STATUS_CREDITED; + $this->status = self::STATUS_CREDITED; $this->db->commit(); return 0; @@ -618,9 +663,9 @@ class BonPrelevement extends CommonObject /** * Set withdrawal to transmited status * - * @param User $user id of user - * @param int $date date of action - * @param string $method method of transmision to bank (0=Internet, 1=Api...) + * @param User $user Id of user + * @param int $date Date of action + * @param string $method Method of transmision to bank (0=Internet, 1=Api...) * @return int >0 if OK, <0 if KO */ public function set_infotrans($user, $date, $method) @@ -631,6 +676,7 @@ class BonPrelevement extends CommonObject $error = 0; dol_syslog(get_class($this)."::set_infotrans Start", LOG_INFO); + if ($this->db->begin()) { $sql = "UPDATE ".MAIN_DB_PREFIX."prelevement_bons "; $sql .= " SET fk_user_trans = ".$user->id; @@ -639,7 +685,7 @@ class BonPrelevement extends CommonObject $sql .= " , statut = ".self::STATUS_TRANSFERED; $sql .= " WHERE rowid = ".((int) $this->id); $sql .= " AND entity = ".((int) $conf->entity); - $sql .= " AND statut = 0"; + $sql .= " AND statut = ".self::STATUS_DRAFT; if ($this->db->query($sql)) { $this->method_trans = $method; @@ -655,8 +701,10 @@ class BonPrelevement extends CommonObject if ($error == 0) { $this->date_trans = $date; - $this->statut = 1; + $this->statut = self::STATUS_TRANSFERED; + $this->status = self::STATUS_TRANSFERED; $this->user_trans = $user->id; + $this->db->commit(); return 0; @@ -673,41 +721,50 @@ class BonPrelevement extends CommonObject } /** - * Get invoice list + * Get invoice or salary list (with amount or not) * - * @param int $amounts If you want to get the amount of the order for each invoice - * @return array Id of invoices + * @param int $amounts If you want to get the amount of the order for each invoice or salary + * @param string $type 'salary' for type=salary + * @return array Array(Id of invoices/salary, Amount to pay) */ - private function getListInvoices($amounts = 0) + private function getListInvoices($amounts = 0, $type = '') { global $conf; $arr = array(); - /* - * Returns all invoices presented within same order - */ + dol_syslog(get_class($this)."::getListInvoices"); + + // Returns all invoices presented within same order $sql = "SELECT "; if ($this->type == 'bank-transfer') { - $sql .= " p.fk_facture_fourn"; + if ($type == 'salary') { + $sql .= " p.fk_salary"; + } else { + $sql .= " p.fk_facture_fourn"; + } } else { $sql .= " p.fk_facture"; } if ($amounts) { $sql .= ", SUM(pl.amount)"; } - $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; - $sql .= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; - $sql .= " , ".MAIN_DB_PREFIX."prelevement as p"; + $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as pb,"; + $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,"; + $sql .= " ".MAIN_DB_PREFIX."prelevement as p"; $sql .= " WHERE p.fk_prelevement_lignes = pl.rowid"; - $sql .= " AND pl.fk_prelevement_bons = p.rowid"; - $sql .= " AND p.rowid = ".((int) $this->id); - $sql .= " AND p.entity = ".((int) $conf->entity); + $sql .= " AND pl.fk_prelevement_bons = pb.rowid"; + $sql .= " AND pb.rowid = ".((int) $this->id); + $sql .= " AND pb.entity = ".((int) $conf->entity); if ($amounts) { if ($this->type == 'bank-transfer') { - $sql .= " GROUP BY fk_facture_fourn"; + if ($type == 'salary') { + $sql .= " GROUP BY p.fk_salary"; + } else { + $sql .= " GROUP BY p.fk_facture_fourn"; + } } else { - $sql .= " GROUP BY fk_facture"; + $sql .= " GROUP BY p.fk_facture"; } } @@ -732,7 +789,7 @@ class BonPrelevement extends CommonObject } $this->db->free($resql); } else { - dol_syslog(get_class($this)."::getListInvoices Erreur"); + $this->error = $this->db->lasterror(); } return $arr; @@ -749,8 +806,6 @@ class BonPrelevement extends CommonObject public function SommeAPrelever($mode = 'direct-debit', $type = '') { // phpcs:enable - global $conf; - $sql = "SELECT sum(pd.amount) as nb"; if ($type !== 'salary') { if ($mode != 'bank-transfer') { @@ -817,7 +872,7 @@ class BonPrelevement extends CommonObject * Get number of invoices to pay * * @param string $type 'direct-debit' or 'bank-transfer' - * @param int $forsalary 0= for facture & facture_supplier, 1=for salary + * @param int $forsalary 0= for facture & facture_supplier, 1=for salary * @return int Return integer db->escape($ref)."%'"; @@ -1230,18 +1285,11 @@ class BonPrelevement extends CommonObject } if (!$error) { + dol_syslog(__METHOD__." Now loop on each document to insert them in llx_prelevement_demande"); + // Add lines for the bon if (count($factures_prev) > 0) { foreach ($factures_prev as $fac) { // Add a link in database for each invoice ro salary - // Fetch invoice - /* - $result = $fact->fetch($fac[0]); - if ($result < 0) { - $this->error = 'ERRORBONPRELEVEMENT Failed to load invoice with id '.$fac[0]; - break; - } - */ - /* * Add standing order. This add record into llx_prelevement_lignes and llx_prelevement * @@ -1259,7 +1307,6 @@ class BonPrelevement extends CommonObject * $fac[11] : IBAN * $fac[12] : frstrcur */ - $ri = $this->AddFacture($fac[0], $fac[2], $fac[8], $fac[7], $fac[3], $fac[4], $fac[5], $fac[6], $type, $sourcetype); if ($ri <> 0) { @@ -1799,7 +1846,7 @@ class BonPrelevement extends CommonObject * Section Creditor (sepa Crediteurs bloc lines) */ if (!empty($user_dest)) { - $sql = "SELECT u.rowid as userId, c.code as country_code, CONCAT(u.firstname,' ',u.lastname) as nom,"; + $sql = "SELECT u.rowid as userId, u.address, u.zip, u.town, c.code as country_code, CONCAT(u.firstname,' ',u.lastname) as nom,"; $sql .= " pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,"; $sql .= " s.ref as reffac, p.fk_salary as idfac,"; $sql .= " rib.rowid, rib.datec, rib.iban_prefix as iban, rib.bic as bic, rib.rowid as drum, '' as rum, '' as date_rum"; @@ -1807,15 +1854,14 @@ class BonPrelevement extends CommonObject $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,"; $sql .= " ".MAIN_DB_PREFIX."salary as s,"; $sql .= " ".MAIN_DB_PREFIX."prelevement as p,"; - $sql .= " ".MAIN_DB_PREFIX."c_country as c,"; - $sql .= " ".MAIN_DB_PREFIX."user as u,"; + $sql .= " ".MAIN_DB_PREFIX."user as u"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON u.fk_country = c.rowid,"; $sql .= " ".MAIN_DB_PREFIX."user_rib as rib"; $sql .= " WHERE pl.fk_prelevement_bons=".((int) $this->id); $sql .= " AND pl.rowid = p.fk_prelevement_lignes"; $sql .= " AND p.fk_salary = s.rowid"; $sql .= " AND s.fk_user = u.rowid"; $sql .= " AND rib.fk_user = s.fk_user"; - $sql .= " AND rib.fk_country = c.rowid"; } else { $sql = "SELECT soc.rowid as socid, soc.code_client as code, soc.address, soc.zip, soc.town, c.code as country_code,"; $sql .= " pl.client_nom as nom, pl.code_banque as cb, pl.code_guichet as cg, pl.number as cc, pl.amount as somme,"; @@ -1825,14 +1871,13 @@ class BonPrelevement extends CommonObject $sql .= " ".MAIN_DB_PREFIX."prelevement_lignes as pl,"; $sql .= " ".MAIN_DB_PREFIX."facture_fourn as f,"; $sql .= " ".MAIN_DB_PREFIX."prelevement as p,"; - $sql .= " ".MAIN_DB_PREFIX."societe as soc,"; - $sql .= " ".MAIN_DB_PREFIX."c_country as c,"; + $sql .= " ".MAIN_DB_PREFIX."societe as soc"; + $sql .= " LEFT JOIN ".MAIN_DB_PREFIX."c_country as c ON soc.fk_pays = c.rowid,"; $sql .= " ".MAIN_DB_PREFIX."societe_rib as rib"; $sql .= " WHERE pl.fk_prelevement_bons = ".((int) $this->id); $sql .= " AND pl.rowid = p.fk_prelevement_lignes"; $sql .= " AND p.fk_facture_fourn = f.rowid"; $sql .= " AND f.fk_soc = soc.rowid"; - $sql .= " AND soc.fk_pays = c.rowid"; $sql .= " AND rib.fk_soc = f.fk_soc"; $sql .= " AND rib.default_rib = 1"; $sql .= " AND rib.type = 'ban'"; @@ -1854,8 +1899,12 @@ class BonPrelevement extends CommonObject $cachearraytotestduplicate[$obj->idfac] = $obj->rowid; $daterum = (!empty($obj->date_rum)) ? $this->db->jdate($obj->date_rum) : $this->db->jdate($obj->datec); + $refobj = $obj->reffac; + if (empty($refobj) && !empty($user_dest)) { // If ref of salary not defined, we force a value + $refobj = "SAL".$obj->idfac; + } - $fileCrediteurSection .= $this->EnregDestinataireSEPA($obj->code, $obj->nom, $obj->address, $obj->zip, $obj->town, $obj->country_code, $obj->cb, $obj->cg, $obj->cc, $obj->somme, $obj->reffac, $obj->idfac, $obj->iban, $obj->bic, $daterum, $obj->drum, $obj->rum, $type, $obj->fac_ref_supplier); + $fileCrediteurSection .= $this->EnregDestinataireSEPA($obj->code, $obj->nom, $obj->address, $obj->zip, $obj->town, $obj->country_code, $obj->cb, $obj->cg, $obj->cc, $obj->somme, $refobj, $obj->idfac, $obj->iban, $obj->bic, $daterum, $obj->drum, $obj->rum, $type, $obj->fac_ref_supplier); $this->total = $this->total + $obj->somme; $i++; @@ -2071,6 +2120,7 @@ class BonPrelevement extends CommonObject fputs($this->file, "\n"); } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Write recipient (thirdparty concerned by request) @@ -2120,7 +2170,7 @@ class BonPrelevement extends CommonObject $XML_DEBITOR .= ' '.$CrLf; $XML_DEBITOR .= ' '.$CrLf; // Add EndToEndId. Must be a unique ID for each payment (for example by including bank, buyer or seller, date, checksum) - $XML_DEBITOR .= ' '.(($conf->global->PRELEVEMENT_END_TO_END != "") ? $conf->global->PRELEVEMENT_END_TO_END : ('DD-'.dol_trunc($row_idfac.'-'.$row_ref, 20, 'right', 'UTF-8', 1)).'-'.$Rowing).''.$CrLf; // ISO20022 states that EndToEndId has a MaxLength of 35 characters + $XML_DEBITOR .= ' '.((getDolGlobalString('PRELEVEMENT_END_TO_END') != "") ? $conf->global->PRELEVEMENT_END_TO_END : ('DD-'.dol_trunc($row_idfac.'-'.$row_ref, 20, 'right', 'UTF-8', 1)).'-'.$Rowing).''.$CrLf; // ISO20022 states that EndToEndId has a MaxLength of 35 characters $XML_DEBITOR .= ' '.$CrLf; $XML_DEBITOR .= ' '.round($row_somme, 2).''.$CrLf; $XML_DEBITOR .= ' '.$CrLf; @@ -2166,7 +2216,7 @@ class BonPrelevement extends CommonObject $XML_CREDITOR .= ' '.$CrLf; $XML_CREDITOR .= ' '.$CrLf; // Add EndToEndId. Must be a unique ID for each payment (for example by including bank, buyer or seller, date, checksum) - $XML_CREDITOR .= ' '.(($conf->global->PRELEVEMENT_END_TO_END != "") ? $conf->global->PRELEVEMENT_END_TO_END : ('CT-'.dol_trunc($row_idfac.'-'.$row_ref, 20, 'right', 'UTF-8', 1)).'-'.$Rowing).''.$CrLf; // ISO20022 states that EndToEndId has a MaxLength of 35 characters + $XML_CREDITOR .= ' '.((getDolGlobalString('PRELEVEMENT_END_TO_END') != "") ? $conf->global->PRELEVEMENT_END_TO_END : ('CT-'.dol_trunc($row_idfac.'-'.$row_ref, 20, 'right', 'UTF-8', 1)).'-'.$Rowing).''.$CrLf; // ISO20022 states that EndToEndId has a MaxLength of 35 characters $XML_CREDITOR .= ' '.$CrLf; if (!empty($this->sepa_xml_pti_in_ctti)) { $XML_CREDITOR .= ' ' . $CrLf; @@ -2302,6 +2352,7 @@ class BonPrelevement extends CommonObject fputs($this->file, "\n"); } + // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** * Write sender of request (me). @@ -2623,8 +2674,6 @@ class BonPrelevement extends CommonObject public function load_board($user, $mode) { // phpcs:enable - global $conf, $langs; - if ($user->socid) { return -1; // protection pour eviter appel par utilisateur externe } @@ -2739,7 +2788,7 @@ class BonPrelevement extends CommonObject if ($id) { $sql = "SELECT COUNT(*) AS nb FROM ".MAIN_DB_PREFIX."prelevement_lignes"; $sql .= " WHERE fk_prelevement_bons = ".((int) $id); - $sql .= " AND fk_soc = 0"; + $sql .= " AND fk_soc = 0"; // fk_soc can't be NULL $sql .= " AND fk_user IS NOT NULL"; $num = 0; diff --git a/htdocs/compta/prelevement/class/rejetprelevement.class.php b/htdocs/compta/prelevement/class/rejetprelevement.class.php index 0dbe720d1d1..85b911a4cea 100644 --- a/htdocs/compta/prelevement/class/rejetprelevement.class.php +++ b/htdocs/compta/prelevement/class/rejetprelevement.class.php @@ -97,27 +97,28 @@ class RejetPrelevement } /** - * Create + * Create a reject * * @param User $user User object * @param int $id Id * @param string $motif Motif - * @param int $date_rejet Date rejet + * @param int $date_rejet Date reject * @param int $bonid Bon id - * @param int $facturation Facturation - * @return void + * @param int $facturation 1=Bill the reject + * @return int Return >=0 if OK, <0 if KO */ public function create($user, $id, $motif, $date_rejet, $bonid, $facturation = 0) { - global $langs, $conf; + global $langs; $error = 0; $this->id = $id; $this->bon_id = $bonid; $now = dol_now(); - dol_syslog("RejetPrelevement::Create id $id"); - $bankaccount = ($this->type == 'bank-transfer' ? $conf->global->PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT : $conf->global->PRELEVEMENT_ID_BANKACCOUNT); + dol_syslog("RejetPrelevement::Create id ".$id); + + $bankaccount = ($this->type == 'bank-transfer' ? getDolGlobalString('PAYMENTBYBANKTRANSFER_ID_BANKACCOUNT') : getDolGlobalString('PRELEVEMENT_ID_BANKACCOUNT')); $facs = $this->getListInvoices(1); require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class.php'; @@ -172,30 +173,34 @@ class RejetPrelevement $fac->fetch($facs[$i][0]); - // Make a negative payment - //$pai = new Paiement($this->db); + $amountrejected = $facs[$i][1]; + // Make a negative payment + // Amount must be an array (id of invoice -> amount) $pai->amounts = array(); - /* - * We replace the comma with a point otherwise some - * PHP installs sends only the part integer negative - */ + //var_dump($this->type);exit; + + $pai->amounts[$facs[$i][0]] = price2num($amountrejected * -1); // The payment must be negative because it is a refund - $pai->amounts[$facs[$i][0]] = price2num($facs[$i][1] * ($this->type == 'bank-transfer' ? 1 : -1)); $pai->datepaye = $date_rejet; $pai->paiementid = 3; // type of payment: withdrawal - $pai->num_paiement = $fac->ref; - $pai->num_payment = $fac->ref; + $pai->num_paiement = $langs->trans('Rejection').' '.$fac->ref; + $pai->num_payment = $langs->trans('Rejection').' '.$fac->ref; $pai->id_prelevement = $this->bon_id; $pai->num_prelevement = $lipre->bon_ref; if ($pai->create($this->user) < 0) { - // we call with no_commit $error++; dol_syslog("RejetPrelevement::Create Error creation payment invoice ".$facs[$i][0]); } else { - $result = $pai->addPaymentToBank($user, 'payment', '(InvoiceRefused)', $bankaccount, '', ''); + // We record entry into bank + $mode = 'payment'; + if ($this->type == 'bank-transfer') { + $mode = 'payment_supplier'; + } + + $result = $pai->addPaymentToBank($user, $mode, '(InvoiceRefused)', $bankaccount, '', ''); if ($result < 0) { dol_syslog("RejetPrelevement::Create AddPaymentToBan Error"); $error++; @@ -220,9 +225,13 @@ class RejetPrelevement if ($error == 0) { dol_syslog("RejetPrelevement::Create Commit"); $this->db->commit(); + + return 1; } else { dol_syslog("RejetPrelevement::Create Rollback"); $this->db->rollback(); + + return -1; } } diff --git a/htdocs/compta/prelevement/factures.php b/htdocs/compta/prelevement/factures.php index a1fd08bc7fc..f1d9c22cc19 100644 --- a/htdocs/compta/prelevement/factures.php +++ b/htdocs/compta/prelevement/factures.php @@ -96,6 +96,7 @@ llxHeader('', $langs->trans("WithdrawalsReceipts")); if ($id > 0 || $ref) { if ($object->fetch($id, $ref) >= 0) { $head = prelevement_prepare_head($object); + print dol_get_fiche_head($head, 'invoices', $langs->trans("WithdrawalsReceipts"), -1, 'payment'); $linkback = ''.$langs->trans("BackToList").''; @@ -293,8 +294,9 @@ if ($resql) { print ''; $massactionbutton = ''; + $title = ($salaryBonPl ? $langs->trans("Salaries") : ($object->type == 'bank-transfer' ? $langs->trans("SupplierInvoices") : $langs->trans("Invoices"))); - print_barre_liste(($salaryBonPl ? $langs->trans("Salaries") : $langs->trans("Invoices")), $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit); + print_barre_liste($title, $page, $_SERVER["PHP_SELF"], $param, $sortfield, $sortorder, $massactionbutton, $num, $nbtotalofrecords, '', 0, '', '', $limit); print"\n\n"; print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table @@ -308,7 +310,6 @@ if ($resql) { print_liste_field_titre(($salaryBonPl ? "AmountSalary" : "AmountInvoice"), $_SERVER["PHP_SELF"], "f.total_ttc", "", $param, 'class="right"', $sortfield, $sortorder); print_liste_field_titre("AmountRequested", $_SERVER["PHP_SELF"], "pl.amount", "", $param, 'class="right"', $sortfield, $sortorder); print_liste_field_titre("Status", $_SERVER["PHP_SELF"], "", "", $param, 'align="center"', $sortfield, $sortorder); - print_liste_field_titre(''); print "\n"; $totalinvoices = 0; @@ -340,9 +341,8 @@ if ($resql) { print '
'; - print '\n"; if ($object->type == 'bank-transfer' && !$salaryBonPl) { @@ -376,8 +376,6 @@ if ($resql) { } print ""; - print ""; - print "\n"; $totalinvoices += $obj->total_ttc; @@ -403,7 +401,6 @@ if ($resql) { print price($totalamount_requested); print "\n"; print ''; - print ''; print "\n"; } diff --git a/htdocs/compta/prelevement/line.php b/htdocs/compta/prelevement/line.php index aca3966f7ed..2d21dd6a3a1 100644 --- a/htdocs/compta/prelevement/line.php +++ b/htdocs/compta/prelevement/line.php @@ -85,7 +85,7 @@ $error = 0; if ($action == 'confirm_rejet' && $permissiontoadd) { if (GETPOST("confirm") == 'yes') { if (GETPOST('remonth', 'int')) { - $daterej = mktime(2, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); + $daterej = dol_mktime(0, 0, 0, GETPOST('remonth', 'int'), GETPOST('reday', 'int'), GETPOST('reyear', 'int')); } if (empty($daterej)) { @@ -108,10 +108,12 @@ if ($action == 'confirm_rejet' && $permissiontoadd) { if ($lipre->fetch($id) == 0) { $rej = new RejetPrelevement($db, $user, $type); - $rej->create($user, $id, GETPOST('motif', 'alpha'), $daterej, $lipre->bon_rowid, GETPOST('facturer', 'int')); + $result = $rej->create($user, $id, GETPOST('motif', 'alpha'), $daterej, $lipre->bon_rowid, GETPOST('facturer', 'int')); - header("Location: line.php?id=".urlencode($id).'&type='.urlencode($type)); - exit; + if ($result > 0) { + header("Location: line.php?id=".urlencode($id).'&type='.urlencode($type)); + exit; + } } } else { $action = "rejet"; @@ -202,30 +204,35 @@ if ($id) { dol_print_error($db); } + // Form to record a reject if ($action == 'rejet' && $user->hasRight('prelevement', 'bons', 'credit')) { $soc = new Societe($db); $soc->fetch($lipre->socid); $rej = new RejetPrelevement($db, $user, $type); - print ''; + print ''; print ''; print ''; print ''; + + print '
'; // You can use div-table-responsive-no-min if you dont need reserved height for your table print '
'.$langs->trans("NotifyCredit").'
'; - print($salaryBonPl ? $salarytmp->getNomUrl(1) : $invoicetmp->getNomUrl(1)); + print ($salaryBonPl ? $salarytmp->getNomUrl(1) : $invoicetmp->getNomUrl(1)); print "
  
'; print ''; - print ''; + print ''; + print ''; + print ''; //Select yes/no print ''; - print ''; //Date print ''; - print ''; @@ -236,11 +243,15 @@ if ($id) { print ''; //Facturer - print ''; - print ''; + print ''; - print '
'.$langs->trans("WithdrawalRefused").'
'.$langs->trans("WithdrawalRefused").'
'.$langs->trans("WithdrawalRefusedConfirm").' '.$soc->name.' ?'; + print ''; print $form->selectyesno("confirm", 1, 0); print '
'.$langs->trans("RefusedData").''; + print ''; print $form->selectDate('', '', '', '', '', "confirm_rejet"); print '
'.$langs->trans("RefusedInvoicing").''; - print $form->selectarray("facturer", $rej->labelsofinvoicing, GETPOSTISSET('facturer') ? GETPOST('facturer', 'int') : ''); + print '
'; + print $form->textwithpicto($langs->trans("RefusedInvoicing"), $langs->trans("DirectDebitRefusedInvoicingDesc")); + print ''; + print $form->selectarray("facturer", $rej->labelsofinvoicing, GETPOSTISSET('facturer') ? GETPOST('facturer', 'int') : '', 0); print '

'; + + print ''; + print ''; //Confirm Button print '
'; @@ -274,6 +285,9 @@ if ($id) { $sql = "SELECT pf.rowid"; $sql .= " ,f.rowid as facid, f.ref as ref, f.total_ttc, f.paye, f.fk_statut"; $sql .= " , s.rowid as socid, s.nom as name"; + + $sqlfields = $sql; // $sql fields to remove for count total + $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; $sql .= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; $sql .= " , ".MAIN_DB_PREFIX."prelevement as pf"; @@ -296,6 +310,30 @@ if ($id) { if ($socid) { $sql .= " AND s.rowid = ".((int) $socid); } + + // Count total nb of records + $nbtotalofrecords = ''; + 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); + $nbtotalofrecords = $objforcount->nbtotalofrecords; + } else { + dol_print_error($db); + } + + if (($page * $limit) > $nbtotalofrecords) { // if total resultset is smaller than the paging size (filtering), goto and load page 0 + $page = 0; + $offset = 0; + } + $db->free($resql); + } + + $result = $db->query($sql); + $sql .= $db->order($sortfield, $sortorder); $sql .= $db->plimit($conf->liste_limit + 1, $offset); @@ -306,8 +344,12 @@ if ($id) { $i = 0; $urladd = "&id=".urlencode($id); + $title = $langs->trans("Bills"); + if ($type == 'bank-transfer') { + $title = $langs->trans("SupplierInvoices"); + } - print_barre_liste($langs->trans("Bills"), $page, "factures.php", $urladd, $sortfield, $sortorder, '', $num, 0, ''); + print_barre_liste($title, $page, "factures.php", $urladd, $sortfield, $sortorder, '', $num, $nbtotalofrecords, ''); print"\n\n"; print ''; diff --git a/htdocs/compta/prelevement/rejets.php b/htdocs/compta/prelevement/rejets.php index baed8076f6b..30db9e40c50 100644 --- a/htdocs/compta/prelevement/rejets.php +++ b/htdocs/compta/prelevement/rejets.php @@ -31,6 +31,8 @@ require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/ligneprelevement.class require_once DOL_DOCUMENT_ROOT.'/compta/paiement/class/paiement.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/bank/class/account.class.php'; require_once DOL_DOCUMENT_ROOT.'/compta/prelevement/class/bonprelevement.class.php'; +require_once DOL_DOCUMENT_ROOT.'/societe/class/societe.class.php'; +require_once DOL_DOCUMENT_ROOT.'/user/class/user.class.php'; // Load translation files required by the page $langs->loadLangs(array('banks', 'categories', 'withdrawals', 'companies')); @@ -83,14 +85,16 @@ if ($sortfield == "") { $rej = new RejetPrelevement($db, $user, $type); $line = new LignePrelevement($db); +$thirdpartystatic = new Societe($db); +$userstatic = new User($db); $hookmanager->initHooks(array('withdrawalsreceiptsrejectedlist')); // List of invoices -$sql = "SELECT pl.rowid, pr.motif, p.ref, pl.statut, p.rowid as bonId"; -$sql .= " , s.rowid as socid, s.nom as name, p.datec"; +$sql = "SELECT pl.rowid, pr.motif, p.ref, pl.statut, p.rowid as bonId,"; +$sql .= " s.rowid as socid, s.nom as name, p.datec"; $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; $sql .= " , ".MAIN_DB_PREFIX."prelevement_rejet as pr"; $sql .= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; @@ -98,19 +102,20 @@ $sql .= " , ".MAIN_DB_PREFIX."societe as s"; $sql .= " WHERE pr.fk_prelevement_lignes = pl.rowid"; $sql .= " AND pl.fk_prelevement_bons = p.rowid"; $sql .= " AND pl.fk_soc = s.rowid"; -$sql .= " AND p.entity = ".$conf->entity; +$sql .= " AND p.entity = ".((int) $conf->entity); if ($type == 'bank-transfer') { $sql .= " AND p.type = 'bank-transfer'"; } else { $sql .= " AND p.type = 'debit-order'"; } -if ($socid) { +if ($socid > 0) { $sql .= " AND s.rowid = ".((int) $socid); } +// Add list for salaries if ($type == 'bank-transfer') { $sql .= " UNION"; - $sql .= " SELECT pl.rowid, pr.motif, p.ref, pl.statut, p.rowid as bonId"; - $sql .= " ,u.rowid as socid, CONCAT(u.firstname,' ', u.lastname) as name, p.datec"; + $sql .= " SELECT pl.rowid, pr.motif, p.ref, pl.statut, p.rowid as bonId,"; + $sql .= " u.rowid as socid, CONCAT(u.firstname,' ', u.lastname) as name, p.datec"; $sql .= " FROM ".MAIN_DB_PREFIX."prelevement_bons as p"; $sql .= " , ".MAIN_DB_PREFIX."prelevement_rejet as pr"; $sql .= " , ".MAIN_DB_PREFIX."prelevement_lignes as pl"; @@ -118,7 +123,7 @@ if ($type == 'bank-transfer') { $sql .= " WHERE pr.fk_prelevement_lignes = pl.rowid"; $sql .= " AND pl.fk_prelevement_bons = p.rowid"; $sql .= " AND pl.fk_user = u.rowid"; - $sql .= " AND p.entity = ".$conf->entity; + $sql .= " AND p.entity = ".((int) $conf->entity); $sql .= " AND p.type = 'bank-transfer'"; if ($socid) { $sql .= " AND s.rowid = ".((int) $socid); @@ -129,10 +134,10 @@ if ($type == 'bank-transfer') { } $sql .= $db->order($sortfield, $sortorder); $sql .= $db->plimit($limit + 1, $offset); + $result = $db->query($sql); if ($result) { $num = $db->num_rows($result); - $i = 0; $param = ''; @@ -147,7 +152,9 @@ if ($result) { $bon = new BonPrelevement($db); if ($num) { - while ($i < min($num, $limit)) { + $i = 0; + $maxlim = min($num, $limit); + while ($i < $maxlim) { $obj = $db->fetch_object($result); $bon->fetch($obj->bonId); @@ -157,10 +164,14 @@ if ($result) { print $line->LibStatut($obj->statut, 2).' '; print ''; print substr('000000'.$obj->rowid, -6).""; + if ($bon->checkIfSalaryBonPrelevement()) { - print '\n"; + print '\n"; } else { - print '\n"; + $thirdpartystatic->id = $obj->socid; + $thirdpartystatic->name = $obj->name; + + print '\n"; } print ''; diff --git a/htdocs/compta/resultat/result.php b/htdocs/compta/resultat/result.php index eb71104e0e3..310230c6e30 100644 --- a/htdocs/compta/resultat/result.php +++ b/htdocs/compta/resultat/result.php @@ -79,7 +79,7 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e if ($q == 0) { // We define date_start and date_end $year_end = $year_start + ($nbofyear - 1); - $month_start = GETPOST("month", 'int') ? GETPOST("month", 'int') : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = GETPOST("month", 'int') ? GETPOST("month", 'int') : getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); $date_startmonth = $month_start; if (!GETPOST('month')) { if (!$year && $month_start > $month_current) { diff --git a/htdocs/compta/stats/byratecountry.php b/htdocs/compta/stats/byratecountry.php index 1970440e9ad..dced36d44a6 100644 --- a/htdocs/compta/stats/byratecountry.php +++ b/htdocs/compta/stats/byratecountry.php @@ -63,7 +63,7 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $q = GETPOST("q", "int"); if (empty($q)) { // We define date_start and date_end - $month_start = GETPOST("month") ? GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = GETPOST("month") ? GETPOST("month") : getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); $year_end = $year_start; $month_end = $month_start; if (!GETPOST("month")) { // If month not forced @@ -300,7 +300,7 @@ if ($modecompta == 'CREANCES-DETTES') { print ''; $i = 0; while ($i < 12) { - $j = $i + (!getDolGlobalString('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); + $j = $i + (!getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); if ($j > 12) { $j -= 12; } @@ -350,7 +350,7 @@ if ($modecompta == 'CREANCES-DETTES') { print $langs->trans("Country".$obj->code) != "Country".$obj->code ? $langs->trans("Country".$obj->code) : $obj->country; print ''; for ($i = 0; $i < 12; $i++) { - $j = $i + (!getDolGlobalString('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); + $j = $i + (!getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); if ($j > 12) { $j -= 12; } @@ -369,14 +369,14 @@ if ($modecompta == 'CREANCES-DETTES') { print ''; print ''; for ($i = 0; $i < 12; $i++) { - $j = $i + (!getDolGlobalString('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); + $j = $i + (!getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); if ($j > 12) { $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 @@ -387,7 +387,7 @@ if ($modecompta == 'CREANCES-DETTES') { print ''; $i = 0; while ($i < 12) { - $j = $i + (!getDolGlobalString('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); + $j = $i + (!getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); if ($j > 12) { $j -= 12; } @@ -437,7 +437,7 @@ if ($modecompta == 'CREANCES-DETTES') { print $langs->trans("Country".$obj->code) != "Country".$obj->code ? $langs->trans("Country".$obj->code) : $obj->country; print ''; for ($i = 0; $i < 12; $i++) { - $j = $i + (!getDolGlobalString('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); + $j = $i + (!getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); if ($j > 12) { $j -= 12; } @@ -456,7 +456,7 @@ if ($modecompta == 'CREANCES-DETTES') { print ''; print ''; for ($i = 0; $i < 12; $i++) { - $j = $i + (!getDolGlobalString('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); + $j = $i + (!getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') ? 1 : $conf->global->SOCIETE_FISCAL_MONTH_START); if ($j > 12) { $j -= 12; } diff --git a/htdocs/compta/stats/cabyprodserv.php b/htdocs/compta/stats/cabyprodserv.php index 2c706827ca9..b0e9b529d5d 100644 --- a/htdocs/compta/stats/cabyprodserv.php +++ b/htdocs/compta/stats/cabyprodserv.php @@ -106,7 +106,7 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $q = GETPOST("q", "int"); if (empty($q)) { // We define date_start and date_end - $month_start = GETPOST("month") ? GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = GETPOST("month") ? GETPOST("month") : getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); $year_end = $year_start; $month_end = $month_start; if (!GETPOST("month")) { // If month not forced diff --git a/htdocs/compta/stats/cabyuser.php b/htdocs/compta/stats/cabyuser.php index ab9728491cd..2456623f95a 100644 --- a/htdocs/compta/stats/cabyuser.php +++ b/htdocs/compta/stats/cabyuser.php @@ -87,7 +87,7 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $q = GETPOST("q") ? GETPOST("q") : 0; if ($q == 0) { // We define date_start and date_end - $month_start = GETPOST("month") ? GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = GETPOST("month") ? GETPOST("month") : getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); $year_end = $year_start; $month_end = $month_start; if (!GETPOST("month")) { // If month not forced diff --git a/htdocs/compta/stats/casoc.php b/htdocs/compta/stats/casoc.php index e2a9cb632b0..006840cdf0f 100644 --- a/htdocs/compta/stats/casoc.php +++ b/htdocs/compta/stats/casoc.php @@ -110,7 +110,7 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $q = GETPOST("q", "int") ? GETPOST("q", "int") : 0; if (empty($q)) { // We define date_start and date_end - $month_start = GETPOST("month") ? GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = GETPOST("month") ? GETPOST("month") : getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); $year_end = $year_start; $month_end = $month_start; if (!GETPOST("month")) { // If month not forced diff --git a/htdocs/compta/stats/index.php b/htdocs/compta/stats/index.php index 902ded12bba..7b5b23f726f 100644 --- a/htdocs/compta/stats/index.php +++ b/htdocs/compta/stats/index.php @@ -383,7 +383,7 @@ $now = dol_now(); $casenow = dol_print_date($now, "%Y-%m"); // Loop on each month -$nb_mois_decalage = GETPOSTISSET('date_startmonth') ? (GETPOST('date_startmonth', 'int') - 1) : (!getDolGlobalString('SOCIETE_FISCAL_MONTH_START') ? 0 : ($conf->global->SOCIETE_FISCAL_MONTH_START - 1)); +$nb_mois_decalage = GETPOSTISSET('date_startmonth') ? (GETPOST('date_startmonth', 'int') - 1) : (!getDolGlobalInt('SOCIETE_FISCAL_MONTH_START') ? 0 : ($conf->global->SOCIETE_FISCAL_MONTH_START - 1)); for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++) { $mois_modulo = $mois; // ajout if ($mois > 12) { @@ -419,7 +419,7 @@ for ($mois = 1 + $nb_mois_decalage; $mois <= 12 + $nb_mois_decalage; $mois++) { // Value turnover of month w/o VAT print '", 3); + $buffer .= '
'.$obj->nom."'.$obj->name."'.$obj->nom."'.$thirdpartystatic->getNomUrl(1)."'.$rej->motifs[$obj->motif].''.$langs->trans("Country").''.price($totalpermonth[$j]).''.price((empty($totalpermonth[$j]) ? 0 : $totalpermonth[$j])).''.price($totalpermonth['total']).''.price((empty($totalpermonth['total']) ? 0 : $totalpermonth['total'])).'
'.$langs->trans("Country").''; 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_by_prodserv.php b/htdocs/compta/stats/supplier_turnover_by_prodserv.php index 182f2c6381b..d95b2921d56 100644 --- a/htdocs/compta/stats/supplier_turnover_by_prodserv.php +++ b/htdocs/compta/stats/supplier_turnover_by_prodserv.php @@ -87,7 +87,7 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $q = GETPOST("q", "int"); if (empty($q)) { // We define date_start and date_end - $month_start = GETPOST("month") ? GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = GETPOST("month") ? GETPOST("month") : getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); $year_end = $year_start; $month_end = $month_start; if (!GETPOST("month")) { // If month not forced diff --git a/htdocs/compta/stats/supplier_turnover_by_thirdparty.php b/htdocs/compta/stats/supplier_turnover_by_thirdparty.php index 0da377a7f1c..7223a5458d5 100644 --- a/htdocs/compta/stats/supplier_turnover_by_thirdparty.php +++ b/htdocs/compta/stats/supplier_turnover_by_thirdparty.php @@ -97,7 +97,7 @@ if (empty($date_start) || empty($date_end)) { // We define date_start and date_e $q = GETPOST("q", "int") ? GETPOST("q", "int") : 0; if (empty($q)) { // We define date_start and date_end - $month_start = GETPOST("month") ? GETPOST("month") : ($conf->global->SOCIETE_FISCAL_MONTH_START ? ($conf->global->SOCIETE_FISCAL_MONTH_START) : 1); + $month_start = GETPOST("month") ? GETPOST("month") : getDolGlobalInt('SOCIETE_FISCAL_MONTH_START', 1); $year_end = $year_start; $month_end = $month_start; if (!GETPOST("month")) { // If month not forced diff --git a/htdocs/compta/tva/card.php b/htdocs/compta/tva/card.php index a7b1e10312a..0b89a923153 100644 --- a/htdocs/compta/tva/card.php +++ b/htdocs/compta/tva/card.php @@ -181,7 +181,7 @@ if (empty($reshook)) { $amount = price2num(GETPOST("amount", 'alpha')); if ($refund == 1) { - $amount = -$amount; + $amount = price2num(-1 * $amount); } $object->amount = $amount; $object->label = GETPOST("label", 'alpha'); diff --git a/htdocs/compta/tva/initdatesforvat.inc.php b/htdocs/compta/tva/initdatesforvat.inc.php index 983e9197960..59106f8750c 100644 --- a/htdocs/compta/tva/initdatesforvat.inc.php +++ b/htdocs/compta/tva/initdatesforvat.inc.php @@ -23,7 +23,7 @@ $now = dol_now(); $current_date = dol_getdate($now); -if (!getDolGlobalString('SOCIETE_FISCAL_MONTH_START')) { +if (!getDolGlobalInt('SOCIETE_FISCAL_MONTH_START')) { $conf->global->SOCIETE_FISCAL_MONTH_START = 1; } diff --git a/htdocs/contact/class/contact.class.php b/htdocs/contact/class/contact.class.php index 25ca192e6fa..f87217d2e02 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; } @@ -781,7 +776,7 @@ class Contact extends CommonObject $info = array(); // Object classes - $info["objectclass"] = explode(',', $conf->global->LDAP_CONTACT_OBJECT_CLASS); + $info["objectclass"] = explode(',', getDolGlobalString('LDAP_CONTACT_OBJECT_CLASS')); $this->fullname = $this->getFullName($langs); @@ -2169,7 +2164,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 +2180,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/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 ''."\n"; @@ -1030,7 +1036,7 @@ print '
'; // Action column if (getDolGlobalString('MAIN_CHECKBOX_LEFT_COLUMN')) { - print ''; diff --git a/htdocs/contrat/card.php b/htdocs/contrat/card.php index 7c991630275..6b0e29a207f 100644 --- a/htdocs/contrat/card.php +++ b/htdocs/contrat/card.php @@ -68,9 +68,9 @@ $origin = GETPOST('origin', 'alpha'); $originid = GETPOST('originid', 'int'); // PDF -$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS) ? 1 : 0)); -$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_DESC) ? 1 : 0)); -$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (!empty($conf->global->MAIN_GENERATE_DOCUMENTS_HIDE_REF) ? 1 : 0)); +$hidedetails = (GETPOST('hidedetails', 'int') ? GETPOST('hidedetails', 'int') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DETAILS') ? 1 : 0)); +$hidedesc = (GETPOST('hidedesc', 'int') ? GETPOST('hidedesc', 'int') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_DESC') ? 1 : 0)); +$hideref = (GETPOST('hideref', 'int') ? GETPOST('hideref', 'int') : (getDolGlobalString('MAIN_GENERATE_DOCUMENTS_HIDE_REF') ? 1 : 0)); $datecontrat = ''; diff --git a/htdocs/contrat/class/api_contracts.class.php b/htdocs/contrat/class/api_contracts.class.php index 6a86b31bf73..523eb59ea03 100644 --- a/htdocs/contrat/class/api_contracts.class.php +++ b/htdocs/contrat/class/api_contracts.class.php @@ -202,6 +202,12 @@ class Contracts extends DolibarrApi $result = $this->_validate($request_data); foreach ($request_data as $field => $value) { + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->contract->context['caller'] = $request_data['caller']; + continue; + } + $this->contract->$field = $value; } /*if (isset($request_data["lines"])) { @@ -509,6 +515,12 @@ class Contracts extends DolibarrApi if ($field == 'id') { continue; } + if ($field === 'caller') { + // Add a mention of caller so on trigger called after action, we can filter to avoid a loop if we try to sync back again whith the caller + $this->contract->context['caller'] = $request_data['caller']; + continue; + } + $this->contract->$field = $value; } diff --git a/htdocs/contrat/class/contrat.class.php b/htdocs/contrat/class/contrat.class.php index 08bb4caa932..d524c6973a1 100644 --- a/htdocs/contrat/class/contrat.class.php +++ b/htdocs/contrat/class/contrat.class.php @@ -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 .= ''; @@ -3413,7 +3413,7 @@ class ContratLigne extends CommonObjectLine */ public function update($user, $notrigger = 0) { - global $conf, $langs, $mysoc; + global $mysoc; $error = 0; @@ -3615,10 +3615,10 @@ class ContratLigne extends CommonObjectLine // phpcs:disable PEAR.NamingConventions.ValidFunctionName.ScopeNotCamelCaps /** - * Mise a jour en base des champs total_xxx de ligne - * Used by migration process + * Update in database the fields total_xxx of lines + * Used by migration process * - * @return int Return integer <0 if KO, >0 if OK + * @return int Return integer <0 if KO, >0 if OK */ public function update_total() { @@ -3656,7 +3656,7 @@ class ContratLigne extends CommonObjectLine */ public function insert($notrigger = 0) { - global $conf, $user; + global $user; $error = 0; @@ -3753,8 +3753,6 @@ class ContratLigne extends CommonObjectLine public function active_line($user, $date, $date_end = '', $comment = '') { // phpcs:enable - global $langs, $conf; - $error = 0; $this->db->begin(); @@ -3813,9 +3811,6 @@ class ContratLigne extends CommonObjectLine public function close_line($user, $date_end_real, $comment = '', $notrigger = 0) { // phpcs:enable - global $langs, $conf; - - // Update object $this->date_cloture = $date_end_real; $this->date_end_real = $date_end_real; $this->user_closing_id = $user->id; diff --git a/htdocs/core/actions_massactions.inc.php b/htdocs/core/actions_massactions.inc.php index 6e375c363bd..c7de54e22e0 100644 --- a/htdocs/core/actions_massactions.inc.php +++ b/htdocs/core/actions_massactions.inc.php @@ -410,7 +410,7 @@ if (!$error && $massaction == 'confirm_presend') { $tmp = explode(',', $user->email_aliases); $from = trim($tmp[($reg[1] - 1)]); } elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) { - $tmp = explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); + $tmp = explode(',', getDolGlobalString('MAIN_INFO_SOCIETE_MAIL_ALIASES')); $from = trim($tmp[($reg[1] - 1)]); } elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) { $sql = "SELECT rowid, label, email FROM ".MAIN_DB_PREFIX."c_email_senderprofile WHERE rowid = ".(int) $reg[1]; @@ -751,7 +751,7 @@ if (!$error && $massaction == "builddoc" && $permissiontoread && !GETPOST('butto $result = $objecttmp->fetch($toselectid); if ($result > 0) { $listofobjectid[$toselectid] = $toselectid; - $thirdpartyid = $objecttmp->fk_soc ? $objecttmp->fk_soc : $objecttmp->socid; + $thirdpartyid = !empty($objecttmp->fk_soc) ? $objecttmp->fk_soc : $objecttmp->socid; $listofobjectthirdparties[$thirdpartyid] = $thirdpartyid; $listofobjectref[$toselectid] = $objecttmp->ref; } diff --git a/htdocs/core/actions_sendmails.inc.php b/htdocs/core/actions_sendmails.inc.php index b05e13d76eb..6fbe2440fb3 100644 --- a/htdocs/core/actions_sendmails.inc.php +++ b/htdocs/core/actions_sendmails.inc.php @@ -286,7 +286,7 @@ if (($action == 'send' || $action == 'relance') && !GETPOST('addfile') && !GETPO $tmp = explode(',', $user->email_aliases); $from = trim($tmp[($reg[1] - 1)]); } elseif (preg_match('/global_aliases_(\d+)/', $fromtype, $reg)) { - $tmp = explode(',', $conf->global->MAIN_INFO_SOCIETE_MAIL_ALIASES); + $tmp = explode(',', getDolGlobalString('MAIN_INFO_SOCIETE_MAIL_ALIASES')); $from = trim($tmp[($reg[1] - 1)]); } elseif (preg_match('/senderprofile_(\d+)_(\d+)/', $fromtype, $reg)) { $sql = 'SELECT rowid, label, email FROM '.MAIN_DB_PREFIX.'c_email_senderprofile'; @@ -328,7 +328,7 @@ if (($action == 'send' || $action == 'relance') && !GETPOST('addfile') && !GETPO $deliveryreceipt = GETPOST('deliveryreceipt'); if ($action == 'send' || $action == 'relance') { - $actionmsg2 = $langs->transnoentities('MailSentBy').' '.CMailFile::getValidAddress($from, 4, 0, 1).' '.$langs->transnoentities('To').' '.CMailFile::getValidAddress($sendto, 4, 0, 1); + $actionmsg2 = $langs->transnoentities('MailSentByTo', CMailFile::getValidAddress($from, 4, 0, 1), CMailFile::getValidAddress($sendto, 4, 0, 1)); /*if ($message) { $actionmsg = $langs->transnoentities('MailFrom').': '.dol_escape_htmltag($from); $actionmsg = dol_concatdesc($actionmsg, $langs->transnoentities('MailTo').': '.dol_escape_htmltag($sendto)); diff --git a/htdocs/core/ajax/ajaxtooltip.php b/htdocs/core/ajax/ajaxtooltip.php index 301b9ef1d6e..129658ef8fd 100644 --- a/htdocs/core/ajax/ajaxtooltip.php +++ b/htdocs/core/ajax/ajaxtooltip.php @@ -38,7 +38,6 @@ include '../../main.inc.php'; include_once DOL_DOCUMENT_ROOT.'/core/class/html.form.class.php'; - $id = GETPOST('id', 'aZ09'); $objecttype = GETPOST('objecttype', 'aZ09arobase'); // 'module' or 'myobject@mymodule', 'mymodule_myobject' diff --git a/htdocs/core/ajax/fileupload.php b/htdocs/core/ajax/fileupload.php index 177154cee3a..fc89b77c56b 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,7 +36,7 @@ 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'; $id = GETPOST('fk_element', 'int'); 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/pingresult.php b/htdocs/core/ajax/pingresult.php index 854188f7d6e..96700b261da 100644 --- a/htdocs/core/ajax/pingresult.php +++ b/htdocs/core/ajax/pingresult.php @@ -1,5 +1,5 @@ +/* Copyright (C) 2019-2023 Laurent Destailleur * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by @@ -16,9 +16,10 @@ */ /** - * \file htdocs/core/ajax/pingresult.php - * \brief Page called after a ping was done in js to the official dolibarr ping service. - * This ajax URL is called with parameter 'firstpingok' or 'firstpingko' depending on the result of the ping. + * \file htdocs/core/ajax/pingresult.php + * \brief Page called after a ping was done in js to the official dolibarr ping service. + * This ajax URL is called with parameter 'firstpingok' or 'firstpingko' depending on the result of the ping. + * You can use &forceping=1 in parameters to force the ping if the ping was already sent. */ if (!defined('NOTOKENRENEWAL')) { 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_comptes.php b/htdocs/core/boxes/box_comptes.php index 295a14159cf..c8f683a86ec 100644 --- a/htdocs/core/boxes/box_comptes.php +++ b/htdocs/core/boxes/box_comptes.php @@ -63,7 +63,7 @@ class box_comptes extends ModeleBoxes $this->db = $db; // disable module for such cases - $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); + $listofmodulesforexternal = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL')); if (!in_array('banque', $listofmodulesforexternal) && !empty($user->socid)) { $this->enabled = 0; // disabled for external users } 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/box_members_by_tags.php b/htdocs/core/boxes/box_members_by_tags.php index df8192c2055..45404727d96 100644 --- a/htdocs/core/boxes/box_members_by_tags.php +++ b/htdocs/core/boxes/box_members_by_tags.php @@ -63,7 +63,7 @@ class box_members_by_tags extends ModeleBoxes $this->db = $db; // disable module for such cases - $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); + $listofmodulesforexternal = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL')); if (!in_array('adherent', $listofmodulesforexternal) && !empty($user->socid)) { $this->enabled = 0; // disabled for external users } diff --git a/htdocs/core/boxes/box_members_by_type.php b/htdocs/core/boxes/box_members_by_type.php index 9bcb20b2826..4a684011139 100644 --- a/htdocs/core/boxes/box_members_by_type.php +++ b/htdocs/core/boxes/box_members_by_type.php @@ -63,7 +63,7 @@ class box_members_by_type extends ModeleBoxes $this->db = $db; // disable module for such cases - $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); + $listofmodulesforexternal = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL')); if (!in_array('adherent', $listofmodulesforexternal) && !empty($user->socid)) { $this->enabled = 0; // disabled for external users } diff --git a/htdocs/core/boxes/box_members_last_modified.php b/htdocs/core/boxes/box_members_last_modified.php index a961a478385..2d9d580f8b8 100644 --- a/htdocs/core/boxes/box_members_last_modified.php +++ b/htdocs/core/boxes/box_members_last_modified.php @@ -62,7 +62,7 @@ class box_members_last_modified extends ModeleBoxes $this->db = $db; // disable module for such cases - $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); + $listofmodulesforexternal = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL')); if (!in_array('adherent', $listofmodulesforexternal) && !empty($user->socid)) { $this->enabled = 0; // disabled for external users } diff --git a/htdocs/core/boxes/box_members_last_subscriptions.php b/htdocs/core/boxes/box_members_last_subscriptions.php index 3d1e88627f2..b7eaad8cd13 100644 --- a/htdocs/core/boxes/box_members_last_subscriptions.php +++ b/htdocs/core/boxes/box_members_last_subscriptions.php @@ -62,7 +62,7 @@ class box_members_last_subscriptions extends ModeleBoxes $this->db = $db; // disable module for such cases - $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); + $listofmodulesforexternal = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL')); if (!in_array('adherent', $listofmodulesforexternal) && !empty($user->socid)) { $this->enabled = 0; // disabled for external users } diff --git a/htdocs/core/boxes/box_members_subscriptions_by_year.php b/htdocs/core/boxes/box_members_subscriptions_by_year.php index 999640c3ae4..9a94f6f071b 100644 --- a/htdocs/core/boxes/box_members_subscriptions_by_year.php +++ b/htdocs/core/boxes/box_members_subscriptions_by_year.php @@ -62,7 +62,7 @@ class box_members_subscriptions_by_year extends ModeleBoxes $this->db = $db; // disable module for such cases - $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); + $listofmodulesforexternal = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL')); if (!in_array('adherent', $listofmodulesforexternal) && !empty($user->socid)) { $this->enabled = 0; // disabled for external users } diff --git a/htdocs/core/boxes/box_produits_alerte_stock.php b/htdocs/core/boxes/box_produits_alerte_stock.php index ff01ceb810d..748c58f2381 100644 --- a/htdocs/core/boxes/box_produits_alerte_stock.php +++ b/htdocs/core/boxes/box_produits_alerte_stock.php @@ -63,7 +63,7 @@ class box_produits_alerte_stock extends ModeleBoxes $this->db = $db; - $listofmodulesforexternal = explode(',', $conf->global->MAIN_MODULES_FOR_EXTERNAL); + $listofmodulesforexternal = explode(',', getDolGlobalString('MAIN_MODULES_FOR_EXTERNAL')); $tmpentry = array('enabled'=>((isModEnabled("product") || isModEnabled("service")) && isModEnabled('stock')), 'perms'=>!empty($user->rights->stock->lire), 'module'=>'product|service|stock'); $showmode = isVisibleToUserType(($user->socid > 0 ? 1 : 0), $tmpentry, $listofmodulesforexternal); $this->hidden = ($showmode != 1); 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 ceb65e8cfa9..5f053ae6e18 100644 --- a/htdocs/core/class/CMailFile.class.php +++ b/htdocs/core/class/CMailFile.class.php @@ -311,7 +311,7 @@ class CMailFile // Add auto copy to if not already in $to (Note: Adding bcc for specific modules are also done from pages) // For example MAIN_MAIL_AUTOCOPY_TO can be 'email@example.com, __USER_EMAIL__, ...' if (getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO')) { - $listofemailstoadd = explode(',', $conf->global->MAIN_MAIL_AUTOCOPY_TO); + $listofemailstoadd = explode(',', getDolGlobalString('MAIN_MAIL_AUTOCOPY_TO')); foreach ($listofemailstoadd as $key => $val) { $emailtoadd = $listofemailstoadd[$key]; if (trim($emailtoadd) == '__USER_EMAIL__') { diff --git a/htdocs/core/class/commoninvoice.class.php b/htdocs/core/class/commoninvoice.class.php index 0f3b8628122..83f38d2a70f 100644 --- a/htdocs/core/class/commoninvoice.class.php +++ b/htdocs/core/class/commoninvoice.class.php @@ -49,6 +49,12 @@ abstract class CommonInvoice extends CommonObject */ public $subtype; + /** + * @var int Thirdparty ID + * @deprecated + * @see $socid + */ + public $fk_soc; /** * @var int Thirdparty ID */ @@ -63,6 +69,8 @@ abstract class CommonInvoice extends CommonObject */ public $date; + public $date_lim_reglement; + public $cond_reglement_id; // Id in llx_c_paiement public $cond_reglement_code; // Code in llx_c_paiement public $cond_reglement_label; @@ -1131,14 +1139,18 @@ abstract class CommonInvoice extends CommonObject } // Load the pending payment request to process (with rowid=$did) - $sql = "SELECT rowid, date_demande, amount, fk_facture, fk_facture_fourn, fk_prelevement_bons"; + $sql = "SELECT rowid, date_demande, amount, fk_facture, fk_facture_fourn, fk_salary, fk_prelevement_bons"; $sql .= " FROM ".$this->db->prefix()."prelevement_demande"; $sql .= " WHERE rowid = ".((int) $did); if ($type != 'bank-transfer' && $type != 'credit-transfer') { - $sql .= " AND fk_facture = ".((int) $this->id); // Add a protection to not pay another invoice than current one + $sql .= " AND fk_facture = ".((int) $this->id); // Add a protection to not pay another invoice than current one } if ($type != 'direct-debit') { - $sql .= " AND fk_facture_fourn = ".((int) $this->id); // Add a protection to not pay another invoice than current one + if ($$sourcetype == 'salary') { + $sql .= " AND fk_salary = ".((int) $this->id); // Add a protection to not pay another salary than current one + } else { + $sql .= " AND fk_facture_fourn = ".((int) $this->id); // Add a protection to not pay another invoice than current one + } } $sql .= " AND traite = 0"; // To not process payment request that were already converted into a direct debit or credit transfer order (Note: fk_prelevement_bons is also empty when traite = 0) diff --git a/htdocs/core/class/commonobject.class.php b/htdocs/core/class/commonobject.class.php index fdc1fc4bf6a..140b7a92d26 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; @@ -675,9 +676,14 @@ abstract class CommonObject public $sendtoid; /** - * @var float Amount already paid (used to show correct status) + * @var float Amount already paid from getSommePaiement() (used to show correct status) + * @deprecated Duplicate of $totalpaid */ public $alreadypaid; + /** + * @var float Amount already paid from getSommePaiement() (used to show correct status) + */ + public $totalpaid; /** * @var array Array with label of status @@ -854,6 +860,7 @@ abstract class CommonObject // Add extrafields if (!empty($extrafields->attributes[$this->table_element]['label'])) { + $datas['opendivextra'] = '
'; foreach ($extrafields->attributes[$this->table_element]['label'] as $key => $val) { if ($extrafields->attributes[$this->table_element]['type'][$key] == 'separate') { continue; @@ -894,6 +901,7 @@ abstract class CommonObject $count++; } } + $datas['closedivextra'] = '
'; } $hookmanager->initHooks(array($this->element . 'dao')); @@ -1730,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; } @@ -3654,7 +3660,7 @@ abstract class CommonObject if (!empty($MODULE)) { if (!empty($conf->global->$MODULE)) { - $modsactivated = explode(',', $conf->global->$MODULE); + $modsactivated = explode(',', getDolGlobalString($MODULE)); foreach ($modsactivated as $mod) { if (isModEnabled($mod)) { return 1; // update was disabled by specific setup @@ -4533,6 +4539,9 @@ abstract class CommonObject if ($elementTable == 'commande_fournisseur_dispatch') { $fieldstatus = "status"; } + if ($elementTable == 'prelevement_bons') { + $fieldstatus = "statut"; + } if (isset($this->fields) && is_array($this->fields) && array_key_exists('status', $this->fields)) { $fieldstatus = 'status'; } @@ -5617,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; @@ -5637,10 +5648,13 @@ 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); @@ -6818,15 +6832,23 @@ abstract class CommonObject } } + // $new_array_options will be used for direct update, so must contains formated data for the UPDATE. + $new_array_options = $this->array_options; + //dol_syslog("attributeLabel=".$attributeLabel, LOG_DEBUG); //dol_syslog("attributeType=".$attributeType, LOG_DEBUG); if (!empty($attrfieldcomputed)) { if (getDolGlobalString('MAIN_STORE_COMPUTED_EXTRAFIELDS')) { $value = dol_eval($attrfieldcomputed, 1, 0, '2'); dol_syslog($langs->trans("Extrafieldcomputed")." sur ".$attributeLabel."(".$value.")", LOG_DEBUG); - $this->array_options["options_".$key] = $value; + + $new_array_options["options_".$key] = $value; + + $this->array_options["options_".$key] = $new_array_options["options_".$key]; } else { - $this->array_options["options_".$key] = null; + $new_array_options["options_".$key] = null; + + $this->array_options["options_".$key] = $new_array_options["options_".$key]; } } @@ -6836,7 +6858,9 @@ abstract class CommonObject $this->errors[] = $langs->trans("ExtraFieldHasWrongValue", $attributeLabel); return -1; } elseif ($value === '') { - $this->array_options["options_".$key] = null; + $new_array_options["options_".$key] = null; + + $this->array_options["options_".$key] = $new_array_options["options_".$key]; } break; case 'double': @@ -6849,19 +6873,24 @@ abstract class CommonObject $value = null; } //dol_syslog("double value"." sur ".$attributeLabel."(".$value." is '".$attributeType."')", LOG_DEBUG); - $this->array_options["options_".$key] = $value; + $new_array_options["options_".$key] = $value; + + $this->array_options["options_".$key] = $new_array_options["options_".$key]; break; /*case 'select': // Not required, we chosed value='0' for undefined values if ($value=='-1') { - $this->array_options[$key] = null; + $new_array_options["options_".$key] = $value; + + $this->array_options["options_".$key] = $new_array_options["options_".$key]; } break;*/ case 'price': - $this->array_options["options_".$key] = price2num($this->array_options["options_".$key]); + $new_array_options["options_".$key] = price2num($this->array_options["options_".$key]); + + $this->array_options["options_".$key] = $new_array_options["options_".$key]; break; case 'password': - $new_array_options = array(); $algo = ''; if ($this->array_options["options_".$key] != '' && is_array($extrafields->attributes[$this->table_element]['param'][$attributeKey]['options'])) { // If there is an encryption choice, we use it to crypt data before insert @@ -6915,26 +6944,34 @@ abstract class CommonObject case 'date': case 'datetime': if (empty($this->array_options["options_".$key])) { - $this->array_options["options_".$key] = null; + $new_array_options["options_".$key] = null; + + $this->array_options["options_".$key] = $new_array_options["options_".$key]; } else { - $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]); + $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key]); } break; case 'datetimegmt': if (empty($this->array_options["options_".$key])) { - $this->array_options["options_".$key] = null; + $new_array_options["options_".$key] = null; + + $this->array_options["options_".$key] = $new_array_options["options_".$key]; } else { - $this->array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt'); + $new_array_options["options_".$key] = $this->db->idate($this->array_options["options_".$key], 'gmt'); } break; case 'boolean': if (empty($this->array_options["options_".$key])) { - $this->array_options["options_".$key] = null; + $new_array_options["options_".$key] = null; + + $this->array_options["options_".$key] = $new_array_options["options_".$key]; } break; case 'link': if ($this->array_options["options_".$key] === '') { - $this->array_options["options_".$key] = null; + $new_array_options["options_".$key] = null; + + $this->array_options["options_".$key] = $new_array_options["options_".$key]; } break; /* @@ -6993,12 +7030,12 @@ abstract class CommonObject } } - //var_dump('linealreadyfound='.$linealreadyfound.' sql='.$sql); + //var_dump('linealreadyfound='.$linealreadyfound.' sql='.$sql); exit; if ($linealreadyfound) { if ($this->array_options["options_".$key] === null) { $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = null"; } else { - $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($this->array_options["options_".$key])."'"; + $sql = "UPDATE ".$this->db->prefix().$this->table_element."_extrafields SET ".$key." = '".$this->db->escape($new_array_options["options_".$key])."'"; } $sql .= " WHERE fk_object = ".((int) $this->id); @@ -7674,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) 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/doleditor.class.php b/htdocs/core/class/doleditor.class.php index 1125eb0cfcb..01a17f605b6 100644 --- a/htdocs/core/class/doleditor.class.php +++ b/htdocs/core/class/doleditor.class.php @@ -171,7 +171,7 @@ class DolEditor if (!getDolGlobalString('FCKEDITOR_ENABLE_PDF')) { $pluginstodisable .= ',exportpdf'; } - if (getDolGlobalString('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS')) { + if (getDolGlobalInt('MAIN_DISALLOW_URL_INTO_DESCRIPTIONS') == 2) { $this->uselocalbrowser = 0; // Can't use browser to navigate into files. Only links with "htmlname.'">'.$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 . '