<?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 WikiController extends BaseController
{

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

		$this->_topMenuClasses['wiki'] = " class='currentitem'";
		
		parent::__construct($model, $controller, $queryString);
		
		$this->model('UsersModel');
		$this->model('WikiModel');
		$this->model('WikirevisionsModel');
		$this->model('WikitalkModel');

		$this->m['WikiModel']->id_user = (int)$this->s['registered']->status['id_user'];
	}
	
	public function insert($lang = 'en')
	{
		$this->shift(1);

		$data['pagePreview'] = null;
		
		$data['title'] = 'insert a wiki page - '.Website::$generalName;
		
		$this->m['WikiModel']->setFields('title,page','sanitizeAll');

		$data['notice'] = null;

		$this->s['registered']->checkStatus();
		
		if ($this->s['registered']->status['status'] === 'logged')
		{
			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']))
			{
				//insert the new wiki page
				$this->m['WikiModel']->updateTable('insert');

				if ($this->m['WikiModel']->queryResult)
				{
					header('Location: http://'.DOMAIN_NAME.'/wiki/page/'.$this->lang.'/'.$this->m['WikiModel']->lastTitleClean);
					die();
				}
			}

			$data['pagePreview'] = $this->getPreview();
			
			$data['notice'] = $this->m['WikiModel']->notice;
			
			$data['submitName'] = "insertAction";
			$data['hiddenInput'] = null;
			
			$data['values'] = $this->m['WikiModel']->getFormValues('insert','sanitizeHtml');
			$this->append($data);

			$this->load('form');
			$this->load('bottom_left');
			$this->right();
		}
		else
		{
			$this->redirect("users/login/".$this->lang."?redirect=".$this->controller."/insert/".$this->lang,0);
		}
	}
	
	public function update($lang = 'en')
	{
		$this->shift(1);

		$data['pagePreview'] = null;
		
		$data['title'] = 'update a wiki page - '.Website::$generalName;
		
		$this->m['WikiModel']->setFields('title,page','sanitizeAll');
		
		$data['notice'] = null;
		$this->s['registered']->checkStatus();
		
		if (isset($_POST['id_wiki']))
		{
			//get the id
			$clean['id_wiki'] = (int)$_POST['id_wiki'];
			$title = $this->m['WikiModel']->getTheModelName($clean['id_wiki']);
				
			if ($this->s['registered']->status['status'] === 'logged')
			{			

				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['WikiModel']->isBlocked($clean['id_wiki'])) $this->redirect('wiki/page/'.$this->lang,2,'this page has been blocked..');

				if ($this->m['WikiModel']->isDeleted($clean['id_wiki'])) $this->redirect('wiki/page/'.$this->lang,2,'this page has been deleted..');
				
				$deleted = $this->m['WikiModel']->select("wiki.deleted")->where(array("id_wiki"=>$clean['id_wiki']))->limit(1)->toList('wiki.deleted')->send();
				
				$data['tree_name'] = $title;

				if (isset($_POST['updateAction']))
				{
					//carry out the update database action
					$this->m['WikiModel']->updateTable('update');

					if ($this->m['WikiModel']->queryResult)
					{
						header('Location: http://'.DOMAIN_NAME.'/wiki/page/'.$this->lang.'/'.$this->m['WikiModel']->lastTitleClean);
						die();
					}
				}

				$data['pagePreview'] = $this->getPreview();
				
				$data['notice'] = $this->m['WikiModel']->notice;

				$data['id_wiki'] = $clean['id_wiki'];
				$data['submitName'] = "updateAction";

				$data['values'] = $this->m['WikiModel']->getFormValues('update','sanitizeHtml');
				$data['hiddenInput'] = "<input type='hidden' name='id_wiki' value='".$clean['id_wiki']."'>\n";

				$this->append($data);

				$this->load('form');
				$this->load('bottom_left');
				$this->right();
			}
			else
			{
				header('Location: http://'.DOMAIN_NAME."/users/login/".$this->lang."?redirect=".$this->controller."/page/".$this->lang."/".titleForRedirect($title));
				die();
			}
		}
		else
		{
			$this->redirect($this->controller.'/page/'.$this->lang);
		}
	}
	
	//get the preview of the description entry
	protected function getPreview()
	{
		if (isset($_POST['previewAction']))
		{
			$this->m['WikiModel']->result = false;
			return $this->request->post('page','','sanitizeHtml');
		}
		return null;
	}
	
	public function page($lang = 'en', $title_clean = null)
	{
		$this->shift(2);

		$data['title'] = 'main page - '.Website::$generalName;
		$clean['title_clean'] = sanitizeAll($title_clean);

		$data['isDeleted'] = false;
		$data['isBlocked'] = false;
		
		if (isset($title_clean))
		{
			$res = $this->m['WikiModel']->select()->where(array('title_clean'=>$clean['title_clean']))->orderBy('id_wiki desc')->limit(1)->send();

			if ( count($res) > 0 )
			{
				$data['table'] = $res;
				$data['tree_name'] = $res[0]['wiki']['title'];
				$data['title'] = $res[0]['wiki']['title'] . ' - ' . Website::$generalName;
				$data['isDeleted'] = $this->m['WikiModel']->isDeleted($res[0]['wiki']['id_wiki']);
				$data['isBlocked'] = $this->m['WikiModel']->isBlocked($res[0]['wiki']['id_wiki']);

				if ( count($res) < 2 )
				{
					$data['talk_number'] = $this->m['WikitalkModel']->select('count(*) as numb,id_wiki')->where(array('id_wiki'=>$res[0]['wiki']['id_wiki'],'deleted'=>'no'))->rowNumber();

					$viewFile = 'wiki_page';
					$data['id_wiki'] = $res[0]['wiki']['id_wiki'];
				}
				else
				{
					$viewFile = 'select';
				}
			}
			else
			{
				$rev = new WikirevisionsModel();
				$res_rev = $rev->select()->where(array('title_clean'=>$clean['title_clean']))->orderBy('id_rev desc')->limit(1)->send();
				if ( count($res_rev) > 0 )
				{
					$clean['idWiki'] = $rev->getIdPage($res_rev[0]['wiki_revisions']['id_rev']);
					$newTitle = $this->m['WikiModel']->getTheModelName($clean['idWiki']);
					$n = titleForRedirect($newTitle);
					header('Location: http://'.DOMAIN_NAME.'/wiki/page/'.$this->lang.'/'.$n);
					die();
				}
				else
				{
					$viewFile = 'not_found';
				}
			}
		}
		else
		{
			$this->redirect('wiki/page/'.$this->lang.'/Main-Page');
		}

		$data['md_javascript'] = "moderator_dialog(\"pageblock\",\"page\");moderator_dialog(\"pageunblock\",\"page\");moderator_dialog(\"pagehide\",\"page_del\");moderator_dialog(\"pageshow\",\"page_del\");";
		
		$this->append($data);

		$this->load($viewFile);
		$this->load('bottom_left');
		$this->load('moderator_dialog');
		$this->right();
	}

	public function history($lang = 'en', $id = 0)
	{
		$argKeys = array(
			'page:forceNat'	=>	1,
		);

		$this->setArgKeys($argKeys);
		$this->shift(2);
		
		$clean['id'] = (int)$id;
		$data['id'] = $clean['id'];
		$data['tree_name'] = $this->m['WikiModel']->getTheModelName($clean['id']);
		$data['isBlocked'] = $this->m['WikiModel']->isBlocked($clean['id']);
		$data['isDeleted'] = $this->m['WikiModel']->isDeleted($clean['id']);
		
		$data['title'] = 'history - '.Website::$generalName;
		
		//get the first revision
		$res = $this->m['WikirevisionsModel']->db->select('revisions','id_rev','id_wiki='.$clean['id'],null,'id_rev',1);
		if (count($res) > 0)
		{
			$data['firstRev'] = $res[0]['wiki_revisions']['id_rev'];
		}
		
		$res1 = $this->m['WikiModel']->db->select('wiki','update_date,created_by','id_wiki='.$clean['id']);
		
		$this->m['WikirevisionsModel']->setWhereQueryClause(array('id_wiki' => $clean['id']));
		
		//load the Pages helper
		$this->helper('Pages',$this->controller.'/history/'.$this->lang.'/'.$clean['id'],'page');
		//get the number of records
		$recordNumber = $this->m['WikirevisionsModel']->rowNumber();
		$page = $this->viewArgs['page'];
		//set the limit clause
		$this->m['WikirevisionsModel']->limit = $this->h['Pages']->getLimit($page,$recordNumber,20);
		$res2 = $this->m['WikirevisionsModel']->getFields('update_date,created_by,id_rev');
		
		$data['pageList'] = $this->h['Pages']->render($page-3,7);

		$data['rev1'] = $res1;
		$data['rev2'] = $res2;

		$this->append($data);
		$this->load('history');
		$this->load('bottom_left');
		$this->right();
	}
	
	public function revision($lang = 'en', $id_rev = 0)
	{
		$argKeys = array(
			'page:forceNat'	=>	1,
		);

		$this->setArgKeys($argKeys);
		$this->shift(2);

		$clean['id_rev'] = (int)$id_rev;
		
		$this->m['WikirevisionsModel']->setWhereQueryClause(array("id_rev" => $clean['id_rev']));
		$data['table'] = $this->m['WikirevisionsModel']->getAll();
		
		$data['id_wiki'] = 0;
		$data['created_by'] = null;
		$data['update_date'] = null;
		$data['tree_name'] = null;
		$data['tree'] = null;
		$data['tree'] = null;
		$data['title'] = 'revision - '.Website::$generalName;
		$data['isDeleted'] = false;
		
		if (count($data['table']) > 0)
		{
			$data['id_wiki'] = (int)$data['table'][0]['wiki_revisions']['id_wiki'];
			$data['isDeleted'] = $this->m['WikiModel']->isDeleted($data['id_wiki']);
			$data['tree_name'] = $this->m['WikiModel']->getTheModelName($data['id_wiki']);
			$data['tree'] = $this->getSpecPageLink() . " &raquo;  " . "<a href='".$this->m['WikiModel']->toWikiPage($data['id_wiki'])."'>".$data['tree_name']."</a>"." &raquo; " . $this->getHistoryLink($data['id_wiki']) . " &raquo; ".gtext('Revision');
			
			$data['created_by'] = $data['table'][0]['wiki_revisions']['created_by'];
			$data['update_date'] = $data['table'][0]['wiki_revisions']['update_date'];
		}
		
		$this->append($data);
		$this->load('wiki_page');
		$this->load('bottom_left');
		$this->right();
	}

	public function differences($lang = 'en', $id_wiki = 0, $id_rev = 0)
	{
		$this->shift(3);
		
		$data['title'] = 'differences - '.Website::$generalName;
		
		$clean['id_wiki'] = (int)$id_wiki;
		$clean['id_rev'] = (int)$id_rev;
		
		$data['id_wiki'] = $clean['id_wiki'];
		$tree_name = $this->m['WikiModel']->getTheModelName((int)$clean['id_wiki']);
		$data['tree_name'] = $tree_name;
		$data['tree'] = $this->getSpecPageLink() . " &raquo;  " . "<a href='".$this->m['WikiModel']->toWikiPage($clean['id_wiki'])."'>".$data['tree_name']."</a>" ." &raquo; " . $this->getHistoryLink($data['id_wiki']) . " &raquo; ".gtext('Differences');

		$data['isDeleted'] = $this->m['WikiModel']->isDeleted($clean['id_wiki']);
		$data['showDiff'] = false;
		
		$diffArray = array();
		
		if (strcmp($clean['id_wiki'],0) !== 0 and strcmp($clean['id_rev'],0) !== 0)
		{
			$this->m['WikirevisionsModel']->where(array('id_wiki' => $clean['id_wiki'],'id_rev' => '<='.$clean['id_rev']));
			$this->m['WikirevisionsModel']->limit = 2;
			$res = $this->m['WikirevisionsModel']->getAll();
			if (count($res) > 1)
			{
				$newArray = $res[0]['wiki_revisions'];
				$oldArray = $res[1]['wiki_revisions'];
				
				$data['update_new'] = $newArray['update_date'];
				$data['update_old'] = $oldArray['update_date'];
				$data['created_by'] = $newArray['created_by'];

				$diffArray = $this->m['WikiModel']->getDiffArray($oldArray, $newArray);
				
				$data['showDiff'] = true;
			}
		}
		else if (strcmp($clean['id_wiki'],0) !== 0 and strcmp($clean['id_rev'],0) === 0)
		{
			$this->m['WikiModel']->where(array('id_wiki' => $clean['id_wiki']));
			$lastRes = $this->m['WikiModel']->getAll();
			
			if (count($lastRes) > 0)
			{
				$this->m['WikirevisionsModel']->setWhereQueryClause(array('id_wiki' => $clean['id_wiki']));
				$this->m['WikirevisionsModel']->limit = 1;
				$revRes = $this->m['WikirevisionsModel']->getAll();
				
				if (count($revRes) > 0)
				{
					$newArray = $lastRes[0]['wiki'];
					$oldArray = $revRes[0]['wiki_revisions'];
					
					$data['update_new'] = $newArray['update_date'];
					$data['update_old'] = $oldArray['update_date'];
					$data['created_by'] = $newArray['created_by'];
				
					$diffArray = $this->m['WikiModel']->getDiffArray($oldArray, $newArray);
					
					$data['showDiff'] = true;
				}
			}
			
		}
		
		$data['fieldsWithBreaks'] = $this->m['WikiModel']->fieldsWithBreaks;
		$data['diffArray'] = $diffArray;
		
		$this->append($data);		
		$this->load('differences');
		$this->load('bottom_left');
		$this->right();
	}

	public function climb($lang = 'en', $id_rev = 0)
	{
		$this->shift(2);

		$this->m['WikiModel']->setFields('title,page','sanitizeAll');
		
		$data['title'] = 'make current - '.Website::$generalName;
		
		$clean['id_rev'] = (int)$id_rev;
		$clean['id_wiki'] = (int)$this->m['WikirevisionsModel']->getIdPage($clean['id_rev']);
		
		if ($clean['id_wiki'] !== 0)
		{

			$data['isDeleted'] = $this->m['WikiModel']->isDeleted($clean['id_wiki']);
			
			$data['id_rev'] = $clean['id_rev'];
			$data['id_wiki'] = $clean['id_wiki'];
			$data['tree_name'] = $this->m['WikiModel']->getTheModelName($clean['id_wiki']);
			$data['name'] = $data['tree_name'];
			$data['tree'] = $this->getSpecPageLink() . " &raquo;  " . "<a href='".$this->m['WikiModel']->toWikiPage($clean['id_wiki'])."'>".$data['tree_name']."</a>"." &raquo; " . $this->getHistoryLink($clean['id_wiki']) . " &raquo; " . gtext('Make current');
			
			$data['notice'] = null;
			$this->s['registered']->checkStatus();
			
			if ($this->s['registered']->status['status'] === 'logged')
			{	
				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['WikiModel']->isBlocked($clean['id_wiki'])) $this->redirect('wiki/page/'.$this->lang,2,'this page has been blocked..');

				if ($this->m['WikiModel']->isDeleted($clean['id_wiki'])) $this->redirect('wiki/page/'.$this->lang,2,'this page has been deleted..');
				
				if (isset($_POST['confirmAction']))
				{				
					$this->m['WikiModel']->makeCurrent($clean['id_rev']);

					if ($this->m['WikiModel']->queryResult)
					{
						header('Location: http://'.DOMAIN_NAME.'/wiki/page/'.$this->lang.'/'.$this->m['WikiModel']->lastTitleClean);
						die();
					}

					$data['notice'] = $this->m['WikiModel']->notice;
				}
				
				$this->append($data);
				$this->load('climb');
				$this->load('bottom_left');
				$this->right();
			}
			else
			{
				$this->redirect("users/login/".$this->lang."?redirect=".$this->controller."/page/".$this->lang."/".encodeUrl($data['tree_name']),0);
			}
		}
	}

	public function talk($lang = 'en', $id_wiki = 0)
	{		
		$this->shift(2);
		
		$this->m['WikitalkModel']->setFields('title,message','sanitizeAll');
		
		$data['title'] = 'talk - '.Website::$generalName;

		$clean['id_wiki'] = (int)$id_wiki;
		$data['id_wiki'] = $clean['id_wiki'];
		$data['tree_name'] = $this->m['WikiModel']->getTheModelName($clean['id_wiki']);
		$data['isBlocked'] = $this->m['WikiModel']->isBlocked($clean['id_wiki']);
		$data['isDeleted'] = $this->m['WikiModel']->isDeleted($clean['id_wiki']);
		
		$data['tree'] = $this->getSpecPageLink() . " &raquo;  " . "<a href='".$this->m['WikiModel']->toWikiPage($clean['id_wiki'])."'>".$data['tree_name']."</a>"." &raquo; ".gtext('Talk');
		
		if (isset($_POST['insertAction']))
		{
			if ($this->s['registered']->status['status'] === 'logged')
			{
				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['WikiModel']->isBlocked($clean['id_wiki'])) $this->redirect('wiki/page/'.$this->lang,2,'this page has been blocked..');

				if ($this->m['WikiModel']->isDeleted($clean['id_wiki'])) $this->redirect('wiki/page/'.$this->lang,2,'this page has been deleted..');
				
				$this->m['WikitalkModel']->values['created_by'] = $this->s['registered']->status['id_user'];
				$this->m['WikitalkModel']->values['id_wiki'] = $clean['id_wiki'];
				
				$this->m['WikitalkModel']->updateTable('insert');

// 				if ($this->m['WikitalkModel']->queryResult)
// 				{
// 					header('Refresh: 0;url=http://'.DOMAIN_NAME.$_SERVER['REQUEST_URI']);
// 					die();
// 				}
			}
		}
		
		$data['table'] = $this->m['WikitalkModel']->select()->where(array('id_wiki'=>$clean['id_wiki']))->orderBy('id_talk')->send();
		
		$data['values'] = $this->m['WikitalkModel']->getFormValues('insert','sanitizeHtml');
		$data['notice'] = $this->m['WikitalkModel']->notice;
		
// 		javascript for moderator
		$data['md_javascript'] = "moderator_dialog(\"hide\",\"wiki_talk\");moderator_dialog(\"show\",\"wiki_talk\");";
		$data['go_to'] = $this->currPage."/".$this->lang."/".$clean['id_wiki'];
		
		$this->append($data);
		$this->load('talk');
		$this->load('moderator_dialog');
		$this->right();
	}

	public function pages($lang = 'en')
	{
		$data['topString'] = 'list of pages';
		$data['title'] = gtext('list of pages').' - '.Website::$generalName;

		$this->setArgKeys(array('page:forceNat'=>1));

		$this->shift(1);

		$this->helper('Pages','wiki/pages/'.$this->lang,'page');

		$this->m['WikiModel']->clear()->select()->where(array('-deleted'=>'no'))->orderBy('id_wiki desc');

		$recordNumber = $this->m['WikiModel']->rowNumber();
		$page = $this->viewArgs['page'];

		$this->m['WikiModel']->limit = $this->h['Pages']->getLimit($page,$recordNumber,30);

		$data['table'] = $this->m['WikiModel']->send();
		
		$data['pageList'] = $this->h['Pages']->render($page-7,15);

		$this->append($data);
		$this->load('pages');
		$this->right();
	}

	protected function see($lang = 'en', $status = 'blocked')
	{
		$this->s['registered']->check('admin');

		switch ($status)
		{
			case 'deleted':
				$data['topString'] = 'list of deleted pages';
				$data['title'] = gtext('list of deleted pages').' - '.Website::$generalName;
				$whereClause = '-deleted';
				break;
			case 'blocked':
				$data['topString'] = 'list of blocked pages';
				$data['title'] = gtext('list of blocked pages').' - '.Website::$generalName;
				$whereClause = 'blocked';
				break;
		}

		$this->setArgKeys(array('page:forceNat'=>1));

		$this->shift(1);

		$this->helper('Pages','wiki/'.$status.'/'.$this->lang,'page');

		$this->m['WikiModel']->clear()->select()->where(array($whereClause=>'yes'))->orderBy('id_wiki desc');

		$recordNumber = $this->m['WikiModel']->rowNumber();
		$page = $this->viewArgs['page'];

		$this->m['WikiModel']->limit = $this->h['Pages']->getLimit($page,$recordNumber,30);

		$data['table'] = $this->m['WikiModel']->send();

		$data['pageList'] = $this->h['Pages']->render($page-7,15);

		$this->append($data);
		$this->load('pages');
		$this->right();
	}

	public function deleted($lang = 'en')
	{
		$this->see($lang,'deleted');
	}

	public function blocked($lang = 'en')
	{
		$this->see($lang,'blocked');
	}

	//print all the modifications to the wiki
	public function modifications($lang = 'en')
	{
		$data['title'] = gtext('last modifications').' - '.Website::$generalName;

		$this->setArgKeys(array('page:forceNat'=>1));

		$this->shift(1);

		$whereClauseArray = array(
			'gr'	=>	'registered',
			'type'	=>	'wiki',
		);

		$this->helper('Pages','wiki/modifications/'.$this->lang,'page');

		$this->m['HistoryModel']->clear()->select()->where($whereClauseArray)->orderBy('id_history desc');

		$recordNumber = $this->m['HistoryModel']->rowNumber();
		$page = $this->viewArgs['page'];

		$this->m['HistoryModel']->limit = $this->h['Pages']->getLimit($page,$recordNumber,30);

		$data['table'] = $this->m['HistoryModel']->send();

		$data['pageList'] = $this->h['Pages']->render($page-7,15);

		$this->append($data);
		$this->load('modifications');
		$this->right();
	}
	
	protected function getViewLink($ne_name)
	{
		return "<a href='".$this->baseUrl.'/'.$this->controller.'/page/'.$this->lang.'/'.encodeUrl($ne_name)."'>".$ne_name."</a>";
	}

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

	protected function getSpecPageLink()
	{
		return "<a href='".$this->baseUrl.'/'.$this->controller.'/page/'.$this->lang."/Main-Page'>".ucfirst($this->controller)."</a>";
	}

}