<?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.5.7
   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('wctsearch', array(&$this,'show_search'));
			if(is_admin())
			{
				add_action('admin_menu', array (&$this, 'add_menupages'));
			}
		}
		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_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=\"min-width:148px;width:148px;font-family: 'Lucida Grande',Verdana,Arial,'Bitstream Vera Sans',sans-serif;color: ";
			if ($wcttab == $shorttag && $wcttab2 == '') { $out .= "black"; }
			elseif ($wcttab == 'setup' && $wcttab2 == $_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;
			$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>";

				echo $this->tab_link($wcttab,'Table Setup','');
				echo $this->tab_link($wcttab,'Edit Content','content');
				echo $this->tab_link($wcttab,'Import / Export','importexport');
				echo $this->tab_link($wcttab,'View Setup','setup');

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

			switch ($wcttab) {
				default:
					include("pages/table_create.php");
				break;	

				case 'content':
					include("pages/editcontent.php");
				break;

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

				case 'setup':
					include("pages/viewsetup.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);
			}
		}
		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`;");
			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;
			$mincap = 'level_8';
			add_menu_page('Custom Tables','Custom Tables', $mincap, __FILE__, array(&$this, 'wctmenu'));
			add_submenu_page(__FILE__, __('Create Table', 'wct'), __('Create Table', 'wct'), $mincap, 'wct_table_create', array(&$this, 'create_table'));
			$qry = $wpdb->get_results("SELECT `id`,`name` FROM `".$wpdb->prefix."wct_list`;");
			foreach ($qry as $row)
			{
				if ($_POST['vipID'] == '' OR $_POST['vipID'] != $row->id) { add_submenu_page(__FILE__, __('Table', 'wct')." ".$row->id , "&raquo; ".$row->name , $mincap, 'wct_table_'.$row->id , array(&$this, 'create_table')); }
			}
			
			add_submenu_page(__FILE__, __('Edit CSS', 'wct'), __('Edit CSS', 'wct'), $mincap, "plugin-editor.php?file=custom_tables/css/style.css&plugin=custom_tables/custom_tables.php");
			add_submenu_page(__FILE__, 'Changelog','Changelog', $mincap, 'wct_changelog', array(&$this, 'ChangeLog'));
		}
		function ChangeLog() {
			$fp = fopen(plugin_dir_path( __FILE__ ).'readme.txt',"r");
			$inhalt = fread($fp,filesize(plugin_dir_path( __FILE__ ).'readme.txt'));
			fclose($fp);
			$ch = explode("== Changelog ==\n\n",$inhalt);
			$ch = explode("\n== Upgrade Notice ==",$ch[1]);

			$changelog = preg_replace("/\* (.*?)\n/","<li>$1</li>",$ch[0]);
			$changelog = preg_replace("/= (.*?) =/","</lu><strong>= $1 =</strong><lu>",$changelog);
			$changelog = preg_replace("/`(.*?)`/","<span style=\"background-color: #E1E1E1;\">$1</span>",$changelog);

			$changelog = preg_replace("/\[(.*?)\]\((.*?)\"(.*?)\"\)/","<a href=\"$2\" rel=\"external nofollow\" alt=\"$3\">$1</a>",$changelog);
			include("pages/wuk.php");
			print "<div class='wrap'><h2>Changelog</h2>". $changelog."</div>";
		}

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

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

?>