<?php
/***************************************************************************
 *                                                                          *
 * Copyright (c) 2005 ISPG Technologies (I) Pvt Ltd. All rights reserved.   *
 *                                                                          *
 * This  is  commercial  software,  only  users  who have purchased a valid *
 * license  and  accept  to the terms of the  License Agreement can install *
 * and use this program.                                                    *
 *                                                                          *
 ****************************************************************************
 * PLEASE READ THE FULL TEXT  OF THE SOFTWARE  LICENSE   AGREEMENT  IN  THE *
 * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE.            *
 ****************************************************************************/ //
//$Id: ActiveproductsController.php, v 2.0 2011/12/10 20:52:11
//
class SitemapController extends Controller {
    public function __construct() {
        parent::__construct();
        $this->ObjView->assign('statPageName', 'sitemap');
    }
    public function indexAction() //generate dynamic sitemap
        {
        $ObjCustommenu  = new CustommenuModel();
        $ObjMenu        = new MenuModel();
        $ObjBrand       = new BrandModel();
        $languageIDs    = $this->ObjView->languageIDs;
        $userID         = $this->ObjSession->getSession("REGISTERED_USER_ID");
        $userSubgroupID = $this->ObjSession->getSession("REGISTERED_USER_GROUP_ID");
        $listMenus      = $ObjCustommenu->listMenus($languageIDs, '', '', '', 'Active', '', 'menuItemCount', 'DESC', 'sitemap', $userSubgroupID, 'frontend');
        $sslCheckout    = $this->getSettingValue('site_settings', 'enable_ssl_checkout');
        $httpURL        = rtrim($this->getSettingValue('site_settings', 'global_http_url'), "/") . "/";
        $httpsUrl       = rtrim($this->getSettingValue('site_settings', 'global_https_url'), "/") . "/";
        foreach ($listMenus as $menu) {
            $menuTree     = array();
            $reslistMenus = $ObjCustommenu->getMenusItemsSiteMap($languageIDs, $menu['menuID'], $userSubgroupID); //print_r($reslistMenus);
            foreach ($reslistMenus as $key => $list) {
                $urlForMenuItem = $hrefelmnt = '';
                $menuitemparams = json_decode($list['params'], true);
                $enableSSL      = isset($menuitemparams['enableSSL']) ? $menuitemparams['enableSSL'] : '';
                //$hrefelmnt			=	($enableSSL=='Yes')?$httpsUrl:$httpURL;
                if ($sslCheckout == 'Enable')
                    $hrefelmnt = ($enableSSL == 'Yes') ? $httpsUrl : $httpURL;
                else
                    $hrefelmnt = $httpURL;
                if ($list['moduleKey'] == 'url')
                    $urlForMenuItem = "http://" . ltrim($list['itemLink'], "http://,httpps://");
                else if ($list['moduleKey'] == 'text')
                    $urlForMenuItem = '';
                else if ($list['moduleKey'] == 'seperator')
                    continue;
                else {
                    $ObjUrl         = new UrlrewriteModel();
                    $resUrl         = $ObjUrl->getRequestPathByIdPath($languageIDs['Current'], 'menu/' . $list['menuItemID'] . '/');
                    $urlForMenuItem = $hrefelmnt . $resUrl['requestPath'];
                }
                $reslistMenus[$key]['newLink']               = $urlForMenuItem;
                $menuTree[$reslistMenus[$key]['parentID']][] = $reslistMenus[$key];
            }
            $mainTree      = $this->createTreeLeft($menuTree, $menuTree[0]);
            $listItem      = $mainTree;
            $resMenuList[] = array(
                $menu['menuID'],
                $menu['menuName'],
                $listItem
            );
        }
        $params    = array(
            'languageIDs' => $languageIDs
        );
        $listBrand = $ObjBrand->listBrand($params);
        $this->ObjView->assign('listBrand', $listBrand);
        $this->ObjView->assign('resMenuList', $resMenuList);
        $this->ObjView->assign('userID', $userID);
        $this->ObjView->display('SiteMaps.tpl');
    }
	public function sefPathByID($currID, $type = 'product') {
        $languageIDs = $this->ObjView->languageIDs;
        $ObjUrl      = new UrlrewriteModel();
        $idPath      = $type . '/' . $currID . '/';
        $resUrl      = $ObjUrl->getRequestPathByIdPath($languageIDs['Current'], $idPath);
        return $resUrl['requestPath'];
    }
    public function generateAction() {
        $sitemap        = new Sitemap();
        //$ObjBrand       = new BrandModel();
        $ObjProductList = new ProductListModel();
        $mainCategories = $this->ObjCommon->CategoryRoot;
        $languageInUrl  = $this->getSettingValue('seo_settings', 'language_in_url');
        $lCIDstring     = '';
        $languageIDs    = $this->ObjView->languageIDs;
        if ($languageInUrl == "Yes") {
            $ObjLanguage = new LanguageModel();
            $lCIDstring  = $ObjLanguage->getLanguageLCIDstring($languageIDs['Current']) . '/';
        }
        /* $params    = array(
            'languageIDs' => $languageIDs
        );
        $listBrand = $ObjBrand->listBrand($params);
        foreach ($listBrand as $brand) {
            $brands[] = $lCIDstring . 'brand/' . $brand['brandKey'];
        } */
        //$this->generate_Xmlfile('brands', $brands);
        foreach ($mainCategories as $category) {
            $mainCategoryID = $category['productCategoryID'];
            $mainCategory   = $category['productCategoryKey'];
            $subCategories  = $this->ObjCommon->getSubCategories($mainCategoryID, 'List');
            foreach ($subCategories as $categories) {
                $urlSlash = '';
                if($lCIDstring!='') {
                    $urlSlash = '/';
                }
                //$subCategory[] = $lCIDstring . $urlSlash . $this->ObjView->getSefRequestPath($categories['productCategoryID'], 'catalog');
				$cartrequestPath = $this->sefPathByID($categories['productCategoryID'], 'catalog');
                $subCategory[] = rtrim($lCIDstring,"/") . '/series/' . $cartrequestPath;
            }
            $catIDAndSubcategories = implode(",", array_merge(array(
                $mainCategoryID
            ), $this->ObjCommon->getSubCategories($mainCategoryID, 'ID')));
            $resAllProducts        = $ObjProductList->listSitemapProducts($languageIDs, $catIDAndSubcategories);
            foreach ($resAllProducts as $resproduct) {
				$requestPath = $this->sefPathByID($resproduct['productID'], 'product');
                $products[] = rtrim($lCIDstring,"/") . '/' . $requestPath;
            }
            if ((count($products) > 0) || (count($subCategory) > 0)) {
                $this->generate_Xmlfile($mainCategory, $subCategory, $products);
            } 
            unset($products);
            unset($subCategory);
        }
        $map    = $this->generate_sitemap($mainCategories);
        $Handle = fopen("sitemap.xml", "w");
        fwrite($Handle, "" . $map . "");
        fclose($Handle);
        //$this->ping("http://" . $_SERVER['SERVER_NAME'] . $_SERVER['REQUEST_URI']);
    }
    public function generate_Xmlfile($filename, $urlArry = '', $urlArry1 = '') {
        $zipName         = $filename . ".xml.gz"; // Zip name
        $settingsSiteUrl = $this->getSettingValue('site_settings', 'global_http_url');
        $settingsSiteUrl = rtrim($settingsSiteUrl, "/") . "/";
        $xml             = '<?xml version="1.0" encoding="UTF-8"?>' . "\n";
        $xml .= '<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">' . "\n";
        if (($urlArry != '') && ($urlArry1 != '')) {
            foreach ($urlArry as $url) {
                $xml .= '  <url>' . "\n";
                $xml .= "    <loc>" . htmlspecialchars($settingsSiteUrl . $url) . "</loc>\n";
                $xml .= "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
                $xml .= "    <changefreq>" . weekly . "</changefreq>\n";
                $xml .= '  </url>' . "\n";
            }
            foreach ($urlArry1 as $url1) {
                $xml .= '  <url>' . "\n";
                $xml .= "    <loc>" . htmlspecialchars($settingsSiteUrl . $url1) . "</loc>\n";
                $xml .= "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
                $xml .= "    <changefreq>" . weekly . "</changefreq>\n";
                $xml .= '  </url>' . "\n";
            }
        } else if (($urlArry != '') && ($urlArry1 == '')) {
            foreach ($urlArry as $url) {
                $xml .= '  <url>' . "\n";
                $xml .= "    <loc>" . htmlspecialchars($settingsSiteUrl . $url) . "</loc>\n";
                $xml .= "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
                $xml .= "    <changefreq>" . weekly . "</changefreq>\n";
                $xml .= '  </url>' . "\n";
            }
        } else if (($urlArry1 != '') && ($urlArry == '')) {
            foreach ($urlArry1 as $url1) {
                $xml .= '  <url>' . "\n";
                $xml .= "    <loc>" . htmlspecialchars($settingsSiteUrl . $url1) . "</loc>\n";
                $xml .= "    <lastmod>" . date('Y-m-d') . "</lastmod>\n";
                $xml .= "    <changefreq>" . weekly . "</changefreq>\n";
                $xml .= '  </url>' . "\n";
            }
        }
        $xml .= '</urlset>' . "\n";
        $xml = gzencode($xml, 9);
        $fp  = fopen($zipName, 'wb');
        fwrite($fp, $xml);
        fclose($fp);
    }
    public function generate_sitemap($mainCategories) {
        $ObjProductList  = new ProductListModel();
        $settingsSiteUrl = $this->getSettingValue('site_settings', 'global_http_url');
        $settingsSiteUrl = rtrim($settingsSiteUrl, "/") . "/";
        $languageIDs     = $this->ObjView->languageIDs;
        //$xmlMap[]      = "brands.xml.gz";
        //$xmlMap[]        = "";
        foreach ($mainCategories as $category) {
            $mainCategoryID        = $category['productCategoryID'];
            $mainCategory          = $category['productCategoryKey'];
            $subCategories         = $this->ObjCommon->getSubCategories($mainCategoryID, 'List');
            $catIDAndSubcategories = implode(",", array_merge(array(
                $mainCategoryID
            ), $this->ObjCommon->getSubCategories($mainCategoryID, 'ID')));
            $resAllProducts        = $ObjProductList->listSitemapProducts($languageIDs, $catIDAndSubcategories);
            if ((!empty($subCategories)) || (!empty($resAllProducts))) {
                $xmlMap[] = $mainCategory . ".xml.gz";
            }
        }
        $sitemap = new SimpleXMLElement('<sitemapindex xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://www.sitemaps.org/schemas/sitemap/0.9 http://www.sitemaps.org/schemas/sitemap/0.9/siteindex.xsd"
        xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"></sitemapindex>');
        foreach ($xmlMap as $url) {
            $url_tag = $sitemap->addChild("sitemap");
            $url_tag->addChild("loc", htmlspecialchars($settingsSiteUrl . $url));
            $url_tag->addChild("lastmod", date('Y-m-d'));
            //$url_tag->addChild("changefreq", weekly);
        }
        return $sitemap->asXML();
    }
    //notifies services like google, bing, yahoo, ask and moreover about your site map update
    public function ping($sitemap_url, $title = "", $siteurl = "") {
        // for curl handlers
        $curl_handlers = array();
        $sitemap_url   = trim($sitemap_url);
        if (strpos($sitemap_url, "http") !== 0) {
            $sitemap_url = "http://" . $sitemap_url;
        }
        $site   = explode("//", $sitemap_url);
        $start  = $site[0];
        $site   = explode("/", $site[1]);
        $middle = $site[0];
        if (trim($title) == "") {
            $title = $middle;
        }
        if (trim($siteurl) == "") {
            $siteurl = $start . "//" . $middle;
        }
        //urls to ping
        $urls[0] = "http://www.google.com/webmasters/tools/ping?sitemap=" . urlencode($sitemap_url);
        $urls[1] = "http://www.bing.com/webmaster/ping.aspx?siteMap=" . urlencode($sitemap_url);
        $urls[2] = "http://search.yahooapis.com/SiteExplorerService/V1/updateNotification" . "?appid=YahooDemo&url=" . urlencode($sitemap_url);
        $urls[3] = "http://submissions.ask.com/ping?sitemap=" . urlencode($sitemap_url);
        $urls[4] = "http://rpc.weblogs.com/pingSiteForm?name=" . urlencode($title) . "&url=" . urlencode($siteurl) . "&changesURL=" . urlencode($sitemap_url);
        //setting curl handlers
        foreach ($urls as $url) {
            $curl = curl_init();
            curl_setopt($curl, CURLOPT_URL, $url);
            curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
            curl_setopt($curl, CURL_HTTP_VERSION_1_1, 1);
            $curl_handlers[] = $curl;
        }
        //initiating multi handler
        $multi_curl_handler = curl_multi_init();
        // adding all the single handler to a multi handler
        foreach ($curl_handlers as $key => $curl) {
            curl_multi_add_handle($multi_curl_handler, $curl);
        }
        // executing the multi handler
        do {
            $multi_curl = curl_multi_exec($multi_curl_handler, $active);
        } while ($multi_curl == CURLM_CALL_MULTI_PERFORM || $active);
        // check if there any error
        $submitted = true;
        foreach ($curl_handlers as $key => $curl) {
            //you may use curl_multi_getcontent($curl); for getting content
            //and curl_error($curl); for getting errors
            if (curl_errno($curl) != CURLE_OK) {
                $submitted = false;
            }
        }
        curl_multi_close($multi_curl_handler);
        return $submitted;
    }
    function getMenusAction() {
        $ObjCustommenu = new CustommenuModel();
        $ObjMenu       = new MenuModel();
        $languageIDs   = $this->ObjView->languageIDs;
        $listMenus     = $ObjCustommenu->listMenus($languageIDs, '', '', '', 'Active', '', 'menuItemCount', 'DESC', 'sitemap'); //print_r($listMenus	);
        $httpURL       = rtrim($this->getSettingValue('site_settings', 'global_http_url'), "/") . "/";
        $httpsUrl      = rtrim($this->getSettingValue('site_settings', 'global_https_url'), "/") . "/";
        foreach ($listMenus as $menu) {
            $menuTree     = array();
            $reslistMenus = $ObjCustommenu->getMenusItemsSiteMap($languageIDs, $menu['menuID']); //print_r($reslistMenus);
            //if(is_array($reslistMenus) && (!empty($reslistMenus))) {
            foreach ($reslistMenus as $key => $list) {
                $urlForMenuItem = $hrefelmnt = '';
                $menuitemparams = json_decode($list['params'], true);
                $enableSSL      = $menuitemparams['enableSSL'];
                $hrefelmnt      = ($enableSSL == 'Yes') ? $httpsUrl : $httpURL;
                if ($list['moduleKey'] == 'url')
                    $urlForMenuItem = "http://" . ltrim($list['itemLink'], "http://,httpps://");
                else
                    $urlForMenuItem = $hrefelmnt . rtrim($list['itemLink'], "/");
                $reslistMenus[$key]['newLink']               = $urlForMenuItem;
                $menuTree[$reslistMenus[$key]['parentID']][] = $reslistMenus[$key];
            }
            $mainTree      = $this->createTreeLeft($menuTree, $menuTree[0]);
            $listItem      = $mainTree;
            $resMenuList[] = array(
                $menu['menuID'],
                $menu['menuName'],
                $listItem
            );
            //}
        }
        $this->ObjView->assign('resMenuList', $resMenuList); //print_r($resMenuList);
        $this->ObjView->display('MenuSiteMap.tpl');
    }
    private function createTreeLeft(&$list, $parent) {
        $tree = array();
        if (is_array($parent)) {
            foreach ($parent as $k => $l) {
                if (isset($list[$l['parentID']]) && !empty($list[$l['orderID']])) {
                    $l['children'] = $this->createTreeLeft($list, $list[$l['orderID']]);
                }
                $tree[] = $l;
            }
        }
        return $tree;
    }
}
