/*!
Delegate to eZPaymentGateway subclass.
970225
function cleanup( $process, $event )
    {
        $theGateway = $this->getCurrentGateway( $event );
        if( $theGateway != null and $theGateway->needCleanup() )
        {
            $theGateway->cleanup( $process, $event );
        }
    }
285962
public function checkEntityPayments($payments = array())
    {
        $requestReferenceDetails = new Structure\RequestEntityPayments();
        if ($payments) {
            foreach ($payments as $key => $value) {
                $requestPayment = new Structure\RequestReferenceDetails($value);
                $requestReferenceDetails->addPayment($requestPayment);
            }
        }

        $this->response = parent::checkEntityPayments($this->entity, $requestReferenceDetails);

        /**
         * Checks the state of the platform integration.
         */
        if (Exception\IntegrationState::check($this->response->state)) {
            throw new Exception\IntegrationState($this->response->state);
        }

        if ($this->response->state->state == 0) {
            throw new Exception\IntegrationResponse($this->response->state->message, $this->response->state->code);
        }

        return $this->response;
    }
45996
function(){
					console.log("handleOnlinePrivatePayment queued, will wait for "+key);
					eventBus.once(key, function(bValid){
						if (!bValid)
							return cancelAllKeys();
						assocValidatedByKey[key] = true;
						if (bParsingComplete)
							checkIfAllValidated();
						else
							console.log('parsing incomplete yet');
					});
					cb();
				}
594582
public function onPaymentDone(PaymentEvent $event)
    {
        $payment = $event->getPayment();
        if (!$payment instanceof OrderPayment) {
            return;
        }

        $order = $payment->getOrder();
        if ($order->getLocked()) {
            $order->setLocked(false);
            $this->updateOrder($order, $event);
        }

        $returnPath = null;
        $details = $payment->getDetails();
        if (array_key_exists('done_redirect_path', $details)) {
            $returnPath = $details['done_redirect_path'];
        } else {
            $type = $order->getType();
            if ($type === OrderTypes::TYPE_CART) {
                $returnPath = $this->urlGenerator->generate('ekyna_cart_payment');
            } elseif ($type === OrderTypes::TYPE_QUOTE) {
                throw new \BadMethodCallException('Not yet implemented');
            } elseif ($type === OrderTypes::TYPE_ORDER) {
                if ($this->authorization->isGranted('ROLE_ADMIN')) {
                    $returnPath = $this->urlGenerator->generate(
                        'ekyna_order_order_admin_show',
                        array('orderId' => $order->getId())
                    );
                } else {
                    $returnPath = $this->urlGenerator->generate(
                        'ekyna_cart_confirmation',
                        array(
                            'orderKey' => $order->getKey(),
                            'paymentId' => $payment->getId(),
                        )
                    );
                }
            }
        }

        if (null === $returnPath) {
            throw new LogicException('Unable to determine return path.');
        }

        $event->setResponse(new RedirectResponse($returnPath));
    }
983898
private function getHttpClient($endpoint, TransferInterface $transfer, $needsPublicKey = false) {
        // Prepare the headers
        $headers = $transfer->getHeaders();
        if ($needsPublicKey) {
            $headers['Authorization'] = $this->gatewayConfig->getPublicKey();
        }

        // Build the client
        $client = new ZendClient($endpoint);
        $client->setMethod('POST');
        $client->setRawData( json_encode( $transfer->getBody()) ) ;
        $client->setHeaders($headers);
        
        return $client;
    }
108247
function executeCompiledTemplate( $tpl, &$textElements,
                                      $keyData, $uri, $resourceData, $templatePath,
                                      &$extraParameters, $timestamp,
                                      $rootNamespace, $currentNamespace )
    {
        $key = $this->cacheKey( $keyData, $resourceData, $templatePath, $extraParameters );
        return eZTemplateCompiler::executeCompilation( $tpl, $textElements, $key, $resourceData,
                                                       $rootNamespace, $currentNamespace );
    }
343473
public function pay(OrderPaymentEvent $event)
    {
        $order = $event->getOrder();

        /* call pay method */
        if (null === $paymentModule = ModuleQuery::create()->findPk($order->getPaymentModuleId())) {
            throw new \RuntimeException(
                Translator::getInstance()->trans(
                    "Failed to find a payment Module with ID=%mid for order ID=%oid",
                    [
                        "%mid" => $order->getPaymentModuleId(),
                        "%oid" => $order->getId()
                    ]
                )
            );
        }

        $paymentModuleInstance = $paymentModule->getPaymentModuleInstance($this->container);

        $response = $paymentModuleInstance->pay($order);

        if (null !== $response && $response instanceof Response) {
            $event->setResponse($response);
        }
    }
197289
public function mapPaymentToPreAuthorization(SpyPaymentPayone $paymentEntity): AuthorizationContainerInterface
    {
        $preAuthorizationContainer = new PreAuthorizationContainer();
        $preAuthorizationContainer = $this->mapPaymentToAbstractAuthorization($paymentEntity, $preAuthorizationContainer);
        $preAuthorizationContainer = $this->mapEmail($paymentEntity, $preAuthorizationContainer);
        $preAuthorizationContainer = $this->mapAmount($paymentEntity, $preAuthorizationContainer);
        $preAuthorizationContainer = $this->mapBusinessRelation($preAuthorizationContainer);

        return $preAuthorizationContainer;
    }
883929
protected function loadBasicPaymentMethodClass()
    {

        if (!class_exists("Icepay_Api_Basic"))
            return $this;

        $this->pm_class = Icepay_Api_Basic::getInstance()
                ->readFolder()
                ->getClassByPaymentMethodCode($this->data->ic_paymentmethod);

        if (count($this->pm_class->getSupportedIssuers()) == 1) {
            $this->setIssuer(current($this->pm_class->getSupportedIssuers()));
        }
        return $this;
    }
459001
private Payment toPayment(final UUID paymentId,
                              @Nullable final Iterable<PaymentTransactionInfoPlugin> pluginTransactions,
                              final boolean withAttempts,
                              final InternalTenantContext tenantContext) {
        final PaymentModelDao paymentModelDao = paymentDao.getPayment(paymentId, tenantContext);
        if (paymentModelDao == null) {
            log.warn("Unable to find payment id " + paymentId);
            return null;
        }

        return toPayment(paymentModelDao, pluginTransactions, withAttempts, tenantContext);
    }
962482
public function getGateway()
    {
        /* @var $module \gplcart\modules\omnipay_library\Main */
        $module = $this->module->getInstance('omnipay_library');

        /** @var \Omnipay\Stripe\Gateway $gateway */
        $gateway = $module->getGatewayInstance('Stripe');

        if (!$gateway instanceof Gateway) {
            throw new UnexpectedValueException('Gateway must be instance of Omnipay\Stripe\Gateway');
        }

        return $gateway;
    }
647260
public function actionNotice($gateway)
    {
        if (!$this->module->hasGateway($gateway)) {
            throw new NotFoundHttpException("Unknown payment gateway '{$gateway}'");
        }
        $gateway = $this->module->getGateway($gateway);
        $status = $gateway->notice(Yii::$app->request, $this->paymentId, $this->money, $this->message, $this->payId);
        Payment::setPayStatus($this->paymentId, $status, ['money' => $this->money, 'message' => $this->message, 'pay_id' => $this->payId]);
        Yii::$app->end();
    }
19029
public function processPayment()
    {
        $gestpayMethod = new GestpayMethod();

        /*
         * At this point, order must be created given a cart, and placed in PaymentBridge.
         *
         * So, $this->paymentBridge->getOrder() must return an object
         */
        $this
            ->paymentEventDispatcher
            ->notifyPaymentOrderLoad(
                $this->paymentBridge,
                $gestpayMethod
            );

        /*
         * Order Not found Exception must be thrown just here.
         */
        if (!$this->paymentBridge->getOrder()) {
            throw new PaymentOrderNotFoundException();
        }

        /*
         * Order exists right here.
         */
        $this
            ->paymentEventDispatcher
            ->notifyPaymentOrderCreated(
                $this->paymentBridge,
                $gestpayMethod
            );

        return $this->gestpayEncrypter->encryptedUrl();
    }
47257
private function _processGatewayResponse($response, $expectedType)
    {
        $gatewayRspCode = (isset($response->Header->GatewayRspCode) ? $response->Header->GatewayRspCode : null);
        $transactionId = (isset($response->Header->GatewayTxnId) ? $response->Header->GatewayTxnId : null);

        if ($gatewayRspCode == '0') {
            return;
        }

        if ($gatewayRspCode == '30') {
            try {
                $this->void($transactionId);
            } catch (Exception $e) {
                throw new HpsGatewayException(
                    HpsExceptionCodes::GATEWAY_TIMEOUT_REVERSAL_ERROR,
                    'Error occurred while reversing a charge due to HPS gateway timeout',
                    $e,
                    null,
                    null,
                    $transactionId
                );
            }
        }

        HpsGatewayResponseValidation::checkResponse($response, $expectedType);
    }
508167
public function ExecutePayment(TdbShopOrder &$oOrder, $sMessageConsumer = '')
    {
        $bPaymentOk = parent::ExecutePayment($oOrder);

        $oCurrency = null;
        if (method_exists($oOrder, 'GetFieldPkgShopCurrency')) {
            $oCurrency = $oOrder->GetFieldPkgShopCurrency();
        }
        $sCurrency = $this->GetCurrencyIdentifier($oCurrency);
        $request = $this->getCurrentRequest();
        $aCommand = array(
            'TOKEN' => $this->sPayPalToken,
            'PAYERID' => $this->aCheckoutDetails['PAYERID'],
            'PAYMENTREQUEST_0_PAYMENTACTION' => 'Sale',
            'PAYMENTREQUEST_0_AMT' => round($oOrder->fieldValueTotal, 2),
            'PAYMENTREQUEST_0_CURRENCYCODE' => $sCurrency,
            'IPADDRESS' => null === $request ? '' : $request->getClientIp(),
            'PAYMENTREQUEST_0_INVNUM' => $this->GetOrderNumber($oOrder),
            'PAYMENTREQUEST_0_CUSTOM' => $this->id.','.$oOrder->id,
        );
        $sIPNURL = $this->GetInstantPaymentNotificationListenerURL($oOrder);
        if (!empty($sIPNURL)) {
            $aCommand['PAYMENTREQUEST_0_NOTIFYURL'] = $sIPNURL;
        }

        $aAnswer = $this->ExecutePayPalCall('DoExpressCheckoutPayment', $aCommand);
        $ack = strtoupper($aAnswer['ACK']);
        if ('SUCCESS' == $ack) {
            $bPaymentOk = true;
            // add the response data to the order
            foreach ($aAnswer as $sKey => $sVal) {
                if (!array_key_exists($sKey, $this->aPaymentUserData)) {
                    $this->aPaymentUserData[$sKey] = $sVal;
                }
            }
            //        $this->SaveUserPaymentDataToOrder($oOrder->id);

            if (array_key_exists('PAYMENTINFO_0_PAYMENTSTATUS', $aAnswer) && 'COMPLETED' == strtoupper($aAnswer['PAYMENTINFO_0_PAYMENTSTATUS'])) {
                $oOrder->SetStatusPaid();
            }
        } else {
            $bPaymentOk = false;
        }

        if (!$bPaymentOk) {
            // error!
            $oMsgManager = TCMSMessageManager::GetInstance();
            $oMsgManager->AddMessage($sMessageConsumer, 'ERROR-ORDER-REQUEST-PAYMENT-ERROR', array('errorMsg' => self::GetPayPalErrorMessage($aAnswer)));
            $logContext = array(
                'Command' => $aCommand,
                'PayPalAnswer' => $aAnswer,
            );
            $this->getPaypalLogger()->critical('PayPal payment could not be executed for order id '.$oOrder->id, $logContext);
        }

        return $bPaymentOk;
    }
209924
function paypalwpp() {
    include_once(zen_get_file_directory(DIR_FS_CATALOG . DIR_WS_LANGUAGES . $_SESSION['language'] . '/modules/payment/', 'paypalwpp.php', 'false'));
    global $order;
    $this->code = 'paypalwpp';
    $this->codeTitle = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_EC;
    $this->codeVersion = '1.5.1';
    $this->enableDirectPayment = FALSE;
    $this->enabled = (MODULE_PAYMENT_PAYPALWPP_STATUS == 'True');
    // Set the title & description text based on the mode we're in ... EC vs US/UK vs admin
    if (IS_ADMIN_FLAG === true) {
      $this->description = sprintf(MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_DESCRIPTION, ' (rev' . $this->codeVersion . ')');
      switch (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE) {
        case ('PayPal'):
          $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_EC;
        break;
        case ('Payflow-UK'):
          $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_PRO20;
        break;
        case ('Payflow-US'):
          if (defined('MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC') && MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC == 'Yes') {
            $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_PF_EC;
          } else {
            $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_PF_GATEWAY;
          }
        break;
        default:
          $this->title = MODULE_PAYMENT_PAYPALWPP_TEXT_ADMIN_TITLE_EC;
      }
      if ($this->enabled) {
        if ( (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE == 'PayPal' && (MODULE_PAYMENT_PAYPALWPP_APISIGNATURE == '' || MODULE_PAYMENT_PAYPALWPP_APIUSERNAME == '' || MODULE_PAYMENT_PAYPALWPP_APIPASSWORD == ''))
          || (substr(MODULE_PAYMENT_PAYPALWPP_MODULE_MODE,0,7) == 'Payflow' && (MODULE_PAYMENT_PAYPALWPP_PFPARTNER == '' || MODULE_PAYMENT_PAYPALWPP_PFVENDOR == '' || MODULE_PAYMENT_PAYPALWPP_PFUSER == '' || MODULE_PAYMENT_PAYPALWPP_PFPASSWORD == ''))
          ) $this->title .= '<span class="alert"><strong> NOT CONFIGURED YET</strong></span>';
        if (MODULE_PAYMENT_PAYPALWPP_SERVER =='sandbox') $this->title .= '<strong><span class="alert"> (sandbox active)</span></strong>';
        if (MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log File' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log and Email') $this->title .= '<strong> (Debug)</strong>';
        if (!function_exists('curl_init')) $this->title .= '<strong><span class="alert"> CURL NOT FOUND. Cannot Use.</span></strong>';
      }
    } else {
      $this->description = MODULE_PAYMENT_PAYPALWPP_TEXT_DESCRIPTION;
      $this->title = MODULE_PAYMENT_PAYPALWPP_EC_TEXT_TITLE; //pp
    }

    if ((!defined('PAYPAL_OVERRIDE_CURL_WARNING') || (defined('PAYPAL_OVERRIDE_CURL_WARNING') && PAYPAL_OVERRIDE_CURL_WARNING != 'True')) && !function_exists('curl_init')) $this->enabled = false;

    $this->enableDebugging = (MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log File' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log and Email');
    $this->emailAlerts = (MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Log File' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING =='Log and Email' || MODULE_PAYMENT_PAYPALWPP_DEBUGGING == 'Alerts Only');
    $this->doDPonly = (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE =='Payflow-US' && !(defined('MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC') && MODULE_PAYMENT_PAYPALWPP_PAYFLOW_EC == 'Yes'));
    $this->showPaymentPage = (MODULE_PAYMENT_PAYPALWPP_SKIP_PAYMENT_PAGE == 'No') ? true : false;
    $this->sort_order = MODULE_PAYMENT_PAYPALWPP_SORT_ORDER;

    $this->buttonSourceEC = 'ZenCart-EC_us';
    $this->buttonSourceDP = 'ZenCart-DP_us';
    if (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE == 'Payflow-UK') {
      $this->buttonSourceEC = 'ZenCart-EC_uk';
      $this->buttonSourceDP = 'ZenCart-DP_uk';
    }
    if (MODULE_PAYMENT_PAYPALWPP_MODULE_MODE == 'Payflow-US') {
      $this->buttonSourceEC = 'ZenCart-ECGW_us';
      $this->buttonSourceDP = 'ZenCart-GW_us';
    }

    $this->order_pending_status = MODULE_PAYMENT_PAYPALWPP_ORDER_PENDING_STATUS_ID;
    if ((int)MODULE_PAYMENT_PAYPALWPP_ORDER_STATUS_ID > 0) {
      $this->order_status = MODULE_PAYMENT_PAYPALWPP_ORDER_STATUS_ID;
    }
    $this->new_acct_notify = MODULE_PAYMENT_PAYPALWPP_NEW_ACCT_NOTIFY;
    $this->zone = (int)MODULE_PAYMENT_PAYPALWPP_ZONE;
    if (is_object($order)) $this->update_status();

    if (PROJECT_VERSION_MAJOR != '1' && substr(PROJECT_VERSION_MINOR, 0, 3) != '5.0') $this->enabled = false;

    $this->cards = array();
    // if operating in markflow mode, start EC process when submitting order
    if (!$this->in_special_checkout()) {
      $this->form_action_url = zen_href_link('ipn_main_handler.php', 'type=ec&markflow=1&clearSess=1&stage=final', 'SSL', true, true, true);
    }

    // debug setup
    if (!@is_writable($this->_logDir)) $this->_logDir = DIR_FS_CATALOG . $this->_logDir;
    if (!@is_writable($this->_logDir)) $this->_logDir = DIR_FS_SQL_CACHE;
    // Regular mode:
    if ($this->enableDebugging) $this->_logLevel = 2;
    // DEV MODE:
    if (defined('PAYPAL_DEV_MODE') && PAYPAL_DEV_MODE == 'true') $this->_logLevel = 3;

    if (IS_ADMIN_FLAG === true) $this->tableCheckup();

  }
244237
static function compileTemplate( $tpl, $key, &$resourceData )
    {
        if ( !eZTemplateCompiler::isCompilationEnabled() )
            return false;

        $resourceData['use-comments'] = eZTemplateCompiler::isCommentsEnabled();

        $cacheFileName = eZTemplateCompiler::compilationFilename( $key, $resourceData );
        $resourceData['uniqid'] = md5( $resourceData['template-filename']. uniqid( "ezp". getmypid(), true ) );

        // Time limit #1:
        // We reset the time limit to 30 seconds to ensure that templates
        // have enough time to compile
        // However if time limit is unlimited (0) we leave it be
        // Time limit will also be reset after subtemplates are compiled
        $maxExecutionTime = ini_get( 'max_execution_time' );
        if ( $maxExecutionTime != 0 && $maxExecutionTime < 30 )
        {
            @set_time_limit( 30 );
        }

        $rootNode =& $resourceData['root-node'];
        if ( !$rootNode )
            return false;

        $GLOBALS['eZTemplateCompilerResourceCache'][$resourceData['template-filename']] =& $resourceData;

        $useComments = eZTemplateCompiler::isCommentsEnabled();

        if ( !$resourceData['test-compile'] )
        {
            eZTemplateCompiler::createCommonCompileTemplate();
        }

        /* Check if we need to disable the generation of spacing for the compiled templates */
        $ini = eZINI::instance();
        $spacing = 'disabled';
        if ( $ini->variable( 'TemplateSettings', 'UseFormatting' ) == 'enabled' )
        {
            $spacing = 'enabled';
        }

        $php = new eZPHPCreator( eZTemplateCompiler::compilationDirectory(), $cacheFileName,
                                 eZTemplateCompiler::TemplatePrefix(), array( 'spacing' => $spacing ) );
        $php->addComment( 'URI:       ' . $resourceData['uri'] );
        $php->addComment( 'Filename:  ' . $resourceData['template-filename'] );
        $php->addComment( 'Timestamp: ' . $resourceData['time-stamp'] . ' (' . date( 'D M j G:i:s T Y', $resourceData['time-stamp'] ) . ')' );

        $php->addCodePiece("\$oldSetArray_{$resourceData['uniqid']} = isset( \$setArray ) ? \$setArray : array();\n".
                           "\$setArray = array();\n");
// Code to decrement include level of the templates
        $php->addCodePiece( "\$tpl->Level++;\n" );
        $php->addCodePiece( "if ( \$tpl->Level > $tpl->MaxLevel )\n".
                            "{\n".
                            "\$text = \$tpl->MaxLevelWarning;".
                            "\$tpl->Level--;\n".
                            "return;\n".
                            "}\n" );
        if ( $resourceData['locales'] && count( $resourceData['locales'] ) )
        {
            $php->addComment( 'Locales:   ' . join( ', ', $resourceData['locales'] ) );

            $php->addCodePiece(
                '$locales = array( "'. join( '", "', $resourceData['locales'] ) . "\" );\n".
                '$oldLocale_'. $resourceData['uniqid']. ' = setlocale( LC_CTYPE, null );'. "\n".
                '$currentLocale_'. $resourceData['uniqid']. ' = setlocale( LC_CTYPE, $locales );'. "\n"
            );
        }
//         $php->addCodePiece( "print( \"" . $resourceData['template-filename'] . " ($cacheFileName)<br/>\n\" );" );
        if ( $useComments )
        {
            $templateFilename = $resourceData['template-filename'];
            if ( file_exists( $templateFilename ) )
            {
                $fd = fopen( $templateFilename, 'rb' );
                if ( $fd )
                {
                    $templateText = fread( $fd, filesize( $templateFilename ) );
                    $php->addComment( "Original code:\n" . $templateText );
                    fclose( $fd );
                }
            }
        }
        $php->addVariable( 'eZTemplateCompilerCodeDate', eZTemplateCompiler::CODE_DATE );
        $php->addCodePiece( "if ( !defined( 'EZ_TEMPLATE_COMPILER_COMMON_CODE' ) )\n" );
        $php->addInclude( eZTemplateCompiler::compilationDirectory() . '/common.php', eZPHPCreator::INCLUDE_ONCE_STATEMENT, array( 'spacing' => 4 ) );
        $php->addSpace();

        if ( eZTemplateCompiler::isAccumulatorsEnabled() )
        {
            $php->addCodePiece( "eZDebug::accumulatorStart( 'template_compiled_execution', 'template_total', 'Template compiled execution', true );\n" );
        }
        if ( eZTemplateCompiler::isTimingPointsEnabled() )
        {
            $php->addCodePiece( "eZDebug::addTimingPoint( 'Script start $cacheFileName' );\n" );
        }

//         $php->addCodePiece( "if ( !isset( \$vars ) )\n    \$vars =& \$tpl->Variables;\n" );
//         $php->addSpace();

        $parameters = array();
        $textName = eZTemplateCompiler::currentTextName( $parameters );

//         $php->addCodePiece( "if ( !isset( \$$textName ) )\n    \$$textName = '';\n" );
//         $php->addSpace();

        $transformedTree = array();
        eZTemplateCompiler::processNodeTransformation( $useComments, $php, $tpl, $rootNode, $resourceData, $transformedTree );

        if ( $ini->variable( 'TemplateSettings', 'TemplateOptimization' ) == 'enabled' )
        {
            /* Retrieve class information for the attribute lookup table */
            if ( isset( $resourceData['handler']->Keys ) and isset( $resourceData['handler']->Keys['class'] ) ) {
                $resourceData['class-info'] = eZTemplateOptimizer::fetchClassDeclaration( $resourceData['handler']->Keys['class'] );
            }
            /* Run the optimizations */
            eZTemplateOptimizer::optimize( $useComments, $php, $tpl, $transformedTree, $resourceData );
        }

        $staticTree = array();
        eZTemplateCompiler::processStaticOptimizations( $useComments, $php, $tpl, $transformedTree, $resourceData, $staticTree );

        $combinedTree = array();
        eZTemplateCompiler::processNodeCombining( $useComments, $php, $tpl, $staticTree, $resourceData, $combinedTree );

        $finalTree = $combinedTree;
        if ( !eZTemplateCompiler::isNodePlacementEnabled() )
            eZTemplateCompiler::processRemoveNodePlacement( $finalTree );

        eZTemplateCompiler::generatePHPCode( $useComments, $php, $tpl, $finalTree, $resourceData );

        if ( eZTemplateCompiler::isTreeEnabled( 'final' ) )
            $php->addVariable( 'finalTree', $finalTree, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'full-tree' => true ) );
        if ( eZTemplateCompiler::isTreeEnabled( 'combined' ) )
            $php->addVariable( 'combinedTree', $combinedTree, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'full-tree' => true ) );
        if ( eZTemplateCompiler::isTreeEnabled( 'static' ) )
            $php->addVariable( 'staticTree', $staticTree, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'full-tree' => true ) );
        if ( eZTemplateCompiler::isTreeEnabled( 'transformed' ) )
            $php->addVariable( 'transformedTree', $transformedTree, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'full-tree' => true ) );
        if ( eZTemplateCompiler::isTreeEnabled( 'original' ) )
            $php->addVariable( 'originalTree', $rootNode, eZPHPCreator::VARIABLE_ASSIGNMENT, array( 'full-tree' => true ) );

        if ( eZTemplateCompiler::isTimingPointsEnabled() )
            $php->addCodePiece( "eZDebug::addTimingPoint( 'Script end $cacheFileName' );\n" );
        if ( eZTemplateCompiler::isAccumulatorsEnabled() )
            $php->addCodePiece( "eZDebug::accumulatorStop( 'template_compiled_execution', true );\n" );

        if ( $resourceData['locales'] && count( $resourceData['locales'] ) )
        {
            $php->addCodePiece(
                'setlocale( LC_CTYPE, $oldLocale_'. $resourceData['uniqid']. ' );'. "\n"
            );
        }
        $php->addCodePiece('$setArray = $oldSetArray_'. $resourceData['uniqid']. ";\n");

// Code to decrement include level of the templates
        $php->addCodePiece("\$tpl->Level--;\n" );

        /*
        // dump names of all defined PHP variables
        $php->addCodePiece( "echo \"defined vars in $resourceData[uri]:<br/><pre>\\n\";\n" );
        $php->addCodePiece( 'foreach ( array_keys( get_defined_vars() ) as $var_name  ) echo "- $var_name\n";' );
        // dump tpl vars
        $php->addCodePiece( 'echo "\n-----------------------------------------------------------\nvars: ";' );
        $php->addCodePiece( 'var_dump( $vars );' );
        $php->addCodePiece( 'echo "</pre><hr/>\n";' );
        */

        if ( !$resourceData['test-compile'] )
        {
            $php->store( true );
        }

        return true;
    }