Your IP : 216.73.216.248


Current Path : /home/digilove/public_html/components/com_marketplace/controllers/
Upload File :
Current File : /home/digilove/public_html/components/com_marketplace/controllers/addproduct.php

<?php
/**
 * Marketplace - Component Marketplace 
 * ******************************************************************
 *
 * PHP version 7.0
 *
 * @category   Component
 * @package    Joomla
 * @author     WebKul software private limited <support@webkul.com>
 * @copyright  2010 WebKul software private limited
 * @license    http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
 * @version    GIT:5.2
 * @filesource http://store.webkul.com
 * @link       Technical Support:  webkul.uvdesk.com
 * ******************************************************************
 */
// no direct access
defined('_JEXEC') or die('Restricted access');
jimport('joomla.application.component.controller');
jimport('joomla.filesystem.file');
$user = JFactory::getUser();
$param  = JComponentHelper::getParams('com_marketplace');
$wk_addproduct_imgsize = $param->get('wk_addproduct_imgsize');
if (!class_exists('VmConfig')) {
    include JPATH_ADMINISTRATOR.
    '/components/com_virtuemart/helpers/config.php';
}
JTable::addIncludePath(JPATH_COMPONENT_SITE.DIRECTORY_SEPARATOR.'tables');
if (!class_exists('MarketplaceHelper')) {
    include JPATH_ADMINISTRATOR.DIRECTORY_SEPARATOR.
    'components'.DIRECTORY_SEPARATOR.'com_marketplace'.
    DIRECTORY_SEPARATOR.'helpers'.DIRECTORY_SEPARATOR.'marketplace.php';
}
if (!class_exists('MarketplaceControllerAddproduct')) {
    /**
     * MarketplaceControllerAddproduct class
     * 
     * @category Component
     * @package  Joomla
     * @author   WebKul software private limited <support@webkul.com>
     * @license  http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL
     * @link     Technical Support:  webkul.uvdesk.com
     */
    class MarketplaceControllerAddproduct extends JControllerLegacy
    {
        /**
         * Display function
         *
         * @param boolean $cachable  var
         * @param array   $urlparams var
         * 
         * @return void
         */
        public function display($cachable = false, $urlparams = array())
        {
            parent::display();
        }
        /**
         * Multilang function
         *
         * @return void
         */
        public function multilang()
        {
            $defaultcountry_code = VmConfig::$vmlang;
            $app = JFactory::getApplication();
            $_input = $app->input;
            $code = $_input->getInt('code', 0);
            $virtuemart_product_id = $_input->getInt('virtuemart_product_id', 0);
            $country_table = explode(' ', $code);
            $country_table_name = strtolower(
                str_replace("-", "_", $country_table['0'])
            );
            $model=$this->getModel('addproduct');
            $result=$model->checkUpdateLangTable(
                $country_table_name,
                $virtuemart_product_id,
                $defaultcountry_code
            );
            $jsonstring = json_encode($result);
            echo $jsonstring;
            $app->close();
        }
        /**
         * GetProductDetail function
         *
         * @return void
         */
        public function getProductDetail()
        {
            $app = JFactory::getApplication();
            $_input = $app->input;
            $virtuemart_product_id=$_input->getInt('vmid');
            $model=$this->getModel('addproduct');
            $pro_detail=$model->getProductDetail($virtuemart_product_id);
            $detail['product_sku']=@$pro_detail[0]->product_sku;
            $detail['product_weight']=@$pro_detail[0]->product_weight;
            $detail['product_in_stock']=@$pro_detail[0]->product_in_stock;
            $mediaModel=VmModel::getModel('media');
            $data=$mediaModel->getFiles(false, false, $virtuemart_product_id);
            $image=array();
            $vmmediaid=array();
            foreach ($data as $key => $value) {
                $fileName = explode('.', $value->file_url);
                $NewFileName = $fileName[0].'_clone'.rand().'.'.$fileName[1];
                JFile::copy($value->file_url, $NewFileName);
                $image[]=$NewFileName;
                $vmmediaid[]=$value->virtuemart_media_id;
            }

            $detail['image']=$image;
            $detail['virtuemart_media_id']=$vmmediaid;
            $productModel=VmModel::getModel('product');
            $product=$productModel->getProduct($virtuemart_product_id);
            if (!isset($product->allPrices[0]['costPrice'])) {
                $product->allPrices[0]['costPrice']='';
            }
            $detail['baseprice']=$product->allPrices[0]['costPrice'];
            if (!isset($product->allPrices[0]['salesPrice'])) {
                $product->allPrices[0]['salesPrice']=0;
            }
            $detail['salesprice']=number_format(
                $product->allPrices[0]['salesPrice'], 2
            );
            if (!count($product->virtuemart_manufacturer_id)) {
                $detail['manufacturer'][0]='0';
            } else {
                $detail['manufacturer']=$product->virtuemart_manufacturer_id;
            }
            if (!count($product->categories)) {
                $detail['categories'][0]='0';
            } else {
                $detail['categories']=$product->categories;
            }
            if (!isset($product->allPrices[0]['product_discount_id'])) {
                $product->allPrices[0]['product_discount_id']='na';
            }
            $detail['price_discount']=$product->allPrices[0]['product_discount_id'];
            if (!isset($product->allPrices[0]['product_tax_id'])) {
                $product->allPrices[0]['product_tax_id']='na';
            }
            $detail['price_tax']=$product->allPrices[0]['product_tax_id'];
            $detail['product_description_short']=$product->product_s_desc;
            $detail['product_description']=$product->product_desc;
            $detail['customfields']=$product->customfields;
            echo json_encode($detail);
            JFactory::getApplication()->close();
        }
        /**
         * CategoryRequest function
         *
         * @return void
         */
        public function categoryRequest()
        {
            $jinput=JFactory::getApplication()->input;
            $method=$jinput->getMethod();
            $catname=$jinput->get('catval', '', $method);
            $catinfo=$jinput->get('catinfo', '', $method);
            $catdesc=$jinput->get('catdesc', '', $method);
            $seller_email=$jinput->get('seller_email', '', $method);
            $model=$this->getModel('addproduct');
            $config=JFactory::getConfig();
            $mailer=JFactory::getMailer();
            $reciepient=$config->get('mailfrom');
            $reciepientName=$config->get('fromname');
            $message='';
            $subject=JText::_('COM_MARKETPLACE_CATEGORY_REQUEST_SUBJECT');
            $message.=JText::_('COM_MARKETPLACE_HELLO').$reciepientName.
            ",<br>".JText::_('COM_MARKETPLACE_CATEGORY_REQUEST')."<strong>".$catname.
            "</strong>".JText::_('COM_MARKETPLACE_CATEGORY_REQUEST_GENERATED')
            ."<strong>".JFactory::getUser()->name."</strong>.<br>".
            JText::_('COM_MARKETPLACE_PLEASE_GO').
            "<a href='".JURI::root().
            'administrator/index.php?option=com_marketplace&view=suggestedcategory'.
            "'>".JText::_('COM_MARKETPLACE_CATEGORY_TAB').
            "</a>".JText::_('COM_MARKETPLACE_TO_APPROVE');
            if (strlen($reciepient)) {
                $check = $model->categoryRequest(
                    $catname,
                    $catdesc,
                    $catinfo,
                    $seller_email,
                    $reciepient
                );
                if ($check>0) {
                    $mailer->addRecipient($reciepient);
                    $mailer->isHtml(true);
                    $mailer->setSender($seller_email);
                    $mailer->setSubject($subject);
                    $mailer->setBody($message);
                    $mailer->send();
                }
                echo $check;
                JFactory::getApplication()->close();
            } else {
                echo "Admin Email Is Not Set";
                JFactory::getApplication()->close();
            }
        }
        /**
         * Deleteimage function
         *
         * @return void
         */
        public function deleteimage()
        {
            $jinput=JFactory::getApplication()->input;
            $id = $jinput->getInt('id', 0);
            $model=$this->getModel('addproduct');
            $success=$model->deleteimage($id);
            if ($success) {
                echo "true";
            } else {
                echo "false";
            }
            JFactory::getApplication()->close();
        }
        /**
         * UploadImage function
         *
         * @return void
         */
        public function uploadImage()
        {
            $app = JFactory::getApplication();
            $_input = $app->input;
            $vmconf=VmConfig::loadConfig();
            $rawData = $_input->get('imgBase64');
            $filteredData = explode(',', $rawData);
            $unencoded = base64_decode($filteredData[1]);
            $randomName = rand(0, 99999);
            $uploadpath = JPATH_ROOT . DIRECTORY_SEPARATOR
            . $vmconf->get("media_product_path");
            $fp = fopen($uploadpath.$randomName.'.jpg', 'w');
            fwrite($fp, $unencoded);
            fclose($fp);
            $file_size=filesize($uploadpath.$randomName.'.jpg');
            echo $randomName.'.jpg'.','.$file_size;
            $app->close();
        }
        /**
         * Deleteimagepreview function
         *
         * @return void
         */
        public function deleteimagepreview()
        {
            $app = JFactory::getApplication();
            $_input = $app->input;
            $name = $_input->get('imgBase64');
            $vmconf=VmConfig::loadConfig();
            $uploadpath = JPATH_ROOT . DIRECTORY_SEPARATOR
            . $vmconf->get("media_product_path");
            unlink($uploadpath.$name);
            echo "true";
            $app->close();
        }
        /**
         * SelectProduct function
         *
         * @return void
         */
        public function selectProduct()
        {
            $app = JFactory::getApplication();
            $_input = $app->input;
            $name = $_input->get('keyword');
            if (!empty($name)) {
                $model=$this->getModel('addproduct');
                $result = $model->selectProduct($name);
                if (!empty($result)) {
                    ?>
                    <ul id="product-list">
                        <?php
                        foreach ($result as $result1) {
                        ?>
                          <li id="<?php echo $result1->virtuemart_product_id ?>" onClick="selectproducts('<?php echo $result1->product_name; ?>','<?php echo $result1->virtuemart_product_id ?>');">
                            <?php echo $result1->product_name; ?>
                          </li>
                        <?php
                        } ?>
                    </ul>
                    <?php
                }
            }
            $app->close();
        }
        /**
         * Product_save function
         *
         * @return void
         */
        public function productSave()
        {
            $app   = JFactory::getApplication();
            $jinput=JFactory::getApplication()->input;

            $addproductmenu=plgSystemMarketplace::getMenuId(
                'index.php?option=com_marketplace&view=addproduct'
            );
            $productmenu=plgSystemMarketplace::getMenuId(
                'index.php?option=com_marketplace&view=products'
            );
            $usr=JFactory::getUser();
            if (!MarketplaceHelper::checkSeller($usr->id)) {
                $app->enqueueMessage(JText::_("NOT_AUTH"), 'error');
                $this->setRedirect(
                    JRoute::_(
                        'index.php?option=com_marketplace&view=addproduct&Itemid='.
                        $addproductmenu, false
                    )
                );
                return false;
            }
            $model=$this->getModel('Addproduct', 'MarketplaceModel');
            $requestData = $this->input->post->get('jform', array(), 'array');
            $postVar = $this->input->getArray($requestData);
            if (in_array('exif', get_loaded_extensions())) {
                $exif_enable = true;
            } else {
                $exif_enable = false;
            }
            $vmconf=VmConfig::loadConfig();
            $form = $model->getForm();
            $params = JComponentHelper::getParams('com_marketplace');
            $recaptcha_enable=trim($params->get('recaptcha_enable'));
            $captcha=(boolean)$params->get('captcha');
            if ($recaptcha_enable && $captcha) {
                $url_str="";
                if (isset($postVar['virtuemart_product_id'])
                    && $postVar['virtuemart_product_id']!=""
                ) {
                    $url_str = '&virtuemart_product_id='
                    .$postVar['virtuemart_product_id'];
                }
                $data = $model->validate($form, $requestData);
                if ($data === false) {
                    $errors = $model->getErrors();
                    for ($i = 0, $n = count($errors); $i < $n && $i < 3; $i++) {
                        if ($errors[$i] instanceof Exception) {
                            $app->enqueueMessage(
                                $errors[$i]->getMessage(),
                                'warning'
                            );
                        } else {
                            $app->enqueueMessage($errors[$i], 'warning');
                        }
                    }
                    $this->setRedirect(
                        JRoute::_(
                            'index.php?option=com_marketplace&view=addprodu'.
                            'ct&Itemid='.$addproductmenu.$url_str,
                            false
                        )
                    );
                    return false;
                }
            }
            $jinput->set('post_max_size', ini_get('post_max_size'));
            $lastchar=strrev($jinput->get('post_max_size'));
            $lastchar=$lastchar{0};
            $max_file_uploads=ini_get('max_file_uploads');
            $global_size=$jinput->get('post_max_size', '0', 'INT');
            $param  = JComponentHelper::getParams('com_marketplace');
            $wk_addproduct_imgsize = $param->get('wk_addproduct_imgsize');
            $model = $this->getModel('productsave');
            
            $postVar['product_description'] = $jinput->get(
                'product_description',
                '',
                'RAW'
            );
            $postVar['product_description_short'] = $jinput->get(
                'product_description_short',
                '',
                'RAW'
            );
            $image = $jinput->files->get('image');
            $imagepre = $jinput->get('imagepre', "", "RAW");
            
            $mpdownloadable_file = $jinput->files->get('downloadable_file');
            
            if (isset($mpdownloadable_file['size'])) {
                $downloadableFileSize = $mpdownloadable_file['size'];
                if ($wk_unit == 'K') {
                    $fileunit = 'KB';
                    $downloadableFileSize = $downloadableFileSize/1000;
                } elseif ($wk_unit == 'M') {
                    $downloadableFileSize = $downloadableFileSize/(1000*1000);
                    $fileunit = 'MB';
                } elseif ($wk_unit == 'G') {
                    $downloadableFileSize = $downloadableFileSize/(1000*1000*1000);
                    $fileunit = 'GB';
                }
                if (($downloadableFileSize>$global_size)
                    || ($downloadableFileSize >$configDownloadfilesize)
                ) {
                    $this->setRedirect(
                        'index.php?option=com_marketplace&view=addproduct',
                        JText::_('MAX_UPLOAD_FILE_SIZE').$configDownloadfilesize
                        . $fileunit
                    );
                    return false;
                }
            }

            $uploadpath = JPATH_ROOT . DIRECTORY_SEPARATOR .
            $vmconf->get("media_product_path");
            if (!is_dir($uploadpath)) {
                $message = "Error Uploading Image";
                $app->enqueueMessage($message, 'error');
                return false;
            }
            $imagePath = '';
            $countimg = count($image);
            
            /**
             * GenerateRandomString function
             *
             * @param integer $length var
             * 
             * @return void
             */
            function generateRandomString($length = 10)
            {
                $characters = '0123456789abcdefghijklmnopqrstuvw'.
                'xyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
                $randomString = '';
                for ($i = 0; $i < $length; $i++) {
                    $randomString .= $characters[rand(0, strlen($characters) - 1)];
                }
                return $randomString;
            }

            $imagepre_count=count($imagepre);
            if ($imagepre && $max_file_uploads>$imagepre_count ) {
                if (is_array($image)) {
                    for ($k=0;$k<$imagepre_count;$k++) {
                        for ($i=0;$i<$countimg;$i++) {
                            if ($image[$i]['name']==rawurldecode($imagepre[$k])) {
                                if ($image[$i]['name']!='') {
                                    $safename = JFile::makeSafe($image[$i]['name']);
                                    
                                    $safename = strtolower($safename);
                                    $ext = pathinfo($safename, PATHINFO_EXTENSION);
                                    $allowedExts = array(
                                        "gif",
                                        "jpeg",
                                        "jpg",
                                        "png"
                                    );
                                    if ((($ext == "gif")
                                        || ($ext == "jpeg")
                                        || ($ext == "jpg")
                                        || ($ext == "pjpeg")
                                        || ($ext == "x-png")
                                        || ($ext == "png"))
                                        && in_array($ext, $allowedExts)
                                    ) {
                                    } else {
                                        $this->setRedirect(
                                            'index.php?option=com_marketplace&vie'.
                                            'w=addproduct&virtuemart_product_id='.
                                            $postVar['virtuemart_product_id'],
                                            JText::_('ACCEPTED_PROD_IMG_EXTENSION')
                                        );
                                        return false;
                                    }
                                    $param  = JComponentHelper::getParams(
                                        'com_marketplace'
                                    );
                                    $bytes = $param->get('wk_addproduct_imgsize');
                                    if ($lastchar=='K') {
                                        $bytes=$bytes;
                                        $fileunit='KB';
                                        $imgsize=$image[$i]['size']/1000;
                                    } elseif ($lastchar=='M') {
                                        $bytes=$bytes/1000;
                                        $imgsize=$image[$i]['size']/(1000*1000);
                                        $fileunit='MB';
                                    } elseif ($lastchar=='G') {
                                        $bytes=$bytes/(1000*1000);
                                        $imgsize=$image[$i]['size']/(1000*1000*1000);
                                        $fileunit='GB';
                                    }


                                    if (($imgsize>$global_size)
                                        || ($imgsize >$bytes)
                                    ) {
                                        $this->setRedirect(
                                            'index.php?option=com_marketplace&vie'.
                                            'w=addproduct&Itemid='.$addproductmenu.
                                            '&virtuemart_product_id='.
                                            $postVar['virtuemart_product_id'],
                                            JText::_('MAX_UPLOAD_IMG_SIZE').
                                            $bytes. $fileunit
                                        );
                                        return false;
                                    } else {
                                        $wk_rename[$i] = generateRandomString();
                                        $today = date("s");
                                        if (!JFile::upload(
                                            $image[$i]['tmp_name'],
                                            $uploadpath . DIRECTORY_SEPARATOR .
                                            $wk_rename[$i].$today.'.'.$ext
                                        )
                                        ) {
                                            $this->setRedirect(
                                                'index.php?option=com_marketpl'.
                                                'ace&view=addproduct&Itemid='
                                                .$addproductmenu,
                                                $this->getError(),
                                                'error'
                                            );
                                        }
                                        chmod(
                                            $uploadpath . DIRECTORY_SEPARATOR .
                                            $wk_rename[$i].$today.'.'.$ext, 0755
                                        );
                                        if ($exif_enable && ($ext==='jpeg' || $ext==='jpg')) {
                                            
                                            $exif = exif_read_data(
                                                $uploadpath . DIRECTORY_SEPARATOR .
                                                $wk_rename[$i].$today.'.'.$ext
                                            );
                                            if (isset($exif)
                                                && isset($exif['Orientation'])
                                            ) {
                                                $ort = $exif['Orientation'];
                                                $source = imagecreatefromjpeg(
                                                    $uploadpath . DIRECTORY_SEPARATOR
                                                    . $wk_rename[$i].$today.'.'.$ext
                                                );
                                                $rotate=null;
                                                switch ($ort) {
                                                case 3:
                                                    $rotate = imagerotate(
                                                        $source,
                                                        180,
                                                        0
                                                    );
                                                    break;
                                                case 6:
                                                    $rotate = imagerotate(
                                                        $source,
                                                        -90,
                                                        0
                                                    );
                                                    break;
                                                case 8:
                                                    $rotate = imagerotate(
                                                        $source,
                                                        90,
                                                        0
                                                    );
                                                    break;
                                                }
                                                if ($rotate !== null) {
                                                    imagejpeg(
                                                        $rotate,
                                                        $uploadpath.
                                                        DIRECTORY_SEPARATOR.
                                                        $wk_rename[$i].$today.
                                                        '.'.$ext
                                                    );
                                                    imagedestroy($rotate);
                                                }
                                            }
                                        }
                                        $imagePath = $vmconf->get(
                                            "media_product_path"
                                        ). $wk_rename[$i].$today.'.'.$ext;
                                        
                                        $postVar['imagepath'][$k] = $imagePath;
                                        $postVar['imagepath'][$k]
                                            = $postVar['imagepath'][$k];
                                        $postVar['imagetype'][$k]
                                            = $image[$i]['type'];
                                    }
                                }
                            }
                        }
                    }
                    
                    if (isset($postVar['imagepath'])
                        && $postVar['imagepath']!= null
                    ) {
                        $totalImages = count($postVar['imagepath']);
                    } else {
                        $totalImages = 0;
                    }

                    for ($k=$totalImages;$k<$imagepre_count;$k++) {
                        $postVar['imagetype'][$k] = 'image/jpeg';
                        $postVar['imagepath'][$k] = $postVar['imagepre'][$k];
                    }
                    $pics=$jinput->get('mydata', '');
                    
                    if ($pics!='') {
                        $pics=explode(',', $pics);
                        unset($pics[0]);

                        foreach ($pics as $key => $value) {
                            if ($key!='0') {
                                $postVar['imagepath'][]
                                    =$vmconf->get("media_product_path").$value;
                            }
                            $postVar['imagetype'][]='image/jpeg';
                        }
                    }
                }
            } else {
                $this->setRedirect(
                    'index.php?option=com_marketplace&view=ad'.
                    'dproduct&virtuemart_product_id='
                    .$postVar['virtuemart_product_id']."&Itemid=".$addproductmenu,
                    ($imagepre_count-$max_file_uploads).
                    " ".JText::_('MAX_UPLOAD_IMG_COUNT')
                );
            }
            
            $app=JFactory::getApplication();
            /* Mp Trigger onSellerBeforeAddProduct */
            JPluginHelper::importPlugin('system');
            $dispatcher =JDispatcher::getInstance();
            $addonData=$dispatcher->trigger(
                'onSellerBeforeAddProduct', array(&$postVar)
            );
            
            $validate=true;
            foreach ($addonData as $value) {
                if (!$value) {
                    $validate=false;
                    break;
                }
            }

            if (!$validate) {
                $this->setRedirect(
                    'index.php?option=com_marketplace&view=add'.
                    'product&virtuemart_product_id='.
                    $postVar['virtuemart_product_id']."&Itemid=".$addproductmenu,
                    JText::_('SOME_ERROR_OCCURRED'),
                    "error"
                );
                return;
            }
            if (!$model->saveProduct($postVar)) {
                $app->enqueueMessage(JText::_('SOME_ERROR_OCCURRED'), 'error');
                $app->redirect(
                    JRoute::_(
                        'index.php?option=com_marketplace&view=addproduct&Itemid='.
                        $addproductmenu,
                        false
                    )
                );
            } else {
                $app->enqueueMessage(JText::_('PRODUCT_SAVED'), 'success');
                $app->redirect(
                    JRoute::_(
                        'index.php?option=com_marketplace&view=products&Itemid='
                        .$productmenu,
                        false
                    )
                );
            }
        }
    }
}