<?php 

// h-source, a web software to build a community of people that want to share their hardware information.
// Copyright (C) 2010  Antonio Gallo (h-source-copyright.txt)
//
// This file is part of h-source
//
// h-source is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// 
// h-source is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
// 
// You should have received a copy of the GNU General Public License
// along with h-source.  If not, see <http://www.gnu.org/licenses/>.

if (!defined('EG')) die('Direct access not allowed!');

class GenericController extends BaseController
{

	protected $_controllerName = null; //as in the URL
	
	public $orderPopup;

	public function __construct($model, $controller, $queryString) {

		$this->_topMenuClasses['hardware'] = " class='currentitem ui-btn-active'";
		
		parent::__construct($model, $controller, $queryString);

		$this->model('VendorsModel');
		
		$popup = new Popup();
		$popup->name = gtext('sort by');

		$popNames = array(gtext('last inserted'),gtext('alphabetically'),gtext('alphabetically desc'),gtext('compatibility'));
		$popValues = array('last-inserted','alphabetically','alphabetically-desc','compatibility');

		switch ($this->controller)
		{
			case 'printers':
				$popup->itemsName = $popNames;
				$popup->itemsValue = $popValues;
				break;
			case 'notebooks':
				$popup->itemsName = $popNames;
				$popup->itemsValue = $popValues;
				break;
			case 'scanners':
				$popup->itemsName = $popNames;
				$popup->itemsValue = $popValues;
				break;
			default:
				array_pop($popNames);
				array_pop($popValues);
				$popup->itemsName = $popNames;
				$popup->itemsValue = $popValues;
				break;
		}
		
		$this->orderPopup = $popup;

// 		$data['howToCompileLabel'] = null;
		$data['isApproved'] = true;

		$data['tracksHelpLabel'] = $this->getModule(array('devices',$this->controller,'form','it_tracks_users'));
		$data['howToCompileLabel'] = $this->getModule(array('devices','all','form','how_to_compile'));
		$data['modelNameLabel'] = $this->getModule(array('devices','all','form','model_name_entry_help_label'));
		$data['vendoridProductidLabel'] = $this->getModule(array('devices','not_notebook','form','vendorid_productid_label'));
		$data['descriptionLabel'] = $this->getModule(array('devices','all','form','description_entry_help_label'));
		$data['preventWifiLabel'] = $this->getModule(array('devices','notebook','form','prevent_wifi_label'));
		
		$this->append($data);
	}

	protected function insert($lang = 'en', $token = '')
	{
		$this->shift(2);

		if ( strcmp($this->_updating,'no') !== 0 ) $this->redirect('users/login/'.$this->lang,0);

		$clean['token'] = sanitizeAlphanum($token);

		$data['descriptionPreview'] = null; //contains the HTML of the preview of the description entry
		
		$data['notice'] = null;
		$data['submission_response'] = 'error';
		
		$data['tree'] = $this->getSpecHardLink() . " &raquo;  " . " <span class='last_tree_element'>".gtext("Insert")."</span>";
		
		$this->s['registered']->checkStatus();
		
		if ($this->s['registered']->status['status'] === 'logged' or Website::$allowAnonymousSubmission === "yes")
		{
// 			if (!$this->s['registered']->checkCsrf($clean['token'])) $this->redirect($this->controller.'/catalogue/'.$this->lang,2,'wrong token..');
			
// 			if ($this->m['UsersModel']->isBlocked($this->s['registered']->status['id_user'])) $this->redirect('my/home/'.$this->lang,2,'your account has been blocked..');
			
			if (isset($_POST['insertAction']))
			{
				if ($this->checkDist())
				{
					$pci_id = $this->request->post('pci_id','','sanitizeAll');
					$interface = $this->request->post('interface','not-defined','sanitizeAll');

					if ($this->checkVendorId($interface))
					{
						if (strcmp($this->m['HardwareModel']->type,'notebook') !== 0)
						{
							$this->m['HardwareModel']->values['vendor'] = sanitizeAll($this->m['VendorsModel']->getName($pci_id,$interface));

							$this->m['HardwareModel']->databaseConditions['insert']['+checkUnique'] = 'pci_id|<i>VendorID:ProductID</i> is already present in the database. This means that the device you are trying to insert is already in the database. See here: '.$this->getAlreadyExixtsLink($pci_id);
						}

						//insert the new device
						$this->m['HardwareModel']->updateTable('insert');

						if ($this->m['HardwareModel']->queryResult)
						{
							if (strcmp($this->controller,'notebooks') === 0)
							{
								@session_start();
								$_SESSION['notebook_inserted'] = 'yes';
							}

							$data['submission_response'] = 'executed';
						}

						$this->viewRedirect($this->m['HardwareModel']->lastId);

					}
				}
			}

			$data['descriptionPreview'] = $this->getPreview();

			$data['notice'] = $this->m['HardwareModel']->notice;
			
			$data['submitName'] = "insertAction";
			$data['hiddenInput'] = null;

			$data['values'] = $this->m['HardwareModel']->getFormValues('insert','sanitizeHtml');
			$this->append($data);

			if (!isset($_POST['from_client']))
			{
				$this->load('top_left');
				$this->load('license_notice');
				$this->load('form');
				$this->load('bottom_left');
				$this->right();
			}
			else
			{
				header ("Content-Type:text/xml");
				$this->clean();
				$this->load('xml_response');
			}
		}
		else
		{
			$this->redirect("users/login/".$this->lang."?redirect=".$this->controller."/catalogue/".$this->lang,0);
		}
	}

	public function del($lang = 'en', $token = '')
	{
		header('Content-type: text/html; charset=UTF-8');
		
		$this->shift(2);
		
		$this->clean();
		
		$clean['token'] = sanitizeAlphanum($token);
		
		if ($this->s['registered']->status['status'] === 'logged')
		{
			if (!$this->s['registered']->checkCsrf($clean['token'])) die("wrong token");
			
			if ($this->m['UsersModel']->isBlocked($this->s['registered']->status['id_user'])) die("your account has been blocked");
			
			$clean['id_user'] = (int)$this->s['registered']->status['id_user'];
			$clean['id_hard'] = $this->request->post('id_hard',0,'forceInt');
			
			$this->model("DeletionModel");
			
			$numb = $this->m['DeletionModel']->where(array("id_hard"=>$clean['id_hard'],"created_by"=>$clean['id_user']))->rowNumber();

			if ($numb === 0)
			{
				$id_dup = $this->request->post('id_duplicate',0,'forceInt');
				$object = $this->request->post('object','','sanitizeAll');
				
				if ($id_dup === 0 and strcmp($object,'duplication') === 0)
				{
					echo "you have no specified the device duplicated by this model";
				}
				else
				{
					$this->m['DeletionModel']->setFields('id_hard:forceInt,object,message,id_duplicate:forceInt','sanitizeAll');
					$this->m['DeletionModel']->values['created_by'] = $clean['id_user'];
					
					$this->m['DeletionModel']->updateTable('insert');
					if ($this->m['DeletionModel']->queryResult)
					{
						$hard = new HardwareModel();
						$c = $hard->where(array('id_hard'=>$clean['id_hard'],'ask_for_del'=>'yes'))->rowNumber();
						if ($c < 1)
						{
							$hard->db->update('hardware','ask_for_del',array('yes'),'id_hard='.$clean['id_hard']);
						}
						echo "operation executed";
					}
					else
					{
						echo "one error occurred, please try later";
					}
				}
			}
			else
			{
				echo "you have already asked for the deletion of this device";
			}
		}
	}
	
	protected function update($lang = 'en', $token = '')
	{
		$this->shift(2);
		
		$clean['token'] = sanitizeAlphanum($token);

		$data['descriptionPreview'] = null; //contains the HTML of the preview of the description entry
		
		$data['notice'] = null;
		$data['submission_response'] = 'error';
		
		$this->s['registered']->checkStatus();
		
		if (isset($_POST['id_hard']))
		{
			//get the id
			$clean['id_hard'] = isset($_POST['id_hard']) ? (int)$_POST['id_hard'] : 0;
				
			if ($this->s['registered']->status['status'] === 'logged')
			{			
				if (!$this->s['registered']->checkCsrf($clean['token'])) $this->redirect($this->controller.'/catalogue/'.$this->lang,2,'wrong token..');
				
				if ($this->m['UsersModel']->isBlocked($this->s['registered']->status['id_user'])) $this->redirect('my/home/'.$this->lang,2,'your account has been blocked..');

				if ($this->m['HardwareModel']->isCleared($clean['id_hard'])) $this->redirect('generic/cleared/'.$this->lang,0);
				
				$deleted = $this->m['HardwareModel']->select("hardware.deleted")->where(array("id_hard"=>$clean['id_hard']))->limit(1)->toList('deleted')->send();
				
				if (strcmp($deleted[0],'no') === 0)
				{
					$ne_name = $this->m['HardwareModel']->getTheModelName($clean['id_hard']);
					$name = encodeUrl($ne_name);
					$data['name'] = $name;
					$data['ne_name'] = $ne_name;
					$data['tree'] = $this->getSpecHardLink() . " &raquo;  " . $this->getViewLink($clean['id_hard'],$ne_name) . " &raquo; <span class='last_tree_element'>".gtext("Edit")."</span>";

					if (isset($_POST['updateAction']))
					{
						if ($this->checkDist())
						{
							$pci_id = $this->request->post('pci_id','','sanitizeAll');
							$interface = $this->request->post('interface','not-defined','sanitizeAll');
								
							if ($this->checkVendorId($interface))
							{
								if (strcmp($this->m['HardwareModel']->type,'notebook') !== 0)
								{
									$this->m['HardwareModel']->values['vendor'] = sanitizeAll($this->m['VendorsModel']->getName($pci_id,$interface));
									
									$this->m['HardwareModel']->databaseConditions['update']['+checkUniqueCompl'] = 'pci_id|<i>VendorID:ProductID</i> is already present in the database. This means that the device you are trying to insert is already in the database. See here: '.$this->getAlreadyExixtsLink($pci_id);
								}

								//carry out the update database action
								$this->m['HardwareModel']->updateTable('update');

								if ($this->m['HardwareModel']->queryResult)
								{
									$data['submission_response'] = 'executed';
								}
								$this->viewRedirect($this->m['HardwareModel']->lastId);
							}
						}
					}

					$data['descriptionPreview'] = $this->getPreview();
					
					$data['notice'] = $this->m['HardwareModel']->notice;
					
					$data['id_hard'] = $clean['id_hard'];
					$data['submitName'] = "updateAction";
		// 			echo $this->m['HardwareModel']->fields;
					$data['values'] = $this->m['HardwareModel']->getFormValues('update','sanitizeHtml');
					$data['hiddenInput'] = "<input type='hidden' name='id_hard' value='".$clean['id_hard']."'>\n";

					$this->append($data);

					if (!isset($_POST['from_client']))
					{
						$this->load('top_left');
						$this->load('license_notice');
						$this->load('form');
						$this->load('bottom_left');
						$this->right();
					}
					else
					{
						header ("Content-Type:text/xml");
						$this->clean();
						$this->load('xml_response');
					}
				}
				else
				{
					$this->redirect($this->controller.'/catalogue/'.$this->lang,2,'deleted..');
				}
			}
			else
			{
				$this->redirect("users/login/".$this->lang."?redirect=".$this->controller."/view/".$this->lang."/".$clean['id_hard'],0);
			}
		}
		else
		{
			$this->redirect($this->controller.'/catalogue/'.$this->lang);
		}
	}

	//get the preview of the description entry
	protected function getPreview()
	{
		if (isset($_POST['previewAction']))
		{
			$this->m['HardwareModel']->result = false;
			return $this->request->post('description','','sanitizeHtml');
		}
		return null;
	}
	
	protected function checkVendorId($interface)
	{
		if (strcmp($this->m['HardwareModel']->type,'notebook') === 0) return true;
		
		if (array_key_exists('pci_id',$_POST))
		{
			if (strcmp($_POST['pci_id'],"") !== 0)
			{
				if (preg_match('/^[a-zA-Z0-9]{4}(\:)[a-zA-Z0-9]{4}$/',$_POST['pci_id']))
				{
					if ($this->m['VendorsModel']->check($_POST['pci_id'],$interface))
					{
						return true;
					}
					else
					{
						$this->m['HardwareModel']->result = false;
						$this->m['HardwareModel']->notice = "<div class='alert'>Your vendor has not been found.<br /><br />Your vendorid code is not present in the list. If it is a USB device, please choose the right interface (USB), otherwise the system will check inside the PCI ID vendors' list. If it is not a USB device, and you are not sure about the right interface, choose not-defined, and it should work fine (the system will check inside the PCI ID vendors' list if you choose an interface other than USB). <br/><br />If your vendor has not been found yet, please open an issue <a href='".$this->baseUrl."/issues/viewall/".Lang::$current."'>here</a> in order to ask the insertion of your vendor.<br /><br />If your vendor has not been found you could also send your PCI ID or USB ID to the PCI ID repository (http://pciids.sourceforge.net/) or to the USB ID repository (http://www.linux-usb.org/usb-ids.html).</div>\n";
						return false;
					}
				}
				else
				{
					$this->m['HardwareModel']->result = false;
					$this->m['HardwareModel']->notice = "<div class='alert'><i>VendorID:ProductID</i> has to have the following format: [a-zA-Z0-9]{4}(\:)[a-zA-Z0-9]{4}</div>";
				}
			}
			else
			{
				$this->m['HardwareModel']->result = false;
				$this->m['HardwareModel']->notice = "<div class='alert'>Vendorid:Productid code not defined..</div>\n";
				return false;
			}
		}
		$this->m['HardwareModel']->result = false;
		return false;
	}
	
	protected function checkDist()
	{
		if (array_key_exists('distribution',$_POST))
		{
			if (strcmp($_POST['distribution'],"") !== 0)
			{
				if (Distributions::check($_POST['distribution']))
				{
					return true;
				}
				else
				{
					$this->m['HardwareModel']->result = false;
					$this->m['HardwareModel']->notice = "<div class='alert'>Distribution not allowed..</div>\n";
					return false;
				}
			}
			else
			{
				$this->m['HardwareModel']->result = false;
				$this->m['HardwareModel']->notice = "<div class='alert'>Distribution not defined..</div>\n";
				return false;
			}
		}
		$this->m['HardwareModel']->result = false;
		return false;
	}
	
	protected function viewRedirect($id)
	{
		$clean['id'] = (int)$id;

		if ($this->m['HardwareModel']->queryResult)
		{
			if (!isset($_POST['from_client']))
			{
				$name = encodeUrl($this->m['HardwareModel']->getTheModelName($clean['id']));
				$this->redirect($this->controller.'/view/'.$this->lang.'/'.$clean['id'].'/'.$name.$this->viewStatus);
			}
		}
	}
	
	//load the view files
	protected function loadViewAll($viewName = null)
	{
		$this->load('top_left');
		$viewArray = explode(',',$viewName);
		foreach ($viewArray as $viewFile)
		{
			$this->load($viewFile);
		}
		$this->load('bottom_left');
		$this->right();
	}

	protected function catalogue($lang = 'en')
	{
		$data['title'] = $this->controller.' - '.Website::$generalName;
		
		Params::$nullQueryValue = 'undef';
		
		$data['tree'] = plural($this->controller);

		//look for a string in the model name or in the other_names if the string is different from undef
		if (strcmp($this->viewArgs['search_string'],"undef") !== 0)
		{
			$nWhere = array(
				'OR'	=>	array(
						'model'			=>	"like '%".$this->viewArgs['search_string']."%'",
						'other_names'	=>	"like '%".$this->viewArgs['search_string']."%'",
					),
			);
			$this->mod->aWhere($nWhere);
		}
		
		$this->mod->aWhere(array("deleted"=>"no","cleared"=>"no"));
		
		$this->mod->popupBuild();
		$popup = $this->mod->popupArray;
		$popup['sort-by'] = $this->orderPopup;
		
		$this->helper('Popup',$this->controller.'/catalogue/'.$this->lang,$popup,'inclusive','page');

		$this->h['Popup']->allString = gtext("All");
		
		//create the HTML of the popup
		$data['popup'] = $this->h['Popup']->render();

		if (strcmp($this->controller,'notebooks') === 0)
		{
			$this->mod->popupArray = array();
			$this->mod->morePopups();
			$this->mod->popupBuild();
			$this->h['Popup']->popupArray = $this->mod->popupArray;
			$data['popupMore'] = $this->h['Popup']->render();
		}
		
		$this->mod->orderBy = getOrderByClause($this->viewArgs['sort-by']);
		$recordNumber = $this->mod->rowNumber();

		$data['recordNumber'] = $recordNumber;
		
		//load the Pages helper
		$this->helper('Pages',$this->controller.'/catalogue/'.$this->lang,'page');
		$page = $this->viewArgs['page'];
		//set the limit clause
		$this->mod->limit = $this->h['Pages']->getLimit($page,$recordNumber,10);
		
		$data['table'] = $this->mod->getAll();
// 		echo $this->mod->getQuery();
		
		$data['pageList'] = $this->h['Pages']->render($page-3,7);
		$data['numberOfPages'] = $this->h['Pages']->getNumbOfPages();

		$data['topNotice'] = $this->getModule(array('devices',$this->controller,'catalogue'));

		$data['popupLabel'] = $this->mod->getPopupLabel($this->viewArgs);

		$data["search_string_form_value"] = strcmp($this->viewArgs['search_string'],Params::$nullQueryValue) === 0 ? "" : $this->viewArgs['search_string'];
		
		//set search_string to undef to clean the model name filter
		$temp = $this->viewArgs;
		$temp['page'] = 1;
		$temp['search_string'] = "undef";
		$data['clearViewStatus'] = Url::createUrl($temp);

		$this->append($data);
		
		$this->loadViewAll('catalogue');
	}

	protected function passWhoAskedForDeletion($id_hard)
	{
		$clean['id_hard'] = (int)$id_hard;
		
		$deletion = new DeletionModel();
		$data['deletion'] = $deletion->select()->where(array('id_hard'=>$clean['id_hard']))->send();
		$data['deletionUsers'] = $deletion->getList($data['deletion'],'created_by');

		$this->append($data);
	}

	public function cleared($lang = 'en')
	{
		$data['title'] = 'page permanently deleted - '.Website::$generalName;

		$data['tree'] = "device page permanently deleted";

		$this->append($data);
		
		$this->loadViewAll('cleared');
	}

	protected function view($lang = 'en', $id_hard = 0, $name = null)
	{
		$this->shift(3);
		
		//set the history_page to 1 in the viewStatus
		$this->viewArgs['history_page'] = 1;
		$this->buildStatus();
		
		$clean['id_hard'] = (int)$id_hard;
		$data['id_hard'] = $clean['id_hard'];
		$data['ne_name'] = null;
		$data['name'] = null;
		$data['tree'] = null;
		$data['isDeleted'] = false;

		$data['md_javascript'] = "moderator_dialog(\"devicehide\",\"device\");moderator_dialog(\"deviceshow\",\"device\");moderator_dialog(\"deviceapprove\",\"device_app\");moderator_dialog(\"deviceclear\",\"device_cl\");";

		if ($this->m['HardwareModel']->isCleared($clean['id_hard'])) $this->redirect('generic/cleared/'.$this->lang,0);
		
		if ($this->mod->checkType($clean['id_hard']))
		{
			$this->mod->setWhereQueryClause(array("id_hard" => $clean['id_hard']));
			$data['table'] = $this->mod->getAll();
			
			if (count($data['table']) > 0)
			{
				
				$data['talk_number'] = $this->m['TalkModel']->select('count(*) as numb,id_hard')->where(array('id_hard'=>$clean['id_hard'],'deleted'=>'no'))->rowNumber();
				
				$data['ne_name'] = $data['table'][0]['hardware']['model'];
				$data['name'] =  encodeUrl($data['ne_name']);
				$data['title'] = $data['ne_name'].' - '.Website::$generalName;
				$data['tree'] = $this->getSpecHardLink() . " &raquo; <span class='last_tree_element'>".$data['ne_name']."</span>";
				$data['isDeleted'] = $this->m['HardwareModel']->isDeleted($clean['id_hard']);
				$data['isApproved'] = strcmp($data['table'][0]['hardware']['approved'],'yes') === 0 ? true : false;

				$data['tracksHelpTop'] = $this->getModule(array('devices',$this->controller,'page','it_tracks_users'));
				$data['tracksHelpLabel'] = $this->getModule(array('devices',$this->controller,'form','it_tracks_users'));
				
				$this->passWhoAskedForDeletion($clean['id_hard']);
			}
			
			$this->append($data);
			
			@session_start();
			if ( isset($_SESSION['notebook_inserted']) and strcmp($this->controller,'notebooks') === 0 )
			{
				$viewFilesList = 'suggest_dialog,dialog,page,if_page_deleted,moderator_dialog';
				unset($_SESSION['notebook_inserted']);
			}
			else
			{
				$viewFilesList = 'dialog,page,if_page_deleted,moderator_dialog';
			}
			
			$this->loadViewAll($viewFilesList);
		}
		else
		{
// 			$this->redirect($this->_controller.'/'.);
		}
	}

	protected function history($lang = 'en', $id = 0)
	{
		$this->shift(2);
		$clean['id'] = (int)$id;
		$data['id'] = $clean['id'];
		$data['ne_name'] = $this->m['HardwareModel']->getTheModelName($clean['id']);
		$data['name'] = encodeUrl($data['ne_name']);
		$data['tree'] = $this->getSpecHardLink() . " &raquo;  " . $this->getViewLink($clean['id'],$data['ne_name'])." &raquo; <span class='last_tree_element'>".gtext("History")."</span>";
		
		$data['title'] = 'history - '.Website::$generalName;

		$data['isDeleted'] = $this->m['HardwareModel']->isDeleted($clean['id']);

		if ($this->m['HardwareModel']->isCleared($clean['id'])) $this->redirect('generic/cleared/'.$this->lang,0);
		
		//get the first revision
		$res = $this->m['RevisionsModel']->db->select('revisions','id_rev','id_hard='.$clean['id'],null,'id_rev',1);
		if (count($res) > 0)
		{
			$data['firstRev'] = $res[0]['revisions']['id_rev'];
		}
		
		$res1 = $this->m['HardwareModel']->db->select('hardware','update_date,updated_by','id_hard='.$clean['id']);
		
		$this->m['RevisionsModel']->setWhereQueryClause(array('id_hard' => $clean['id']));
		
		//load the Pages helper
		$this->helper('Pages',$this->controller.'/history/'.$this->lang.'/'.$clean['id'],'history_page');
		//get the number of records
		$recordNumber = $this->m['RevisionsModel']->rowNumber();
		$page = $this->viewArgs['history_page'];
		//set the limit clause
		$this->m['RevisionsModel']->limit = $this->h['Pages']->getLimit($page,$recordNumber,20);
		$res2 = $this->m['RevisionsModel']->getFields('update_date,updated_by,id_rev');
		
		$data['pageList'] = $this->h['Pages']->render($page-3,7);
		
		
		$data['rev1'] = $res1;
		$data['rev2'] = $res2;

		$this->passWhoAskedForDeletion($clean['id']);
		
		$this->append($data);
		$this->loadViewAll('history,if_page_deleted');
	}
	
	protected function revision($lang = 'en', $id_rev = 0)
	{
		$this->shift(2);
		$clean['id_rev'] = (int)$id_rev;
		
		$this->m['RevisionsModel']->setWhereQueryClause(array("id_rev" => $clean['id_rev']));
		$data['table'] = $this->m['RevisionsModel']->getAll();
		
		$data['id_hard'] = 0;
		$data['updated_by'] = null;
		$data['update_date'] = null;
		$data['name'] = null;
		$data['ne_name'] = null;
		$data['tree'] = null;
		$data['isDeleted'] = false;
		$data['title'] = 'revision - '.Website::$generalName;
		
		if (count($data['table']) > 0)
		{
			$data['id_hard'] = (int)$data['table'][0]['revisions']['id_hard'];

			if ($this->m['HardwareModel']->isCleared($data['id_hard'])) $this->redirect('generic/cleared/'.$this->lang,0);
			
			$data['ne_name'] = $this->m['HardwareModel']->getTheModelName($data['id_hard']);
			$data['name'] = encodeUrl($data['ne_name']);
			$data['tree'] = $this->getSpecHardLink() . " &raquo;  " . $this->getViewLink($data['id_hard'],$data['ne_name'])." &raquo; " . $this->getHistoryLink($data['id_hard']) . " &raquo; <span class='last_tree_element'>".gtext("Revision")."</span>";
			
			$data['updated_by'] = $data['table'][0]['revisions']['updated_by'];
			$data['update_date'] = $data['table'][0]['revisions']['update_date'];

			$data['isDeleted'] = $this->m['HardwareModel']->isDeleted($data['id_hard']);
		}
		
		$this->append($data);
		$this->loadViewAll('page');
	}

	protected function differences($lang = 'en', $id_hard = 0, $id_rev = 0)
	{
		$this->shift(3);
		
		$data['title'] = 'differences - '.Website::$generalName;
		
		$clean['id_hard'] = (int)$id_hard;
		$clean['id_rev'] = (int)$id_rev;
		
		$data['id_hard'] = $clean['id_hard'];
		$ne_name = $this->m['HardwareModel']->getTheModelName((int)$data['id_hard']);
		$data['name'] = encodeUrl($ne_name);
		$data['tree'] = $this->getSpecHardLink() . " &raquo;  " . $this->getViewLink($data['id_hard'],$ne_name)." &raquo; " . $this->getHistoryLink($clean['id_hard']) . " &raquo; <span class='last_tree_element'>".gtext("Differences")."</span>";

		$data['isDeleted'] = $this->m['HardwareModel']->isDeleted($clean['id_hard']);
		$data['showDiff'] = false;
		
		$diffArray = array();

		if ($this->m['HardwareModel']->isCleared($clean['id_hard'])) $this->redirect('generic/cleared/'.$this->lang,0);
		
		if (strcmp($clean['id_hard'],0) !== 0 and strcmp($clean['id_rev'],0) !== 0)
		{
			$this->m['RevisionsModel']->setWhereQueryClause(array('id_hard' => $clean['id_hard'],'id_rev' => '<='.$clean['id_rev']));
			$this->m['RevisionsModel']->limit = 2;
			$res = $this->m['RevisionsModel']->getAll();
			if (count($res) > 1)
			{
				$newArray = $res[0]['revisions'];
				$oldArray = $res[1]['revisions'];
				
				$data['update_new'] = $newArray['update_date'];
				$data['update_old'] = $oldArray['update_date'];
				$data['updated_by'] = $newArray['updated_by'];
				
				$diffArray = $this->mod->getDiffArray($oldArray, $newArray);
				
				$data['showDiff'] = true;
			}
		}
		else if (strcmp($clean['id_hard'],0) !== 0 and strcmp($clean['id_rev'],0) === 0)
		{
			$this->mod->setWhereQueryClause(array('id_hard' => $clean['id_hard']));
			$lastRes = $this->mod->getAll();
			
			if (count($lastRes) > 0)
			{
				$this->m['RevisionsModel']->setWhereQueryClause(array('id_hard' => $clean['id_hard']));
				$this->m['RevisionsModel']->limit = 1;
				$revRes = $this->m['RevisionsModel']->getAll();
				
				if (count($revRes) > 0)
				{
					$newArray = $lastRes[0]['hardware'];
					$oldArray = $revRes[0]['revisions'];
					
					$data['update_new'] = $newArray['update_date'];
					$data['update_old'] = $oldArray['update_date'];
					$data['updated_by'] = $newArray['updated_by'];
				
					$diffArray = $this->mod->getDiffArray($oldArray, $newArray);
					
					$data['showDiff'] = true;
				}
			}
			
		}
		
		$data['fieldsWithBreaks'] = $this->mod->fieldsWithBreaks;
		$data['diffArray'] = $diffArray;
		
		$this->append($data);		
		$this->loadViewAll('differences');
	}

	protected function climb($lang = 'en', $id_rev = 0, $token = '')
	{
		$this->shift(3);
		
		$data['title'] = 'make current - '.Website::$generalName;
		
		$clean['token'] = sanitizeAlphanum($token);
		
		$clean['id_rev'] = (int)$id_rev;
		$clean['id_hard'] = (int)$this->m['RevisionsModel']->getIdHard($clean['id_rev']);

		if ($this->m['HardwareModel']->isCleared($clean['id_hard'])) $this->redirect('generic/cleared/'.$this->lang,0);
		
		if ($clean['id_hard'] !== 0)
		{
			$deleted = $this->m['HardwareModel']->select("hardware.deleted")->where(array("id_hard"=>$clean['id_hard']))->limit(1)->toList('deleted')->send();
			
			$data['isDeleted'] = $this->m['HardwareModel']->isDeleted($clean['id_hard']);
			
			$data['id_rev'] = $clean['id_rev'];
			$data['id_hard'] = $clean['id_hard'];
			$data['ne_name'] = $this->m['HardwareModel']->getTheModelName($clean['id_hard']);
			$data['name'] = encodeUrl($data['ne_name']);
			$data['tree'] = $this->getSpecHardLink() . " &raquo;  " . $this->getViewLink($data['id_hard'],$data['ne_name'])." &raquo; " . $this->getHistoryLink($clean['id_hard']) . " &raquo; <span class='last_tree_element'>make current</span>";
			
			$data['notice'] = null;
			$this->s['registered']->checkStatus();
			
			if ($this->s['registered']->status['status'] === 'logged')
			{	
				if (!$this->s['registered']->checkCsrf($clean['token'])) $this->redirect($this->controller.'/catalogue/'.$this->lang,2,'wrong token..');

				if ($this->m['UsersModel']->isBlocked($this->s['registered']->status['id_user'])) $this->redirect('my/home/'.$this->lang,2,'your account has been blocked..');

				if ($this->m['HardwareModel']->isDeleted($clean['id_hard'])) $this->redirect($this->controller.'/catalogue/'.$this->lang,2,'this device page has been deleted..');
				
				if (isset($_POST['confirmAction']))
				{				
					$this->m['HardwareModel']->makeCurrent($clean['id_rev']);

					$this->viewRedirect($this->m['HardwareModel']->lastId);

					$data['notice'] = $this->m['HardwareModel']->notice;
				}

				$this->append($data);
				$this->loadViewAll('climb');
			}
			else
			{
				$this->redirect("users/login/".$this->lang."?redirect=".$this->controller."/view/".$this->lang."/".$clean['id_hard'],0);
			}
		}
	}

	protected function talk($lang = 'en', $id_hard = 0, $token = 'token')
	{		
		$this->shift(3);
		
		$this->m['TalkModel']->setFields('title,message','sanitizeAll');
		
		$data['title'] = 'talk - '.Website::$generalName;
		
		$clean['token'] = sanitizeAlphanum($token);
		$clean['id_hard'] = (int)$id_hard;
		$data['id_hard'] = $clean['id_hard'];
		$data['ne_name'] = $this->m['HardwareModel']->getTheModelName($clean['id_hard']);
		$data['name'] = encodeUrl($data['ne_name']);
		$data['tree'] = $this->getSpecHardLink() . " &raquo;  " . $this->getViewLink($clean['id_hard'],$data['ne_name'])." &raquo; <span class='last_tree_element'>".gtext("Talk")."</span>";

		$data['isDeleted'] = $this->m['HardwareModel']->isDeleted($clean['id_hard']);

		if ($this->m['HardwareModel']->isCleared($clean['id_hard'])) $this->redirect('generic/cleared/'.$this->lang,0);
		
		if (isset($_POST['insertAction']))
		{
			if ($this->s['registered']->status['status'] === 'logged')
			{
				if (!$this->s['registered']->checkCsrf($clean['token'])) $this->redirect($this->controller.'/catalogue/'.$this->lang,2,'wrong token..');
				
				if ($this->m['UsersModel']->isBlocked($this->s['registered']->status['id_user'])) $this->redirect('my/home/'.$this->lang,2,'your account has been blocked..');

				if ($this->m['HardwareModel']->isDeleted($clean['id_hard'])) $this->redirect($this->controller.'/catalogue/'.$this->lang,2,'this device page has been deleted..');
				
				$this->m['TalkModel']->values['created_by'] = $this->s['registered']->status['id_user'];
				$this->m['TalkModel']->values['id_hard'] = $clean['id_hard'];
				
				$this->m['TalkModel']->updateTable('insert');
			}
		}
		
		//if preview
		if (isset($_POST['previewAction']))
		{
			if ($this->s['registered']->status['status'] === 'logged')
			{
				if (!$this->s['registered']->checkCsrf($clean['token'])) $this->redirect($this->controller.'/catalogue/'.$this->lang,2,'wrong token..');
				
				$data['preview_message'] = $this->request->post('message','','sanitizeHtml');
				$this->m['TalkModel']->result = false;
			}
		}
		
		$data['table'] = $this->m['TalkModel']->select()->where(array('id_hard'=>$clean['id_hard']))->orderBy('id_talk')->send();
		
		$data['values'] = $this->m['TalkModel']->getFormValues('insert','sanitizeHtml');
		$data['notice'] = $this->m['TalkModel']->notice;
		
// 		javascript for moderator
		$data['md_javascript'] = "moderator_dialog(\"hide\",\"talk\");moderator_dialog(\"show\",\"talk\");";
		$data['go_to'] = $this->currPage."/".$this->lang."/".$clean['id_hard'];

		$this->passWhoAskedForDeletion($clean['id_hard']);
		
		$this->append($data);
		$this->loadViewAll('talk,if_page_deleted,moderator_dialog');
	}

	//get the link to the device page from vendorid:productid code
	protected function getAlreadyExixtsLink($code)
	{
		$hw = new HardwareModel();
		$info = $hw->getModelByCode($code);

		if ($info)
		{
			return $this->getViewLink($info['id_hard'],$info['model'],Hardware::getControllerFromType($info['type']));
		}
		return '';
	}
	
	protected function getViewLink($id,$ne_name,$controller = null)
	{
		$contr = isset($controller) ? $controller : $this->controller;

		return "<a href='".$this->baseUrl.'/'.$contr.'/view/'.$this->lang.'/'.$id.'/'.encodeUrl($ne_name).$this->viewStatus."'>".$ne_name."</a>";
	}

	protected function getHistoryLink($id)
	{
		return "<a href='".$this->baseUrl.'/'.$this->controller.'/history/'.$this->lang.'/'.$id.'/'.$this->viewStatus."'>".gtext("History")."</a>";
	}

	protected function getSpecHardLink()
	{
		return "<a href='".$this->baseUrl.'/'.$this->controller.'/catalogue/'.$this->lang.$this->viewStatus."'>".plural($this->controller)."</a>";
	}

	protected function goToLoginForm()
	{
		if ($this->querySanitized)
		{
			$this->redirect("users/login/".$this->lang."?redirect=".$this->controller."/".$this->action.Url::createUrl($this->_queryString));
		}
		else
		{
			$this->redirect("users/login/".$this->lang."?redirect=home/index".Url::createUrl($this->_queryString));
		}
	}

}