Exemplo n.º 1
0
    /**
     * This function returns the DataElement
     *
     * @param string $name name of the DataElement
     * @param string $type type of the DataElement
     * @param int $length length of the DataElement
     * @param mixed $value value of the DataElement
     * @param array $options options for the DataElement
     * @param int $entityId id of the DataElement
     * @return \Cx\Core\Html\Model\Entity\DataElement
     */
    public function getDataElement($name, $type, $length, $value, &$options, $entityId)
    {
        global $_ARRAYLANG, $_CORELANG;
        if (isset($options['formfield'])) {
            $formFieldGenerator = $options['formfield'];
            $formField = '';
            /* We use json to do the callback. The 'else if' is for backwards compatibility so you can declare
             * the function directly without using json. This is not recommended and not working over session */
            if (is_array($formFieldGenerator) && isset($formFieldGenerator['adapter']) && isset($formFieldGenerator['method'])) {
                $json = new \Cx\Core\Json\JsonData();
                $jsonResult = $json->data($formFieldGenerator['adapter'], $formFieldGenerator['method'], array('name' => $name, 'type' => $type, 'length' => $length, 'value' => $value, 'options' => $options));
                if ($jsonResult['status'] == 'success') {
                    $formField = $jsonResult["data"];
                }
            } else {
                if (is_callable($formFieldGenerator)) {
                    $formField = $formFieldGenerator($name, $type, $length, $value, $options);
                }
            }
            if (is_a($formField, 'Cx\\Core\\Html\\Model\\Entity\\HtmlElement')) {
                return $formField;
            } else {
                $value = $formField;
            }
        }
        if (isset($options['showDetail']) && $options['showDetail'] === false) {
            return '';
        }
        switch ($type) {
            case 'bool':
            case 'boolean':
                // yes/no checkboxes
                $fieldset = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                $inputYes = new \Cx\Core\Html\Model\Entity\DataElement($name, 'yes');
                $inputYes->setAttribute('type', 'radio');
                $inputYes->setAttribute('value', '1');
                $inputYes->setAttribute('id', 'form-' . $this->formId . '-' . $name . '_yes');
                if (isset($options['attributes'])) {
                    $inputYes->setAttributes($options['attributes']);
                }
                $fieldset->addChild($inputYes);
                $labelYes = new \Cx\Core\Html\Model\Entity\HtmlElement('label');
                $labelYes->setAttribute('for', 'form-' . $this->formId . '-' . $name . '_yes');
                $labelYes->addChild(new \Cx\Core\Html\Model\Entity\TextElement($_ARRAYLANG['TXT_YES']));
                $fieldset->addChild($labelYes);
                $inputNo = new \Cx\Core\Html\Model\Entity\DataElement($name, 'no');
                $inputNo->setAttribute('id', 'form-' . $this->formId . '-' . $name . '_no');
                $inputNo->setAttribute('type', 'radio');
                $inputNo->setAttribute('value', '0');
                if (isset($options['attributes'])) {
                    $inputNo->setAttributes($options['attributes']);
                }
                $fieldset->addChild($inputNo);
                $labelNo = new \Cx\Core\Html\Model\Entity\HtmlElement('label');
                $labelNo->setAttribute('for', 'form-' . $this->formId . '-' . $name . '_no');
                $labelNo->addChild(new \Cx\Core\Html\Model\Entity\TextElement($_ARRAYLANG['TXT_NO']));
                $fieldset->addChild($labelNo);
                if ($value) {
                    $inputYes->setAttribute('checked');
                } else {
                    $inputNo->setAttribute('checked');
                }
                return $fieldset;
                break;
            case 'int':
            case 'integer':
                // input field with type number
                $inputNumber = new \Cx\Core\Html\Model\Entity\DataElement($name, $value, \Cx\Core\Html\Model\Entity\DataElement::TYPE_INPUT, new \Cx\Core\Validate\Model\Entity\RegexValidator('/-?[0-9]*/'));
                if (isset($options['attributes'])) {
                    $inputNumber->setAttributes($options['attributes']);
                }
                $inputNumber->setAttribute('type', 'number');
                return $inputNumber;
                break;
            case 'Cx\\Model\\Base\\EntityBase':
                $associatedClass = get_class($value);
                \JS::registerJS('core/Html/View/Script/Backend.js');
                \ContrexxJavascript::getInstance()->setVariable('Form/Error', $_ARRAYLANG['TXT_CORE_HTML_FORM_VALIDATION_ERROR'], 'core/Html/lang');
                if (\Env::get('em')->getClassMetadata($this->entityClass)->isSingleValuedAssociation($name)) {
                    // this case is used to create a select field for 1 to 1 associations
                    $entities = \Env::get('em')->getRepository($associatedClass)->findAll();
                    $foreignMetaData = \Env::get('em')->getClassMetadata($associatedClass);
                    $primaryKeyName = $foreignMetaData->getSingleIdentifierFieldName();
                    $selected = $foreignMetaData->getFieldValue($value, $primaryKeyName);
                    $arrEntities = array();
                    $closeMetaData = \Env::get('em')->getClassMetadata($this->entityClass);
                    $assocMapping = $closeMetaData->getAssociationMapping($name);
                    $validator = null;
                    if (!isset($assocMapping['joinColumns'][0]['nullable']) || $assocMapping['joinColumns'][0]['nullable']) {
                        $arrEntities['NULL'] = $_ARRAYLANG['TXT_CORE_NONE'];
                    } else {
                        $validator = new \Cx\Core\Validate\Model\Entity\RegexValidator('/^(?!null$|$)/');
                    }
                    foreach ($entities as $entity) {
                        $arrEntities[\Env::get('em')->getClassMetadata($associatedClass)->getFieldValue($entity, $primaryKeyName)] = $entity;
                    }
                    $select = new \Cx\Core\Html\Model\Entity\DataElement($name, \Html::getOptions($arrEntities, $selected), \Cx\Core\Html\Model\Entity\DataElement::TYPE_SELECT, $validator);
                    if (isset($options['attributes'])) {
                        $select->setAttributes($options['attributes']);
                    }
                    return $select;
                } else {
                    // this case is used to list all existing values and show an add button for 1 to many associations
                    $closeMetaData = \Env::get('em')->getClassMetadata($this->entityClass);
                    $assocMapping = $closeMetaData->getAssociationMapping($name);
                    $mainDiv = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                    $mainDiv->setAttribute('class', 'entityList');
                    $addButton = new \Cx\Core\Html\Model\Entity\HtmlElement('input');
                    $addButton->setAttribute('type', 'button');
                    $addButton->setClass(array('form-control', 'add_' . $this->createCssClassNameFromEntity($associatedClass), 'mappedAssocciationButton'));
                    $addButton->setAttribute('value', $_CORELANG['TXT_ADD']);
                    $addButton->setAttribute('data-params', 'entityClass:' . $associatedClass . ';' . 'mappedBy:' . $assocMapping['mappedBy'] . ';' . 'cssName:' . $this->createCssClassNameFromEntity($associatedClass) . ';' . 'sessionKey:' . $this->entityClass);
                    if (!isset($_SESSION['vgOptions'])) {
                        $_SESSION['vgOptions'] = array();
                    }
                    $_SESSION['vgOptions'][$this->entityClass] = $this->componentOptions;
                    if ($entityId != 0) {
                        // if we edit the main form, we also want to show the existing associated values we already have
                        $existingValues = $this->getIdentifyingDisplayValue($assocMapping, $associatedClass, $entityId);
                    }
                    if (!empty($existingValues)) {
                        foreach ($existingValues as $existingValue) {
                            $mainDiv->addChild($existingValue);
                        }
                    }
                    $mainDiv->addChild($addButton);
                    // if standard tooltip is not disabled, we load the one to n association text
                    if (!isset($options['showstanardtooltip']) || $options['showstanardtooltip']) {
                        if (!empty($options['tooltip'])) {
                            $options['tooltip'] = $options['tooltip'] . '<br /><br /> ' . $_ARRAYLANG['TXT_CORE_RECORD_ONE_TO_N_ASSOCIATION'];
                        } else {
                            $options['tooltip'] = $_ARRAYLANG['TXT_CORE_RECORD_ONE_TO_N_ASSOCIATION'];
                        }
                    }
                    $cxjs = \ContrexxJavascript::getInstance();
                    $cxjs->setVariable('TXT_CANCEL', $_CORELANG['TXT_CANCEL'], 'Html/lang');
                    $cxjs->setVariable('TXT_SUBMIT', $_CORELANG['TXT_SUBMIT'], 'Html/lang');
                    $cxjs->setVariable('TXT_EDIT', $_CORELANG['TXT_EDIT'], 'Html/lang');
                    $cxjs->setVariable('TXT_DELETE', $_CORELANG['TXT_DELETE'], 'Html/lang');
                    return $mainDiv;
                }
                break;
            case 'Country':
                // this is for customizing only:
                $data = \Cx\Core\Country\Controller\Country::getNameById($value);
                if (empty($data)) {
                    $value = 204;
                }
                $options = \Cx\Core\Country\Controller\Country::getMenuoptions($value);
                $select = new \Cx\Core\Html\Model\Entity\DataElement($name, $options, \Cx\Core\Html\Model\Entity\DataElement::TYPE_SELECT);
                if (isset($options['attributes'])) {
                    $select->setAttributes($options['attributes']);
                }
                return $select;
                break;
            case 'DateTime':
            case 'datetime':
            case 'date':
                // input field with type text and class datepicker
                if ($value instanceof \DateTime) {
                    $value = $value->format(ASCMS_DATE_FORMAT);
                }
                if (is_null($value)) {
                    $value = '';
                }
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'text');
                $input->setAttribute('class', 'datepicker');
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                \DateTimeTools::addDatepickerJs();
                \JS::registerCode('
                        cx.jQuery(function() {
                          cx.jQuery(".datepicker").datetimepicker();
                        });
                        ');
                return $input;
                break;
            case 'multiselect':
            case 'select':
                $values = array();
                if (isset($options['validValues'])) {
                    if (is_array($options['validValues'])) {
                        $values = $options['validValues'];
                    } else {
                        $values = explode(',', $options['validValues']);
                        $values = array_combine($values, $values);
                    }
                }
                if ($type == 'multiselect') {
                    $value = explode(',', $value);
                    $value = array_combine($value, $value);
                }
                $selectOptions = \Html::getOptions($values, $value);
                $select = new \Cx\Core\Html\Model\Entity\DataElement($name, $selectOptions, \Cx\Core\Html\Model\Entity\DataElement::TYPE_SELECT);
                if ($type == 'multiselect') {
                    $select->setAttribute('multiple');
                }
                if (isset($options['attributes'])) {
                    $select->setAttributes($options['attributes']);
                }
                return $select;
                break;
            case 'slider':
                // this code should not be here
                // create sorrounding div
                $element = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                // create div for slider
                $slider = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                $slider->setAttribute('class', 'slider');
                $element->addChild($slider);
                // create hidden input for slider value
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value + 0, \Cx\Core\Html\Model\Entity\DataElement::TYPE_INPUT);
                $input->setAttribute('type', 'hidden');
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                $element->addChild($input);
                // add javascript to update input value
                $min = 0;
                $max = 10;
                if (isset($options['validValues'])) {
                    $values = explode(',', $options['validValues']);
                    $min = $values[0];
                    if (isset($values[1])) {
                        $max = $values[1];
                    }
                }
                if (!isset($value)) {
                    $value = 0;
                }
                $script = new \Cx\Core\Html\Model\Entity\HtmlElement('script');
                $script->addChild(new \Cx\Core\Html\Model\Entity\TextElement('
                    cx.jQuery("#form-' . $this->formId . '-' . $name . ' .slider").slider({
                        value: ' . ($value + 0) . ',
                        min: ' . ($min + 0) . ',
                        max: ' . ($max + 0) . ',
                        slide: function( event, ui ) {
                            cx.jQuery("input[name=' . $name . ']").val(ui.value);
                            cx.jQuery("input[name=' . $name . ']").change();
                        }
                    });
                '));
                $element->addChild($script);
                return $element;
                break;
            case 'checkboxes':
                $dataElementGroupType = \Cx\Core\Html\Model\Entity\DataElementGroup::TYPE_CHECKBOX;
            case 'radio':
                $values = array();
                if (isset($options['validValues'])) {
                    $values = explode(',', $options['validValues']);
                    $values = array_combine($values, $values);
                }
                if (!isset($dataElementGroupType)) {
                    $dataElementGroupType = \Cx\Core\Html\Model\Entity\DataElementGroup::TYPE_RADIO;
                }
                $radio = new \Cx\Core\Html\Model\Entity\DataElementGroup($name, $values, $value, $dataElementGroupType);
                if (isset($options['attributes'])) {
                    $radio->setAttributes($options['attributes']);
                }
                return $radio;
                break;
            case 'text':
                // textarea
                $textarea = new \Cx\Core\Html\Model\Entity\HtmlElement('textarea');
                $textarea->setAttribute('name', $name);
                if (isset($options['readonly']) && $options['readonly']) {
                    $textarea->setAttribute('disabled');
                }
                $textarea->addChild(new \Cx\Core\Html\Model\Entity\TextElement($value));
                if (isset($options['attributes'])) {
                    $textarea->setAttributes($options['attributes']);
                }
                return $textarea;
                break;
            case 'phone':
                // input field with type phone
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'phone');
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                return $input;
                break;
            case 'mail':
                // input field with type mail
                $emailValidator = new \Cx\Core\Validate\Model\Entity\EmailValidator();
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value, 'input', $emailValidator);
                $input->setAttribute('onkeyup', $emailValidator->getJavaScriptCode());
                $input->setAttribute('type', 'mail');
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                return $input;
                break;
            case 'uploader':
                \JS::registerCode('
                    function javascript_callback_function(data) {
                        if(data.type=="file") {
                                cx.jQuery("#' . $name . '").val(data.data[0].datainfo.filepath);
                        }
                    }

                ');
                $mediaBrowser = new \Cx\Core_Modules\MediaBrowser\Model\Entity\MediaBrowser();
                $mediaBrowser->setOptions(array('type' => 'button'));
                $mediaBrowser->setCallback('javascript_callback_function');
                $mediaBrowser->setOptions(array('data-cx-mb-views' => 'filebrowser,uploader', 'id' => 'page_target_browse', 'cxMbStartview' => 'MediaBrowserList'));
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'text');
                $input->setAttribute('id', $name);
                $div = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                $div->addChild($input);
                $div->addChild(new \Cx\Core\Html\Model\Entity\TextElement($mb = $mediaBrowser->getXHtml($_ARRAYLANG['TXT_CORE_CM_BROWSE'])));
                return $div;
                break;
            case 'image':
                \JS::registerCode('
                    function javascript_callback_function(data) {
                        if ( data.data[0].datainfo.extension=="Jpg"
                            || data.data[0].datainfo.extension=="Gif"
                            || data.data[0].datainfo.extension=="Png"
                        ) {
                            cx.jQuery("#' . $name . '").attr(\'value\', data.data[0].datainfo.filepath);
                            cx.jQuery("#' . $name . '").prevAll(\'.deletePreviewImage\').first().css(\'display\', \'inline-block\');
                            cx.jQuery("#' . $name . '").prevAll(\'.previewImage\').first().attr(\'src\', data.data[0].datainfo.filepath);
                        }
                    }

                    jQuery(document).ready(function(){
                        jQuery(\'.deletePreviewImage\').click(function(){
                            cx.jQuery("#' . $name . '").attr(\'value\', \'\');
                            cx.jQuery(this).prev(\'img\').attr(\'src\', \'/images/Downloads/no_picture.gif\');
                            cx.jQuery(this).css(\'display\', \'none\');
                            cx.jQuery(this).nextAll(\'input\').first().attr(\'value\', \'\');
                        });
                    });

                ');
                $mediaBrowser = new \Cx\Core_Modules\MediaBrowser\Model\Entity\MediaBrowser();
                $mediaBrowser->setOptions(array('type' => 'button'));
                $mediaBrowser->setCallback('javascript_callback_function');
                $defaultOptions = array('data-cx-mb-views' => 'filebrowser,uploader', 'id' => 'page_target_browse', 'cxMbStartview' => 'MediaBrowserList');
                $mediaBrowser->setOptions(is_array($options['options']) ? array_merge($defaultOptions, $options['options']) : $defaultOptions);
                // create hidden input to save image
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'hidden');
                $input->setAttribute('id', $name);
                $div = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                if (isset($value) && in_array(pathinfo($value, PATHINFO_EXTENSION), array('gif', 'jpg', 'png')) || $name == 'imagePath') {
                    // this image is meant to be a preview of the selected image
                    $previewImage = new \Cx\Core\Html\Model\Entity\HtmlElement('img');
                    $previewImage->setAttribute('class', 'previewImage');
                    $previewImage->setAttribute('src', $value != '' ? $value : '/images/Downloads/no_picture.gif');
                    // this image is uesd as delete function for the selected image over javascript
                    $deleteImage = new \Cx\Core\Html\Model\Entity\HtmlElement('img');
                    $deleteImage->setAttribute('class', 'deletePreviewImage');
                    $deleteImage->setAttribute('src', '/core/Core/View/Media/icons/delete.gif');
                    $div->addChild($previewImage);
                    $div->addChild($deleteImage);
                    $div->addChild(new \Cx\Core\Html\Model\Entity\HtmlElement('br'));
                }
                $div->addChild($input);
                $div->addChild(new \Cx\Core\Html\Model\Entity\TextElement($mediaBrowser->getXHtml($_ARRAYLANG['TXT_CORE_CM_BROWSE'])));
                return $div;
                break;
            case 'sourcecode':
                //set mode
                $mode = 'html';
                if (isset($options['options']['mode'])) {
                    switch ($options['options']['mode']) {
                        case 'js':
                            $mode = 'javascript';
                            break;
                        case 'yml':
                        case 'yaml':
                            $mode = 'yaml';
                            break;
                    }
                }
                //define textarea
                $textarea = new \Cx\Core\Html\Model\Entity\HtmlElement('textarea');
                $textarea->setAttribute('name', $name);
                $textarea->setAttribute('id', $name);
                $textarea->setAttribute('style', 'display:none;');
                $textarea->addChild(new \Cx\Core\Html\Model\Entity\TextElement($value));
                //define pre
                $pre = new \Cx\Core\Html\Model\Entity\HtmlElement('pre');
                $pre->setAttribute('id', 'editor-' . $name);
                $pre->addChild(new \Cx\Core\Html\Model\Entity\TextElement(contrexx_raw2xhtml($value)));
                //set readonly if necessary
                $readonly = '';
                if (isset($options['readonly']) && $options['readonly']) {
                    $readonly = 'editor.setReadOnly(true);';
                    $textarea->setAttribute('disabled');
                }
                //create div and add all stuff
                $div = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                //     required for the Ace editor to work. Otherwise
                //     it won't be visible as the DIV does have a width of 0px.
                $div->setAttribute('style', 'display:block;');
                $div->addChild($textarea);
                $div->addChild($pre);
                //register js
                $jsCode = <<<CODE
var editor;
\$J(function(){
if (\$J("#editor-{$name}").length) {
    editor = ace.edit("editor-{$name}");
    editor.getSession().setMode("ace/mode/{$mode}");
    editor.setShowPrintMargin(false);
    editor.focus();
    editor.gotoLine(1);
    {$readonly}
}

\$J('form').submit(function(){
    \$J('#{$name}').val(editor.getSession().getValue());
});

});
CODE;
                \JS::activate('ace');
                \JS::registerCode($jsCode);
                return $div;
                break;
            case 'string':
            case 'hidden':
            default:
                // convert NULL to empty string
                if (is_null($value)) {
                    $value = '';
                }
                // input field with type text
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                if (isset($options['validValues'])) {
                    $input->setValidator(new \Cx\Core\Validate\Model\Entity\RegexValidator('/^' . $options['validValues'] . '$/'));
                }
                if ($type == 'hidden') {
                    $input->setAttribute('type', 'hidden');
                } else {
                    $input->setAttribute('type', 'text');
                    $input->setClass('form-control');
                }
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                return $input;
                break;
        }
    }
Exemplo n.º 2
0
 /**
  * Returns an array with all placeholders and their values to be
  * replaced in any shop mailtemplate for the given order ID.
  *
  * You only have to set the 'substitution' index value of your MailTemplate
  * array to the array returned.
  * Customer data is not included here.  See {@see Customer::getSubstitutionArray()}.
  * Note that this method is now mostly independent of the current session.
  * The language of the mail template is determined by the browser
  * language range stored with the order.
  * @access  private
  * @static
  * @param   integer $order_id     The order ID
  * @param   boolean $create_accounts  If true, creates User accounts
  *                                    and Coupon codes.  Defaults to true
  * @return  array                 The array with placeholders as keys
  *                                and values from the order on success,
  *                                false otherwise
  */
 static function getSubstitutionArray($order_id, $create_accounts = true)
 {
     global $_ARRAYLANG;
     /*
                 $_ARRAYLANG['TXT_SHOP_URI_FOR_DOWNLOAD'].":\r\n".
                 'http://'.$_SERVER['SERVER_NAME'].
                 "/index.php?section=download\r\n";
     */
     $objOrder = Order::getById($order_id);
     if (!$objOrder) {
         // Order not found
         return false;
     }
     $lang_id = $objOrder->lang_id();
     if (!intval($lang_id)) {
         $lang_id = \FWLanguage::getLangIdByIso639_1($lang_id);
     }
     $status = $objOrder->status();
     $customer_id = $objOrder->customer_id();
     $customer = Customer::getById($customer_id);
     $payment_id = $objOrder->payment_id();
     $shipment_id = $objOrder->shipment_id();
     $arrSubstitution = array('CUSTOMER_COUNTRY_ID' => $objOrder->billing_country_id(), 'LANG_ID' => $lang_id, 'NOW' => date(ASCMS_DATE_FORMAT_DATETIME), 'TODAY' => date(ASCMS_DATE_FORMAT_DATE), 'ORDER_ID' => $order_id, 'ORDER_ID_CUSTOM' => ShopLibrary::getCustomOrderId($order_id), 'ORDER_DATE' => date(ASCMS_DATE_FORMAT_DATE, strtotime($objOrder->date_time())), 'ORDER_TIME' => date(ASCMS_DATE_FORMAT_TIME, strtotime($objOrder->date_time())), 'ORDER_STATUS_ID' => $status, 'ORDER_STATUS' => $_ARRAYLANG['TXT_SHOP_ORDER_STATUS_' . $status], 'MODIFIED' => date(ASCMS_DATE_FORMAT_DATETIME, strtotime($objOrder->modified_on())), 'REMARKS' => $objOrder->note(), 'ORDER_SUM' => sprintf('% 9.2f', $objOrder->sum()), 'CURRENCY' => Currency::getCodeById($objOrder->currency_id()));
     $arrSubstitution += $customer->getSubstitutionArray();
     if ($shipment_id) {
         $arrSubstitution += array('SHIPMENT' => array(0 => array('SHIPMENT_NAME' => sprintf('%-40s', Shipment::getShipperName($shipment_id)), 'SHIPMENT_PRICE' => sprintf('% 9.2f', $objOrder->shipment_amount()))), 'SHIPPING_ADDRESS' => array(0 => array('SHIPPING_COMPANY' => $objOrder->company(), 'SHIPPING_TITLE' => $_ARRAYLANG['TXT_SHOP_' . strtoupper($objOrder->gender())], 'SHIPPING_FIRSTNAME' => $objOrder->firstname(), 'SHIPPING_LASTNAME' => $objOrder->lastname(), 'SHIPPING_ADDRESS' => $objOrder->address(), 'SHIPPING_ZIP' => $objOrder->zip(), 'SHIPPING_CITY' => $objOrder->city(), 'SHIPPING_COUNTRY_ID' => $objOrder->country_id(), 'SHIPPING_COUNTRY' => \Cx\Core\Country\Controller\Country::getNameById($objOrder->country_id()), 'SHIPPING_PHONE' => $objOrder->phone())));
     }
     if ($payment_id) {
         $arrSubstitution += array('PAYMENT' => array(0 => array('PAYMENT_NAME' => sprintf('%-40s', Payment::getNameById($payment_id)), 'PAYMENT_PRICE' => sprintf('% 9.2f', $objOrder->payment_amount()))));
     }
     $arrItems = $objOrder->getItems();
     if (!$arrItems) {
         \Message::warning($_ARRAYLANG['TXT_SHOP_ORDER_WARNING_NO_ITEM']);
     }
     // Deduct Coupon discounts, either from each Product price, or
     // from the items total.  Mind that the Coupon has already been
     // stored with the Order, but not redeemed yet.  This is done
     // in this method, but only if $create_accounts is true.
     $coupon_code = NULL;
     $coupon_amount = 0;
     $objCoupon = Coupon::getByOrderId($order_id);
     if ($objCoupon) {
         $coupon_code = $objCoupon->code();
     }
     $orderItemCount = 0;
     $total_item_price = 0;
     // Suppress Coupon messages (see Coupon::available())
     \Message::save();
     foreach ($arrItems as $item) {
         $product_id = $item['product_id'];
         $objProduct = Product::getById($product_id);
         if (!$objProduct) {
             //die("Product ID $product_id not found");
             continue;
         }
         //DBG::log("Orders::getSubstitutionArray(): Item: Product ID $product_id");
         $product_name = substr($item['name'], 0, 40);
         $item_price = $item['price'];
         $quantity = $item['quantity'];
         // TODO: Add individual VAT rates for Products
         //            $orderItemVatPercent = $objResultItem->fields['vat_percent'];
         // Decrease the Product stock count,
         // applies to "real", shipped goods only
         $objProduct->decreaseStock($quantity);
         $product_code = $objProduct->code();
         // Pick the order items attributes
         $str_options = '';
         // Any attributes?
         if ($item['attributes']) {
             $str_options = '  ';
             // '[';
             $attribute_name_previous = '';
             foreach ($item['attributes'] as $attribute_name => $arrAttribute) {
                 //DBG::log("Attribute /$attribute_name/ => ".var_export($arrAttribute, true));
                 // NOTE: The option price is optional and may be left out
                 foreach ($arrAttribute as $arrOption) {
                     $option_name = $arrOption['name'];
                     $option_price = $arrOption['price'];
                     $item_price += $option_price;
                     // Recognize the names of uploaded files,
                     // verify their presence and use the original name
                     $option_name_stripped = ShopLibrary::stripUniqidFromFilename($option_name);
                     $path = Order::UPLOAD_FOLDER . $option_name;
                     if ($option_name != $option_name_stripped && \File::exists($path)) {
                         $option_name = $option_name_stripped;
                     }
                     if ($attribute_name != $attribute_name_previous) {
                         if ($attribute_name_previous) {
                             $str_options .= '; ';
                         }
                         $str_options .= $attribute_name . ': ' . $option_name;
                         $attribute_name_previous = $attribute_name;
                     } else {
                         $str_options .= ', ' . $option_name;
                     }
                     // TODO: Add proper formatting with sprintf() and language entries
                     if ($option_price != 0) {
                         $str_options .= ' ' . Currency::formatPrice($option_price) . ' ' . Currency::getActiveCurrencyCode();
                     }
                 }
             }
             //                $str_options .= ']';
         }
         // Product details
         $arrProduct = array('PRODUCT_ID' => $product_id, 'PRODUCT_CODE' => $product_code, 'PRODUCT_QUANTITY' => $quantity, 'PRODUCT_TITLE' => $product_name, 'PRODUCT_OPTIONS' => $str_options, 'PRODUCT_ITEM_PRICE' => sprintf('% 9.2f', $item_price), 'PRODUCT_TOTAL_PRICE' => sprintf('% 9.2f', $item_price * $quantity));
         //DBG::log("Orders::getSubstitutionArray($order_id, $create_accounts): Adding article: ".var_export($arrProduct, true));
         $orderItemCount += $quantity;
         $total_item_price += $item_price * $quantity;
         if ($create_accounts) {
             // Add an account for every single instance of every Product
             for ($instance = 1; $instance <= $quantity; ++$instance) {
                 $validity = 0;
                 // Default to unlimited validity
                 // In case there are protected downloads in the cart,
                 // collect the group IDs
                 $arrUsergroupId = array();
                 if ($objProduct->distribution() == 'download') {
                     $usergroupIds = $objProduct->usergroup_ids();
                     if ($usergroupIds != '') {
                         $arrUsergroupId = explode(',', $usergroupIds);
                         $validity = $objProduct->weight();
                     }
                 }
                 // create an account that belongs to all collected
                 // user groups, if any.
                 if (count($arrUsergroupId) > 0) {
                     // The login names are created separately for
                     // each product instance
                     $username = self::usernamePrefix . "_{$order_id}_{$product_id}_{$instance}";
                     $userEmail = $username . '-' . $arrSubstitution['CUSTOMER_EMAIL'];
                     $userpass = \User::make_password();
                     $objUser = new \User();
                     $objUser->setUsername($username);
                     $objUser->setPassword($userpass);
                     $objUser->setEmail($userEmail);
                     $objUser->setAdminStatus(false);
                     $objUser->setActiveStatus(true);
                     $objUser->setGroups($arrUsergroupId);
                     $objUser->setValidityTimePeriod($validity);
                     $objUser->setFrontendLanguage(FRONTEND_LANG_ID);
                     $objUser->setBackendLanguage(FRONTEND_LANG_ID);
                     $objUser->setProfile(array('firstname' => array(0 => $arrSubstitution['CUSTOMER_FIRSTNAME']), 'lastname' => array(0 => $arrSubstitution['CUSTOMER_LASTNAME']), 'company' => array(0 => $arrSubstitution['CUSTOMER_COMPANY']), 'address' => array(0 => $arrSubstitution['CUSTOMER_ADDRESS']), 'zip' => array(0 => $arrSubstitution['CUSTOMER_ZIP']), 'city' => array(0 => $arrSubstitution['CUSTOMER_CITY']), 'country' => array(0 => $arrSubstitution['CUSTOMER_COUNTRY_ID']), 'phone_office' => array(0 => $arrSubstitution['CUSTOMER_PHONE']), 'phone_fax' => array(0 => $arrSubstitution['CUSTOMER_FAX'])));
                     if (!$objUser->store()) {
                         \Message::error(implode('<br />', $objUser->getErrorMsg()));
                         return false;
                     }
                     if (empty($arrProduct['USER_DATA'])) {
                         $arrProduct['USER_DATA'] = array();
                     }
                     $arrProduct['USER_DATA'][] = array('USER_NAME' => $username, 'USER_PASS' => $userpass);
                 }
                 //echo("Instance $instance");
                 if ($objProduct->distribution() == 'coupon') {
                     if (empty($arrProduct['COUPON_DATA'])) {
                         $arrProduct['COUPON_DATA'] = array();
                     }
                     //DBG::log("Orders::getSubstitutionArray(): Getting code");
                     $code = Coupon::getNewCode();
                     //DBG::log("Orders::getSubstitutionArray(): Got code: $code, calling Coupon::addCode($code, 0, 0, 0, $item_price)");
                     Coupon::storeCode($code, 0, 0, 0, $item_price, 0, 0, 10000000000.0, true);
                     $arrProduct['COUPON_DATA'][] = array('COUPON_CODE' => $code);
                 }
             }
             // Redeem the *product* Coupon, if possible for the Product
             if ($coupon_code) {
                 $objCoupon = Coupon::available($coupon_code, $item_price * $quantity, $customer_id, $product_id, $payment_id);
                 if ($objCoupon) {
                     $coupon_code = NULL;
                     $coupon_amount = $objCoupon->getDiscountAmount($item_price, $customer_id);
                     if ($create_accounts) {
                         $objCoupon->redeem($order_id, $customer_id, $item_price * $quantity);
                     }
                 }
                 //\DBG::log("Orders::getSubstitutionArray(): Got Product Coupon $coupon_code");
             }
         }
         if (empty($arrSubstitution['ORDER_ITEM'])) {
             $arrSubstitution['ORDER_ITEM'] = array();
         }
         $arrSubstitution['ORDER_ITEM'][] = $arrProduct;
     }
     $arrSubstitution['ORDER_ITEM_SUM'] = sprintf('% 9.2f', $total_item_price);
     $arrSubstitution['ORDER_ITEM_COUNT'] = sprintf('% 4u', $orderItemCount);
     // Redeem the *global* Coupon, if possible for the Order
     if ($coupon_code) {
         $objCoupon = Coupon::available($coupon_code, $total_item_price, $customer_id, null, $payment_id);
         if ($objCoupon) {
             $coupon_amount = $objCoupon->getDiscountAmount($total_item_price, $customer_id);
             if ($create_accounts) {
                 $objCoupon->redeem($order_id, $customer_id, $total_item_price);
             }
         }
     }
     \Message::restore();
     // Fill in the Coupon block with proper discount and amount
     if ($objCoupon) {
         $coupon_code = $objCoupon->code();
         //\DBG::log("Orders::getSubstitutionArray(): Coupon $coupon_code, amount $coupon_amount");
     }
     if ($coupon_amount) {
         //\DBG::log("Orders::getSubstitutionArray(): Got Order Coupon $coupon_code");
         $arrSubstitution['DISCOUNT_COUPON'][] = array('DISCOUNT_COUPON_CODE' => sprintf('%-40s', $coupon_code), 'DISCOUNT_COUPON_AMOUNT' => sprintf('% 9.2f', -$coupon_amount));
     } else {
         //\DBG::log("Orders::getSubstitutionArray(): No Coupon for Order ID $order_id");
     }
     Products::deactivate_soldout();
     if (Vat::isEnabled()) {
         //DBG::log("Orders::getSubstitutionArray(): VAT amount: ".$objOrder->vat_amount());
         $arrSubstitution['VAT'] = array(0 => array('VAT_TEXT' => sprintf('%-40s', Vat::isIncluded() ? $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_INCL'] : $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_EXCL']), 'VAT_PRICE' => $objOrder->vat_amount()));
     }
     return $arrSubstitution;
 }
Exemplo n.º 3
0
 /**
  * Generates an overview of the Order for the Customer to confirm
  *
  * Forward her to the processing of the Order after the button has been
  * clicked.
  * @return  boolean             True on success, false otherwise
  */
 static function confirm()
 {
     global $_ARRAYLANG;
     // If the cart or address is missing, return to the shop
     if (!self::verifySessionAddress()) {
         \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', ''));
     }
     self::$show_currency_navbar = false;
     // The Customer clicked the confirm button; this must not be the case
     // the first time this method is called.
     if (isset($_POST['process'])) {
         return self::process();
     }
     // Show confirmation page.
     self::$objTemplate->hideBlock('shopProcess');
     self::$objTemplate->setGlobalVariable($_ARRAYLANG);
     // It may be necessary to refresh the cart here, as the customer
     // may return to the cart, then press "Back".
     self::_initPaymentDetails();
     foreach (Cart::get_products_array() as $arrProduct) {
         $objProduct = Product::getById($arrProduct['id']);
         if (!$objProduct) {
             // TODO: Implement a proper method
             //                unset(Cart::get_product_id($cart_id]);
             continue;
         }
         $price_options = 0;
         $attributes = Attributes::getAsStrings($arrProduct['options'], $price_options);
         $attributes = $attributes[0];
         // Note:  The Attribute options' price is added
         // to the price here!
         $price = $objProduct->get_custom_price(self::$objCustomer, $price_options, $arrProduct['quantity']);
         // Test the distribution method for delivery
         $productDistribution = $objProduct->distribution();
         $weight = $productDistribution == 'delivery' ? Weight::getWeightString($objProduct->weight()) : '-';
         $vatId = $objProduct->vat_id();
         $vatRate = Vat::getRate($vatId);
         $vatPercent = Vat::getShort($vatId);
         $vatAmount = Vat::amount($vatRate, $price * $arrProduct['quantity']);
         self::$objTemplate->setVariable(array('SHOP_PRODUCT_ID' => $arrProduct['id'], 'SHOP_PRODUCT_CUSTOM_ID' => $objProduct->code(), 'SHOP_PRODUCT_TITLE' => contrexx_raw2xhtml($objProduct->name()), 'SHOP_PRODUCT_PRICE' => Currency::formatPrice($price * $arrProduct['quantity']), 'SHOP_PRODUCT_QUANTITY' => $arrProduct['quantity'], 'SHOP_PRODUCT_ITEMPRICE' => Currency::formatPrice($price), 'SHOP_UNIT' => Currency::getActiveCurrencySymbol()));
         if ($attributes && self::$objTemplate->blockExists('attributes')) {
             self::$objTemplate->setVariable('SHOP_PRODUCT_OPTIONS', $attributes);
         }
         if (\Cx\Core\Setting\Controller\Setting::getValue('weight_enable', 'Shop')) {
             self::$objTemplate->setVariable(array('SHOP_PRODUCT_WEIGHT' => $weight, 'TXT_WEIGHT' => $_ARRAYLANG['TXT_WEIGHT']));
         }
         if (Vat::isEnabled()) {
             self::$objTemplate->setVariable(array('SHOP_PRODUCT_TAX_RATE' => $vatPercent, 'SHOP_PRODUCT_TAX_AMOUNT' => Currency::formatPrice($vatAmount) . '&nbsp;' . Currency::getActiveCurrencySymbol()));
         }
         self::$objTemplate->parse("shopCartRow");
     }
     $total_discount_amount = 0;
     if (Cart::get_discount_amount()) {
         $total_discount_amount = Cart::get_discount_amount();
         self::$objTemplate->setVariable(array('SHOP_DISCOUNT_COUPON_TOTAL' => $_ARRAYLANG['TXT_SHOP_DISCOUNT_COUPON_AMOUNT_TOTAL'], 'SHOP_DISCOUNT_COUPON_TOTAL_AMOUNT' => Currency::formatPrice(-$total_discount_amount)));
     }
     self::$objTemplate->setVariable(array('SHOP_UNIT' => Currency::getActiveCurrencySymbol(), 'SHOP_TOTALITEM' => Cart::get_item_count(), 'SHOP_PAYMENT_PRICE' => Currency::formatPrice($_SESSION['shop']['payment_price']), 'SHOP_TOTALPRICE' => Currency::formatPrice(Cart::get_price()), 'SHOP_PAYMENT' => Payment::getProperty($_SESSION['shop']['paymentId'], 'name'), 'SHOP_GRAND_TOTAL' => Currency::formatPrice($_SESSION['shop']['grand_total_price']), 'SHOP_COMPANY' => stripslashes($_SESSION['shop']['company']), 'SHOP_TITLE' => stripslashes($_SESSION['shop']['gender']), 'SHOP_GENDER' => stripslashes($_SESSION['shop']['gender']), 'SHOP_LASTNAME' => stripslashes($_SESSION['shop']['lastname']), 'SHOP_FIRSTNAME' => stripslashes($_SESSION['shop']['firstname']), 'SHOP_ADDRESS' => stripslashes($_SESSION['shop']['address']), 'SHOP_ZIP' => stripslashes($_SESSION['shop']['zip']), 'SHOP_CITY' => stripslashes($_SESSION['shop']['city']), 'SHOP_COUNTRY' => \Cx\Core\Country\Controller\Country::getNameById($_SESSION['shop']['countryId']), 'SHOP_EMAIL' => stripslashes($_SESSION['shop']['email']), 'SHOP_PHONE' => stripslashes($_SESSION['shop']['phone']), 'SHOP_FAX' => stripslashes($_SESSION['shop']['fax'])));
     if (!empty($_SESSION['shop']['lastname2'])) {
         self::$objTemplate->setVariable(array('SHOP_COMPANY2' => stripslashes($_SESSION['shop']['company2']), 'SHOP_TITLE2' => stripslashes($_SESSION['shop']['gender2']), 'SHOP_LASTNAME2' => stripslashes($_SESSION['shop']['lastname2']), 'SHOP_FIRSTNAME2' => stripslashes($_SESSION['shop']['firstname2']), 'SHOP_ADDRESS2' => stripslashes($_SESSION['shop']['address2']), 'SHOP_ZIP2' => stripslashes($_SESSION['shop']['zip2']), 'SHOP_CITY2' => stripslashes($_SESSION['shop']['city2']), 'SHOP_COUNTRY2' => \Cx\Core\Country\Controller\Country::getNameById($_SESSION['shop']['countryId2']), 'SHOP_PHONE2' => stripslashes($_SESSION['shop']['phone2'])));
     }
     if (!empty($_SESSION['shop']['note'])) {
         self::$objTemplate->setVariable(array('SHOP_CUSTOMERNOTE' => $_SESSION['shop']['note']));
     }
     if (Vat::isEnabled()) {
         self::$objTemplate->setVariable(array('TXT_TAX_RATE' => $_ARRAYLANG['TXT_SHOP_VAT_RATE'], 'SHOP_TAX_PRICE' => Currency::formatPrice($_SESSION['shop']['vat_price']), 'SHOP_TAX_PRODUCTS_TXT' => $_SESSION['shop']['vat_products_txt'], 'SHOP_TAX_GRAND_TXT' => $_SESSION['shop']['vat_grand_txt'], 'TXT_TAX_PREFIX' => Vat::isIncluded() ? $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_INCL'] : $_ARRAYLANG['TXT_SHOP_VAT_PREFIX_EXCL']));
         if (Vat::isIncluded()) {
             self::$objTemplate->setVariable(array('SHOP_GRAND_TOTAL_EXCL_TAX' => Currency::formatPrice($_SESSION['shop']['grand_total_price'] - $_SESSION['shop']['vat_price'])));
         }
     }
     // TODO: Make sure in payment() that those two are either both empty or
     // both non-empty!
     if (!Cart::needs_shipment() && empty($_SESSION['shop']['shipperId'])) {
         if (self::$objTemplate->blockExists('shipping_address')) {
             self::$objTemplate->hideBlock('shipping_address');
         }
     } else {
         // Shipment is required, so
         if (empty($_SESSION['shop']['shipperId'])) {
             \Cx\Core\Csrf\Controller\Csrf::redirect(\Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'payment'));
         }
         self::$objTemplate->setVariable(array('SHOP_SHIPMENT_PRICE' => Currency::formatPrice($_SESSION['shop']['shipment_price']), 'SHOP_SHIPMENT' => Shipment::getShipperName($_SESSION['shop']['shipperId'])));
     }
     // Custom.
     // Enable if Discount class is customized and in use.
     //self::showCustomerDiscount(Cart::get_price());
     return true;
 }
Exemplo n.º 4
0
 public function __construct($attrs = array(), $options = array())
 {
     global $_ARRAYLANG;
     if ($attrs instanceof \Cx\Core_Modules\Listing\Model\Entity\DataSet) {
         $hasMasterTableHeader = !empty($options['header']);
         // add master table-header-row
         if ($hasMasterTableHeader) {
             $this->addRow(array(0 => $options['header']), null, 'th');
         }
         $first = true;
         $row = 1 + $hasMasterTableHeader;
         foreach ($attrs as $rowname => $rows) {
             $col = 0;
             $virtual = $rows['virtual'];
             unset($rows['virtual']);
             if (isset($options['multiActions'])) {
                 $this->setCellContents($row, $col, '<input name="select-' . $rowname . '" value="' . $rowname . '" type="checkbox" />', 'TD', '0', false);
                 $col++;
             }
             foreach ($rows as $header => $data) {
                 $encode = true;
                 if (isset($options['fields']) && isset($options['fields'][$header]) && isset($options['fields'][$header]['showOverview']) && !$options['fields'][$header]['showOverview']) {
                     continue;
                 }
                 $origHeader = $header;
                 if (isset($options['fields'][$header]['sorting'])) {
                     $sorting = $options['fields'][$header]['sorting'];
                 } else {
                     if (isset($options['functions']['sorting'])) {
                         $sorting = $options['functions']['sorting'];
                     }
                 }
                 if ($first) {
                     if (isset($options['fields'][$header]['header'])) {
                         $header = $options['fields'][$header]['header'];
                     }
                     if (isset($_ARRAYLANG[$header])) {
                         $header = $_ARRAYLANG[$header];
                     }
                     if (is_array($options['functions']) && isset($options['functions']['sorting']) && $options['functions']['sorting'] && $sorting !== false) {
                         $order = '';
                         $img = '&uarr;&darr;';
                         if (isset($_GET['order'])) {
                             $supOrder = explode('/', $_GET['order']);
                             if (current($supOrder) == $origHeader) {
                                 $order = '/DESC';
                                 $img = '&darr;';
                                 if (count($supOrder) > 1 && $supOrder[1] == 'DESC') {
                                     $order = '';
                                     $img = '&uarr;';
                                 }
                             }
                         }
                         $header = '<a href="' . \Env::get('cx')->getRequest()->getUrl() . '&order=' . $origHeader . $order . '" style="white-space: nowrap;">' . $header . ' ' . $img . '</a>';
                     }
                     if ($hasMasterTableHeader) {
                         $this->setCellContents(1, $col, $header, 'td', 0);
                     } else {
                         $this->setCellContents(0, $col, $header, 'th', 0);
                     }
                 }
                 if (isset($options['fields']) && isset($options['fields'][$origHeader]) && isset($options['fields'][$origHeader]['table']) && isset($options['fields'][$origHeader]['table']['parse']) && is_callable($options['fields'][$origHeader]['table']['parse'])) {
                     $callback = $options['fields'][$origHeader]['table']['parse'];
                     $data = $callback($data, $rows);
                     $encode = false;
                     // todo: this should be set by callback
                 } else {
                     if (is_object($data) && get_class($data) == 'DateTime') {
                         $data = $data->format(ASCMS_DATE_FORMAT);
                     } else {
                         if (isset($options['fields'][$origHeader]) && isset($options['fields'][$origHeader]['type']) && $options['fields'][$origHeader]['type'] == '\\Country') {
                             $data = \Cx\Core\Country\Controller\Country::getNameById($data);
                             if (empty($data)) {
                                 $data = \Cx\Core\Country\Controller\Country::getNameById(204);
                             }
                         } else {
                             if (gettype($data) == 'boolean') {
                                 $data = '<i>' . ($data ? $_ARRAYLANG['TXT_YES'] : $_ARRAYLANG['TXT_NO']) . '</i>';
                                 $encode = false;
                             } else {
                                 if ($data === null) {
                                     $data = '<i>' . $_ARRAYLANG['TXT_CORE_NONE'] . '</i>';
                                     $encode = false;
                                 } else {
                                     if (empty($data)) {
                                         $data = '<i>(empty)</i>';
                                         $encode = false;
                                     }
                                 }
                             }
                         }
                     }
                 }
                 $this->setCellContents($row, $col, $data, 'TD', 0, $encode);
                 $col++;
             }
             if ($this->hasRowFunctions($options['functions'], $virtual)) {
                 if ($first) {
                     $header = 'Functions';
                     if (isset($_ARRAYLANG['TXT_FUNCTIONS'])) {
                         $header = $_ARRAYLANG['TXT_FUNCTIONS'];
                     }
                     if ($hasMasterTableHeader) {
                         $this->setCellContents(1, $col, $header, 'td', 0, true);
                     } else {
                         $this->setCellContents(0, $col, $header, 'th', 0, true);
                     }
                 }
                 $this->updateColAttributes($col, array('style' => 'text-align:right;'));
                 if (empty($options['functions']['baseUrl'])) {
                     $options['functions']['baseUrl'] = clone \Env::get('cx')->getRequest()->getUrl();
                 }
                 $this->setCellContents($row, $col, $this->getFunctionsCode($rowname, $rows, $options['functions'], $virtual), 'TD', 0);
             }
             $first = false;
             $row++;
         }
         // adjust colspan of master-table-header-row
         if ($hasMasterTableHeader) {
             $this->setCellAttributes(0, 0, array('colspan' => $col + is_array($options['functions'])));
             $this->updateRowAttributes(1, array('class' => 'row3'), true);
         }
         // add multi-actions
         if (isset($options['multiActions'])) {
             $multiActionsCode = '
                 <img src="images/icons/arrow.gif" width="38" height="22" alt="^" title="^">
                 <a href="#" onclick="jQuery(\'input[type=checkbox]\').prop(\'checked\', true);return false;">' . $_ARRAYLANG['TXT_SELECT_ALL'] . '</a> /
                 <a href="#" onclick="jQuery(\'input[type=checkbox]\').prop(\'checked\', false);return false;">' . $_ARRAYLANG['TXT_DESELECT_ALL'] . '</a>
                 <img alt="-" title="-" src="images/icons/strike.gif">
             ';
             $multiActions = array('' => $_ARRAYLANG['TXT_SUBMIT_SELECT']);
             foreach ($options['multiActions'] as $actionName => $actionProperties) {
                 $actionTitle = $actionName;
                 if (isset($actionProperties['title'])) {
                     $actionTitle = $actionProperties['title'];
                 } else {
                     if (isset($_ARRAYLANG[$actionName])) {
                         $actionTitle = $_ARRAYLANG[$actionName];
                     }
                 }
                 if (isset($actionProperties['jsEvent'])) {
                     $actionName = $actionProperties['jsEvent'];
                 }
                 $multiActions[$actionName] = $actionTitle;
             }
             $select = new \Cx\Core\Html\Model\Entity\DataElement('cxMultiAction', \Html::getOptions($multiActions), \Cx\Core\Html\Model\Entity\DataElement::TYPE_SELECT);
             // this is not a nice place for this code
             // but we should cleanup this complete class and make
             // it base on templates
             $select->setAttribute('onchange', '
                     var regex = /([a-zA-Z\\/]+):([a-zA-Z\\/]+)/;
                     var matches = jQuery(this).val().match(regex);
                     if (!matches) {
                         return false;
                     }
                     var checkboxes = jQuery(this).closest("table").find("input[type=checkbox]");
                     var activeRows = [];
                     checkboxes.filter(":checked").each(function(el) {
                         activeRows.push(jQuery(this).val());
                     });
                     cx.trigger(matches[1], matches[2], activeRows);
                     checkboxes.prop("checked", false);
                     jQuery(this).val("");
                 ');
             $this->setCellContents($row, 0, $multiActionsCode . $select, 'TD', 0);
             $this->setCellAttributes($row, 0, array('colspan' => $col + is_array($options['functions'])));
         }
         $attrs = array();
     }
     parent::__construct(array_merge($attrs, array('class' => 'adminlist', 'width' => '100%')));
 }
Exemplo n.º 5
0
 /**
  * Returns an array of Customer data for MailTemplate substitution
  *
  * The password is no longer available in the session if the confirmation
  * is sent after paying with some external PSP that uses some form of
  * instant payment notification (i.e. PayPal)!
  * In that case, it is *NOT* included in the template produced.
  * Call {@see Shop::sendLogin()} while processing the Order instead.
  * @return    array               The Customer data substitution array
  * @see       MailTemplate::substitute()
  */
 function getSubstitutionArray()
 {
     global $_ARRAYLANG;
     // See below.
     //        $index_notes = \Cx\Core\Setting\Controller\Setting::getValue('user_profile_attribute_notes','Shop');
     //        $index_type = \Cx\Core\Setting\Controller\Setting::getValue('user_attribute_customer_type','Shop');
     //        $index_reseller = \Cx\Core\Setting\Controller\Setting::getValue('user_attribute_reseller_status','Shop');
     $gender = strtoupper($this->gender());
     $title = $_ARRAYLANG['TXT_SHOP_TITLE_' . $gender];
     $format_salutation = $_ARRAYLANG['TXT_SHOP_SALUTATION_' . $gender];
     $salutation = sprintf($format_salutation, $this->firstname(), $this->lastname(), $this->company(), $title);
     $arrSubstitution = array('CUSTOMER_SALUTATION' => $salutation, 'CUSTOMER_ID' => $this->id(), 'CUSTOMER_EMAIL' => $this->email(), 'CUSTOMER_COMPANY' => $this->company(), 'CUSTOMER_FIRSTNAME' => $this->firstname(), 'CUSTOMER_LASTNAME' => $this->lastname(), 'CUSTOMER_ADDRESS' => $this->address(), 'CUSTOMER_ZIP' => $this->zip(), 'CUSTOMER_CITY' => $this->city(), 'CUSTOMER_COUNTRY' => \Cx\Core\Country\Controller\Country::getNameById($this->country_id()), 'CUSTOMER_PHONE' => $this->phone(), 'CUSTOMER_FAX' => $this->fax(), 'CUSTOMER_USERNAME' => $this->username());
     //DBG::log("Login: "******"/".$_SESSION['shop']['password']);
     if (isset($_SESSION['shop']['password'])) {
         $arrSubstitution['CUSTOMER_LOGIN'] = array(0 => array('CUSTOMER_USERNAME' => $this->username(), 'CUSTOMER_PASSWORD' => $_SESSION['shop']['password']));
     }
     return $arrSubstitution;
 }
Exemplo n.º 6
0
    public function getDataElement($name, $type, $length, $value, $options)
    {
        global $_ARRAYLANG;
        if (isset($options['formfield']) && is_callable($options['formfield'])) {
            $formFieldGenerator = $options['formfield'];
            $formField = $formFieldGenerator($name, $type, $length, $value, $options);
            if (is_a($formField, 'Cx\\Core\\Html\\Model\\Entity\\HtmlElement')) {
                return $formField;
            } else {
                $value = $formField;
            }
        }
        if (isset($options['showDetail']) && $options['showDetail'] === false) {
            return '';
        }
        switch ($type) {
            case 'bool':
            case 'boolean':
                // yes/no checkboxes
                $fieldset = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                $inputYes = new \Cx\Core\Html\Model\Entity\DataElement($name, 'yes');
                $inputYes->setAttribute('type', 'radio');
                $inputYes->setAttribute('value', '1');
                $inputYes->setAttribute('id', 'form-' . $this->formId . '-' . $name . '_yes');
                if (isset($options['attributes'])) {
                    $inputYes->setAttributes($options['attributes']);
                }
                $fieldset->addChild($inputYes);
                $labelYes = new \Cx\Core\Html\Model\Entity\HtmlElement('label');
                $labelYes->setAttribute('for', 'form-' . $this->formId . '-' . $name . '_yes');
                $labelYes->addChild(new \Cx\Core\Html\Model\Entity\TextElement($_ARRAYLANG['TXT_YES']));
                $fieldset->addChild($labelYes);
                $inputNo = new \Cx\Core\Html\Model\Entity\DataElement($name, 'no');
                $inputNo->setAttribute('id', 'form-' . $this->formId . '-' . $name . '_no');
                $inputNo->setAttribute('type', 'radio');
                $inputNo->setAttribute('value', '0');
                if (isset($options['attributes'])) {
                    $inputNo->setAttributes($options['attributes']);
                }
                $fieldset->addChild($inputNo);
                $labelNo = new \Cx\Core\Html\Model\Entity\HtmlElement('label');
                $labelNo->setAttribute('for', 'form-' . $this->formId . '-' . $name . '_no');
                $labelNo->addChild(new \Cx\Core\Html\Model\Entity\TextElement($_ARRAYLANG['TXT_NO']));
                $fieldset->addChild($labelNo);
                if ($value) {
                    $inputYes->setAttribute('checked');
                } else {
                    $inputNo->setAttribute('checked');
                }
                return $fieldset;
                break;
            case 'int':
            case 'integer':
                // input field with type number
                $inputNumber = new \Cx\Core\Html\Model\Entity\DataElement($name, $value, \Cx\Core\Html\Model\Entity\DataElement::TYPE_INPUT, new \Cx\Core\Validate\Model\Entity\RegexValidator('/-?[0-9]*/'));
                if (isset($options['attributes'])) {
                    $inputNumber->setAttributes($options['attributes']);
                }
                $inputNumber->setAttribute('type', 'number');
                return $inputNumber;
                break;
            case 'Cx\\Model\\Base\\EntityBase':
                $entityClass = get_class($value);
                $entities = \Env::get('em')->getRepository($entityClass)->findAll();
                $foreignMetaData = \Env::get('em')->getClassMetadata($entityClass);
                $primaryKeyName = $foreignMetaData->getSingleIdentifierFieldName();
                $selected = $foreignMetaData->getFieldValue($value, $primaryKeyName);
                $arrEntities = array();
                $closeMetaData = \Env::get('em')->getClassMetadata($this->entityClass);
                $assocMapping = $closeMetaData->getAssociationMapping($name);
                if (!isset($assocMapping['joinColumns'][0]['nullable']) || $assocMapping['joinColumns'][0]['nullable']) {
                    $arrEntities['NULL'] = $_ARRAYLANG['TXT_CORE_NONE'];
                }
                foreach ($entities as $entity) {
                    $arrEntities[\Env::get('em')->getClassMetadata($entityClass)->getFieldValue($entity, $primaryKeyName)] = $entity;
                }
                $select = new \Cx\Core\Html\Model\Entity\DataElement($name, \Html::getOptions($arrEntities, $selected), \Cx\Core\Html\Model\Entity\DataElement::TYPE_SELECT);
                if (isset($options['attributes'])) {
                    $select->setAttributes($options['attributes']);
                }
                return $select;
                break;
            case 'Country':
                // this is for customizing only:
                $data = \Cx\Core\Country\Controller\Country::getNameById($value);
                if (empty($data)) {
                    $value = 204;
                }
                $options = \Cx\Core\Country\Controller\Country::getMenuoptions($value);
                $select = new \Cx\Core\Html\Model\Entity\DataElement($name, $options, \Cx\Core\Html\Model\Entity\DataElement::TYPE_SELECT);
                if (isset($options['attributes'])) {
                    $select->setAttributes($options['attributes']);
                }
                return $select;
                break;
            case 'DateTime':
            case 'datetime':
            case 'date':
                // input field with type text and class datepicker
                if ($value instanceof \DateTime) {
                    $value = $value->format(ASCMS_DATE_FORMAT);
                }
                if (is_null($value)) {
                    $value = '';
                }
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'text');
                $input->setAttribute('class', 'datepicker');
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                \DateTimeTools::addDatepickerJs();
                \JS::registerCode('
                        cx.jQuery(function() {
                          cx.jQuery(".datepicker").datetimepicker();
                        });
                        ');
                return $input;
                break;
            case 'multiselect':
            case 'select':
                $values = array();
                if (isset($options['validValues'])) {
                    if (is_array($options['validValues'])) {
                        $values = $options['validValues'];
                    } else {
                        $values = explode(',', $options['validValues']);
                        $values = array_combine($values, $values);
                    }
                }
                if ($type == 'multiselect') {
                    $value = explode(',', $value);
                    $value = array_combine($value, $value);
                }
                $selectOptions = \Html::getOptions($values, $value);
                $select = new \Cx\Core\Html\Model\Entity\DataElement($name, $selectOptions, \Cx\Core\Html\Model\Entity\DataElement::TYPE_SELECT);
                if ($type == 'multiselect') {
                    $select->setAttribute('multiple');
                }
                if (isset($options['attributes'])) {
                    $select->setAttributes($options['attributes']);
                }
                return $select;
                break;
            case 'slider':
                // this code should not be here
                // create sorrounding div
                $element = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                // create div for slider
                $slider = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                $slider->setAttribute('class', 'slider');
                $element->addChild($slider);
                // create hidden input for slider value
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value + 0, \Cx\Core\Html\Model\Entity\DataElement::TYPE_INPUT);
                $input->setAttribute('type', 'hidden');
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                $element->addChild($input);
                // add javascript to update input value
                $min = 0;
                $max = 10;
                if (isset($options['validValues'])) {
                    $values = explode(',', $options['validValues']);
                    $min = $values[0];
                    if (isset($values[1])) {
                        $max = $values[1];
                    }
                }
                if (!isset($value)) {
                    $value = 0;
                }
                $script = new \Cx\Core\Html\Model\Entity\HtmlElement('script');
                $script->addChild(new \Cx\Core\Html\Model\Entity\TextElement('
                    cx.jQuery("#form-' . $this->formId . '-' . $name . ' .slider").slider({
                        value: ' . ($value + 0) . ',
                        min: ' . ($min + 0) . ',
                        max: ' . ($max + 0) . ',
                        slide: function( event, ui ) {
                            cx.jQuery("input[name=' . $name . ']").val(ui.value);
                            cx.jQuery("input[name=' . $name . ']").change();
                        }
                    });
                '));
                $element->addChild($script);
                return $element;
                break;
            case 'checkboxes':
                $dataElementGroupType = \Cx\Core\Html\Model\Entity\DataElementGroup::TYPE_CHECKBOX;
            case 'radio':
                $values = array();
                if (isset($options['validValues'])) {
                    $values = explode(',', $options['validValues']);
                    $values = array_combine($values, $values);
                }
                if (!isset($dataElementGroupType)) {
                    $dataElementGroupType = \Cx\Core\Html\Model\Entity\DataElementGroup::TYPE_RADIO;
                }
                $radio = new \Cx\Core\Html\Model\Entity\DataElementGroup($name, $values, $value, $dataElementGroupType);
                if (isset($options['attributes'])) {
                    $radio->setAttributes($options['attributes']);
                }
                return $radio;
                break;
            case 'text':
                // textarea
                $textarea = new \Cx\Core\Html\Model\Entity\HtmlElement('textarea');
                $textarea->setAttribute('name', $name);
                if (isset($options['readonly']) && $options['readonly']) {
                    $textarea->setAttribute('disabled');
                }
                $textarea->addChild(new \Cx\Core\Html\Model\Entity\TextElement($value));
                if (isset($options['attributes'])) {
                    $textarea->setAttributes($options['attributes']);
                }
                return $textarea;
                break;
            case 'phone':
                // input field with type phone
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'phone');
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                return $input;
                break;
            case 'mail':
                // input field with type mail
                $emailValidator = new \Cx\Core\Validate\Model\Entity\EmailValidator();
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value, 'input', $emailValidator);
                $input->setAttribute('onkeyup', $emailValidator->getJavaScriptCode());
                $input->setAttribute('type', 'mail');
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                return $input;
                break;
            case 'uploader':
                \JS::registerCode('
                    function javascript_callback_function(data) {
                        if(data.type=="file") {
                                cx.jQuery("#' . $name . '").val(data.data[0].datainfo.filepath);
                        }
                    }

                ');
                $mediaBrowser = new \Cx\Core_Modules\MediaBrowser\Model\Entity\MediaBrowser();
                $mediaBrowser->setOptions(array('type' => 'button'));
                $mediaBrowser->setCallback('javascript_callback_function');
                $mediaBrowser->setOptions(array('data-cx-mb-views' => 'filebrowser,uploader', 'id' => 'page_target_browse', 'cxMbStartview' => 'MediaBrowserList'));
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'text');
                $input->setAttribute('id', $name);
                $div = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                $div->addChild($input);
                $div->addChild(new \Cx\Core\Html\Model\Entity\TextElement($mb = $mediaBrowser->getXHtml($_ARRAYLANG['TXT_CORE_CM_BROWSE'])));
                return $div;
                break;
            case 'image':
                \JS::registerCode('
                    function javascript_callback_function(data) {
                        if ( data.data[0].datainfo.extension=="Jpg"
                            || data.data[0].datainfo.extension=="Gif"
                            || data.data[0].datainfo.extension=="Png"
                        ) {
                            cx.jQuery("#' . $name . '").attr(\'value\', data.data[0].datainfo.filepath);
                            cx.jQuery("#' . $name . '").prevAll(\'.deletePreviewImage\').first().css(\'display\', \'inline-block\');
                            cx.jQuery("#' . $name . '").prevAll(\'.previewImage\').first().attr(\'src\', data.data[0].datainfo.filepath);
                        }
                    }

                    jQuery(document).ready(function(){
                        jQuery(\'.deletePreviewImage\').click(function(){
                            cx.jQuery("#' . $name . '").attr(\'value\', \'\');
                            cx.jQuery(this).prev(\'img\').attr(\'src\', \'/images/Downloads/no_picture.gif\');
                            cx.jQuery(this).css(\'display\', \'none\');
                            cx.jQuery(this).nextAll(\'input\').first().attr(\'value\', \'\');
                        });
                    });

                ');
                $mediaBrowser = new \Cx\Core_Modules\MediaBrowser\Model\Entity\MediaBrowser();
                $mediaBrowser->setOptions(array('type' => 'button'));
                $mediaBrowser->setCallback('javascript_callback_function');
                $defaultOptions = array('data-cx-mb-views' => 'filebrowser,uploader', 'id' => 'page_target_browse', 'cxMbStartview' => 'MediaBrowserList');
                $mediaBrowser->setOptions(is_array($options['options']) ? array_merge($defaultOptions, $options['options']) : $defaultOptions);
                // create hidden input to save image
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                $input->setAttribute('type', 'hidden');
                $input->setAttribute('id', $name);
                $div = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                if (isset($value) && in_array(pathinfo($value, PATHINFO_EXTENSION), array('gif', 'jpg', 'png')) || $name == 'imagePath') {
                    // this image is meant to be a preview of the selected image
                    $previewImage = new \Cx\Core\Html\Model\Entity\HtmlElement('img');
                    $previewImage->setAttribute('class', 'previewImage');
                    $previewImage->setAttribute('src', $value != '' ? $value : '/images/Downloads/no_picture.gif');
                    // this image is uesd as delete function for the selected image over javascript
                    $deleteImage = new \Cx\Core\Html\Model\Entity\HtmlElement('img');
                    $deleteImage->setAttribute('class', 'deletePreviewImage');
                    $deleteImage->setAttribute('src', '/core/Core/View/Media/icons/delete.gif');
                    $div->addChild($previewImage);
                    $div->addChild($deleteImage);
                    $div->addChild(new \Cx\Core\Html\Model\Entity\HtmlElement('br'));
                }
                $div->addChild($input);
                $div->addChild(new \Cx\Core\Html\Model\Entity\TextElement($mediaBrowser->getXHtml($_ARRAYLANG['TXT_CORE_CM_BROWSE'])));
                return $div;
                break;
            case 'sourcecode':
                //set mode
                $mode = 'html';
                if (isset($options['options']['mode'])) {
                    switch ($options['options']['mode']) {
                        case 'js':
                            $mode = 'javascript';
                            break;
                        case 'yml':
                        case 'yaml':
                            $mode = 'yaml';
                            break;
                    }
                }
                //define textarea
                $textarea = new \Cx\Core\Html\Model\Entity\HtmlElement('textarea');
                $textarea->setAttribute('name', $name);
                $textarea->setAttribute('id', $name);
                $textarea->setAttribute('style', 'display:none;');
                $textarea->addChild(new \Cx\Core\Html\Model\Entity\TextElement($value));
                //define pre
                $pre = new \Cx\Core\Html\Model\Entity\HtmlElement('pre');
                $pre->setAttribute('id', 'editor-' . $name);
                $pre->addChild(new \Cx\Core\Html\Model\Entity\TextElement(contrexx_raw2xhtml($value)));
                //set readonly if necessary
                $readonly = '';
                if (isset($options['readonly']) && $options['readonly']) {
                    $readonly = 'editor.setReadOnly(true);';
                    $textarea->setAttribute('disabled');
                }
                //create div and add all stuff
                $div = new \Cx\Core\Html\Model\Entity\HtmlElement('div');
                $div->addChild($textarea);
                $div->addChild($pre);
                //register js
                $jsCode = <<<CODE
var editor;                        
\$J(function(){
if (\$J("#editor-{$name}").length) {
    editor = ace.edit("editor-{$name}");
    editor.getSession().setMode("ace/mode/{$mode}");
    editor.setShowPrintMargin(false);
    editor.focus();
    editor.gotoLine(1);
    {$readonly}
}

\$J('form').submit(function(){
    \$J('#{$name}').val(editor.getSession().getValue());
});

});
CODE;
                \JS::activate('ace');
                \JS::registerCode($jsCode);
                return $div;
                break;
            case 'string':
            case 'hidden':
            default:
                // convert NULL to empty string
                if (is_null($value)) {
                    $value = '';
                }
                // input field with type text
                $input = new \Cx\Core\Html\Model\Entity\DataElement($name, $value);
                if (isset($options['validValues'])) {
                    $input->setValidator(new \Cx\Core\Validate\Model\Entity\RegexValidator('/^' . $options['validValues'] . '$/'));
                }
                if ($type == 'hidden') {
                    $input->setAttribute('type', 'hidden');
                } else {
                    $input->setAttribute('type', 'text');
                    $input->setClass('form-control');
                }
                if (isset($options['readonly']) && $options['readonly']) {
                    $input->setAttribute('disabled');
                }
                if (isset($options['attributes'])) {
                    $input->setAttributes($options['attributes']);
                }
                return $input;
                break;
        }
    }
Exemplo n.º 7
0
 public function __construct($attrs = array(), $options = array())
 {
     global $_ARRAYLANG;
     if ($attrs instanceof \Cx\Core_Modules\Listing\Model\Entity\DataSet) {
         $hasMasterTableHeader = !empty($options['header']);
         // add master table-header-row
         if ($hasMasterTableHeader) {
             $this->addRow(array(0 => $options['header']), null, 'th');
         }
         $first = true;
         $row = 1 + $hasMasterTableHeader;
         $sortBy = isset($options['functions']['sortBy']) && is_array($options['functions']['sortBy']) ? $options['functions']['sortBy'] : array();
         $sortingKey = !empty($sortBy) && isset($sortBy['sortingKey']) ? $sortBy['sortingKey'] : '';
         $sortField = !empty($sortingKey) && isset($sortBy['field']) ? key($sortBy['field']) : '';
         $component = !empty($sortBy) && isset($sortBy['component']) ? $sortBy['component'] : '';
         $entity = !empty($sortBy) && isset($sortBy['entity']) ? $sortBy['entity'] : '';
         $sortOrder = !empty($sortBy) && isset($sortBy['sortOrder']) ? $sortBy['sortOrder'] : '';
         $pagingPos = !empty($sortBy) && isset($sortBy['pagingPosition']) ? $sortBy['pagingPosition'] : '';
         foreach ($attrs as $rowname => $rows) {
             $col = 0;
             $virtual = $rows['virtual'];
             unset($rows['virtual']);
             if (isset($options['multiActions'])) {
                 $this->setCellContents($row, $col, '<input name="select-' . $rowname . '" value="' . $rowname . '" type="checkbox" />', 'TD', '0', false);
                 $col++;
             }
             foreach ($rows as $header => $data) {
                 if (!empty($sortingKey) && $header === $sortingKey) {
                     //Add the additional attribute id, for getting the updated sort order after the row sorting
                     $this->updateRowAttributes($row, array('id' => 'sorting' . $entity . '_' . $data), true);
                 }
                 $encode = true;
                 if (isset($options['fields']) && isset($options['fields'][$header]) && isset($options['fields'][$header]['showOverview']) && !$options['fields'][$header]['showOverview']) {
                     continue;
                 }
                 if (!empty($sortField) && $header === $sortField) {
                     //Add the additional attribute class, to display the updated sort order after the row sorting
                     $this->updateColAttributes($col, array('class' => 'sortBy' . $sortField));
                 }
                 $origHeader = $header;
                 if (isset($options['fields'][$header]['sorting'])) {
                     $sorting = $options['fields'][$header]['sorting'];
                 } else {
                     if (isset($options['functions']['sorting'])) {
                         $sorting = $options['functions']['sorting'];
                     }
                 }
                 if ($first) {
                     if (isset($options['fields'][$header]['header'])) {
                         $header = $options['fields'][$header]['header'];
                     }
                     if (isset($_ARRAYLANG[$header])) {
                         $header = $_ARRAYLANG[$header];
                     }
                     if (is_array($options['functions']) && isset($options['functions']['sorting']) && $options['functions']['sorting'] && $sorting !== false) {
                         $order = '';
                         $img = '&uarr;&darr;';
                         $sortParamName = !empty($sortBy) ? $entity . 'Order' : 'order';
                         if (isset($_GET[$sortParamName])) {
                             $supOrder = explode('/', $_GET[$sortParamName]);
                             if (current($supOrder) == $origHeader) {
                                 $order = '/DESC';
                                 $img = '&darr;';
                                 if (count($supOrder) > 1 && $supOrder[1] == 'DESC') {
                                     $order = '';
                                     $img = '&uarr;';
                                 }
                             }
                         }
                         $header = '<a href="' . \Env::get('cx')->getRequest()->getUrl() . '&' . $sortParamName . '=' . $origHeader . $order . '" style="white-space: nowrap;">' . $header . ' ' . $img . '</a>';
                     }
                     if ($hasMasterTableHeader) {
                         $this->setCellContents(1, $col, $header, 'td', 0);
                     } else {
                         $this->setCellContents(0, $col, $header, 'th', 0);
                     }
                 }
                 /* We use json to do parse the field function. The 'else if' is for backwards compatibility so you can declare
                  * the function directly without using json. This is not recommended and not working over session */
                 if (isset($options['fields']) && isset($options['fields'][$origHeader]) && isset($options['fields'][$origHeader]['table']) && isset($options['fields'][$origHeader]['table']['parse'])) {
                     $callback = $options['fields'][$origHeader]['table']['parse'];
                     if (is_array($callback) && isset($callback['adapter']) && isset($callback['method'])) {
                         $json = new \Cx\Core\Json\JsonData();
                         $jsonResult = $json->data($callback['adapter'], $callback['method'], array('data' => $data, 'rows' => $rows));
                         if ($jsonResult['status'] == 'success') {
                             $data = $jsonResult["data"];
                         }
                     } else {
                         if (is_callable($callback)) {
                             $data = $callback($data, $rows);
                         }
                     }
                     $encode = false;
                     // todo: this should be set by callback
                 } else {
                     if (is_object($data) && get_class($data) == 'DateTime') {
                         $data = $data->format(ASCMS_DATE_FORMAT);
                     } else {
                         if (isset($options['fields'][$origHeader]) && isset($options['fields'][$origHeader]['type']) && $options['fields'][$origHeader]['type'] == '\\Country') {
                             $data = \Cx\Core\Country\Controller\Country::getNameById($data);
                             if (empty($data)) {
                                 $data = \Cx\Core\Country\Controller\Country::getNameById(204);
                             }
                         } else {
                             if (gettype($data) == 'boolean') {
                                 $data = '<i>' . ($data ? $_ARRAYLANG['TXT_YES'] : $_ARRAYLANG['TXT_NO']) . '</i>';
                                 $encode = false;
                             } else {
                                 if ($data === null) {
                                     $data = '<i>' . $_ARRAYLANG['TXT_CORE_NONE'] . '</i>';
                                     $encode = false;
                                 } else {
                                     if (empty($data)) {
                                         $data = '<i>(empty)</i>';
                                         $encode = false;
                                     }
                                 }
                             }
                         }
                     }
                 }
                 $this->setCellContents($row, $col, $data, 'TD', 0, $encode);
                 $col++;
             }
             if ($this->hasRowFunctions($options['functions'], $virtual)) {
                 if ($first) {
                     $header = 'Functions';
                     if (isset($_ARRAYLANG['TXT_FUNCTIONS'])) {
                         $header = $_ARRAYLANG['TXT_FUNCTIONS'];
                     }
                     if ($hasMasterTableHeader) {
                         $this->setCellContents(1, $col, $header, 'td', 0, true);
                     } else {
                         $this->setCellContents(0, $col, $header, 'th', 0, true);
                     }
                 }
                 $this->updateColAttributes($col, array('style' => 'text-align:right;'));
                 if (empty($options['functions']['baseUrl'])) {
                     $options['functions']['baseUrl'] = clone \Env::get('cx')->getRequest()->getUrl();
                 }
                 $this->setCellContents($row, $col, $this->getFunctionsCode($rowname, $rows, $options['functions'], $virtual), 'TD', 0);
             }
             $first = false;
             $row++;
         }
         // adjust colspan of master-table-header-row
         if ($hasMasterTableHeader) {
             $this->setCellAttributes(0, 0, array('colspan' => $col + is_array($options['functions'])));
             $this->updateRowAttributes(1, array('class' => 'row3'), true);
         }
         // add multi-actions
         if (isset($options['multiActions'])) {
             $multiActionsCode = '
                 <img src="images/icons/arrow.gif" width="38" height="22" alt="^" title="^">
                 <a href="#" onclick="jQuery(\'input[type=checkbox]\').prop(\'checked\', true);return false;">' . $_ARRAYLANG['TXT_SELECT_ALL'] . '</a> /
                 <a href="#" onclick="jQuery(\'input[type=checkbox]\').prop(\'checked\', false);return false;">' . $_ARRAYLANG['TXT_DESELECT_ALL'] . '</a>
                 <img alt="-" title="-" src="images/icons/strike.gif">
             ';
             $multiActions = array('' => $_ARRAYLANG['TXT_SUBMIT_SELECT']);
             foreach ($options['multiActions'] as $actionName => $actionProperties) {
                 $actionTitle = $actionName;
                 if (isset($actionProperties['title'])) {
                     $actionTitle = $actionProperties['title'];
                 } else {
                     if (isset($_ARRAYLANG[$actionName])) {
                         $actionTitle = $_ARRAYLANG[$actionName];
                     }
                 }
                 if (isset($actionProperties['jsEvent'])) {
                     $actionName = $actionProperties['jsEvent'];
                 }
                 $multiActions[$actionName] = $actionTitle;
             }
             $select = new \Cx\Core\Html\Model\Entity\DataElement('cxMultiAction', \Html::getOptions($multiActions), \Cx\Core\Html\Model\Entity\DataElement::TYPE_SELECT);
             // this is not a nice place for this code
             // but we should cleanup this complete class and make
             // it base on templates
             $select->setAttribute('onchange', '
                     var regex = /([a-zA-Z\\/]+):([a-zA-Z\\/]+)/;
                     var matches = jQuery(this).val().match(regex);
                     if (!matches) {
                         return false;
                     }
                     var checkboxes = jQuery(this).closest("table").find("input[type=checkbox]");
                     var activeRows = [];
                     checkboxes.filter(":checked").each(function(el) {
                         activeRows.push(jQuery(this).val());
                     });
                     cx.trigger(matches[1], matches[2], activeRows);
                     checkboxes.prop("checked", false);
                     jQuery(this).val("");
                 ');
             $this->setCellContents($row, 0, $multiActionsCode . $select, 'TD', 0);
             $this->setCellAttributes($row, 0, array('colspan' => $col + is_array($options['functions'])));
         }
         $attrs = array();
     }
     //add the sorting parameters as table attribute
     //if the row sorting functionality is enabled
     $className = 'adminlist';
     if (!empty($sortField)) {
         $className = '\'adminlist sortable\'';
         if (!empty($component)) {
             $attrs['data-component'] = $component;
         }
         if (!empty($entity)) {
             $attrs['data-entity'] = $entity;
         }
         if (!empty($sortOrder)) {
             $attrs['data-order'] = $sortOrder;
         }
         if (!empty($sortField)) {
             $attrs['data-field'] = $sortField;
         }
         if (isset($pagingPos)) {
             $attrs['data-pos'] = $pagingPos;
         }
         $attrs['data-object'] = 'Html';
         $attrs['data-act'] = 'updateOrder';
         if (isset($sortBy['jsonadapter']) && !empty($sortBy['jsonadapter']['object']) && !empty($sortBy['jsonadapter']['act'])) {
             $attrs['data-object'] = $sortBy['jsonadapter']['object'];
             $attrs['data-act'] = $sortBy['jsonadapter']['act'];
         }
     }
     parent::__construct(array_merge($attrs, array('class' => $className, 'width' => '100%')));
 }
Exemplo n.º 8
0
 /**
  * Show modify block
  *
  * Show the block modification page
  *
  * @access private
  * @global array
  * @see blockLibrary::_getBlockContent(), blockLibrary::blockNamePrefix
  */
 private function _showModifyBlock($copy = false)
 {
     global $_ARRAYLANG;
     \JS::activate('cx');
     \JS::activate('ckeditor');
     \JS::activate('jqueryui');
     \JS::registerJS('lib/javascript/tag-it/js/tag-it.min.js');
     \JS::registerCss('lib/javascript/tag-it/css/tag-it.css');
     $mediaBrowserCkeditor = new MediaBrowser();
     $mediaBrowserCkeditor->setCallback('ckeditor_image_button');
     $mediaBrowserCkeditor->setOptions(array('id' => 'ckeditor_image_button', 'type' => 'button', 'style' => 'display:none'));
     $blockId = !empty($_REQUEST['blockId']) ? intval($_REQUEST['blockId']) : 0;
     $blockCat = 0;
     $blockName = '';
     $blockStart = 0;
     $blockEnd = 0;
     $blockRandom = 0;
     $blockRandom2 = 0;
     $blockRandom3 = 0;
     $blockRandom4 = 0;
     $blockGlobal = 0;
     $blockDirect = 0;
     $blockCategory = 0;
     $blockWysiwygEditor = 1;
     $blockContent = array();
     $blockAssociatedPageIds = array();
     $blockLangActive = array();
     $blockGlobalAssociatedPageIds = array();
     $blockDirectAssociatedPageIds = array();
     $blockCategoryAssociatedPageIds = array();
     $this->_objTpl->loadTemplateFile('module_block_modify.html');
     $this->_objTpl->setGlobalVariable(array('TXT_BLOCK_CONTENT' => $_ARRAYLANG['TXT_BLOCK_CONTENT'], 'TXT_BLOCK_NAME' => $_ARRAYLANG['TXT_BLOCK_NAME'], 'TXT_BLOCK_RANDOM' => $_ARRAYLANG['TXT_BLOCK_RANDOM'], 'TXT_BLOCK_GLOBAL' => $_ARRAYLANG['TXT_BLOCK_SHOW_IN_GLOBAL'], 'TXT_BLOCK_SAVE' => $_ARRAYLANG['TXT_BLOCK_SAVE'], 'TXT_BLOCK_DEACTIVATE' => $_ARRAYLANG['TXT_BLOCK_DEACTIVATE'], 'TXT_BLOCK_ACTIVATE' => $_ARRAYLANG['TXT_BLOCK_ACTIVATE'], 'TXT_DONT_SHOW_ON_PAGES' => $_ARRAYLANG['TXT_DONT_SHOW_ON_PAGES'], 'TXT_SHOW_ON_ALL_PAGES' => $_ARRAYLANG['TXT_SHOW_ON_ALL_PAGES'], 'TXT_SHOW_ON_SELECTED_PAGES' => $_ARRAYLANG['TXT_SHOW_ON_SELECTED_PAGES'], 'TXT_BLOCK_CATEGORY' => $_ARRAYLANG['TXT_BLOCK_CATEGORY'], 'TXT_BLOCK_NONE' => $_ARRAYLANG['TXT_BLOCK_NONE'], 'TXT_BLOCK_SHOW_FROM' => $_ARRAYLANG['TXT_BLOCK_SHOW_FROM'], 'TXT_BLOCK_SHOW_UNTIL' => $_ARRAYLANG['TXT_BLOCK_SHOW_UNTIL'], 'TXT_BLOCK_SHOW_TIMED' => $_ARRAYLANG['TXT_BLOCK_SHOW_TIMED'], 'TXT_BLOCK_SHOW_ALWAYS' => $_ARRAYLANG['TXT_BLOCK_SHOW_ALWAYS'], 'TXT_BLOCK_LANG_SHOW' => $_ARRAYLANG['TXT_BLOCK_SHOW_BLOCK_IN_THIS_LANGUAGE'], 'TXT_BLOCK_BASIC_DATA' => $_ARRAYLANG['TXT_BLOCK_BASIC_DATA'], 'TXT_BLOCK_ADDITIONAL_OPTIONS' => $_ARRAYLANG['TXT_BLOCK_ADDITIONAL_OPTIONS'], 'TXT_BLOCK_SELECTED_PAGES' => $_ARRAYLANG['TXT_BLOCK_SELECTED_PAGES'], 'TXT_BLOCK_AVAILABLE_PAGES' => $_ARRAYLANG['TXT_BLOCK_AVAILABLE_PAGES'], 'TXT_BLOCK_SELECT_ALL' => $_ARRAYLANG['TXT_BLOCK_SELECT_ALL'], 'TXT_BLOCK_UNSELECT_ALL' => $_ARRAYLANG['TXT_BLOCK_UNSELECT_ALL'], 'TXT_BLOCK_GLOBAL_PLACEHOLDERS' => $_ARRAYLANG['TXT_BLOCK_GLOBAL_PLACEHOLDERS'], 'TXT_BLOCK_GLOBAL_PLACEHOLDERS_INFO' => $_ARRAYLANG['TXT_BLOCK_GLOBAL_PLACEHOLDERS_INFO'], 'TXT_BLOCK_DIRECT_PLACEHOLDERS' => $_ARRAYLANG['TXT_BLOCK_DIRECT_PLACEHOLDERS'], 'TXT_BLOCK_DIRECT_PLACEHOLDERS_INFO' => $_ARRAYLANG['TXT_BLOCK_DIRECT_PLACEHOLDERS_INFO'], 'TXT_BLOCK_CATEGORY_PLACEHOLDERS' => $_ARRAYLANG['TXT_BLOCK_CATEGORY_PLACEHOLDERS'], 'TXT_BLOCK_CATEGORY_PLACEHOLDERS_INFO' => $_ARRAYLANG['TXT_BLOCK_CATEGORY_PLACEHOLDERS_INFO'], 'TXT_BLOCK_DISPLAY_TIME' => $_ARRAYLANG['TXT_BLOCK_DISPLAY_TIME'], 'TXT_BLOCK_FORM_DESC' => $_ARRAYLANG['TXT_BLOCK_CONTENT'], 'TXT_BLOCK_USE_WYSIWYG_EDITOR' => $_ARRAYLANG['TXT_BLOCK_USE_WYSIWYG_EDITOR'], 'TXT_BLOCK_TARGETING' => $_ARRAYLANG['TXT_BLOCK_TARGETING'], 'TXT_BLOCK_TARGETING_SHOW_PANE' => $_ARRAYLANG['TXT_BLOCK_TARGETING_SHOW_PANE'], 'TXT_BLOCK_TARGETING_ALL_USERS' => $_ARRAYLANG['TXT_BLOCK_TARGETING_ALL_USERS'], 'TXT_BLOCK_TARGETING_VISITOR_CONDITION_BELOW' => $_ARRAYLANG['TXT_BLOCK_TARGETING_VISITOR_CONDITION_BELOW'], 'TXT_BLOCK_TARGETING_INCLUDE' => $_ARRAYLANG['TXT_BLOCK_TARGETING_INCLUDE'], 'TXT_BLOCK_TARGETING_EXCLUDE' => $_ARRAYLANG['TXT_BLOCK_TARGETING_EXCLUDE'], 'TXT_BLOCK_TARGETING_TYPE_LOCATION' => $_ARRAYLANG['TXT_BLOCK_TARGETING_TYPE_LOCATION'], 'TXT_BLOCK_TARGETING_GEOIP_DISABLED_WARNING' => $_ARRAYLANG['TXT_BLOCK_TARGETING_GEOIP_DISABLED_WARNING']));
     $targetingStatus = isset($_POST['targeting_status']) ? contrexx_input2int($_POST['targeting_status']) : 0;
     $targeting = array();
     foreach ($this->availableTargeting as $targetingType) {
         $targetingArr = isset($_POST['targeting'][$targetingType]) ? $_POST['targeting'][$targetingType] : array();
         if (empty($targetingArr)) {
             continue;
         }
         $targeting[$targetingType] = array('filter' => !empty($targetingArr['filter']) && in_array($targetingArr['filter'], array('include', 'exclude')) ? contrexx_input2raw($targetingArr['filter']) : 'include', 'value' => isset($targetingArr['value']) ? contrexx_input2raw($targetingArr['value']) : array());
     }
     if (isset($_POST['block_save_block'])) {
         $blockCat = !empty($_POST['blockCat']) ? intval($_POST['blockCat']) : 0;
         $blockContent = isset($_POST['blockFormText_']) ? array_map('contrexx_input2raw', $_POST['blockFormText_']) : array();
         $blockName = !empty($_POST['blockName']) ? contrexx_input2raw($_POST['blockName']) : $_ARRAYLANG['TXT_BLOCK_NO_NAME'];
         $blockStart = strtotime($_POST['inputStartDate']);
         $blockEnd = strtotime($_POST['inputEndDate']);
         $blockRandom = !empty($_POST['blockRandom']) ? intval($_POST['blockRandom']) : 0;
         $blockRandom2 = !empty($_POST['blockRandom2']) ? intval($_POST['blockRandom2']) : 0;
         $blockRandom3 = !empty($_POST['blockRandom3']) ? intval($_POST['blockRandom3']) : 0;
         $blockRandom4 = !empty($_POST['blockRandom4']) ? intval($_POST['blockRandom4']) : 0;
         $blockWysiwygEditor = isset($_POST['wysiwyg_editor']) ? 1 : 0;
         $blockLangActive = isset($_POST['blockFormLanguages']) ? array_map('intval', $_POST['blockFormLanguages']) : array();
         // placeholder configurations
         // global block
         // 0 = not activated , 1 = on all pages , 2 = selected pages
         $blockGlobal = !empty($_POST['blockGlobal']) ? intval($_POST['blockGlobal']) : 0;
         // direct block and category block placeholders
         // 0 = on all pages , 1 = selected pages
         $blockDirect = !empty($_POST['blockDirect']) ? intval($_POST['blockDirect']) : 0;
         $blockCategory = !empty($_POST['blockCategory']) ? intval($_POST['blockCategory']) : 0;
         // block on page relations for each placeholder
         $blockGlobalAssociatedPageIds = isset($_POST['globalSelectedPagesList']) ? array_map('intval', explode(",", $_POST['globalSelectedPagesList'])) : array();
         $blockDirectAssociatedPageIds = isset($_POST['directSelectedPagesList']) ? array_map('intval', explode(",", $_POST['directSelectedPagesList'])) : array();
         $blockCategoryAssociatedPageIds = isset($_POST['categorySelectedPagesList']) ? array_map('intval', explode(",", $_POST['categorySelectedPagesList'])) : array();
         if ($blockId) {
             if ($this->_updateBlock($blockId, $blockCat, $blockContent, $blockName, $blockStart, $blockEnd, $blockRandom, $blockRandom2, $blockRandom3, $blockRandom4, $blockWysiwygEditor, $blockLangActive)) {
                 if ($this->storePlaceholderSettings($blockId, $blockGlobal, $blockDirect, $blockCategory, $blockGlobalAssociatedPageIds, $blockDirectAssociatedPageIds, $blockCategoryAssociatedPageIds)) {
                     $this->storeTargetingSettings($blockId, $targetingStatus, $targeting);
                     \Cx\Core\Csrf\Controller\Csrf::header('location: index.php?cmd=Block&modified=true&blockname=' . $blockName);
                     exit;
                 }
             }
             $this->_strErrMessage = $_ARRAYLANG['TXT_BLOCK_BLOCK_COULD_NOT_BE_UPDATED'];
         } else {
             if ($blockId = $this->_addBlock($blockCat, $blockContent, $blockName, $blockStart, $blockEnd, $blockRandom, $blockRandom2, $blockRandom3, $blockRandom4, $blockWysiwygEditor, $blockLangActive)) {
                 if ($this->storePlaceholderSettings($blockId, $blockGlobal, $blockDirect, $blockCategory, $blockGlobalAssociatedPageIds, $blockDirectAssociatedPageIds, $blockCategoryAssociatedPageIds)) {
                     $this->storeTargetingSettings($blockId, $targetingStatus, $targeting);
                     \Cx\Core\Csrf\Controller\Csrf::header('location: index.php?cmd=Block&added=true&blockname=' . $blockName);
                     exit;
                 }
             }
             $this->_strErrMessage = $_ARRAYLANG['TXT_BLOCK_BLOCK_COULD_NOT_BE_ADDED'];
         }
     } elseif (($arrBlock = $this->_getBlock($blockId)) !== false) {
         $blockStart = $arrBlock['start'];
         $blockEnd = $arrBlock['end'];
         $blockCat = $arrBlock['cat'];
         $blockRandom = $arrBlock['random'];
         $blockRandom2 = $arrBlock['random2'];
         $blockRandom3 = $arrBlock['random3'];
         $blockRandom4 = $arrBlock['random4'];
         $blockWysiwygEditor = $arrBlock['wysiwyg_editor'];
         $blockContent = $arrBlock['content'];
         $blockLangActive = $arrBlock['lang_active'];
         $blockName = $arrBlock['name'];
         $blockGlobal = $arrBlock['global'];
         $blockDirect = $arrBlock['direct'];
         $blockCategory = $arrBlock['category'];
         $blockGlobalAssociatedPageIds = $this->_getAssociatedPageIds($blockId, 'global');
         $blockDirectAssociatedPageIds = $this->_getAssociatedPageIds($blockId, 'direct');
         $blockCategoryAssociatedPageIds = $this->_getAssociatedPageIds($blockId, 'category');
         $targeting = $this->loadTargetingSettings($blockId);
         if (!empty($targeting)) {
             $targetingStatus = 1;
         }
     }
     $pageTitle = $blockId != 0 ? sprintf($copy ? $_ARRAYLANG['TXT_BLOCK_COPY_BLOCK'] : $_ARRAYLANG['TXT_BLOCK_MODIFY_BLOCK'], contrexx_raw2xhtml($blockName)) : $_ARRAYLANG['TXT_BLOCK_ADD_BLOCK'];
     $this->_pageTitle = $pageTitle;
     if ($copy) {
         $blockId = 0;
     }
     $this->_objTpl->setVariable(array('BLOCK_ID' => $blockId, 'BLOCK_MODIFY_TITLE' => $pageTitle, 'BLOCK_NAME' => contrexx_raw2xhtml($blockName), 'BLOCK_CATEGORIES_PARENT_DROPDOWN' => $this->_getCategoriesDropdown($blockCat), 'BLOCK_START' => !empty($blockStart) ? strftime('%Y-%m-%d %H:%M', $blockStart) : $blockStart, 'BLOCK_END' => !empty($blockEnd) ? strftime('%Y-%m-%d %H:%M', $blockEnd) : $blockEnd, 'BLOCK_WYSIWYG_EDITOR' => $blockWysiwygEditor == 1 ? 'checked="checked"' : '', 'BLOCK_RANDOM' => $blockRandom == '1' ? 'checked="checked"' : '', 'BLOCK_RANDOM_2' => $blockRandom2 == '1' ? 'checked="checked"' : '', 'BLOCK_RANDOM_3' => $blockRandom3 == '1' ? 'checked="checked"' : '', 'BLOCK_RANDOM_4' => $blockRandom4 == '1' ? 'checked="checked"' : '', 'BLOCK_GLOBAL_0' => $blockGlobal == '0' ? 'checked="checked"' : '', 'BLOCK_GLOBAL_1' => $blockGlobal == '1' ? 'checked="checked"' : '', 'BLOCK_GLOBAL_2' => $blockGlobal == '2' ? 'checked="checked"' : '', 'BLOCK_GLOBAL_SHOW_PAGE_SELECTOR' => $blockGlobal == '2' ? 'block' : 'none', 'BLOCK_DIRECT_0' => $blockDirect == '0' ? 'checked="checked"' : '', 'BLOCK_DIRECT_1' => $blockDirect == '1' ? 'checked="checked"' : '', 'BLOCK_DIRECT_SHOW_PAGE_SELECTOR' => $blockDirect == '1' ? 'block' : 'none', 'BLOCK_CATEGORY_0' => $blockCategory == '0' ? 'checked="checked"' : '', 'BLOCK_CATEGORY_1' => $blockCategory == '1' ? 'checked="checked"' : '', 'BLOCK_CATEGORY_SHOW_PAGE_SELECTOR' => $blockCategory == '1' ? 'block' : 'none', 'BLOCK_WYSIWYG_MEDIABROWSER' => $mediaBrowserCkeditor->getXHtml(), 'BLOCK_TARGETING_ALL_USERS' => $targetingStatus == 0 ? 'checked="checked"' : '', 'BLOCK_TARGETING_VISITOR_CONDITION_BELOW' => $targetingStatus == 1 ? 'checked="checked"' : '', 'BLOCK_TARGETING_COUNTRY_INCLUDE' => !empty($targeting['country']) && $targeting['country']['filter'] == 'include' ? 'selected="selected"' : '', 'BLOCK_TARGETING_COUNTRY_EXCLUDE' => !empty($targeting['country']) && $targeting['country']['filter'] == 'exclude' ? 'selected="selected"' : ''));
     if (!empty($targeting['country']) && !empty($targeting['country']['value'])) {
         foreach ($targeting['country']['value'] as $countryId) {
             $countryName = \Cx\Core\Country\Controller\Country::getNameById($countryId);
             if (empty($countryName)) {
                 continue;
             }
             $this->_objTpl->setVariable(array('BLOCK_TARGET_COUNTRY_ID' => contrexx_raw2xhtml($countryId), 'BLOCK_TARGET_COUNTRY_NAME' => contrexx_raw2xhtml($countryName)));
             $this->_objTpl->parse('block_targeting_country');
         }
     }
     $jsonData = new \Cx\Core\Json\JsonData();
     $pageTitlesTree = $jsonData->data('node', 'getPageTitlesTree');
     $pageTitlesTree = $pageTitlesTree['data'];
     $objJs = \ContrexxJavascript::getInstance();
     $blockGlobalPageSelects = $this->getPageSelections($pageTitlesTree, $blockGlobalAssociatedPageIds);
     $blockDirectPageSelects = $this->getPageSelections($pageTitlesTree, $blockDirectAssociatedPageIds);
     $blockCategoryPageSelects = $this->getPageSelections($pageTitlesTree, $blockCategoryAssociatedPageIds);
     $objJs->setVariable('globalPagesUnselectedOptions', $jsonData->json($blockGlobalPageSelects[1]), 'block');
     $objJs->setVariable('globalPagesSelectedOptions', $jsonData->json($blockGlobalPageSelects[0]), 'block');
     $objJs->setVariable('directPagesUnselectedOptions', $jsonData->json($blockDirectPageSelects[1]), 'block');
     $objJs->setVariable('directPagesSelectedOptions', $jsonData->json($blockDirectPageSelects[0]), 'block');
     $objJs->setVariable('categoryPagesUnselectedOptions', $jsonData->json($blockCategoryPageSelects[1]), 'block');
     $objJs->setVariable('categoryPagesSelectedOptions', $jsonData->json($blockCategoryPageSelects[0]), 'block');
     $objJs->setVariable('ckeditorconfigpath', substr(\Env::get('ClassLoader')->getFilePath(ASCMS_CORE_PATH . '/Wysiwyg/ckeditor.config.js.php'), strlen(ASCMS_DOCUMENT_ROOT) + 1), 'block');
     $arrActiveSystemFrontendLanguages = \FWLanguage::getActiveFrontendLanguages();
     $this->parseLanguageOptionsByPlaceholder($arrActiveSystemFrontendLanguages, 'global');
     $this->parseLanguageOptionsByPlaceholder($arrActiveSystemFrontendLanguages, 'direct');
     $this->parseLanguageOptionsByPlaceholder($arrActiveSystemFrontendLanguages, 'category');
     if (count($arrActiveSystemFrontendLanguages) > 0) {
         $intLanguageCounter = 0;
         $arrLanguages = array(0 => '', 1 => '', 2 => '');
         $strJsTabToDiv = '';
         foreach ($arrActiveSystemFrontendLanguages as $langId => $arrLanguage) {
             $boolLanguageIsActive = $blockId == 0 && $intLanguageCounter == 0 ? true : (isset($blockLangActive[$langId]) && $blockLangActive[$langId] == 1 ? true : false);
             $arrLanguages[$intLanguageCounter % 3] .= '<input id="languagebar_' . $langId . '" ' . ($boolLanguageIsActive ? 'checked="checked"' : '') . ' type="checkbox" name="blockFormLanguages[' . $langId . ']" value="1" onclick="switchBoxAndTab(this, \'lang_blockContent_' . $langId . '\');" /><label for="languagebar_' . $langId . '">' . contrexx_raw2xhtml($arrLanguage['name']) . ' [' . $arrLanguage['lang'] . ']</label><br />';
             $strJsTabToDiv .= 'arrTabToDiv["lang_blockContent_' . $langId . '"] = "langTab_' . $langId . '";' . "\n";
             ++$intLanguageCounter;
         }
         $this->_objTpl->setVariable(array('TXT_BLOCK_LANGUAGE' => $_ARRAYLANG['TXT_BLOCK_LANGUAGE'], 'EDIT_LANGUAGES_1' => $arrLanguages[0], 'EDIT_LANGUAGES_2' => $arrLanguages[1], 'EDIT_LANGUAGES_3' => $arrLanguages[2], 'EDIT_JS_TAB_TO_DIV' => $strJsTabToDiv));
     }
     $arrLanguages = \FWLanguage::getLanguageArray();
     $i = 0;
     $activeFlag = 0;
     foreach ($arrLanguages as $langId => $arrLanguage) {
         if ($arrLanguage['frontend'] != 1) {
             continue;
         }
         $tmpBlockContent = isset($blockContent[$langId]) ? $blockContent[$langId] : '';
         $tmpBlockLangActive = isset($blockLangActive[$langId]) ? $blockLangActive[$langId] : 0;
         $tmpBlockContent = preg_replace('/\\{([A-Z0-9_-]+)\\}/', '[[\\1]]', $tmpBlockContent);
         if ($blockId != 0) {
             if (!$activeFlag && isset($blockLangActive[$langId])) {
                 $activeClass = 'active';
                 $activeFlag = 1;
             }
         } elseif (!$activeFlag) {
             $activeClass = 'active';
             $activeFlag = 1;
         }
         $this->_objTpl->setVariable(array('BLOCK_LANG_TAB_LANG_ID' => intval($langId), 'BLOCK_LANG_TAB_CLASS' => isset($activeClass) ? $activeClass : '', 'TXT_BLOCK_LANG_TAB_LANG_NAME' => contrexx_raw2xhtml($arrLanguage['name']), 'BLOCK_LANGTAB_DISPLAY' => $tmpBlockLangActive == 1 ? 'display:inline;' : ($blockId == 0 && $i == 0 ? 'display:inline;' : 'display:none;')));
         $this->_objTpl->parse('block_language_tabs');
         $this->_objTpl->setVariable(array('BLOCK_LANG_ID' => intval($langId), 'BLOCK_CONTENT_TEXT_HIDDEN' => contrexx_raw2xhtml($tmpBlockContent)));
         $this->_objTpl->parse('block_language_content');
         $activeClass = '';
         $i++;
     }
     if (!$this->getGeoIpComponent() || !$this->getGeoIpComponent()->getGeoIpServiceStatus()) {
         $this->_objTpl->touchBlock('warning_geoip_disabled');
     } else {
         $this->_objTpl->hideBlock('warning_geoip_disabled');
     }
 }
Exemplo n.º 9
0
 /**
  * Set up the detail view of the selected order
  * @access  public
  * @param   \Cx\Core\Html\Sigma $objTemplate    The Template, by reference
  * @param   boolean             $edit           Edit if true, view otherwise
  * @global  ADONewConnection    $objDatabase    Database connection object
  * @global  array               $_ARRAYLANG     Language array
  * @return  boolean                             True on success,
  *                                              false otherwise
  * @static
  * @author  Reto Kohli <*****@*****.**> (parts)
  * @version 3.1.0
  */
 static function view_detail(&$objTemplate = null, $edit = false)
 {
     global $objDatabase, $_ARRAYLANG, $objInit;
     $backend = $objInit->mode == 'backend';
     if ($objTemplate->blockExists('order_list')) {
         $objTemplate->hideBlock('order_list');
     }
     $have_option = false;
     // The order total -- in the currency chosen by the customer
     $order_sum = 0;
     // recalculated VAT total
     $total_vat_amount = 0;
     $order_id = intval($_REQUEST['order_id']);
     if (!$order_id) {
         return \Message::error($_ARRAYLANG['TXT_SHOP_ORDER_ERROR_INVALID_ORDER_ID']);
     }
     if (!$objTemplate) {
         $template_name = $edit ? 'module_shop_order_edit.html' : 'module_shop_order_details.html';
         $objTemplate = new \Cx\Core\Html\Sigma(\Cx\Core\Core\Controller\Cx::instanciate()->getCodeBaseModulePath() . '/Shop/View/Template/Backend');
         //DBG::log("Orders::view_list(): new Template: ".$objTemplate->get());
         $objTemplate->loadTemplateFile($template_name);
         //DBG::log("Orders::view_list(): loaded Template: ".$objTemplate->get());
     }
     $objOrder = Order::getById($order_id);
     if (!$objOrder) {
         //DBG::log("Shop::shopShowOrderdetails(): Failed to find Order ID $order_id");
         return \Message::error(sprintf($_ARRAYLANG['TXT_SHOP_ORDER_NOT_FOUND'], $order_id));
     }
     // lsv data
     $query = "\n            SELECT `holder`, `bank`, `blz`\n              FROM " . DBPREFIX . "module_shop" . MODULE_INDEX . "_lsv\n             WHERE order_id={$order_id}";
     $objResult = $objDatabase->Execute($query);
     if (!$objResult) {
         return self::errorHandler();
     }
     if ($objResult->RecordCount() == 1) {
         $objTemplate->setVariable(array('SHOP_ACCOUNT_HOLDER' => contrexx_raw2xhtml($objResult->fields['holder']), 'SHOP_ACCOUNT_BANK' => contrexx_raw2xhtml($objResult->fields['bank']), 'SHOP_ACCOUNT_BLZ' => contrexx_raw2xhtml($objResult->fields['blz'])));
     }
     $customer_id = $objOrder->customer_id();
     if (!$customer_id) {
         //DBG::log("Shop::shopShowOrderdetails(): Invalid Customer ID $customer_id");
         \Message::error(sprintf($_ARRAYLANG['TXT_SHOP_INVALID_CUSTOMER_ID'], $customer_id));
     }
     $objCustomer = Customer::getById($customer_id);
     if (!$objCustomer) {
         //DBG::log("Shop::shopShowOrderdetails(): Failed to find Customer ID $customer_id");
         \Message::error(sprintf($_ARRAYLANG['TXT_SHOP_CUSTOMER_NOT_FOUND'], $customer_id));
         $objCustomer = new Customer();
         // No editing allowed!
         $have_option = true;
     }
     Vat::is_reseller($objCustomer->is_reseller());
     Vat::is_home_country(\Cx\Core\Setting\Controller\Setting::getValue('country_id', 'Shop') == $objOrder->country_id());
     $objTemplate->setGlobalVariable($_ARRAYLANG + array('SHOP_CURRENCY' => Currency::getCurrencySymbolById($objOrder->currency_id())));
     //DBG::log("Order sum: ".Currency::formatPrice($objOrder->sum()));
     $objTemplate->setVariable(array('SHOP_CUSTOMER_ID' => $customer_id, 'SHOP_ORDERID' => $order_id, 'SHOP_DATE' => date(ASCMS_DATE_FORMAT_INTERNATIONAL_DATETIME, strtotime($objOrder->date_time())), 'SHOP_ORDER_STATUS' => $edit ? Orders::getStatusMenu($objOrder->status(), false, null, 'swapSendToStatus(this.value)') : $_ARRAYLANG['TXT_SHOP_ORDER_STATUS_' . $objOrder->status()], 'SHOP_SEND_MAIL_STYLE' => $objOrder->status() == Order::STATUS_CONFIRMED ? 'display: inline;' : 'display: none;', 'SHOP_SEND_MAIL_STATUS' => $edit ? $objOrder->status() != Order::STATUS_CONFIRMED ? \Html::ATTRIBUTE_CHECKED : '' : '', 'SHOP_ORDER_SUM' => Currency::formatPrice($objOrder->sum()), 'SHOP_DEFAULT_CURRENCY' => Currency::getDefaultCurrencySymbol(), 'SHOP_GENDER' => $edit ? Customer::getGenderMenu($objOrder->billing_gender(), 'billing_gender') : $_ARRAYLANG['TXT_SHOP_' . strtoupper($objOrder->billing_gender())], 'SHOP_COMPANY' => $objOrder->billing_company(), 'SHOP_FIRSTNAME' => $objOrder->billing_firstname(), 'SHOP_LASTNAME' => $objOrder->billing_lastname(), 'SHOP_ADDRESS' => $objOrder->billing_address(), 'SHOP_ZIP' => $objOrder->billing_zip(), 'SHOP_CITY' => $objOrder->billing_city(), 'SHOP_COUNTRY' => $edit ? \Cx\Core\Country\Controller\Country::getMenu('billing_country_id', $objOrder->billing_country_id()) : \Cx\Core\Country\Controller\Country::getNameById($objOrder->billing_country_id()), 'SHOP_PHONE' => $objOrder->billing_phone(), 'SHOP_FAX' => $objOrder->billing_fax(), 'SHOP_EMAIL' => $objOrder->billing_email(), 'SHOP_SHIP_GENDER' => $edit ? Customer::getGenderMenu($objOrder->gender(), 'shipPrefix') : $_ARRAYLANG['TXT_SHOP_' . strtoupper($objOrder->gender())], 'SHOP_SHIP_COMPANY' => $objOrder->company(), 'SHOP_SHIP_FIRSTNAME' => $objOrder->firstname(), 'SHOP_SHIP_LASTNAME' => $objOrder->lastname(), 'SHOP_SHIP_ADDRESS' => $objOrder->address(), 'SHOP_SHIP_ZIP' => $objOrder->zip(), 'SHOP_SHIP_CITY' => $objOrder->city(), 'SHOP_SHIP_COUNTRY' => $edit ? \Cx\Core\Country\Controller\Country::getMenu('shipCountry', $objOrder->country_id()) : \Cx\Core\Country\Controller\Country::getNameById($objOrder->country_id()), 'SHOP_SHIP_PHONE' => $objOrder->phone(), 'SHOP_PAYMENTTYPE' => Payment::getProperty($objOrder->payment_id(), 'name'), 'SHOP_CUSTOMER_NOTE' => $objOrder->note(), 'SHOP_COMPANY_NOTE' => $objCustomer->companynote(), 'SHOP_SHIPPING_TYPE' => $objOrder->shipment_id() ? Shipment::getShipperName($objOrder->shipment_id()) : '&nbsp;'));
     if ($backend) {
         $objTemplate->setVariable(array('SHOP_CUSTOMER_IP' => $objOrder->ip() ? '<a href="index.php?cmd=NetTools&amp;tpl=whois&amp;address=' . $objOrder->ip() . '" title="' . $_ARRAYLANG['TXT_SHOW_DETAILS'] . '">' . $objOrder->ip() . '</a>' : '&nbsp;', 'SHOP_CUSTOMER_HOST' => $objOrder->host() ? '<a href="index.php?cmd=NetTools&amp;tpl=whois&amp;address=' . $objOrder->host() . '" title="' . $_ARRAYLANG['TXT_SHOW_DETAILS'] . '">' . $objOrder->host() . '</a>' : '&nbsp;', 'SHOP_CUSTOMER_LANG' => \FWLanguage::getLanguageParameter($objOrder->lang_id(), 'name'), 'SHOP_CUSTOMER_BROWSER' => $objOrder->browser() ? $objOrder->browser() : '&nbsp;', 'SHOP_LAST_MODIFIED' => $objOrder->modified_on() && $objOrder->modified_on() != '0000-00-00 00:00:00' ? $objOrder->modified_on() . '&nbsp;' . $_ARRAYLANG['TXT_EDITED_BY'] . '&nbsp;' . $objOrder->modified_by() : $_ARRAYLANG['TXT_ORDER_WASNT_YET_EDITED']));
     } else {
         // Frontend: Order history ONLY.  Repeat the Order, go to cart
         $objTemplate->setVariable(array('SHOP_ACTION_URI_ENCODED' => \Cx\Core\Routing\Url::fromModuleAndCmd('Shop', 'cart')));
     }
     $ppName = '';
     $psp_id = Payment::getPaymentProcessorId($objOrder->payment_id());
     if ($psp_id) {
         $ppName = PaymentProcessing::getPaymentProcessorName($psp_id);
     }
     $objTemplate->setVariable(array('SHOP_SHIPPING_PRICE' => $objOrder->shipment_amount(), 'SHOP_PAYMENT_PRICE' => $objOrder->payment_amount(), 'SHOP_PAYMENT_HANDLER' => $ppName, 'SHOP_LAST_MODIFIED_DATE' => $objOrder->modified_on()));
     if ($edit) {
         // edit order
         $strJsArrShipment = Shipment::getJSArrays();
         $objTemplate->setVariable(array('SHOP_SEND_TEMPLATE_TO_CUSTOMER' => sprintf($_ARRAYLANG['TXT_SEND_TEMPLATE_TO_CUSTOMER'], $_ARRAYLANG['TXT_ORDER_COMPLETE']), 'SHOP_SHIPPING_TYP_MENU' => Shipment::getShipperMenu($objOrder->country_id(), $objOrder->shipment_id(), "calcPrice(0);"), 'SHOP_JS_ARR_SHIPMENT' => $strJsArrShipment, 'SHOP_PRODUCT_IDS_MENU_NEW' => Products::getMenuoptions(null, null, $_ARRAYLANG['TXT_SHOP_PRODUCT_MENU_FORMAT']), 'SHOP_JS_ARR_PRODUCT' => Products::getJavascriptArray($objCustomer->group_id(), $objCustomer->is_reseller())));
     }
     $options = $objOrder->getOptionArray();
     if (!empty($options[$order_id])) {
         $have_option = true;
     }
     // Order items
     $total_weight = $i = 0;
     $total_net_price = $objOrder->view_items($objTemplate, $edit, $total_weight, $i);
     // Show VAT with the individual products:
     // If VAT is enabled, and we're both in the same country
     // ($total_vat_amount has been set above if both conditions are met)
     // show the VAT rate.
     // If there is no VAT, the amount is 0 (zero).
     //if ($total_vat_amount) {
     // distinguish between included VAT, and additional VAT added to sum
     $tax_part_percentaged = Vat::isIncluded() ? $_ARRAYLANG['TXT_TAX_PREFIX_INCL'] : $_ARRAYLANG['TXT_TAX_PREFIX_EXCL'];
     $objTemplate->setVariable(array('SHOP_TAX_PRICE' => Currency::formatPrice($total_vat_amount), 'SHOP_PART_TAX_PROCENTUAL' => $tax_part_percentaged));
     //} else {
     // No VAT otherwise
     // remove it from the details overview if empty
     //$objTemplate->hideBlock('taxprice');
     //$tax_part_percentaged = $_ARRAYLANG['TXT_NO_TAX'];
     //}
     // Parse Coupon if applicable to this product
     // Coupon
     $objCoupon = Coupon::getByOrderId($order_id);
     if ($objCoupon) {
         $discount = $objCoupon->discount_amount() != 0 ? $objCoupon->discount_amount() : $total_net_price / 100 * $objCoupon->discount_rate();
         $objTemplate->setVariable(array('SHOP_COUPON_NAME' => $_ARRAYLANG['TXT_SHOP_DISCOUNT_COUPON_CODE'], 'SHOP_COUPON_CODE' => $objCoupon->code(), 'SHOP_COUPON_AMOUNT' => Currency::formatPrice(-$discount)));
         $total_net_price -= $discount;
         //DBG::log("Order::view_detail(): Coupon: ".var_export($objCoupon, true));
     }
     $objTemplate->setVariable(array('SHOP_ROWCLASS_NEW' => 'row' . (++$i % 2 + 1), 'SHOP_TOTAL_WEIGHT' => Weight::getWeightString($total_weight), 'SHOP_NET_PRICE' => Currency::formatPrice($total_net_price)));
     $objTemplate->setVariable(array('TXT_PRODUCT_ID' => $_ARRAYLANG['TXT_ID'], 'TXT_TAX_RATE' => Vat::isIncluded() ? $_ARRAYLANG['TXT_TAX_PREFIX_INCL'] : $_ARRAYLANG['TXT_TAX_PREFIX_EXCL'], 'TXT_SHOP_ACCOUNT_VALIDITY' => $_ARRAYLANG['TXT_SHOP_VALIDITY']));
     // Disable the "edit" button when there are Attributes
     if ($backend && !$edit) {
         if ($have_option) {
             if ($objTemplate->blockExists('order_no_edit')) {
                 $objTemplate->touchBlock('order_no_edit');
             }
         } else {
             if ($objTemplate->blockExists('order_edit')) {
                 $objTemplate->touchBlock('order_edit');
             }
         }
     }
     return true;
 }
Exemplo n.º 10
0
 /**
  * Set up the customer details
  */
 function view_customer_details()
 {
     global $_ARRAYLANG;
     self::$objTemplate->loadTemplateFile("module_shop_customer_details.html");
     if (isset($_POST['store'])) {
         self::storeCustomerFromPost();
     }
     $customer_id = intval($_REQUEST['customer_id']);
     $objCustomer = Customer::getById($customer_id);
     if (!$objCustomer) {
         return \Message::error($_ARRAYLANG['TXT_SHOP_CUSTOMER_ERROR_NOT_FOUND']);
     }
     $customer_type = $objCustomer->is_reseller() ? $_ARRAYLANG['TXT_RESELLER'] : $_ARRAYLANG['TXT_CUSTOMER'];
     $active = $objCustomer->active() ? $_ARRAYLANG['TXT_ACTIVE'] : $_ARRAYLANG['TXT_INACTIVE'];
     self::$objTemplate->setVariable(array('SHOP_CUSTOMERID' => $objCustomer->id(), 'SHOP_GENDER' => $_ARRAYLANG['TXT_SHOP_' . strtoupper($objCustomer->gender())], 'SHOP_LASTNAME' => $objCustomer->lastname(), 'SHOP_FIRSTNAME' => $objCustomer->firstname(), 'SHOP_COMPANY' => $objCustomer->company(), 'SHOP_ADDRESS' => $objCustomer->address(), 'SHOP_CITY' => $objCustomer->city(), 'SHOP_USERNAME' => $objCustomer->username(), 'SHOP_COUNTRY' => \Cx\Core\Country\Controller\Country::getNameById($objCustomer->country_id()), 'SHOP_ZIP' => $objCustomer->zip(), 'SHOP_PHONE' => $objCustomer->phone(), 'SHOP_FAX' => $objCustomer->fax(), 'SHOP_EMAIL' => $objCustomer->email(), 'SHOP_COMPANY_NOTE' => $objCustomer->companynote(), 'SHOP_IS_RESELLER' => $customer_type, 'SHOP_REGISTER_DATE' => date(ASCMS_DATE_FORMAT_DATETIME, $objCustomer->register_date()), 'SHOP_CUSTOMER_STATUS' => $active, 'SHOP_DISCOUNT_GROUP_CUSTOMER' => Discount::getCustomerGroupName($objCustomer->group_id())));
     // TODO: TEST
     $count = NULL;
     $orders = Orders::getArray($count, NULL, array(), \Paging::getPosition(), \Cx\Core\Setting\Controller\Setting::getValue('numof_orders_per_page_backend', 'Shop'));
     $i = 1;
     foreach ($orders as $order) {
         Currency::init($order->currency_id());
         self::$objTemplate->setVariable(array('SHOP_ROWCLASS' => 'row' . (++$i % 2 + 1), 'SHOP_ORDER_ID' => $order->id(), 'SHOP_ORDER_ID_CUSTOM' => ShopLibrary::getCustomOrderId($order->id(), $order->date_time()), 'SHOP_ORDER_DATE' => $order->date_time(), 'SHOP_ORDER_STATUS' => $_ARRAYLANG['TXT_SHOP_ORDER_STATUS_' . $order->status()], 'SHOP_ORDER_SUM' => Currency::getDefaultCurrencySymbol() . ' ' . Currency::getDefaultCurrencyPrice($order->sum())));
         self::$objTemplate->parse('orderRow');
     }
     return true;
 }