<?php

$sop = new String_Operator();

class String_Operator {
	
	// Set datetime to database format
	public function not_null_date($datetime) {
		if(!is_null($datetime) AND strpos($datetime, '0000-00-00')===false) {
			return true;
		}
		
		return false;
	}
	public function date_to_db($datetime, $change_time='') {
		if(!$datetime) return false;
		
		if(is_numeric($datetime)) {
			RETURN date("Y-m-d", $datetime); 
		} elseif(is_string($datetime)) {
			if($change_time) {
				RETURN date("Y-m-d", strtotime($datetime.' '.$change_time));
			} else {
				RETURN date("Y-m-d", strtotime($datetime));
			}
		} else {
			return false;
		}
	}
	public function datetime_to_db($datetime) {
		RETURN date("Y-m-d H:i", strtotime($datetime));
	}
	public function date_to_print($datetime) {
		RETURN date("d.m.Y", strtotime($datetime));
	}
	public function date_to_print_YY($datetime) {
		RETURN date("d.m.y", strtotime($datetime));
	}
	public function datetime_to_print($datetime) {
		RETURN date("d.m.Y H:i", strtotime($datetime));
	}
	public function datetime_to_time($datetime) {
		RETURN date("H:i", strtotime($datetime));
	}
	public function date_to_weekday($datetime, $type='short') {
		include('components/yleiset_language.inc.php');
		
		switch($type) {
			case 'long':
				return $l_weekday_names_by_daynbr[date('N', strtotime($datetime))];
			break;
			case 'short':
			default:
				return $l_short_weekday_names_assoc[date('N', strtotime($datetime))];
		}
	}
	public function time_difference($time1, $time2) {
		
		$time1 = date_create($time1);
		$time2 = date_create($time2);
		$difference = date_diff($time1, $time2);
		
		// Return a array
		$returndata = array();
		$returndata['Y'] = $difference->format('%y');
		$returndata['m'] = $difference->format('%m');
		$returndata['d'] = $difference->format('%d');
		$returndata['H'] = $difference->format('%h');
		$returndata['i'] = $difference->format('%i');
		$returndata['s'] = $difference->format('%s');

		foreach($returndata as $this_type => $this_data) {
			if($this_data < 10) {
				$returndata[$this_type] = '0'.$returndata[$this_type];
			}
		}
		
		return $returndata;
	}
	public function datediff($interval, $datefrom, $dateto, $using_timestamps = false) {
		/*
		$interval can be:
		yyyy - Number of full years
		q    - Number of full quarters
		m    - Number of full months
		y    - Difference between day numbers
			   (eg 1st Jan 2004 is "1", the first day. 2nd Feb 2003 is "33". The datediff is "-32".)
		d    - Number of full days
		w    - Number of full weekdays
		ww   - Number of full weeks
		h    - Number of full hours
		n    - Number of full minutes
		s    - Number of full seconds (default)
		*/

		if (!$using_timestamps) {
			$datefrom = strtotime($datefrom, 0);
			$dateto   = strtotime($dateto, 0);
		}

		$difference        = $dateto - $datefrom; // Difference in seconds
		$months_difference = 0;

		switch ($interval) {
			case 'yyyy': // Number of full years
				$years_difference = floor($difference / 31536000);
				if (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom), date("j", $datefrom), date("Y", $datefrom)+$years_difference) > $dateto) {
					$years_difference--;
				}

				if (mktime(date("H", $dateto), date("i", $dateto), date("s", $dateto), date("n", $dateto), date("j", $dateto), date("Y", $dateto)-($years_difference+1)) > $datefrom) {
					$years_difference++;
				}

				$datediff = $years_difference;
			break;

			case "q": // Number of full quarters
				$quarters_difference = floor($difference / 8035200);

				while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($quarters_difference*3), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
					$months_difference++;
				}

				$quarters_difference--;
				$datediff = $quarters_difference;
			break;

			case "m": // Number of full months
				$months_difference = floor($difference / 2678400);

				while (mktime(date("H", $datefrom), date("i", $datefrom), date("s", $datefrom), date("n", $datefrom)+($months_difference), date("j", $dateto), date("Y", $datefrom)) < $dateto) {
					$months_difference++;
				}

				$months_difference--;

				$datediff = $months_difference;
			break;

			case 'y': // Difference between day numbers
				$datediff = date("z", $dateto) - date("z", $datefrom);
			break;

			case "d": // Number of full days
				$datediff = floor($difference / 86400);
			break;

			case "w": // Number of full weekdays
				$days_difference  = floor($difference / 86400);
				$weeks_difference = floor($days_difference / 7); // Complete weeks
				$first_day        = date("w", $datefrom);
				$days_remainder   = floor($days_difference % 7);
				$odd_days         = $first_day + $days_remainder; // Do we have a Saturday or Sunday in the remainder?

				if ($odd_days > 7) { // Sunday
					$days_remainder--;
				}

				if ($odd_days > 6) { // Saturday
					$days_remainder--;
				}

				$datediff = ($weeks_difference * 5) + $days_remainder;
			break;

			case "ww": // Number of full weeks
				$datediff = floor($difference / 604800);
			break;

			case "h": // Number of full hours
				$datediff = floor($difference / 3600);
			break;

			case "n": // Number of full minutes
				$datediff = floor($difference / 60);
			break;

			default: // Number of full seconds (default)
				$datediff = $difference;
			break;
		}

		return $datediff;
	}
	public function datetime_split($datetime) {
		$data['date'] = date("d-m-Y", strtotime($datetime));
		$data['year'] = date("Y", strtotime($datetime));
		$data['month'] = date("m", strtotime($datetime));
		$data['day'] = date("d", strtotime($datetime));
		$data['hour'] = date("H", strtotime($datetime));
		$data['minute'] = date("i", strtotime($datetime));
		
		RETURN $data;
	}
	public function split_date_ymd($date) {
		$returndata = substr($date, 0, 4);
		$returndata .= '-';
		$returndata .= substr($date, 4, 2);
		$returndata .= '-';
		$returndata .= substr($date, 6, 2);

		return $returndata;
	}
	public function month_last_date($date) {
		return date("Y-m-t", strtotime($date));
	}
	public function seconds_to_time($input_seconds) {
		
		$seconds_in_minute = 60;
		$seconds_in_hour = 60 * $seconds_in_minute;
		$seconds_in_day = 24 * $seconds_in_hour;
		
		// Extract days
		$days = floor($input_seconds / $seconds_in_day);
		
		// Extract hours
		$hoursSeconds = $input_seconds % $seconds_in_day;
		$hours = floor($hoursSeconds / $seconds_in_hour);
		
		// Extract minutes
		$minuteSeconds = $hoursSeconds % $seconds_in_hour;
		$minutes = floor($minuteSeconds / $seconds_in_minute);
		
		// Extract seconds
		$remaining = $minuteSeconds % $seconds_in_minute;
		$seconds = ceil($remaining);
		
		$returndata = array(
			'd' => $days,
			'h' => $hours,
			'm' => $minutes,
			's' => $seconds
		);
		
		return $returndata;
	}
	public function decimal_to_db($string) {
		RETURN str_replace(",", ".", $string);
	}
	public function decimal_to_print($string) {
		RETURN str_replace(".", ",", $string);
	}
	
	public function price_to_print($string) {
		RETURN number_format((float)$string, 2, ",", " ");
	}
	
	public function price_to_db($string) {
		RETURN str_replace(",", ".", $string);
	}
	
	public function input_test($data) {
		$returndata = trim($data);
		$returndata = stripslashes($data);
		$returndata = htmlspecialchars($data);
		/*
		$returndata = mysql_real_escape_string($data);
		*/
		RETURN $returndata;
	}
	
	public function to_html($data) {
		if(function_exists('nl2br')) {
			//$returndata = nl2br(htmlspecialchars_decode($data));
			$returndata = htmlspecialchars_decode($data);
		} else {
			$returndata = htmlspecialchars_decode($data);
		}
		
		RETURN $returndata;
	}
	
	public function decimal_hours_to_Hi($decimal_hours) {
		$returndata['minutes'] = ($decimal_hours-floor($decimal_hours))*60;
		$returndata['hours'] = floor($decimal_hours);
		
		if($returndata['minutes'] < 0) {
			$returndata['minutes'] = $returndata['minutes'] * -1;
		}
		
		if(strlen($returndata['minutes'])<2) {
			$returndata['minutes'] = "0".$returndata['minutes'];
		}
		
		return $returndata;
	}
	
	public function is_date($date) {
		
		try {
			new \Datetime($date);
			return true;
		} catch (\Exception $e) {
			return false;
		}
	}
	
	public function compare_dates($date1, $date2, $compare_sign) {
		$returndata = false;
		
		if(!$this->is_date($date1)) {
			return null;
		} elseif(!$this->is_date($date2)) {
			return null;
		}
		
		$date1 = strtotime($date1);
		$date2 = strtotime($date2);
		
		switch($compare_sign) {
			case "==":
			case "=":
				if($date1==$date2) {
					$returndata = true;
				}
			break;
			case "!=":
				if($date1!=$date2) {
					$returndata = true;
				}
			break;
			case "<":
				if($date1<$date2) {
					$returndata = true;
				}
			break;
			case "=<":
			case "<=":
				if($date1<=$date2) {
					$returndata = true;
				}
			break;
			case ">":
				if($date1>$date2) {
					$returndata = true;
				}
			break;
			case ">=":
			case "=>":
				if($date1>=$date2) {
					$returndata = true;
				}
			break;
		}
		
		
		return $returndata;
	}
	
	public function date_difference($date1_input, $date2_input) {
		
		$date1 = new Datetime($date1_input);
		$date2 = new Datetime($date2_input);
		
		$interval = $date1->diff($date2);
		
		return $interval->format('%r%a');
	}
	
	public function remove_html_tags($string) {
		return strip_tags($string);
	}
	
	public function half_year_periods() {
		return array(
			1 => array('name' => 'H1', 'months' => array(1, 2, 3, 4, 5, 6), 'start_date' => '01-01', 'end_date' => '06-30'),
			2 => array('name' => 'H2', 'months' => array(7, 8, 9, 10, 11, 12), 'start_date' => '07-01', 'end_date' => '12-31')
		);
	}
	
	public function html_to_db($string) {
		$string = htmlspecialchars($string);
		return $string;
		return base64_encode($string);
	}
	
	public function dbHtml_to_print($string) {
		$string = htmlspecialchars_decode($string);
		return $string;
		$string = base64_decode($string);
	}
}


function check_password($user_id, $login_name, $compare_password) {
	global $con;
	
	$query = "SELECT password FROM accounts WHERE ";
	
	if($user_id) {
		$query .= "id= ?";
		$bind_type = 'i';
		$bind_value = $user_id;
	} elseif($login_name) {
		$query .= "login_name= ?";
		$bind_type = 's';
		$bind_value = $login_name;
	} else {
		return false;
	}

	if ($stmt = $con->prepare($query)) {
		$stmt->bind_param($bind_type, $bind_value);
		$stmt->execute();
		$stmt->store_result();
		
		if ($stmt->num_rows > 0) {
			$stmt->bind_result($password);
			$stmt->fetch();
			
			if (password_verify($compare_password, $password)) {
				return true;
			} else {
				return false;
			}
		} else {
			return false;
		}
		
	} else {
		return false;
	}
	
}

function add_user($variables) {
	global $con;
	
	$query = "INSERT INTO accounts (";
	$columns = "id";
	$values = "0";
	
	if(isset($variables['login_name'])) {
		$columns .= ", login_name";
		$values .= ", '".$variables['login_name']."'";
	}
	
	if(isset($variables['user_name'])) {
		$columns .= ", user_name";
		$values .= ", '".$variables['user_name']."'";
	}
	
	if(isset($variables['password'])) {
		$columns .= ", password";
		$values .= ", '".$variables['password']."'";
	}
	
	if(isset($variables['email'])) {
		$columns .= ", email";
		$values .= ", '".$variables['email']."'";
	}
	
	if(isset($variables['admin'])) {
		$columns .= ", admin";
		$values .= ", '".$variables['admin']."'";
	}
	
	if(isset($variables['lang'])) {
		$columns .= ", lang";
		$values .= ", '".$variables['lang']."'";
	}
	
	$query .= $columns.") VALUES (".$values.")";
	
	$result = $con->query($query);
	
	if($result) {
		return $con->insert_id;
	} else {
		return false;
	}
}

function edit_user($variables) {
	global $con;
	
	if(!isset($variables['id'])) {
		return false;
	}
	
	$query = "UPDATE accounts SET ";
	$set_values = "";
	
	if(isset($variables['login_name'])) {
		if($set_values) $set_values .= ", ";
		$set_values .= "login_name='".$variables['login_name']."'";
	}
	
	if(isset($variables['user_name'])) {
		if($set_values) $set_values .= ", ";
		$set_values .= "user_name='".$variables['user_name']."'";
	}
	
	if(isset($variables['password'])) {
		if($set_values) $set_values .= ", ";
		$set_values .= "password='".$variables['password']."'";
	}
	
	if(isset($variables['email'])) {
		if($set_values) $set_values .= ", ";
		$set_values .= "email='".$variables['email']."'";
	}
	
	if(isset($variables['admin'])) {
		if($set_values) $set_values .= ", ";
		$set_values .= "admin='".$variables['admin']."'";
	}
	
	if(isset($variables['lang'])) {
		if($set_values) $set_values .= ", ";
		$set_values .= "lang='".$variables['lang']."'";
	}	

	$query .= $set_values." WHERE id=".$variables['id'];

	$result = $con->query($query);

	if($result) {
		return $variables['id'];
	} else {
		return false;
	}
	
}

function get_week_dates($week, $year, $day_as_key=false) {
	// Edit 20171214
	
	// Find date of monday
	if(strlen($week)<2) {
		$week = "0".$week;
	}
	$this_day = date("Y-m-d", strtotime($year."W".$week));
	if($day_as_key)
		$returndata[$this_day] = array();
	else
		$returndata[] = $this_day;
	$days = 6; // There are 6 more days to get
	$at_day = 1;
	while($days >= $at_day) {
		$this_day = date("Y-m-d", strtotime("+1 day", strtotime($this_day)));
		if($day_as_key)
			$returndata[$this_day] = array();
		else
			$returndata[] = $this_day;
		$at_day++;
	}
	
	
	
	RETURN $returndata;
}

function get_week_year($date=null, $week=null, $year=null, $todo='add') {
	/*
		Function return week for this date
	*/
	
	if(isset($week) AND isset($year)) {
		$last_week_of_year = date("W", strtotime($year."-12-26"));
		
		if($todo == 'add') {
			$week++;
		} else {
			$week--;
		}
		
		if($week < 1) {
			$year--;
			$week = date("W", strtotime($year."-12-26"));
		} elseif($week > $last_week_of_year) {
			$week = 1;
			$year++;
		}
		
		return array('week' => $week, 'year' => $year);
	}
	
	if(!$date)
		$date = date("Y-m-d", time());
	
	$date_ts = strtotime($date);
	
	$year = date("Y", $date_ts);
	
	$month = date("m", $date_ts);

	$week = date("W", $date_ts);
	
	if($month == 12 AND $week < 50) {
		$year++;
	} else	if($month == 1 AND $week > 5) {
		$year--;
	}
	
	$returndata = array('week' => $week, 'year' => $year);
	
	RETURN $returndata;
}

function print_date($date) {
	return date('d-m-Y', strtotime($date));
}

function check_vars($var) {
	global $con;
	
	return $con->real_escape_string($var);
}

function get_url_variables($variables) {
	/*
		$variables['to_get'] = post/get
	*/
	
	switch($variables['to_get']) {
		case "post":
			$array = $_POST;
		break;
		case "get":
		default:
			$array = $_GET;
	}
	
	foreach($array as $this_var => $this_value) {
		$returndata[$this_var] = check_vars($this_value);
	}
	
	return $returndata;
}

function get_available_languages() {
	$returndata = array();
	
	if($dh = opendir('./languages/')) {
		while(($file = readdir($dh)) !== false) {
			if($file == "." OR $file == "..") {
				continue;
			} else {
				$returndata[] = substr($file, 0, -4);
			}
		}		
	}
	
	return $returndata;
}

function get_scheduler_log($vars) {
	/*
		$vars['scheduler_log_id']
		$vars['datetime']
		$vars['datetime_start']
		$vars['datetime_end']
		$vars['name']
		$vars['info']
	*/
	$returndata = false;
	
	$query = "SELECT * FROM scheduler_log";
	$query_where = "";
	
	if(isset($vars['scheduler_log_id'])) {
		$query_where .= 'scheduler_log_id='.$vars['scheduler_log_id'];
	}
	
	if(isset($vars['datetime'])) {
		if($query_where) $query_where .= " AND ";
		$query_where .= 'datetime="'.$vars['datetime'].'"';
	}
	
	if(isset($vars['datetime_start'])) {
		if($query_where) $query_where .= " AND ";
		$query_where .= 'datetime>="'.$vars['datetime_start'].'"';
	}
	
	if(isset($vars['datetime_end'])) {
		if($query_where) $query_where .= " AND ";
		$query_where .= 'datetime<="'.$vars['datetime_end'].'"';
	}
	
	if(isset($vars['name'])) {
		if($query_where) $query_where .= " AND ";
		$query_where .= 'name="'.$vars['name'].'"';
	}
	
	if(isset($vars['info'])) {
		if($query_where) $query_where .= " AND ";
		$query_where .= 'info LIKE "%'.$vars['info'].'%"';
	}
	
	if($query_where) {
		$query .= " where ".$query_where;
	}
	
	$result = run_query($query);

	if($result) {
		$returndata = array();
		while($row = $result->fetch_assoc()) {
			$returndata[$row['scheduler_log_id']] = $row;
		}
	}
	
	return $returndata;
}

function get_prev_next_month_year($direction, $month, $year) {
	/*
		Returns array with ['month'] and ['year'] next or prev to given month/year
	*/
	
	switch($direction) {
		case "prev":
			$month--;
			
			if($month < 1) {
				$month = 12;
				$year--;
			}
		break;
		case "next":
			$month++;
			
			if($month > 12) {
				$month = 1;
				$year++;
			}
		break;
	}
	
	return array('month' => $month, 'year' => $year);
}

function get_finish_word($getWord) {
	include("languages/fin.php");
	
	if($$getWord) {
		return $$getWord;
	} else {
		return false;
	}
		
}

function get_swedish_word($getWord) {
	include("languages/swe.php");
	
	if($$getWord) {
		return $$getWord;
	} else {
		return false;
	}
		
}

function date_to_print($date) {
	
	if($date) {
		return date("d.m.Y", strtotime($date));
	} else {
		return $date;
	}
	
}

// Debugging function
function debugbhb() {
	return "<br><hr><br>";
}

function get_passed_variables($type, $passed_vars='', $db_correct_dates=false) {
	global $sop;
	$returndata = null;
	$serialized = false;
	
	switch($type) {
		case "GET":
		case "get":
			$vars = $_GET;
		break;
		case "POST":
		case "post":
			$vars = $_POST;
		break;
		case "passed":
			$vars = $passed_vars;
		break;
		case 'stringify':
		case 'stingify':
			$vars = json_decode($passed_vars, true);
		break;
		case 'all':
			$get_vars = get_passed_variables('get');
			$post_vars = array();
			if(isset($_POST)) {
				$post_vars = get_passed_variables('post');
			}
			return array_merge($get_vars, $post_vars);
		break;
	}
	
	if(is_array($vars)) {
		$returndata = array();
		foreach($vars as $key => $value) {
			if(is_array($value)) {
				if(isset($value['name'])) {
					
					$this_name = $sop->input_test($value['name']);
					
					$this_value = $sop->input_test($value['value']);
					if($db_correct_dates) {
						if(stripos($this_name, 'date') !== false) {
							if(strlen($this_value) >= 13) {
								// Assume this is with time
								$this_value = $sop->datetime_to_db($this_value);
							} else {
								// Assume this is only date
								$this_value = $sop->date_to_db($this_value);
							}
						}
					}
					
					if(isset($returndata[$this_name])) {
						if(is_array($returndata[$this_name])) {
							$returndata[$this_name][] = $this_value;
						} else {
							$tmp_value = $returndata[$this_name];
							unset($returndata[$this_name]);
							$returndata[$this_name] = array();
							$returndata[$this_name][] = $tmp_value;
							$returndata[$this_name][] = $this_value;
						}
					} else {
						$returndata[$this_name] = $this_value;
					}
				} else {
					foreach($value as $this_value) {
						$this_value = $sop->input_test($this_value);
						if($db_correct_dates) {
							if($sop->is_date($this_value) !== false) {
								if(strlen($this_value) >= 13) {
									// Assume this is with time
									$this_value = $sop->datetime_to_db($this_value);
								} else {
									// Assume this is only date
									$this_value = $sop->date_to_db($this_value);
								}
							}
						}
						
						$returndata[$key][] = $this_value;
					}
				}
			} else {
				$this_value = $sop->input_test($value);
				if($db_correct_dates) {
					if(stripos($key, 'date') !== false) {
						if(strlen($this_value) >= 13) {
							// Assume this is with time
							$this_value = $sop->datetime_to_db($this_value);
						} else {
							// Assume this is only date
							$this_value = $sop->date_to_db($this_value);
						}
					}
				}
				$returndata[$key] = $this_value;
			}
		}
	}

	RETURN $returndata;
}


?>