<?php
/*
Plugin Name: CSV Export pour la prevention.be
Plugin URI: 
Description: 
Author: Fred
Version: 1.0
Author URI: http://naxialis.com/
*/

if ( is_admin() ) {

	if ($_GET['page'] == "csvexportprevention.php") {
		function _valToCsvHelper($val, $separator, $trimFunction) {
			if ($trimFunction) $val = $trimFunction($val);
			//If there is a separator (;) or a quote (") or a linebreak in the string, we need to quote it.
			$needQuote = FALSE;
			do {
				if (strpos($val, '"') !== FALSE) {
					$val = str_replace('"', '""', $val);
					$needQuote = TRUE;
					break;
				}
				if (strpos($val, $separator) !== FALSE) {
					$needQuote = TRUE;
					break;
				}
				if ((strpos($val, "\n") !== FALSE) || (strpos($val, "\r") !== FALSE)) { // \r is for mac
					$needQuote = TRUE;
					break;
				}
			} 
			while (FALSE);
			if ($needQuote) {
				$val = '"' . $val . '"';
			}
			return $val;
		}

		function arrayToCsvString($array, $separator=';', $trim='both', $removeEmptyLines=TRUE) {
			if (!is_array($array) || empty($array)) return '';
			switch ($trim) {
				case 'none':
					$trimFunction = FALSE;
					break;
				case 'left':
					$trimFunction = 'ltrim';
					break;
				case 'right':
					$trimFunction = 'rtrim';
					break;
				default: //'both':
					$trimFunction = 'trim';
				break;
			}
			$ret = array();
			reset($array);
			if (is_array(current($array))) {
				while (list(,$lineArr) = each($array)) {
					if (!is_array($lineArr)) {
						//Could issue a warning ...
						$ret[] = array();
					} else {
						$subArr = array();
						while (list(,$val) = each($lineArr)) {
							$val      = _valToCsvHelper($val, $separator, $trimFunction);
							$subArr[] = $val;
						}
					}
					$ret[] = join($separator, $subArr);
				}
				$crlf = _define_newline();
				return join($crlf, $ret);
			} else {
				while (list(,$val) = each($array)) {
					$val   = _valToCsvHelper($val, $separator, $trimFunction);
					$ret[] = $val;
				}
				return join($separator, $ret);
			}
		}

		function _define_newline() {
			$unewline = "\r\n";
			if (strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), 'win')) {
			   $unewline = "\r\n";
			} else if (strstr(strtolower($_SERVER["HTTP_USER_AGENT"]), 'mac')) {
			   $unewline = "\r";
			} else {
			   $unewline = "\n";
			}
			return $unewline;
		}

		function _get_browser_type() {
			$USER_BROWSER_AGENT="";

			if (ereg('OPERA(/| )([0-9].[0-9]{1,2})', strtoupper($_SERVER["HTTP_USER_AGENT"]), $log_version)) {
				$USER_BROWSER_AGENT='OPERA';
			} else if (ereg('MSIE ([0-9].[0-9]{1,2})',strtoupper($_SERVER["HTTP_USER_AGENT"]), $log_version)) {
				$USER_BROWSER_AGENT='IE';
			} else if (ereg('OMNIWEB/([0-9].[0-9]{1,2})', strtoupper($_SERVER["HTTP_USER_AGENT"]), $log_version)) {
				$USER_BROWSER_AGENT='OMNIWEB';
			} else if (ereg('MOZILLA/([0-9].[0-9]{1,2})', strtoupper($_SERVER["HTTP_USER_AGENT"]), $log_version)) {
				$USER_BROWSER_AGENT='MOZILLA';
			} else if (ereg('KONQUEROR/([0-9].[0-9]{1,2})', strtoupper($_SERVER["HTTP_USER_AGENT"]), $log_version)) {
		    	$USER_BROWSER_AGENT='KONQUEROR';
			} else {
		    	$USER_BROWSER_AGENT='OTHER';
			}
	
			return $USER_BROWSER_AGENT;
		}

		function _get_mime_type() {
			$USER_BROWSER_AGENT= _get_browser_type();

			$mime_type = ($USER_BROWSER_AGENT == 'IE' || $USER_BROWSER_AGENT == 'OPERA')
				? 'application/octetstream'
				: 'application/octet-stream';
			return $mime_type;
		}

		function createcsv($table = 'users', $sep) {
			global $wpdb;
			// Get the columns and create the first row of the CSV
			switch($table) {
				case 'comments':
					$fields = array('Name','E-Mail','URL');
					break;
				case 'users':
				default:
					$fields = array('Utilisateur ID','E-Mail','Site web','Nom utilisateur','Date inscription','Nom','prenom','Pseudonime','Abonnement','Telephone','GSM','Adresse numero','Adresse rue','Adresse ville','Adresse postal','Adresse pays','Service','Nom et Prenom','Tva');
					break;
			}
			$csv = arrayToCsvString($fields, $sep);
			$csv .= _define_newline();

			// Query the entire contents from the Users table and put it into the CSV
			switch($table) {
				case 'comments':
					$query = "SELECT DISTINCT comment_author, comment_author_email, comment_author_url FROM $wpdb->comments WHERE comment_approved = '1'";
					break;
				case 'users':
				default:
					$query = "SELECT ID as UID,  user_email, user_url, user_nicename, user_registered FROM $wpdb->users";
					break;
			}
			$results = $wpdb->get_results($query,ARRAY_A);
			$i=0;
			if ($table == 'users') {
				while ($i < count($results)) {
					$query = "SELECT meta_value FROM ".$wpdb->prefix."usermeta WHERE user_id = ".$results[$i]['UID']." AND meta_key = ";
					$fnquery = $query . "'nom'";
					$results[$i]['nom'] = $wpdb->get_var($fnquery);
					$lnquery = $query . "'prenom'";
					$results[$i]['prenom'] = $wpdb->get_var($lnquery);
					$nnquery = $query . "'nickname'";
					$results[$i]['nickname'] = $wpdb->get_var($nnquery);
					//
					$nnquery = $query . "'abonnement'";
					$results[$i]['abonnement'] = $wpdb->get_var($nnquery);
					//
					$telquery = $query . "'tel'";
					$results[$i]['tel'] = $wpdb->get_var($telquery);
					$gsmquery = $query . "'gsm'";
					$results[$i]['gsm'] = $wpdb->get_var($gsmquery);
					// adresse
					$numeroquery = $query . "'numero'";
					$results[$i]['numero'] = $wpdb->get_var($numeroquery);
					$ruequery = $query . "'rue'";
					$results[$i]['rue'] = $wpdb->get_var($ruequery);
					$villequery = $query . "'ville'";
					$results[$i]['ville'] = $wpdb->get_var($villequery);
					$postalquery = $query . "'postal'";
					$results[$i]['postal'] = $wpdb->get_var($postalquery);
					$paysquery = $query . "'pays'";
					$results[$i]['pays'] = $wpdb->get_var($paysquery);
					//adresse fin
					
					// adminitrative
					$servicequery = $query . "'service_user'";
					$results[$i]['service_user'] = $wpdb->get_var($servicequery);
					$nom_prenomquery = $query . "'nom_prenom'";
					$results[$i]['nom_prenom'] = $wpdb->get_var($nom_prenomquery);
					$tvaquery = $query . "'tva'";
					$results[$i]['tva'] = $wpdb->get_var($tvaquery);
					
					
					$i++;
				}
			}
			$csv .= arrayToCsvString($results, $sep);

			$now = gmdate('D, d M Y H:i:s') . ' GMT';
			
			

			header('Content-Type: application/force-download');
			header('Expires: ' . $now);

			header('Content-Disposition: attachment; filename="'.$table.'.csv"');
			header("Content-Transfer-Encoding: application/vnd.ms-excel\n");
			header('Pragma: no-cache');
			header("Content-Transfer-Encoding: application/vnd.ms-excel\n");

			echo $csv;
		}

		function naxialis_getcsv() {
			if (isset($_GET['csv']) && $_GET['csv'] == "true") {
				if ( !current_user_can('edit_users') )
					wpdie('No, that won\'t be working, sorry.');
				$table = $_GET['table'];
				$sep = ";";
				if (isset($_GET['sep'])) {
					$sep = $_GET['sep'];
					if ($sep == "tab") {
						$sep = "\t";
					}
				}
				// echo $table;
				createcsv($table, $sep);
				exit;
			}			
		}
		add_action('admin_menu','naxialis_getcsv');
	}

	if ( ! class_exists( 'exportCSVprevention' ) && !$_GET['csv'] == "true" ) {

		class exportCSVprevention {

			function add_config_page() {
				global $wpdb;
				add_submenu_page('users.php', 'Export CSV excel', 'exportCSVprevention', 'edit_users', basename(__FILE__), array('exportCSVprevention','config_page'));
				add_filter( 'plugin_action_links', array( 'exportCSVprevention', 'filter_plugin_actions'), 10, 2 );
				add_filter( 'ozh_adminmenu_icon', array( 'exportCSVprevention', 'add_ozh_adminmenu_icon' ) );				
			}
		
			function config_page() {
				$baseurl = admin_url( 'users.php?page=' . basename(__FILE__) );
			?>
			<div class="wrap" style="max-width:600px !important;">
				<h2>Export CSV</h2>
				
				<p><strong>Exportation normale avec des points-virgules comme s&eacute;parateur:</strong></p>
				<ul>
					<li><a href="<?php echo $baseurl ?>&amp;csv=true&amp;table=users">Exporter Utilisateur</a></li>
					
				</ul>
				<p><strong>Exporter avec des onglets en tant que s&eacute;parateur:</strong></p>
				<ul>
					<li><a href="<?php echo $baseurl ?>&amp;csv=true&amp;table=users&amp;sep=tab">Exporter Utilisateur</a></li>
					
				</ul>
				
				
			</div>
			<?php
			}
			
			function add_ozh_adminmenu_icon($hook) {
				static $users2csvicon;
				if (!$users2csvicon) {
					$users2csvicon = plugin_dir_url( __FILE__ ). '/icon-csv.png';
				}
				if ($hook == 'csvexportprevention.php') return $users2csvicon;
				return $hook;
			}

			function filter_plugin_actions( $links, $file ){
				//Static so we don't call plugin_basename on every plugin row.
				static $this_plugin;
				if ( ! $this_plugin ) $this_plugin = plugin_basename(__FILE__);

				if ( $file == $this_plugin ){
					$settings_link = '<a href="'.admin_url('users.php?page=csvexportprevention.php').'">' . __('Export') . '</a>';
					array_unshift( $links, $settings_link ); // before other links
				}
				return $links;
			}
			
		}
		add_action('admin_menu', array('exportCSVprevention','add_config_page'));
	}

}
?>
