HEX
Server: Microsoft-IIS/8.5
System: Windows NT YDAWBH120 6.3 build 9600 (Windows Server 2012 R2 Standard Edition) AMD64
User: tentjecom_web (0)
PHP: 7.4.14
Disabled: NONE
Upload Files
File: D:/HostingSpaces/SBogers10/spire.komma-mediadesign.nl/wwwroot/kms/client/models/m_where_to_buy.php
<?php

/*
	
	This class handles all tasks regarding news-items

*/

require_once DOCUMENT_ROOT.'app/models/m_page.php';

require_once DOCUMENT_ROOT.'client/models/products/m_products.php';

require_once DOCUMENT_ROOT.'client/models/products/m_pc_accessories.php';
require_once DOCUMENT_ROOT.'client/models/products/m_cpucoolers.php';
require_once DOCUMENT_ROOT.'client/models/products/m_mobile_accessories.php';
require_once DOCUMENT_ROOT.'client/models/products/m_pccases.php';
require_once DOCUMENT_ROOT.'client/models/products/m_power_supply.php';
require_once DOCUMENT_ROOT.'client/models/products/m_system_cooling.php';
require_once DOCUMENT_ROOT.'client/models/products/m_tabletpc.php';

class Where_To_Buy extends Page
{
	/** 
	*
	*	@var array news data
	*/
	private $_data = array('id'=>'', 'title'=>'', 'city'=>'', 'country'=>'', 'link'=>'', 'timest'=>'');
	
	/**
	*
	*	@var int Since this is an extension we need a hardcoded pageId
	*/
	private $_pageId = 15;

    private $_template;
	/**
	*
	* Constructor
	*/
	public function __construct()
	{
		// Storage Session
		$this->dataSession = new DataSession('data_to_store',$this->_data);	
		
		// Name of the databasetable
		$this->tableName = 'page_wheretobuy_items';
	
		// database handler
		$this->dbh = new DatabaseHandler();
		$this->dbh->setTableName($this->tableName);

        // lang
        global $template;
        $this->_template = $template;
        $this->lang = $template->lang;
	}
	
	/**
	* This functions graps data from the database ands returns this in an array
	* If an array of ids is passed trough only those rows from that list of ids will be returned, otherwise all rows wil be returned
	*
	* @access public
	* @param array(optional)
	* @return array
	*/
	public function get($ids = NULL)
	{
		// tell the database handler what data to get switch timest with timestamp
		$getData = array('id'=>'', 'title'=>'', 'city'=>'', 'country'=>'', 'link'=>'', 'timest'=>'');
		$this->dbh->setData($getData);
        $this->dbh->setOrder('country','ASC');
		$data = array();
		if( ! empty($ids))
		{
			// grap categories from specified ids
			$data = array();
			foreach($ids as $id)
			{
				$this->dbh->addRule('id',$id);
				$data[] = $this->dbh->select();
			}
		}
		else
		{ 
			// grap all categories
			$this->dbh->setActiveOnly(TRUE, $this->_pageId);
			$this->dbh->setScope(0,$this->maxItems);
			$data = $this->dbh->select();
		}
		
		return $data;
	}
	
	/**
	* Puts data into the session data_to_store
	*
	* @access public
	* @param int
	* @return null
	*/
	public function setStorageData($id)
	{
		if( ! empty($id) && is_numeric($id))
		{
			$tempdata = $this->get(array($id));
			$data = $tempdata[0];
			
			foreach(array_keys($_SESSION['data_to_store']) as $key)
			{
				if(isset($data[$key]))
				{
					$_SESSION['data_to_store'][$key] = $data[$key];
				}
			}

            // Get all products from the database
            $prDbh = new DatabaseHandler();
            $prDbh->setTableName('page_wheretobuy_products');
            $prDbh->addRule('itemId',$id);
            $prDbh->setData(array('categoryId'=>'','productId'=>''));
            $prDbh->setOrder('id','asc');
            $data = $prDbh->select();

            $products = array();
            foreach($data as $value)
            {
                $products[] = $value['categoryId'] . '_' . $value['productId'];
            }

            $_SESSION['data_to_store']['products'] = $products;
		}
	}
	
	/**
	* Save data in the datasession
	* Valitimest and store a item in the database
	* Id an id is set, the storage needs to be uptimestd, else a new row is inserted
	*
	* @access public
	* @param array
	* @return boolean
	*/
	public function store($id = NULL)
	{
		// data obtained by post
		$this->_data = $this->dataSession->savePost();
        $this->saveProducts();

		if( ! empty($this->_data))
		{
			if($this->validate($id))
			{
                // get timest by time().
                $this->_data['timest'] = time();

                unset($this->_data['products']);
				//unset($this->_data['timest']);

				if($id == NULL)
				{
					// No id is set => Insert
					
					// order - get highest order from the table and add 1
					$orderData = array('itemOrder'=>'');
					$orderDbh = new DatabaseHandler();
					$orderDbh->setTableName($this->tableName);
					$orderDbh->setData($orderData);
					$orderDbh->setActiveOnly(TRUE, $this->_pageId);
					$orderDbh->setOrder('itemOrder','DESC');
					$orderDbh->setScope(0,1);
					if($result = $orderDbh->select())
					{	
						$highestOrder = $result['itemOrder'];
						
						$this->_data['itemOrder'] = $highestOrder + 1;
					}
					else
					{
						$this->_data['itemOrder'] = 1;
					}
					
					// insert data
					$this->dbh->setData($this->_data);
					
					if($insertId = $this->dbh->insert())
					{
                        $this->storeProducts('insert',$insertId);

                        // Active
						$activeDb = new DatabaseHandler();
						$activeDb->setTableName('kms_active');
						$activeDb->setData(array('itemId'=>$insertId,'pageId'=>$this->_pageId,'active'=>1,'lastUpDate'=>time()));
						if($activeDb->insert())
						{
							$this->dataSession->clear();
							return $insertId;
						}
					}
					else
					{
                        $this->errors[] = $this->lang['general_something_went_wrong'];
					}
				}
				else
				{
                    $this->storeProducts('update',$id);

                    // Id is set => Update
					$this->dbh->setData($this->_data);
					$this->dbh->addRule('id',$id);
					if($this->dbh->update())
					{
						$this->dataSession->clear();
						return TRUE;
					}
				}
			}
		}
		return FALSE;
	}


    /*
     Save products in the session
    */
    public function saveProducts()
    {
        $_SESSION['data_to_store']['products'] = $_POST['products'];
    }

    public function storeProducts($method='insert', $itemId = null)
    {
        $newData = $_SESSION['data_to_store']['products'];

        $prDbh = new DatabaseHandler();
        $prDbh->setTableName('page_wheretobuy_products');

        if($method == 'insert')
        {
            // INSERT
            foreach($newData as $value)
            {
                if( ! empty($value))
                {
                    $temp = explode('_',$value);
                    $catId = $temp[0];
                    $productId = $temp[1];

                    $prDbh->setData(array('itemId'=>$itemId,'categoryId'=>$catId,'productId'=>$productId));
                    $prDbh->insert();
                }
            }
        }
        else
        {
            // UPDATE
            // Get all products from the database
            $prDbh->addRule('itemId',$itemId);
            $prDbh->setData(array('id'=>'','itemId'=>'','categoryId'=>'','productId'=>''));
            $prDbh->setOrder('id','asc');
            $oldData = $prDbh->select();
            if(! is_array($oldData[key($oldData)])) $oldData = array($oldData);

            // Compare old and new data, remove matches
            foreach($newData as $key1 => $data1)
            {
                $temp = explode('_',$data1);
                $catId = $temp[0];
                $productId = $temp[1];

                foreach($oldData as $key2 => $data2)
                {
                    if($catId == $data2['categoryId'] && $productId == $data2['productId'])
                    {
                        unset($newData[$key1]);
                        unset($oldData[$key2]);
                    }
                }
            }


            // Remove whats left of old data
            foreach($oldData as $data)
            {
                if( ! empty($data['id']))
                {
                    $prDbh->clearRule();
                    $prDbh->addRule('id',$data['id']);
                    $prDbh->delete();
                }
            }

            // Add whats left of new data
            foreach($newData as $value)
            {
                $temp = explode('_',$value);
                $catId = $temp[0];
                $productId = $temp[1];

                $prDbh->setData(array('itemId'=>$itemId,'categoryId'=>$catId,'productId'=>$productId));
                $prDbh->insert();
            }
        }
    }
	
	/**
	* Validate item
	* Save errors if these appear
	* 
	* @access private
	* @param
	* @return boolean
	*/
	private function validate($id=NULL)
	{
		$required = array();
		$title = $required[] = $this->_data['title'];
        $required[] = $this->_data['country'];
        $required[] = $this->_data['link'];

        // check for empty fields
		foreach($required as $value)
		{
			if(empty($value))
			{
                $errors[] = $this->lang['form_complete_all_fields'];
			}	
		}

		// check unique values (only insert)
		$titleDbh = new DatabaseHandler();
		$titleDbh->setTableName($this->tableName);
		$titleDbh->setData(array('title'=>''));	
		$titleDbh->addRule('title', $title);	
		if( $id != NULL)
		{
			$titleDbh->addRule('id', $id, ' AND NOT ');	
		}
		if($titleDbh->select())
		{
            $errors[] = $this->lang['form_choose_unique_title'];
		}
	
		// check if valid
		
		if(isset($errors))
		{	
			$this->errors = $errors;
			return FALSE;
		}
		else
		{
			return TRUE;
		}
	}

    public function createList()
    {
        // Get products

        isset($_SESSION['data_to_store']['products']) ? $savedProducts = $_SESSION['data_to_store']['products'] : $savedProducts = array();

        $output = '';

        // ACCESSORIES
        $Acc = new Pc_Accessories();
        $accList = $Acc->get(null,null,array('productCode','asc'),true);

        $output .= '<div class="wtb_column">';
            $output .= '<label class="wtb_h"><input type="checkbox" name="products[]" value=""  id="acc_check" /> Accessories</label>';
            $output .= '<ul id="acc_list" class="wtb_products ">';
            foreach($accList as $key => $product)
            {
                $base = str_replace('kms/','',SITE_ROOT);
                $page = 'pc-accessories';
                $sub = $this->_template->encodeUrl($product['title'] . ' ' . $product['productCode']);

                $link = $base . $page . '/' . $sub . '/';

                $output .= '<li><input type="checkbox" name="products[]" id="acc' . $key . '" value="11_' . $product['id'] . '" ';
                if(in_array('11_' . $product['id'],$savedProducts)) $output .= 'checked ';
                $output .= '/> <label for="acc' . $key . '"> ' . $product['productCode'] . ' / ' . $product['title'] . '</label>';
               // $output .= ' - <a href="' . $link . '" target="_blank">web</a>';
                $output .= '</li>';
            }
            $output .= '</ul>';
        $output .= '</div>';

        // COMPUTER CASES
        $PcCases = new PcCases();
        $casesList = $PcCases->get(null,null,array('productCode','asc'),true);

        $output .= '<div class="wtb_column">';
        $output .= '<label class="wtb_h"><input type="checkbox" name="check_all" value="" id="pc_check" /> Computer Cases</label>';
        $output .= '<ul id="pc_list" class="wtb_products ">';
        foreach($casesList as $key => $product)
        {
            $base = str_replace('kms/','',SITE_ROOT);
            $page = 'computer-cases';
            $sub = $this->_template->encodeUrl($product['title'] . ' ' . $product['productCode']);

            $link = $base . $page . '/' . $sub . '/';

            $output .= '<li><input type="checkbox" name="products[]" id="cases' . $key . '" value="10_' . $product['id'] . '" ';
            if(in_array('10_' . $product['id'],$savedProducts)) $output .= 'checked ';
            $output .= '/> <label for="cases' . $key . '">' . $product['productCode'] . ' / ' . $product['title'] . '</label>';
            //$output .= ' - <a href="' . $link . '" target="_blank">web</a>';
            $output .= '</li>';
        }
        $output .= '</ul>';
        $output .= '</div>';

        // CPU COOLERS
        $CpuCooler = new CpuCoolers();
        $cpuList = $CpuCooler->get(null,null,array('productCode','asc'),true);

        $output .= '<div class="wtb_column">';
        $output .= '<label class="wtb_h"><input type="checkbox" name="check_all" value="" id="cpu_check" /> CPU Coolers</label>';
        $output .= '<ul id="cpu_list" class="wtb_products ">';
        foreach($cpuList as $key => $product)
        {
            $base = str_replace('kms/','',SITE_ROOT);
            $page = 'cpu-coolers';
            $sub = $this->_template->encodeUrl($product['title'] . ' ' . $product['productCode']);

            $link = $base . $page . '/' . $sub . '/';

            $output .= '<li><input type="checkbox" name="products[]" id="cpu' . $key . '" value="9_' . $product['id'] . '" ';
            if(in_array('9_' . $product['id'],$savedProducts)) $output .= 'checked ';
            $output .= '/> <label for="cpu' . $key . '">' . $product['productCode'] . ' / ' . $product['title'] . '</label>';
           // $output .= ' - <a href="' . $link . '" target="_blank">web</a>';
            $output .= '</li>';
        }
        $output .= '</ul>';
        $output .= '</div>';

        $output .= '<div class="clear"></div>';

        // MOBILE
        $Mobile = new Mobile_Accessories();
        $mobileList = $Mobile->get(null,null,array('productCode','asc'),true);

        $output .= '<div class="wtb_column">';
        $output .= '<label class="wtb_h"><input type="checkbox" name="check_all" value="" id="mob_check" /> Mobile</label>';
        $output .= '<ul id="mob_list" class="wtb_products ">';
        foreach($mobileList as $key => $product)
        {
            $base = str_replace('kms/','',SITE_ROOT);
            $page = 'mobile-accessories';
            $sub = $this->_template->encodeUrl($product['title'] . ' ' . $product['productCode']);

            $link = $base . $page . '/' . $sub . '/';

            $output .= '<li><input type="checkbox" name="products[]" id="mobile' . $key . '" value="12_' . $product['id'] . '" ';
            if(in_array('12_' . $product['id'],$savedProducts)) $output .= 'checked ';
            $output .= '/> <label for="mobile' . $key . '">' . $product['productCode'] . ' / ' . $product['title'] . '</label>';
           // $output .= ' - <a href="' . $link . '" target="_blank">web</a>';
            $output .= '</li>';
        }
        $output .= '</ul>';
        $output .= '</div>';

        // POWER SUPPLY
        $PowerSupply = new PowerSupply();
        $powSupList = $PowerSupply->get(null,null,array('productCode','asc'),true);

        $output .= '<div class="wtb_column">';
        $output .= '<label class="wtb_h"><input type="checkbox" name="check_all" value="" id="sup_check" /> Power Supply</label>';
        $output .= '<ul id="sup_list" class="wtb_products ">';
        foreach($powSupList as $key => $product)
        {
            $base = str_replace('kms/','',SITE_ROOT);
            $page = 'power-supplies';
            $sub = $this->_template->encodeUrl($product['title'] . ' ' . $product['productCode']);

            $link = $base . $page . '/' . $sub . '/';

            $output .= '<li><input type="checkbox" name="products[]" id="supply' . $key . '" value="8_' . $product['id'] . '" ';
            if(in_array('8_' . $product['id'],$savedProducts)) $output .= 'checked ';
            $output .= '/> <label for="supply' . $key . '">' . $product['productCode'] . ' / ' . $product['title'] . '</label>';
           // $output .= ' - <a href="' . $link . '" target="_blank">web</a>';
            $output .= '</li>';
        }
        $output .= '</ul>';
        $output .= '</div>';

        // SYSTEM COOLING
        $SystemCooling = new SystemCooling();
        $sysCoolingList = $SystemCooling->get(null,null,array('productCode','asc'),true);

        $output .= '<div class="wtb_column">';
        $output .= '<label class="wtb_h"><input type="checkbox" name="check_all" value="" id="sys_check" /> System Cooling</label>';
        $output .= '<ul id="sys_list" class="wtb_products ">';
        foreach($sysCoolingList as $key => $product)
        {
            $base = str_replace('kms/','',SITE_ROOT);
            $page = 'system-cooling';
            $sub = $this->_template->encodeUrl($product['title'] . ' ' . $product['productCode']);

            $link = $base . $page . '/' . $sub . '/';

            $output .= '<li><input type="checkbox" name="products[]" id="system' . $key . '" value="7_' . $product['id'] . '" ';
            if(in_array('7_' . $product['id'],$savedProducts)) $output .= 'checked ';
            $output .= '/> <label for="system' . $key . '">' . $product['productCode'] . ' / ' . $product['title'] . '</label>';
           // $output .= ' - <a href="' . $link . '" target="_blank">web</a>';
            $output .= '</li>';
        }
        $output .= '</ul>';
        $output .= '</div>';

        $output .= '<div class="clear"></div>';

        // TABLET PC
        $TabletPC = new Tablet_Pc();
        $tabletPcList = $TabletPC->get(null,null,array('productCode','asc'),true);

        $output .= '<div class="wtb_column">';
        $output .= '<label class="wtb_h"><input type="checkbox" name="check_all" value="" id="tab_check" /> TabletPC</label>';
        $output .= '<ul id="tab_list" class="wtb_products ">';
        foreach($tabletPcList as $key => $product)
        {
            $base = str_replace('kms/','',SITE_ROOT);
            $page = 'tablet-pc';
            $sub = $this->_template->encodeUrl($product['title'] . ' ' . $product['productCode']);

            $link = $base . $page . '/' . $sub . '/';

            $output .= '<li><input type="checkbox" name="products[]" id="tablet' . $key . '" value="16_' . $product['id'] . '" ';
            if(in_array('16_' . $product['id'],$savedProducts)) $output .= 'checked ';
            $output .= '/> <label for="system' . $key . '">' . $product['productCode'] . ' / ' . $product['title'] . '</label>';
           // $output .= ' - <a href="' . $link . '" target="_blank">web</a>';
            $output .= '</li>';
        }
        $output .= '</ul>';
        $output .= '</div>';


        return $output;
    }

    /**
     * Creates an output string containing listitems to display
     * Also creates an array of ids from items which are displayed in the list
     * These two are returned in an array($output, $ids);
     *
     * @access public
     * @param $data
     * @param bool $editable
     * @internal param $array (two-dimensional), boolean
     * @return array
     */
    public function createDashboardList($data, $editable = TRUE)
    {
        $output = 'Er zijn nog geen items gevonden.';
        $ids = array();

        if($data != NULL)
        {
            $i = 1;
            $output = '';

            // catch problems when only one 1 item is in data
            $keys = array_keys($data);
            if( is_string($keys[0]) )
            {
                $info = $data;
                $data = array($info);
            }
            foreach($data as $info)
            {
                $ids[] = $info['id'];
                if(isset($info['timest']))
                {
                    $added = date('d / m / Y',$info['timest']);
                }
                else if(isset($info['lastUpdate']))
                {
                    $added = date('d / m / Y',$info['lastUpdate']);
                }
                else
                {
                    $added = '';
                }

                $output .= '<li';
                if($i % 2 != 0) $output .= ' class="alt"';
                $output .= '>';
                $output .= '<div class="col cb">';
                if($editable)
                {
                    $output .= '<input type="checkbox" name="selected[]" value="'.$info['id'].'" />';
                }
                else
                {
                    $output .= '&nbsp;';
                }
                $output .= '</div>';
                $output .= '<div class="col title"><a href="'.LANG_ROOT.URL_PAGE . '/wijzig-item/'.$info['id'].'/">'.ucfirst($info['title']).'</a></div>';
                $output .= '<div class="col added">'.$added.'</div>';
                $output .= '<div class="col added"><a href="'. $info['link'] . '" target="_blank">Web link</a></div>';
                $output .= '<div class="col added">'. $info['country'] . '</div>';

                $output .= '<div class="col edit">';
                if($editable)
                {
                    /*
                    $output .= '<div class="subcol">';
                        $output .= '<a href="'.LANG_ROOT.$this->_linkname.'/publish/'.$info['id'].'/">';

                        $published = $this->checkPublished($info['id']);

                        if($published)
                        {
                            $output .= 'Depubliceer';
                        }
                        else
                        {
                            $output .= '<span class="publish">Publiceer</a>';
                        }
                        $output .= '</a>';
                    $output .= '</div>';
                    */
                    $output .= '<div class="subcol">';
                    $output .= '<a href="'.LANG_ROOT.URL_PAGE . '/wijzig-item/'.$info['id'].'/">'.$this->lang['edit'].'</a>';
                    $output .= '</div>';

                    $output .= '<div class="subcol">';
                    $output .= '<a href="'.LANG_ROOT.URL_PAGE . '/verwijder-item/'.$info['id'].'/">'.$this->lang['delete'].'</a>';
                    $output .= '</div>';


                    $output .= '<div class="clear"></div>';
                }
                else
                {
                    $output .= '&nbsp;';
                }
                $output .= '</div>';
                $output .= '</li>';
                $i++;
            }
        }
        return array($output, $ids);
    }
}