<?php
 
// table_edit2.inc.php, 0.9+calc0.3+func0.2 2006/09/19 taru        plugin
 
define('PLUGIN_TABLE_EDIT_TEXT_SIZE',  68);
define('PLUGIN_TABLE_EDIT_TABLE_HEADER', 'h');		// 'h' or ''	06.09.12
define('PLUGIN_TABLE_EDIT_TD_SHOW', TRUE);		// td_edit_and_add	06.09.16

function plugin_table_edit2_convert()
{
	global $script, $vars, $edit_auth_pages;
	static $number = array();
	$line_count = 1;
	$table_end = 0;
	$table_sub_num = 1;
	$cell_format = 'RIGHT: ';		//06.09.15	calc 0.2
	$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' => '',
//		'copy' => '',
	);

	$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 = '';
	$body_table = '';

	$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';
	}
	if($opt['edit'] != 'off' || $calc == 'on') $editoff_or_calcon = 1;		//06.09.19
	foreach ($args as $args_line) {
		if (preg_match('/^\|(.+)\|([hHfFcC]?)$/', $args_line, $matches) && $editoff_or_calcon){
			$cell_count = 1;		//move 06.09.16
			$match_cells = explode("|", $matches[1]);		//move 06.09.16
			if (strtolower($matches[2]) == "c") {		//06.09.15	calc 0.2
				$cell_format = '';
			}
			if ( $calc == 'on' ){		//calc  06.09.12 taru
				$comma = isset($opt['comma']) ? ',' : '';
				$body_table .= '|';
				$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_table .= $cell_format . number_format((float) $cell, $opt['dot'], '.', $comma) . '|';
						$calc_cell_count++;
					} else {
						$body_table .= $cell . '|';
					}
					$cells[$line_count][$cell_count] = $cell;
					$cell_count++;
//					$cell_sum += $cell;
				}
				if ( $calc == 'on' ){
					$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_table .= 'RIGHT: ' . number_format((float) $cell_calc, $opt['dot'], '.', $comma) . '|';
						$cell_count++;
					}
					$cell_count_max = $cell_count;
				}
			} else {
				$body_table .= '|' . $matches[1] . "|";
			}
			if( $opt['edit'] != 'off' ){		//edit
				$body_table .= "&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_table .= "|";
			}
			$body_table .= $matches[2] . "\n";
			$line_count++;
			$table_end = 1;
			$table_header = 1;
		} else {
			if( $table_header === 1 && $opt['edit'] != 'off' && PLUGIN_TABLE_EDIT_TD_SHOW === TRUE){		//td edit and add 06.09.16
				$cell_count = 1;
				$table_line_count = $line_count- 1;
				$body .= '|';
				foreach ($match_cells as $cell){
					$body .= "~&table_edit2(edit_mod=tdshow,table_num=$count,table_sub_num=$table_sub_num,line_count=$table_line_count,cell_count=$cell_count);"
						  . "&table_edit2(edit_mod=td,table_num=$count,table_sub_num=$table_sub_num,line_count=$table_line_count,cell_count=$cell_count);|";
					$cell_count++;
				}
				$table_sub_num++;
				if ( $opt['row'] == 'sum' || $opt['row'] == 'average' ){	//06.09.16 (><)b
					$body .= "|";
				}
				$body .= "|h\n" . $body_table;
				$body_table = '';
				$table_header = 0;
			} else {
				$body .= $body_table;
				$body_table = '';
			}
			if ( $opt['column'] == 'sum' || $opt['column'] == 'average' ) $column_sum_or_avg = 1;
			if ( $table_end && $column_sum_or_avg){		//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;
			}
			$cell_format = 'RIGHT: ';		//06.09.15	calc 0.2
			$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 cell_ra 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;
}
//rlative addrss
function cell_ra($row,$column,$cells,$line_count,$cell_count)
{
	$cell = $cells[$line_count - $row][$cell_count - $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' || $opt['edit_mod'] == 'tdshow'){
		$image_png = 'paraedit.png" width="9" height="9" alt="" title="edit"';
	} else if ($opt['edit_mod'] == 'tr' || $opt['edit_mod'] == 'td'){
		$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;table_sub_num=" . $opt['table_sub_num']
		 . "&amp;line_count=" . $opt['line_count'] . "&amp;cell_count=" . $opt['cell_count']
		 . '"><img src="' . IMAGE_URI . 'plus/' . $image_png . ' /></a>';
	return $body;
}
function plugin_table_edit2_action()
{
	global $vars, $post, $script;
	$line_count = 1;
	$table_sub_num = 1;			//td 06.09.18
	$table_sub_num_chk = 1;		//td 06.09.18
	$line_count_td = 1;			//td 06.09.19
	if ($vars['edit_mod'] == 't_edit_td' || $vars['edit_mod'] == 'td'){
		$td_edit = 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
	if ($vars['cancel'] == 'cancel') return;
	$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] . "\n";
					}
				}
			}
			$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 ($table_sub_num == $vars['table_sub_num'] && $table_sub_num_chk){		//td 06.09.18
					$chk_table_sub_first_line = $line_count;
					$table_sub_num_chk = 0;
				}
				if ($vars['line_count'] == $line_count || $line_count === $line_header || $vars['edit_mod'] == 'tdshow' || $td_edit){
					$match_t = explode("|", $match_line[1]);	//move 06.09.16
				}
				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 ( $td_edit && $table_sub_num_chk == 0 && $table_sub_num == $vars['table_sub_num']){			//t_edit_td 06.09.19
					$end_cell = count ($match_t);
					$source_s .= '|';
					for ($x = 0;$x < $end_cell;$x++){
						if ($x == ($vars['cell_count'] - 1)){
							if (isset($vars['delete'])){
								$source_s .= '';
							} else if ($vars['edit_mod'] == 'td'){
								$source_s .= $match_t[$x] . '||';
								$notimestamp = TRUE;
							} else {
								$source_s .= $vars['cell' . $line_count_td] . '|';
							}
						} else {
							$source_s .= $match_t[$x] . '|';
						}
					}
					$source_s .= $match_line[2] . "\n";
					$line_count_td++;
					$table_sub_num_count_chk = 1;
				} else if($vars['line_count'] == $line_count && ! $td_edit){
					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] . "\n";
//						} else if(isset($vars['cancel'])){
//								return;
//						} else if(isset($vars['delete'])){
						}
					} else if($vars['edit_mod'] == 'tr'){				//tr	tr_add
						$notimestamp = TRUE;
						$source_s .= $args_line;
						$source_s .= '|';
						foreach ($match_t as $cell){
							$source_s .= '|';
						}
						$source_s .= "\n";
					} else if($vars['edit_mod'] == 'show'){				//show
//						$match_t = explode("|", $match_line[1]);
						$title = 'table_edit2 ' . $page;
						$body = table_edit_form($page, $vars['edit_mod'], $table_num, $line_count, $match_t);
						break;
					} else if($vars['edit_mod'] == 'tdshow'){			//tdshow
						$cells[$line_count] = $match_t;
						$column_num = $vars['cell_count'] - 1;
						for ( $x = $chk_table_sub_first_line ;$x <= $line_count ; $x++){
							$column_cell[$x] = $cells[$x][$column_num];
						}
						$title = 'table_edit2 ' . $page;
						$body = table_edit_form($page, $vars['edit_mod'], $table_num, $vars['cell_count'], $column_cell, $vars['table_sub_num']);
					}
				} else {
					if ($vars['edit_mod'] == 'tdshow'){		//tdshow and edit_td
						$cells[$line_count] = $match_t;
					}
					$table_sub_num_count_chk = 1;			//td06.09.18
					$source_s .= $args_line;
				}
				$line_count++;
			} else {
				if ($table_sub_num_count_chk == 1){			//td 06.09.18
					$table_sub_num++;
					$table_sub_num_count_chk = 0;
				}
				$source_s .= $args_line;
			}
		} else {
			$source_s .= $args_line;
		}
	}

	if($vars['edit_mod'] == 't_edit' || $vars['edit_mod'] == 'tr' || $td_edit || isset($vars['table_mod'])){
		page_write($page, $source_s, $notimestamp);
	}

	$post['refer'] = $page;

	return array('msg'=>$title, 'body'=>$body);
}

//table edit form
function table_edit_form($page, $_edit_mod, $table_num, $edit_count, $edit_cell, $table_sub_num)
{
	if ($_edit_mod == 'show'){
		$line_name = ' line';
		$edit_mod = 't_edit';
		$x_count = 'line_count';
		$y_count = 'cell_count';
	} else if ($_edit_mod == 'tdshow'){
		$line_name = " (sub number=" . $table_sub_num . ") column line";
		$edit_mod = 't_edit_td';
		$x_count = 'cell_count';
		$y_count = 'line_count';
	}
	$body = '<h3>' . 'table=' . $table_num . $line_name . '=' . $edit_count . '</h3>';
	$body .= '<form action="' . $script . '" method="post">';
	$body .= ' <table cellspacing="0" cellpadding="2" class="style_table">';
	$cell_count = 1;
	foreach ($edit_cell 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="table_sub_num" value="$table_sub_num" />
   <input type="hidden" name="$x_count"      value="$edit_count" />
   <input type="hidden" name="$y_count"      value="$cell_count" />
   <input type="hidden" name="edit_mod"      value="$edit_mod" />
   <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;
	return $body;
}

?>
