<?php
/*
   Plugin Name: Custom Tables
   Plugin URI: http://blog.murawski.ch/2011/08/custom-tables-wordpress-plugin/
   Description: Create Tables and show on a page/article. Usable for all kind of diffrent databases.
   Version: 1.3.1
   Author: Web Updates KMU
   Author URI: http://wuk.ch/

   Copyright (c) 2011 web updates kmu <stefan@wuk.ch>
   All rights reserved.

   This program is distributed under the GNU General Public License, Version 2,
   June 1991. Copyright (C) 1989, 1991 Free Software Foundation, Inc., 51 Franklin
   St, Fifth Floor, Boston, MA 02110, USA

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
   ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

if (!function_exists('mres')) {function mres($t) {$t = mysql_real_escape_string($t);return $t;}}
if (!function_exists('rbr')) {function rbr($t) {$t = html_entity_decode(str_replace(array("\r\n","\n","\r"),array("<br/>","<br/>","<br/>"),$t));return $t;}}

if (!class_exists('wuk_custom_tables')) {
	class wuk_custom_tables {
		var $settings;
		var $info;

		function wuk_custom_tables() {
			$this->getOptions();
			/* Language File will be loaded */
			if (function_exists('load_plugin_textdomain')) load_plugin_textdomain('wct', PLUGINDIR.'/'.dirname(plugin_basename(__FILE__)).'/languages', dirname(plugin_basename( __FILE__ )).'/languages');

			/* Install and Uninstall Procedure */
			add_shortcode('wctable', array(&$this,'show_table'));

			add_shortcode('wctdate', array(&$this,'show_date'));
			add_shortcode('wctarchive', array(&$this,'show_archive'));
			add_shortcode('wctselect', array(&$this,'show_select'));

			add_shortcode('wctsearch', array(&$this,'show_search'));
			add_shortcode('wcteditpage', array(&$this,'show_editpage'));
			add_shortcode('wctclear', array(&$this,'show_clear'));

			if(is_admin())
			{
				add_action('admin_menu', array(&$this, 'add_menupages'));
			}
			if ($_GET['wcttab'] == "setup") {
				add_filter( 'user_can_richedit', array(&$this, 'disable_wysiwyg') );
				add_filter( 'wp_default_editor', create_function('', 'return "html";') );
			}
			elseif ($_GET['wcttab'] == "content") {
				add_filter( 'wp_default_editor', create_function('', 'return "tinymce";') );
			}

			add_filter('wct_table', array( &$this, 'hook_table'));
			add_filter('wct_entry', array( &$this, 'hook_entry'));
			add_filter('wct_overlay', array( &$this, 'hook_overlay'));
		}

		function show_table($atts) {
			global $wpdb;
			/* Table auf der Seite anzeigen per Shortcode einfügen */
			extract(shortcode_atts(array('id' => '1', 'limit' => '50', 'filter' => ''), $atts));
			include("pages/show_table.php");
			return $out;
		}
		function show_date($atts) {
			global $wpdb;		
			include("pages/show_date.php");
			return $out;
		}
		function show_clear($atts) {	
			$url = $this->generate_pagelink("/[&?]+wct(.*)=.*/","");
			$out = "<input type=\"submit\" class=\"wct-button\" onclick=\"top.location.href='".$url."'; return false;\" value=\"".__('Clear','wct')."\">";
			return $out;
		}
		function show_select($atts) {
			global $wpdb;
			extract(shortcode_atts(array('id' => '1', 'field' => '', 'limit' => '20', 'maintext' => __('All entries','wct')), $atts));
			include("pages/show_select.php");
			if ($include_js == '1') { include_once("pages/show_select_js.php"); }
			return $out;
		}
		function show_archive($atts) {
			global $wpdb;	
			include("pages/show_archive.php");
			return $out;
		}
		function show_search($atts) {
			global $wpdb;	
			extract(shortcode_atts(array('felder' => '*', 'text' => 'sss'), $atts));		
			include("pages/show_search.php");
			return $out;
		}
		function show_editpage($atts) {
			global $wpdb;	
			extract(shortcode_atts(array('table' => '*', 'filter' => ''), $atts));

			$url = $this->generate_pagelink("/[&?]+wct_eid=[0-9]*/","");
			echo "<form action=\"".$url."\" method=\"GET\"><select name=\"tableselector\">";
			$qry = $wpdb->get_results("SELECT `id`,`name` FROM `".$wpdb->prefix."wct_list` WHERE `id`!='0';");
			if (count($qry) >= '1') {
				foreach ($qry as $row)
				{
					echo "<option value=\"".$row->id."\">".$row->name."</option>";
				}
			}	
			echo "</select><input type=\"submit\" value=\"". __ ('Change Table', 'wct') ."\"></form><br/>";

			if ($table != '*' OR ($table == '*' AND $_GET['tableselector'] != '')) {
				if ($table == '*') { $tableid = (int)mres($_GET['tableselector']); }
				else { $tableid = $table; }

				$wctmp = $url."tableselector=";

				if ($_POST['submit'] != '') {
					include("pages/save_tables.php");
				}
				include("pages/editcontent.php");
			}
		}
		function tab_link($wcttab,$name,$shorttag,$wcttab2 = '')
		{
			global $_GET;
			if ($wcttab2 != '') { $a = "&wcttab2=".$wcttab2; }
			$out = "<th onclick=\"document.location='admin.php?page=".$_GET['page']."&wcttab=".$shorttag.$a."'\" style=\"cursor:pointer;min-width:148px;width:148px;font-family: 'Lucida Grande',Verdana,Arial,'Bitstream Vera Sans',sans-serif;color: ";
			if ($wcttab == $shorttag && $wcttab2 == '') { $out .= "black"; }
			elseif ($wcttab2 == $_GET['wcttab2'] AND $_GET['wcttab2'] != '') { $out .= "black"; } 
			else { $out .= "#21759b"; }

			$out .= ";\">".__($name, 'wct')."</th>";
			return $out;
		}
		function wctmenu() {
			include("pages/wuk.php");
			echo "<div><h2>".__('Custom Tables', 'wct')."</h2>".
			     __('On the Navigation panel at the left, you can create new Tables or edit the existing ones','wct').":<br/>".
			     "<img src=\"".plugins_url('custom-tables/img/tutorial/createeditdb.jpg')."\" border=\"0\" alt=\"Tutorial Picture\"><br/><br/>".
			     __('If you have questions or problems, please do not hesitate to contact us','wct').": <a href=\"http://wuk.ch/?piwik_campaign=plugin&piwik_kwd=custom-tables\">web updates kmu</a></div>";
		}
		function create_table() {
			global $wpdb, $current_user;

			if ($this->info != '') {
				echo $this->info;
			}

			$arr_user = array('subscriber'=>0, 'contributor'=>1, 'author'=>2, 'editor'=>5, 'administrator'=>8);
			get_currentuserinfo();
			$user = get_userdata($current_user->user_ID);

			$wcttab = $_GET['wcttab'];
			
			include("pages/wuk.php");
			if ($_POST['submit'] != '') {
				include("pages/save_tables.php");
			}

			if ($_GET['page'] != 'wct_table_create') {
				$tableid = str_replace("wct_table_","",$_GET['page']);
				echo "<div style=\"padding-top:15px;\"><table vspace=\"0\" hspace=\"0\" cellspacing=\"0\" cellpadding=\"0\" style=\"background-image:url(" . plugins_url('custom-tables/img/tab.png') . ");height:30px;\" ><tr>";
				if ($tableid != '0') {
					if ($arr_user[$this->settings['crole'.$tableid.'_s']] >= $user->user_level) { echo $this->tab_link($wcttab,'Table Setup',''); }
					if ($arr_user[$this->settings['crole'.$tableid.'_c']] >= $user->user_level) { echo $this->tab_link($wcttab,'Edit Content','content'); }
					if ($arr_user[$this->settings['crole'.$tableid.'_i']] >= $user->user_level) { echo $this->tab_link($wcttab,'Import / Export','importexport'); }
					if ($arr_user[$this->settings['crole'.$tableid.'_s']] >= $user->user_level) { echo $this->tab_link($wcttab,'View Setup','setup'); }
				}
				else {
					if ($arr_user[$this->settings['role_archive']] >= $user->user_level) {
						echo $this->tab_link($wcttab,'Table Setup','show');
						echo $this->tab_link($wcttab,'View Setup','setup');
					}
				}

				echo "</tr></table></div>";
			}

			$wctmp = "admin.php?page=wct_table_";
			switch ($wcttab) {

				default:
					if ($tableid == '0') {
						if ($arr_user[$this->settings['role_archive']] >= $user->user_level) { include("pages/setup_archive.php"); }
						else { include("pages/405.php"); }
					}
					else {
						if ($arr_user[$this->settings['crole'.$tableid.'_s']] >= $user->user_level) { include("pages/setup_table.php"); }
						elseif ($arr_user[$this->settings['crole'.$tableid.'_c']] >= $user->user_level) { include("pages/editcontent.php"); }
						elseif ($arr_user[$this->settings['crole'.$tableid.'_i']] >= $user->user_level) { include("pages/importexport.php"); }
						else { include("pages/405.php"); }
					}
				break;	

				case 'content':
					include("pages/editor_fixes.php");
					if ($arr_user[$this->settings['crole'.$tableid.'_c']] >= $user->user_level) { include("pages/editcontent.php"); }
					else { include("pages/405.php"); }
				break;

				case 'importexport':
					if ($arr_user[$this->settings['crole'.$tableid.'_i']] >= $user->user_level) { include("pages/importexport.php"); }
					else { include("pages/405.php"); }
				break;

				case 'setup':
					include("pages/editor_fixes.php");
					if ($tableid == '0' AND $arr_user[$this->settings['role_archive']] >= $user->user_level) { include("pages/setup_view.php"); }
					elseif ($tableid != '0' AND $arr_user[$this->settings['crole'.$tableid.'_s']] >= $user->user_level) { include("pages/setup_view.php"); }
					else { include("pages/405.php"); }
				break;

				case 'show':
					include("pages/setup_archive.php");
				break;
			}

		}
		function getOptions() {
			global $wpdb;
			$this->settings = get_option('wuk_custom_tables');
			if (!array_key_exists('wct_cachetime',$this->settings)) {
				$this->settings['wct_cachetime'] = '21600';
				update_option('wuk_custom_tables', $this->settings);
			}
			if (!array_key_exists('role_ct',$this->settings)) {
				$this->settings['role_ct'] = 'administrator';
				update_option('wuk_custom_tables', $this->settings);
			}
			if (!array_key_exists('role_css',$this->settings)) {
				$this->settings['role_css'] = 'administrator';
				update_option('wuk_custom_tables', $this->settings);
			}
			if (!array_key_exists('role_archive',$this->settings)) {
				$this->settings['role_archive'] = 'administrator';
				update_option('wuk_custom_tables', $this->settings);
			}
			if (!array_key_exists('wct_immaster',$this->settings)) {
				$this->settings['wct_immaster'] = 'no';
				update_option('wuk_custom_tables', $this->settings);
			}
			if (!array_key_exists('css',$this->settings)) {
				$this->settings['css'] = ".wct-overlay {\n\tpadding: 5px;\n\tbackground-color: white;\n\tborder: 1px black solid;\n\ttop: 1px;\n\tleft: 1px;\n\tvisibility: hidden;\n\toverflow: hidden;\n\tdisplay:none;\n\tmax-width: 300px;\n}\n.wct-td1 {\n\tbackground-color: #808080;\n}\n.wct-td2 {\n\tbackground-color: transparent;\n}\n.wct-td-hover {\n\tbackground-color: #DBD8FE;\n}\n.wct-sortdown {\n\tmargin: 0px 1px 0px 0px !important;\n}\n.wct-sortup {\n\tmargin: 0px 0px 0px 1px !important;\n}\n.wct-table {\n\twidth: 100% !important;\n}\n.wct-search {\n\twidth: 300px !important;\n}\n.wct-errorfield {\n\tborder-right: 0px !important;\n\tborder-bottom: 0px !important;\n\tborder-left: 0px !important;\n}\n.wctarchiveheader {\n\tfont-weight: bold !important;\n}\n.wctarchiveul {\n}\n.wctarchiveli {\n\tline-height: 1.1em !important;\n}\n.wctarchivea {\n\ttext-decoration: none !important;\n}";
				update_option('wuk_custom_tables', $this->settings);
			}
			if (!array_key_exists('dbversion',$this->settings)) {
				// db mutation machen wenn eine db existiert!
				$table = $wpdb->get_row("SHOW CREATE TABLE `".$wpdb->prefix."wct_list`;");
				if (count($table) >= '1') {
					$array=array(); foreach($table as $member=>$data) { $array[$member]=$data; }
					if (strpos("`sort`",$array['Create Table']) == false AND $array['Create Table'] != '') {
						$this->info = __('Database Update done','wct');
						$wpdb->get_row("ALTER TABLE `".$wpdb->prefix."wct_list` ADD COLUMN `sort` varchar(32) NULL DEFAULT 'id', ADD COLUMN `sortB` enum('ASC','DESC') NOT NULL DEFAULT 'ASC';");
						$this->settings['dbversion'] = "2011072801";
						update_option('wuk_custom_tables', $this->settings);
					}
				}
				else {
					$this->settings['dbversion'] = "2011072801";
					update_option('wuk_custom_tables', $this->settings);
				}
			}
		}
		function activate() {
			global $wpdb;
	    		include("pages/activate.php");
		}
		function uninstall() {
			global $wpdb;
			delete_option('wuk_custom_tables');
			$qry = $wpdb->get_results("SELECT `id` FROM `".$wpdb->prefix."wct_list` WHERE `id`!='0';");
			if (count($qry) >= '1') {
				foreach ($qry as $row)
				{
					$wpdb->get_row("DROP TABLE `".$wpdb->prefix."wct".$row->id."`;");
				}
			}
			$wpdb->get_row("DROP TABLE `".$wpdb->prefix."wct_list`;");
		}
		function add_menupages() {
			global $wpdb;

			add_menu_page('Custom Tables','Custom Tables', 'level_0', __FILE__, array(&$this, 'wctmenu'));
			add_submenu_page(__FILE__, __('Create Table', 'wct'), __('Create Table', 'wct'), $this->settings['role_ct'], 'wct_table_create', array(&$this, 'create_table'));
			$qry = $wpdb->get_results("SELECT `id`,`name` FROM `".$wpdb->prefix."wct_list` WHERE `id`!='0' ORDER BY `id` ASC;");

			$arr_user = array('subscriber'=>0, 'contributor'=>1, 'author'=>2, 'editor'=>5, 'administrator'=>8);
			foreach ($qry as $row) {
				if (!array_key_exists('crole'.$row->id.'_s',$this->settings)) {
					$this->settings['crole'.$row->id.'_s'] = 'administrator';
					update_option('wuk_custom_tables', $this->settings);
				}
				if (!array_key_exists('crole'.$row->id.'_c',$this->settings)) {
					$this->settings['crole'.$row->id.'_c'] = 'contributor';
					update_option('wuk_custom_tables', $this->settings);
				}
				if (!array_key_exists('crole'.$row->id.'_i',$this->settings)) {
					$this->settings['crole'.$row->id.'_i'] = 'editor';
					update_option('wuk_custom_tables', $this->settings);
				}
				$mincap = $arr_user[$this->settings['crole'.$row->id.'_c']];
				if ($mincap > $arr_user[$this->settings['crole'.$row->id.'_i']]) { $mincap = $arr_user[$this->settings['crole'.$row->id.'_i']]; };
				if ($mincap > $arr_user[$this->settings['crole'.$row->id.'_s']]) { $mincap = $arr_user[$this->settings['crole'.$row->id.'_s']]; };
				if ($_POST['vipID'] == '' OR $_POST['vipID'] != $row->id) { add_submenu_page(__FILE__, __('Table', 'wct')." ".$row->id , "&raquo; ".$row->name , "level_".$mincap, 'wct_table_'.$row->id , array(&$this, 'create_table')); }
			}
			add_submenu_page(__FILE__, __('Archive'),"&raquo; ".__('Article Archive'), $this->settings['role_archive'], 'wct_table_0', array(&$this, 'create_table'));
			add_submenu_page(__FILE__, __('Edit CSS', 'wct'), __('Edit CSS', 'wct'), $this->settings['role_css'], 'wct_css', array(&$this, 'edit_css'));
			add_submenu_page(__FILE__, __('Settings'),__('Settings'), 'level_8', 'wct_settings', array(&$this, 'Settings'));
			add_submenu_page(__FILE__, 'Changelog','Changelog', 'level_8', 'wct_changelog', array(&$this, 'ChangeLog'));
		}
		function Settings() {
			global $wpdb;
			include("pages/wuk.php");
	    		include("pages/setup_settings.php");
		}
		function ChangeLog() {
			include("pages/wuk.php");
			include("pages/view_changelog.php");
		}
		function edit_css() {
			include("pages/wuk.php");
			include("pages/setup_css.php");
		}
		function wct_sort($feld,$table) {
			$url = $this->generate_pagelink(array("/[&?]+wctinvs=1*/","/[&?]+wctsort=[a-zA-Z]*/"),array("",""));

			if ($feld == $_REQUEST['wctsort']) {
				if ($table->sheme == '1') {
					if ($_REQUEST['wctinvs'] == '1') { $zusatz1 = "_white";  } else { $zusatz2 = "_white"; }
				}
				else {
					if ($_REQUEST['wctinvs'] == '1') { $zusatz1 = "_black";  } else { $zusatz2 = "_black"; }
				}
			}
			$out .= "<a href=\"".$url."wctsort=".$feld."\"><img class=\"wct-sortdown\" src=\"".plugins_url('custom-tables/img/sort_down'.$zusatz2.'.gif')."\" alt=\"sort down\" border=\"0\" /></a>";
			$out .= "<a href=\"".$url."wctsort=".$feld."&wctinvs=1\"><img class=\"wct-sortup\" src=\"".plugins_url('custom-tables/img/sort_up'.$zusatz1.'.gif')."\" alt=\"sort up\" border=\"0\" /></a>";

			return $out;
		}

		function tablerights($label,$role,$recht = 'administrator') {
			global $profileuser;
			$user_roles = $profileuser->roles;
			$user_role = @array_shift($user_roles);
			echo "<tr><td><label for=\"role\">". $label ."</label></td><td><select name=\"wctrole_".$role."\" id=\"wctrole".$role."\">";
			wp_dropdown_roles($recht);
			echo "</select></td></tr>";
			return true;
		}

		function option($label,$role,$recht = '', $desc = '') {
			echo "<tr><td><label for=\"role\">". $label ."</label></td><td><input type=\"text\" name=\"wctrole_".$role."\" id=\"wctrole".$role."\" value=\"".$recht."\"/></td><td>&nbsp;<i>".$desc."</i></td></tr>";
			return true;
		}
		function disable_wysiwyg($wert) {
    			if($_GET['wcttab'] == 'setup') { return false; }
    			return $wert;
		}
		function generate_pagelink($arrayA,$arrayB) {
			include("pages/generate_url.php");
			return $url;
		}
		/* Hooks for additional Extensions */
		function hook_table($content) { return $content; }
		function hook_entry($content) { return $content; }
		function hook_overlay($content) { return $content; }
	}

	add_action('init', 'wuk_custom_tables1');
	function wuk_custom_tables1() {
		global $wuk_custom_tables;
		$wuk_custom_tables = new wuk_custom_tables();
	}
}

if (function_exists('register_activation_hook')) { register_activation_hook(__FILE__, array('wuk_custom_tables', 'activate')); }
if (function_exists('register_uninstall_hook')) { register_uninstall_hook(__FILE__, array('wuk_custom_tables', 'uninstall')); }

?>