<?php
 
// table_edit2.inc.php, 0.7+calc0.2+func0.1 2006/09/14 taru        plugin
 
define('PLUGIN_TABLE_EDIT_TEXT_SIZE',  68);
define('PLUGIN_TABLE_EDIT_TABLE_HEADER', 'h');		// 'h' or ''	06.09.12

function plugin_table_edit2_convert()
{
	global $script, $vars, $edit_auth_pages;
	static $number = array();
	$line_count = 1;
	$table_end = 0;
	$page = isset($vars['page']) ? $vars['page'] : '';
	if (! isset($number[$page])) $number[$page] = 1;
	$count = $number[$page]++;
	$r_page = rawurlencode($page);
	$opt = array(
		'edit' => 'on',
		'auth' => '',
		'table_mod' => '',
		'calc' => '0',
		'row' => '',
		'column' => '',
		'dot' => '0',
//		'comma' => '',
	);

	$auth_chk = auth::check_auth();
	foreach($edit_auth_pages as $key=>$val){
		if (preg_match($key, $page)){
			$opt['edit'] = 'off';
			if(! empty($auth_chk)){
				$opt['edit'] = 'on';
			}
		}
	}
//	if(is_editable($page)){	}

	$head_button = '';
	$body = '';

	$args = func_get_args();
	$arg = array_pop($args);
	foreach ($args as $opt_key) {
		list($key, $val) = explode('=', strtolower($opt_key));
		$opt[$key] = htmlspecialchars($val);
	}

	// if (PKWK_READONLY) {
	if (auth::check_role('readonly') || is_freeze($page) ) {
		$opt['edit'] = 'off';
	}

	// open or close
	if ($opt['table_mod'] != 'off' && $opt['edit'] != 'off'){
		if ($opt['table_mod'] == 'open' || $opt['table_mod'] == ''){
			$image_png = 'close.png" width="11" height="11" alt="" title="close"';
			$table_mod = 'close';
		} else if ($opt['table_mod'] == 'close'){
			$image_png = 'paraedit.png" width="9" height="9" alt="" title="open"';
			$opt['edit'] = 'off';
			$table_mod = 'open';
		}
		$head_button = '<div align="right" class="table_edit"><a href="' . $script
			  . "?plugin=table_edit2&amp;refer=$r_page&amp;table_mod=" . $table_mod . "&amp;table_num=$count"
			  . '"><img src="' . IMAGE_URI . 'plus/' . $image_png . '/></a></div>';
	}

	$arg = preg_replace(array("[\\r|\\n]","[\\r]"), array("\n","\n"), $arg);
	$args = explode("\n", $arg);
//	$args_count = count($args);
	if ($opt['row'] != '' || $opt['column'] != '' || $opt['calc'] != '0'){
		$calc = 'on';
	}
	foreach ($args as $args_line) {
		if (preg_match('/^\|(.+)\|([hHfFcC]?)$/', $args_line, $matches) && ($opt['edit'] != 'off' || $calc == 'on')){
//			if ($matches[2] == "c") {	//C off : c on
//				$matches[2] = "h";
//				$body .= '|' . $matches[1] . "|RIGHT:|c\n";
//			}
			if ( $calc == 'on' ){		//calc  06.09.12 taru
				$match_cells = explode("|", $matches[1]);
				$cell_count = 1;
				$comma = isset($opt['comma']) ? ',' : '';
				$body .= '|';
				$cell_calc = '';
				$calc_cell_count = 0;
				foreach ($match_cells as $cell){
					$exp = mb_convert_kana( $cell, "a");
					if ( preg_match_all('/\@([\w]+)\((\d+),(\d+)\)/', $exp, $matc_cell)){		//func 06.09.13
						$exp = cell_func($matc_cell,$cells,$line_count,$cell_count,$exp);
						$cell = $exp;
					}
					if (preg_match('/^[\d\.\s\+\-\*\/%()]*$/', $exp) && $exp != ''){
						eval("\$cell = $exp;");
						$body .= 'RIGHT: ' . number_format((float) $cell, $opt['dot'], '.', $comma) . '|';
						$calc_cell_count++;
					} else {
						$body .= $cell . '|';
					}
					$cells[$line_count][$cell_count] = $cell;
					$cell_count++;
//					$cell_sum += $cell;
				}
				$cell_calc = '';
				if ( $opt['row'] == 'sum' || $opt['row'] == 'average' ){		//row
					if ($opt['row'] == 'sum') {
						$cell_calc = array_sum($cells[$line_count]);
//						$cell_calc = $cell_sum;
					} else if ($opt['row'] == 'average'){
						if ( $calc_cell_count === 0 ){
							$cell_calc = '';
						} else {
							$cell_calc = array_sum($cells[$line_count]) / $calc_cell_count;
						}
					}
					$cells[$line_count][$cell_count] = $cell_calc;
					$body .= 'RIGHT: ' . number_format((float) $cell_calc, $opt['dot'], '.', $comma) . '|';
					$cell_count++;
				}
				$cell_count_max = $cell_count;
			} else {
				$body .= '|' . $matches[1] . "|";
			}
			if( $opt['edit'] != 'off' ){			//edit
					$body .= "&table_edit2(edit_mod=show,table_num=$count,line_count=$line_count);"
						  . "&table_edit2(edit_mod=tr,table_num=$count,line_count=$line_count);";
			$body .= "|";
			}
		$body .= $matches[2] . "\n";
		$line_count++;
		$table_end = 1;
		} else {
			if ( $table_end && ( $opt['column'] == 'sum' || $opt['column'] == 'average' )){		//column
				$cell_calc = '';
				$body .= '|';
				for ( $x = 1 ;$x < $cell_count_max ;$x++){
					$cell_column = 0;
					for ( $y = 1 ;$y < $line_count ;$y++){
						$cell_column += $cells[$y][$x];
					}
					if ($opt['column'] == 'sum' ) {
						$cell_calc = $cell_column;
					} else if ($opt['column'] == 'average'){
						$cell_calc = $cell_column / ( $line_count - 1);
					}
					$body .= 'RIGHT: ' . number_format((float) $cell_calc, $opt['dot'], '.', $comma) . '|';
				}
				$body .= $opt['edit'] == 'on' ? '|' : '';
				$body .= "\n";
				$table_end = 0;
			}
			$body .= $args_line . "\n";
		}
	}
 
	return $head_button . convert_html($body);
}
function cell_func($matc_cell,$cells,$line_count,$cell_count,$cell)
{
	$func_s = $func_r = array();
	for ($i=0; $i< count($matc_cell[0]); $i++) {
//		$func_chk = function_exists($matc_cell[1][$i]) ? TRUE : FALSE;
		$func_name = "sum_r sum_c cell avg_r avg_c count_r count_c max_r max_c min_r min_c";
		if ( preg_match("/\b" . $matc_cell[1][$i] . "\b/i", $func_name ) ) {
			$cell_func = call_user_func(strtolower($matc_cell[1][$i]),$matc_cell[2][$i],$matc_cell[3][$i],$cells,$line_count,$cell_count);
		}
		$func_s[$i] = '/\@' . $matc_cell[1][$i] . '\(' . $matc_cell[2][$i] . ',' . $matc_cell[3][$i] . '\)/';
		$func_r[$i] = '' . $cell_func . '';
//		$cell .=   "func1: " . $matc_cell[1][$i];	//data test
//		$cell .= ", func2: " . $matc_cell[2][$i];
//		$cell .= ", func3: " . $matc_cell[3][$i];
	}
	$cell = preg_replace($func_s, $func_r, $cell);
	return $cell;
//	return $matc_cell[0][1];
}
function sum_r($start,$end,$cells,$line_count,$cell_count)
{
	$cell_sum = 0;
	for ( $x = $start;$x <= $end;$x++){
		$cell_sum += $cells[$line_count][$x];
	}
	return $cell_sum;
}
function sum_c($start,$end,$cells,$line_count,$cell_count)
{
	$cell_sum = 0;
	for ( $x = $start;$x <= $end;$x++){
		$cell_sum += $cells[$x][$cell_count];
	}
	return $cell_sum;
}
function cell($row,$column,$cells,$line_count,$cell_count)
{
	$cell = $cells[$row][$column];
	return $cell;
}
function avg_r($start,$end,$cells,$line_count,$cell_count)
{
	$cell_sum = 0;
	$sum_count = 0;
	for ( $x = $start;$x <= $end;$x++){
		$cell_sum += $cells[$line_count][$x];
		if (is_numeric($cells[$line_count][$x])){
			$sum_count++;
		}
	}
	$cell_avg = ( $sum_count === 0 ) ? '' : $cell_sum / $sum_count;
	return $cell_avg;
}
function avg_c($start,$end,$cells,$line_count,$cell_count)
{
	$cell_sum = 0;
	$sum_count = 0;
	for ( $x = $start;$x <= $end;$x++){
		$cell_sum += $cells[$x][$cell_count];
		if (is_numeric($cells[$x][$cell_count])){
			$sum_count++;
		}
	}
	$cell_avg = ( $sum_count === 0 ) ? '' : $cell_sum / $sum_count;
	return $cell_avg;
}
function count_r($start,$end,$cells,$line_count,$cell_count)
{
	$count = 0;
	for ( $x = $start;$x <= $end;$x++){
		if (is_numeric($cells[$line_count][$x])){
			$count++;
		}
	}
	return $count;
}
function count_c($start,$end,$cells,$line_count,$cell_count)
{
	$count = 0;
	for ( $x = $start;$x <= $end;$x++){
		if (is_numeric($cells[$x][$cell_count])){
			$count++;
		}
	}
	return $count;
}
function max_r($start,$end,$cells,$line_count,$cell_count)
{
	$max_cell = $cells[$line_count][$start];
	$start++;
	for ( $x = $start;$x <= $end;$x++){
		if ($max_cell < $cells[$line_count][$x]){
			$max_cell = $cells[$line_count][$x];
		}
	}
	return $max_cell;
}
function max_c($start,$end,$cells,$line_count,$cell_count)
{
	$max_cell = $cells[$start][$cell_count];
	$start++;
	for ( $x = $start;$x <= $end;$x++){
		if ($max_cell < $cells[$x][$cell_count]){
			$max_cell = $cells[$x][$cell_count];
		}
	}
	return $max_cell;
}
function min_r($start,$end,$cells,$line_count,$cell_count)
{
	$min_cell = $cells[$line_count][$start];
	$start++;
	for ( $x = $start;$x <= $end;$x++){
		if ($min_cell > $cells[$line_count][$x]){
			$min_cell = $cells[$line_count][$x];
		}
	}
	return $min_cell;
}
function min_c($start,$end,$cells,$line_count,$cell_count)
{
	$min_cell = $cells[$start][$cell_count];
	$start++;
	for ( $x = $start;$x <= $end;$x++){
		if ($min_cell > $cells[$x][$cell_count]){
			$min_cell = $cells[$x][$cell_count];
		}
	}
	return $min_cell;
}
function plugin_table_edit2_inline()
{
	global $script, $vars, $edit_auth_pages;
	$page = isset($vars['page']) ? $vars['page'] : '';
	$r_page = rawurlencode($page);
	$body = '';
	$opt = array(
		'edit_mod' => '',
		'table_num' => '',
		'line_count' => '',
	);
	$args = func_get_args();
	foreach ($args as $opt_key) {
		list($key, $val) = explode('=', strtolower($opt_key));
		$opt[$key] = htmlspecialchars($val);
	}
	if ($opt['edit_mod'] == 'show'){
		$image_png = 'paraedit.png" width="9" height="9" alt="" title="edit"';
	} else if ($opt['edit_mod'] == 'tr'){
		$image_png = 'mini_add.png" width="8" height="8" alt="" title="addition"';
	}
	$body .= '<a href="' . $script . "?plugin=table_edit2&amp;refer=$r_page&amp;edit_mod="
		 . $opt['edit_mod'] . "&amp;table_num=" . $opt['table_num'] . "&amp;line_count=" . $opt['line_count']
		 . '"><img src="' . IMAGE_URI . 'plus/' . $image_png . ' /></a>';
	return $body;
}
function plugin_table_edit2_action()
{
	global $vars, $post, $script;
	$line_count = 1;

	$table_num = 	$vars['table_num'];
	$page = 		$vars['refer'];

	if (auth::check_role('readonly')) die_message('PKWK_READONLY prohibits editing');
	if (! path_check($script,$_SERVER['HTTP_REFERER'])) return;	//06.09.11 upk
	$args  = get_source($page);
	static $count = 0;
	$source_s = '';
	$body = '';
	$title = '';
	$notimestamp = (isset($vars['notimestamp'])) ? TRUE : FALSE;
	if ($vars['table_mod'] == 'close'){
		$search_r = array ('@table_mod=open@si');
		$replace_r = array ('table_mod=close');
	} else if ($vars['table_mod'] == 'open') {
		$search_r = array ('@table_mod=close@si');
		$replace_r = array ('table_mod=open');
	}

	foreach ($args as $args_line) {
//		if (preg_match('/^#table_edit2([^\(\{]+)(?:\(([^\r]*)\))?(\{*)/', $args_line, $matches)){ //2
		if(preg_match('/^#([^\(\{]+)(?:\(([^\r]*)\))?(\{*)/', $args_line, $matches) && $matches[1] == 'table_edit2') {
			$table_find = 1;
			$count++;
			if( $line_count === 1 && $count == $table_num ){
				if(! preg_match('/(auth_check_off)/i',$matches[2])){
					check_editable($page, true, true);
				}
				if ( isset($vars['table_mod']) ){		//table_mod
					$notimestamp = TRUE;
					if(preg_match('/(table_mod)/',$matches[2])){
						$args_line = preg_replace($search_r, $replace_r, $args_line);
					} else {
						$args_line = "#table_edit2(" . $matches[2] . ",table_mod=" . $vars['table_mod'] . ")" . $matches[3] . "
";
					}
				}
			}
			$end_line = strlen($matches[3]);
		}
		if (preg_match('/^\}{' . $end_line . '}/', $args_line)) {
			$table_find = 0;
		}
		if($table_find && $table_num == $count){
			if (preg_match('/^\|(.+)\|([hHfFcC]?)$/', $args_line, $match_line)){
				if($vars['edit_mod'] == 'show'){					//show				header
					if($line_count === 1){
						if( strtolower( $match_line[2] ) == 'c' ){
							$line_header = 2;
						} else {
							$line_header = 1;
						}
					}
					if($line_count === $line_header){
						$match_t = explode("|", $match_line[1]);
						$cell_count = 1;
						foreach ($match_t as $cell){
							if( PLUGIN_TABLE_EDIT_TABLE_HEADER == $match_line[2] || $match_line[2] == 'h' ){	//06.09.12
								$table_header[$cell_count] = $cell;
								$cell_count++;
							}
						}
					} 
				}
				if($vars['line_count'] == $line_count){
					if($vars['edit_mod'] == 't_edit'){				//t_edit
						if(isset($vars['write'])){
							$source_s .= '|';
							for ($i = 1;$i < $vars['cell_count'];$i++){
								$source_s .= $vars['cell' . $i] . '|';
							}
							$source_s .= $match_line[2] . '
';
						} else if(isset($vars['cancel'])){
								return;
						} else if(isset($vars['delete'])){
						}
					} 
					if($vars['edit_mod'] == 'tr'){				//tr	tr_add
						$notimestamp = TRUE;
						$source_s .= $args_line;
						$match_t = explode("|", $match_line[1]);
						$source_s .= '|';
						foreach ($match_t as $cell){
							$source_s .= '|';
						}
						$source_s .= '
';
					}
					if($vars['edit_mod'] == 'show'){				//show
						$match_t = explode("|", $match_line[1]);
						$title = 'table_edit2 ' . $page;
						$body = '<h3>' . 'table=' . $table_num . ' line=' . $line_count . '</h3>';
						$body .= '<form action="' . $script . '" method="post">';
						$body .= ' <table cellspacing="0" cellpadding="2" class="style_table">';
						$cell_count = 1;
						foreach ($match_t as $cell){
							$body .= '  <tr><td>' . $table_header[$cell_count] . '(' . $cell_count . ')</td><td class="style_td">';
							$body .= '   <input type=text name="cell' . $cell_count . '" value="' . $cell . '" size="' . PLUGIN_TABLE_EDIT_TEXT_SIZE . '" /></td></tr>';
							$cell_count++;
						}
						$body .= <<<EOD
  <tr><td  colspan="2">
   <input type="hidden" name="plugin"     value="table_edit2" />
   <input type="hidden" name="refer"      value="$page" />
   <input type="hidden" name="table_num"  value="$table_num" />
   <input type="hidden" name="line_count" value="$line_count" />
   <input type="hidden" name="cell_count" value="$cell_count" />
   <input type="hidden" name="edit_mod"   value="t_edit" />
   <input type="submit" name="write" value="edit" />
   <input type="submit" name="cancel" value="cancel" />
   <input type="submit" name="delete" value="delete" /> no time stamp
   <input type="checkbox" name="notimestamp" />
  </td></tr>
 </table>
</form>
EOD;
						break;
					}
				} else {
					$source_s .= $args_line;
				}
				$line_count++;
			} else {
				$source_s .= $args_line;
			}
		} else {
			$source_s .= $args_line;
		}
	}

	if($vars['edit_mod'] == 't_edit' || $vars['edit_mod'] == 'tr' || isset($vars['table_mod'])){
		page_write($page, $source_s, $notimestamp);
	}

	$post['refer'] = $page;

	return array('msg'=>$title, 'body'=>$body);
}

?>
