<?php
/*
   Plugin Name: Custom Tables
   Plugin URI: http://wuk.ch/
   Description: Create Tables and show on a page/article. Usable for all kind of diffrent databases.
   Version: 0.6.2
   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 (!class_exists('wuk_custom_tables')) {
	class wuk_custom_tables {
		var $settings;

		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_action( 'wp_print_styles', array(&$this, 'enqueue_styles') );
			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'));
			if(is_admin())
			{
				add_action('admin_menu', array(&$this, 'add_menupages'));
			}
			add_filter( 'user_can_richedit', array(&$this, 'disable_wysiwyg') );
		}

		function disable_wysiwyg($wert) {
    			if($_GET['wcttab'] == 'setup') { return false; }
    			return $wert;
		}

		function show_table($atts) {
			global $wpdb;
			/* Table auf der Seite anzeigen per Shortcode einfügen */
			extract(shortcode_atts(array('id' => '1', 'limit' => '50'), $atts));
			include("pages/showtable.php");
			return $out;
		}
		function enqueue_styles() {
        		$myStyleUrl = WP_PLUGIN_URL . '/custom-tables/css/style.css';
        		$myStyleFile = WP_PLUGIN_DIR . '/custom-tables/css/style.css';

        		if ( file_exists($myStyleFile) ) {
            			wp_register_style('myStyleSheets', $myStyleUrl);
            			wp_enqueue_style( 'myStyleSheets');
        		}
		}
		function show_date($atts) {
			global $wpdb;		
			include("pages/date.php");
			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/search.php");
			return $out;
		}
		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;
			$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>";
			}

			switch ($wcttab) {
				default:
					if ($tableid == '0') {
						if ($arr_user[$this->settings['role_archive']] >= $user->user_level) { include("pages/show.php"); }
						else { include("pages/405.php"); }
					}
					else {
						if ($arr_user[$this->settings['crole'.$tableid.'_s']] >= $user->user_level) { include("pages/table_create.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':
					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':
					if ($tableid == '0' AND $arr_user[$this->settings['role_archive']] >= $user->user_level) { include("pages/viewsetup.php"); }
					elseif ($tableid != '0' AND $arr_user[$this->settings['crole'.$tableid.'_s']] >= $user->user_level) { include("pages/viewsetup.php"); }
					else { include("pages/405.php"); }
				break;

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

		}
		function getOptions() {
			$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);
			}
		}
		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'], "plugin-editor.php?file=custom-tables/css/style.css&plugin=custom-tables/custom_tables.php");
			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/settings.php");
		}
		function ChangeLog() {
			include("pages/wuk.php");
			include("pages/changelog.php");
		}

		function wct_sort($feld,$table) {
			$url = str_replace("/&","/?",WP_SITEURL.preg_replace("/[&?]+wctinvs=1*/","",preg_replace("/[&?]+wctsort=[a-zA-Z]*/","",$_SERVER[REQUEST_URI])));
			if (strpos($url,"?") !== FALSE) { $url .= "&"; } else { $url .= "?"; }
			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;
		}

	}

	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')); }

?>