<?php
// DEBUG
if ( ! function_exists( 'pre_print_r' ) ) {
	function pre_print_r( $var ) {
		echo '<pre style="text-align: left; white-space: pre-wrap;">';
			print_r( $var );
		echo '</pre>';
	}
}

if ( ! function_exists( 'pre_var_dump' ) ) {
	function pre_var_dump( $var ) {
		echo '<pre style="text-align: left; white-space: pre-wrap;">';
			var_dump( $var );
		echo '</pre>';
	}
}

if ( ! function_exists( 'write_log' ) ) {
	function write_log ( $log )  {
		if ( is_array( $log ) || is_object( $log ) ) {
			error_log( print_r( $log, true ) );
		} else {
			error_log( $log );
		}
	}
}

// HOST
if ( ! function_exists( 'wpj_get_host' ) ) {
	function wpj_get_host() {
		$possibleHostSources = ['HTTP_X_FORWARDED_HOST', 'HTTP_HOST', 'SERVER_NAME', 'SERVER_ADDR'];

		$sourceTransformations = [
			"HTTP_X_FORWARDED_HOST" => function( $value ) {
				$elements = explode( ',', $value );

				return trim( end( $elements ) );
			}
		];

		$host = '';

		foreach ( $possibleHostSources as $source ) {
			if ( ! empty( $host ) ) break;

			if ( empty( $_SERVER[$source] ) ) continue;

			$host = $_SERVER[$source];

			if ( array_key_exists( $source, $sourceTransformations ) ) {
				$host = $sourceTransformations[$source]( $host );
			}
		}

		// Remove port number from host
		$host = preg_replace( '/:\d+$/', '', $host );

		return trim( $host );
	}
}

if ( ! function_exists( 'wpj_get_host_without_www' ) ) {
	function wpj_get_host_without_www() {
		$host = wpj_get_host();

		if ( substr( $host, 0, 4 ) == 'www.' ) {
			$domain = substr( $host, 4 );

		} else {
			$domain = $host;

		}

		return trim( $domain );
	}
}

if ( ! function_exists( 'wpj_add_content_to_htaccess' ) ) {
	function wpj_add_content_to_htaccess( $file_name = ".htaccess", $code_desc = "WPJ htaccess", $content = [] ) {
		try {
			if ( file_exists(  ABSPATH . 'wp-admin/includes/file.php' ) ) {
				require_once( ABSPATH . 'wp-admin/includes/file.php' );
			}

			if ( file_exists(  ABSPATH . 'wp-admin/includes/misc.php' ) ) {
				require_once( ABSPATH . 'wp-admin/includes/misc.php' );
			}

			if ( function_exists( 'get_home_path' ) && function_exists( 'insert_with_markers' ) && $content ) {
				$file_path = get_home_path() . $file_name;
				return insert_with_markers( $file_path, $code_desc, $content );

			} else {
				return 'We can\'t find the path to your files. Contact support';

			}

		} catch ( Exception $e ) {
			return strtoupper( $code_desc ) . '. We couldn\'t load the code. Contact support.';

		}
	}
}

if ( ! function_exists( 'wpj_get_user_ip' ) ) {
	function wpj_get_user_ip() {
		if ( ! empty( $_SERVER['HTTP_CLIENT_IP'] ) ) {
			$ip = $_SERVER['HTTP_CLIENT_IP'];

		} elseif ( ! empty( $_SERVER['HTTP_X_FORWARDED_FOR'] ) ) {
			$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];

		} else {
			$ip = $_SERVER['REMOTE_ADDR'];

		}

		return $ip;
	}
}

// RANDOM
if ( ! function_exists( 'wpj_generate_random_value' ) ) {
	function wpj_generate_random_value( $length, $type = 'alphanumeric' ) {
		if ( $type == 'alpha' ) $characters = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
		elseif ( $type == 'alpha_lower' ) $characters = 'abcdefghijklmnopqrstuvwxyz';
		elseif ( $type == 'alpha_upper' ) $characters = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
		elseif ( $type == 'numeric' ) $characters = '0123456789';
		else $characters = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';

		$random = '';

		for ( $i = 0; $i < $length; $i++ ) {
			$random .= $characters[rand( 0, strlen( $characters ) - 1)];
		}

		return $random;
	}
}

if ( ! function_exists( 'wpj_crypto_rand_secure' ) ) {
	function wpj_crypto_rand_secure( $min, $max ) {
		$range = $max - $min;

		if ( $range < 0 ) return $min; // not so random...

		$log    = log( $range, 2 );
		$bytes  = ( int ) ( $log / 8 ) + 1; // length in bytes
		$bits   = ( int ) $log + 1; // length in bits
		$filter = ( int ) ( 1 << $bits ) - 1; // set all lower bits to 1

		do {
			$rnd = hexdec( bin2hex( openssl_random_pseudo_bytes( $bytes ) ) );
			$rnd = $rnd & $filter; // discard irrelevant bits
		} while ( $rnd >= $range );

		return $min + $rnd;
	}
}

// URL
if ( ! function_exists( 'wpj_url_exist' ) ) {
	function wpj_url_exist( $url = '' ) {
		$curl = curl_init( $url );

		curl_setopt( $curl, CURLOPT_NOBODY, true );

		$result = curl_exec( $curl);

		if ( $result !== false ) {
			$statusCode = curl_getinfo( $curl, CURLINFO_HTTP_CODE );

			if ( $statusCode == 404 ) {
				$exists = false;

			} else {
				$exists = true;

			}

		} else {
			$exists = false;

		}

		return $exists;
	}
}

if ( ! function_exists( 'wpj_url_is_image' ) ) {
	function wpj_url_is_image( $url = '' ) {
		if ( $url ) {
			// this is quite slow, not recommended to use during the pageload
			if ( ini_get( 'allow_url_fopen' ) && is_array( getimagesize( $url ) ) ) {
				return true;

			} else {
				$curl = curl_init();

				curl_setopt_array( $curl, [
					CURLOPT_URL            => $url,
					CURLOPT_CUSTOMREQUEST  => 'GET',
					CURLOPT_RETURNTRANSFER => false,
					CURLOPT_NOBODY         => true
				] );

				curl_exec( $curl );

				if ( ! curl_errno( $curl ) ) {
					$header = curl_getinfo( $curl, CURLINFO_CONTENT_TYPE );

				} else {
					return false;

				}

				curl_close( $curl );

				if ( strpos( $header, 'image/' ) !== false ) {
					return true;

				}

			}
		}

		return false;
	}
}

if ( ! function_exists( 'wpj_parameter_exist' ) ) {
	function wpj_parameter_exist( $parameter, $has_value = 'yes' ) {
		if ( $has_value && $has_value != '' && $has_value != 'no' ) {
			if ( isset( $_GET[$parameter] ) && $_GET[$parameter] && $_GET[$parameter] != '' ) {
				return 1;

			} else {
				return 0;

			}

		} else {
			if ( isset( $_GET[$parameter] ) ) {
				return 1;

			} else {
				return 0;

			}

		}
	}
}

if ( ! function_exists( 'wpj_get_data_with_cURL' ) ) {
	function wpj_get_data_with_cURL( $url, $post_data = false, $http_header = false ) {
		if ( function_exists( 'curl_init' ) && function_exists( 'curl_setopt' ) && function_exists( 'curl_exec' ) ) {
			$ch = curl_init();

			curl_setopt( $ch, CURLOPT_URL, $url );
			curl_setopt( $ch, CURLOPT_HEADER, false );
			curl_setopt( $ch, CURLOPT_RETURNTRANSFER, true );
			curl_setopt( $ch, CURLOPT_TIMEOUT, 60 );
			curl_setopt( $ch, CURLOPT_SSL_VERIFYPEER, false );

			if ( $http_header ) curl_setopt( $ch, CURLOPT_HTTPHEADER, ( is_array( $http_header ) ? $http_header : [$http_header] ) );
			if ( $post_data ) curl_setopt( $ch, CURLOPT_POSTFIELDS, $post_data );

			$response = curl_exec( $ch );

			curl_close( $ch );

		} else {
			$response = file_get_contents( $url );

		}

		return trim( $response );

	}
}

// FOLDERS
if ( ! function_exists( 'wpj_copy_directory' ) ) {
	function wpj_copy_directory( $src, $dst ) {
		$dir = opendir( $src );

		@mkdir( $dst );

		while ( false !== ( $file = readdir( $dir ) ) ) {
			if ( ( $file != '.' ) && ( $file != '..' ) ) {
				if ( is_dir( $src . '/' . $file ) ) {
					wpj_copy_directory( $src . '/' . $file, $dst . '/' . $file );

				} else {
					copy( $src . '/' . $file,$dst . '/' . $file );

				}
			}
		}

		closedir( $dir );
	}
}

if ( ! function_exists( 'wpj_scan_folders' ) ) {
	function wpj_scan_folders( $path = '', $return = [] ) {
		$path  = $path == '' ? dirname( __FILE__ ) : $path;
		$lists = @scandir( $path );

		if ( ! empty( $lists ) ) {
			foreach ( $lists as $f ) {
				if ( is_dir( $path . DIRECTORY_SEPARATOR . $f ) && $f != "." && $f != ".." ) {
					if ( ! in_array( $path . DIRECTORY_SEPARATOR . $f, $return ) )
						$return[] = trailingslashit( $path . DIRECTORY_SEPARATOR . $f );

					wpj_scan_folders( $path . DIRECTORY_SEPARATOR . $f, $return);
				}
			}
		}

		return $return;
	}
}

// TEXT
if ( ! function_exists( 'wpj_get_parsed_countable_string' ) ) {
	function wpj_get_parsed_countable_string( $raw_string ) {
		$msg  = wpj_stripslashes( $raw_string );
		$msg1 = str_replace( ["\r\n","\n\r"], " ", $msg );

		return str_replace( ["\n"], " ", $msg1 );
	}
}

if ( ! function_exists( 'wpj_trim' ) ) {
	function wpj_trim( $text, $len = 150, $more = '...' ) {
		// wp_trim_words sucks because it counts the words
		// mb_strimwidth counts the characters but cuts words
		// wpj_trim counts the characters and doesn't cut words
		// when the text contains one word only, the word is cut if needed

		$parts = explode( ' ', $text );
		$ic    = count( $parts );
		$tx    = '';
		$txt   = '';

		for ( $i = 0; $i < $ic; $i++ ) {
			$tx   = $txt;
			$txt .= $parts[$i] . ' ';

			if ( mb_strlen( $txt ) >= $len ) {
				break;
			}
		}

		$tx  = trim( $tx );
		$txt = trim( $txt );

		if ( mb_strlen( $text ) > $len ) {
			if ( $i == 0 ) {
				$txt = mb_strimwidth( $txt, 0, $len, $more );

			} else {
				$txt = $tx . $more;

			}
		}

		return $txt;
	}
}

/**
* Truncates text.
*
* Cuts a string to the length of $length and replaces the last characters
* with the ending if the text is longer than length.
*
* ### Options:
*
* - 'ending' Will be used as Ending and appended to the trimmed string
* - 'exact' If false, $text will not be cut mid-word
* - 'html' If true, HTML tags would be handled correctly
*/
if ( ! function_exists( 'wpj_truncate_html' ) ) {
	function wpj_truncate_html( $text, $length = 100, $options = [] ) {
		$default = ['ending' => '...', 'exact' => true, 'html' => true];

		$options = array_merge( $default, $options );

		/**
		 * @var string $ending
		 * @var bool $exact
		 * @var bool $html
		 */
		extract( $options );

		if ( $html ) {
			if ( mb_strlen( preg_replace( '/<.*?>/', '', $text ) ) <= $length )
				return $text;

			$totalLength = mb_strlen( strip_tags( $ending ) );
			$openTags    = [];
			$truncate    = '';

			preg_match_all( '/(<\/?([\w+]+)[^>]*>)?([^<>]*)/', $text, $tags, PREG_SET_ORDER );

			foreach ( $tags as $tag ) {
				if ( ! preg_match( '/img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param/s', $tag[2] ) ) {
					if ( preg_match('/<[\w]+[^>]*>/s', $tag[0] ) ) {
						array_unshift( $openTags, $tag[2] );

					} else if ( preg_match('/<\/([\w]+)[^>]*>/s', $tag[0], $closeTag ) ) {
						$pos = array_search( $closeTag[1], $openTags );

						if ( $pos !== false ) {
							array_splice( $openTags, $pos, 1 );
						}

					}
				}

				$truncate .= $tag[1];

				$contentLength = mb_strlen( preg_replace( '/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $tag[3] ) );

				if ( $contentLength + $totalLength > $length ) {
					$left = $length - $totalLength;
					$entitiesLength = 0;

					if ( preg_match_all( '/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $tag[3], $entities, PREG_OFFSET_CAPTURE ) ) {
						foreach ( $entities[0] as $entity ) {
							if ( $entity[1] + 1 - $entitiesLength <= $left ) {
								$left--;
								$entitiesLength += mb_strlen( $entity[0] );

							} else {
								break;

							}
						}
					}

					$truncate .= mb_substr( $tag[3], 0 , $left + $entitiesLength );

					break;

				} else {
					$truncate    .= $tag[3];
					$totalLength += $contentLength;

				}

				if ( $totalLength >= $length )
					break;

			}

		} else {
			if ( mb_strlen( $text ) <= $length ) {
				return $text;

			} else {
				$truncate = mb_substr( $text, 0, $length - mb_strlen( $ending ) );

			}

		}

		if ( ! $exact ) {
			$spacepos = mb_strrpos( $truncate, ' ' );

			if ( isset( $spacepos ) ) {
				if ( $html ) {
					$bits = mb_substr( $truncate, $spacepos );

					preg_match_all( '/<\/([a-z]+)>/', $bits, $droppedTags, PREG_SET_ORDER );

					if ( ! empty( $droppedTags ) ) {
						foreach ( $droppedTags as $closingTag ) {
							if ( ! in_array( $closingTag[1], $openTags ) ) {
								array_unshift( $openTags, $closingTag[1] );
							}
						}
					}
				}

				$truncate = mb_substr( $truncate, 0, $spacepos );

			}
		}

		$truncate .= $ending;

		if ( $html ) {
			foreach ( $openTags as $tag ) {
				$truncate .= '</' . $tag . '>';
			}
		}

		return $truncate;
	}
}

if ( ! function_exists( 'wpj_number_to_string' ) ) {
	function wpj_number_to_string( $n ) {
		$strings = ['zero', 'one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine', 'ten'];

		if ( 0 <= $n && $n <= 10 ) {
			return $strings[$n];
		}

		return $n;
	}
}

if ( ! function_exists( 'wpj_truncate_text' ) ) {
	function wpj_truncate_text( $text = '', $max_length = 250 ) {
		$tags   = [];
		$result = '';

		$is_open          = false;
		$grab_open        = false;
		$is_close         = false;
		$in_double_quotes = false;
		$in_single_quotes = false;
		$tag              = '';

		$i        = 0;
		$stripped = 0;

		$stripped_text = strip_tags( $text );

		while ( $i < strlen( $text ) && $stripped < strlen( $stripped_text ) && $stripped < $max_length ) {
			$symbol  = $text[$i];
			$result .= $symbol;

			switch ( $symbol ) {
				case '<':
					$is_open   = true;
					$grab_open = true;

					break;

				case '"':
					if ( $in_double_quotes )
						$in_double_quotes = false;
					else
						$in_double_quotes = true;

					break;

				case "'":
					if ( $in_single_quotes )
						$in_single_quotes = false;
					else
						$in_single_quotes = true;

					break;

				case '/':
					if ( $is_open && ! $in_double_quotes && ! $in_single_quotes ) {
						$is_close  = true;
						$is_open   = false;
						$grab_open = false;
					}

					break;

				case ' ':
					if ( $is_open )
						$grab_open = false;
					else
						$stripped++;

					break;

				case '>':
					if ( $is_open ) {
						$is_open   = false;
						$grab_open = false;

						array_push( $tags, $tag );

						$tag = "";

					} elseif ( $is_close ) {
						$is_close = false;

						array_pop( $tags );

						$tag = "";

					}

					break;

				default:
					if ( $grab_open || $is_close )
						$tag .= $symbol;

					if ( ! $is_open && ! $is_close )
						$stripped++;
			}

			$i++;
		}

		while ( $tags )
			$result .= "</" . array_pop( $tags ) . ">";

		return $result;
	}
}

if ( ! function_exists( 'wpj_date_number_to_string' ) ) {
	function wpj_date_number_to_string( $number ) {
		if ( $number == 1 ) { return __( 'January', 'wpjobster' ); }
		elseif ( $number == 2 ) { return __( 'February', 'wpjobster' ); }
		elseif ( $number == 3 ) { return __( 'March', 'wpjobster' ); }
		elseif ( $number == 4 ) { return __( 'April', 'wpjobster' ); }
		elseif ( $number == 5 ) { return __( 'May', 'wpjobster' ); }
		elseif ( $number == 6 ) { return __( 'June', 'wpjobster' ); }
		elseif ( $number == 7 ) { return __( 'July', 'wpjobster' ); }
		elseif ( $number == 8 ) { return __( 'August', 'wpjobster' ); }
		elseif ( $number == 9 ) { return __( 'September', 'wpjobster' ); }
		elseif ( $number == 10 ) { return __( 'October', 'wpjobster' ); }
		elseif ( $number == 11 ) { return __( 'November', 'wpjobster' ); }
		elseif ( $number == 12 ) { return __( 'December', 'wpjobster' ); }

		return false;
	}
}

if ( ! function_exists( 'wpj_date_number_to_string_short' ) ) {
	function wpj_date_number_to_string_short( $number ) {
		if ( $number == 1 ) { return __( 'Jan', 'wpjobster' ); }
		elseif ( $number == 2 ) { return __( 'Feb', 'wpjobster' ); }
		elseif ( $number == 3 ) { return __( 'Mar', 'wpjobster' ); }
		elseif ( $number == 4 ) { return __( 'Apr', 'wpjobster' ); }
		elseif ( $number == 5 ) { return __( 'May', 'wpjobster' ); }
		elseif ( $number == 6 ) { return __( 'Jun', 'wpjobster' ); }
		elseif ( $number == 7 ) { return __( 'Jul', 'wpjobster' ); }
		elseif ( $number == 8 ) { return __( 'Aug', 'wpjobster' ); }
		elseif ( $number == 9 ) { return __( 'Sep', 'wpjobster' ); }
		elseif ( $number == 10 ) { return __( 'Oct', 'wpjobster' ); }
		elseif ( $number == 11 ) { return __( 'Nov', 'wpjobster' ); }
		elseif ( $number == 12 ) { return __( 'Dec', 'wpjobster' ); }

		return false;
	}
}

if ( ! function_exists( 'wpj_change_rate_word' ) ) {
	function wpj_change_rate_word( $word = '', $word_type = 'singular' ) {
		if ( $word == 'hourly' ) {
			if ( $word_type == 'plural' ) { return __( 'hours', 'wpjobster' ); }
			else { return __( 'hour', 'wpjobster' ); }
		}

		if ( $word == 'daily' ) {
			if ( $word_type == 'plural' ) { return __( 'days', 'wpjobster' ); }
			else { return __( 'day', 'wpjobster' ); }
		}

		if ( $word == 'weekly' ) {
			if ( $word_type == 'plural' ) { return __( 'weeks', 'wpjobster' ); }
			else { return __( 'week', 'wpjobster' ); }
		}

		if ( $word == 'monthly' ) {
			if ( $word_type == 'plural' ) { return __( 'months', 'wpjobster' ); }
			else { return __( 'month', 'wpjobster' ); }
		}

		return $word;
	}
}

if ( ! function_exists( 'wpj_filter_words' ) ) {
	function wpj_filter_words( $text, $words, $replace = true ) {
		$escaped = [];

		foreach ( $words as $w ) {
			array_push( $escaped, preg_quote( $w, '/' ) );
		}

		$re = '/(?:[[:space:]]|^)(' . implode( '|', $escaped ) . ')(?:[^\w]|$)/i';

		preg_match_all( $re, $text, $matches, PREG_SET_ORDER );

		$matchesCount = is_array( $matches ) ? count( $matches ) : 0;

		$status = 0;

		for ( $i = 0; $i < $matchesCount; $i++ ) {
			if ( $replace ) {
				$text = str_replace( $matches[$i][0], '*****', $text );
			}

			$status = 1;
		}

		return [$text, $status];
	}
}

if ( ! function_exists( 'wpj_get_string_between' ) ) {
	function wpj_get_string_between( $string, $start, $end ) {
		$string = ' ' . $string;

		$ini = strpos( $string, $start );

		if ( $ini == 0 ) return '';

		$ini += strlen( $start );

		$len = strpos( $string, $end, $ini ) - $ini;

		return trim( substr( $string, $ini, $len ) );
	}
}

if ( ! function_exists( 'wpj_replace_string_between' ) ) {
	function wpj_replace_string_between( $string, $start, $end, $replacement ) {
		$startPos = strpos( $string, $start );
		$endPos = strpos( $string, $end, $startPos );

		if ( $startPos !== false && $endPos !== false ) {
			return substr_replace( $string, $start . ' ' . $replacement . ' ' . $end, $startPos, $endPos + strlen( $end ) - $startPos );
		}

		return $string;
	}
}

if ( ! function_exists( 'wpj_replace_first_occurance' ) ) {
	function wpj_replace_first_occurance( $search, $replace, $subject ) {
		$search = '/' . preg_quote( $search, '/' ) . '/';

		return preg_replace( $search, $replace, $subject, 1 );
	}
}

if ( ! function_exists( 'wpj_br_to_nl' ) ) {
	function wpj_br_to_nl( $string ) {
		return preg_replace( '/<br\s?\/?>/ius', "\n", str_replace( "\n", "", str_replace( "\r", "", htmlspecialchars_decode( $string ) ) ) );
	}
}

if ( ! function_exists( 'wpj_nl_to_space' ) ) {
	function wpj_nl_to_space( $string ) {
		return preg_replace('/\s+/', ' ', $string);
	}
}

if ( ! function_exists( 'wpj_stripslashes' ) ) {
	function wpj_stripslashes( $string ) {
		if ( $string ) {
			if ( is_array( $string ) ) {
				$string = array_map( 'stripslashes', $string );

			} else {
				$string = stripslashes( $string );

			}
		}

		return $string;
	}
}

// DATETIME
if ( ! function_exists( 'wpj_is_timestamp' ) ) {
	function wpj_is_timestamp( $timestamp = '' ) {
		return ( ( string ) ( int ) $timestamp === $timestamp )
			&& ( $timestamp <= PHP_INT_MAX )
			&& ( $timestamp >= ~PHP_INT_MAX );
	}
}

if ( ! function_exists( 'wpj_get_midnight_date_timestamp' ) ) {
	function wpj_get_midnight_date_timestamp( $timestamp ) {
		return strtotime( wpj_date( "d-m-Y 00:00:00", $timestamp ) );
	}
}

if ( ! function_exists( 'wpj_get_unix_timestamp' ) ) {
	function wpj_get_unix_timestamp( $date ) {
		try {
			$ret_date = new DateTime( $date );

			return $ret_date->getTimestamp();
		} catch ( Exception $e ) {}

		return $date;
	}
}

// DATE TO TEXT
if ( ! function_exists( 'wpj_seconds_to_words_joined' ) ) {
	function wpj_seconds_to_words_joined( $seconds ) {

		if ( $seconds < 0 ) return false;

		$years  = ( int ) ( $seconds / ( 365 * 24 * 60 * 60 ) );
		$months = ( int ) ( $seconds / ( 30 * 24 * 60 * 60 ) );
		$days   = ( int ) ( $seconds / ( 24 * 60 * 60 ) );

		$years_word  = _n( "year", "years", $years, "wpjobster" );
		$months_word = _n( "month", "months", $months, "wpjobster" );
		$days_word   = _n( "day", "days", $days, "wpjobster" );

		if ( $days <= 0 ) {
			return __( "today", "wpjobster" );
		}

		if ( $months <= 0 ) {
			return $days . ' ' . $days_word;
		}

		if ( $years <= 0 ) {
			return $months . ' ' . $months_word;
		}

		if ( ( $months % 12 ) <= 0 ) {
			return $years . ' ' . $years_word;
		}

		return $years . ' ' . $years_word . ', ' . ( $months % 12 ) . ' ' . $months_word;
	}
}

if ( ! function_exists( 'wpj_seconds_to_words' ) ) {
	function wpj_seconds_to_words( $seconds, $short = false, $one_interval = false ) {
		$ret = '';

		/*** get the years ***/
		$years = intval( intval( $seconds ) / ( 3600 * 24 * 30 * 12 ) );

		if ( $years > 0 ) {
			$ret .= sprintf( _n( '%d year ', '%d years ', $years, 'wpjobster' ), $years );

			if ( $short ) return sprintf( __( '%dy ', 'wpjobster' ), $years );
			if ( $one_interval ) return sprintf( _n( '%d year ago ', '%d years ago ', $years, 'wpjobster' ), $years );
		}

		/*** get the months ***/
		$months = intval( intval( $seconds ) / ( 3600 * 24 * 30 ) );

		if ( $months > 0 ) {
			$ret .= sprintf( _n( '%d month ', '%d months ', $months, 'wpjobster' ), $months );

			if ( $short ) return sprintf( __( '%dmo ', 'wpjobster' ), $months );
			if ( $one_interval ) return sprintf( _n( '%d month ago ', '%d months ago ', $months, 'wpjobster' ), $months );
		}

		/*** get the weeks ***/
		$weeks = intval( intval( $seconds ) / ( 3600 * 24 * 7 ) );

		if ( $weeks > 0 ) {
			$ret .= sprintf( _n( '%d week ', '%d weeks ', $weeks, 'wpjobster' ), $weeks );

			if ( $short ) return sprintf( __( '%dw ', 'wpjobster' ), $weeks );
			if ( $one_interval ) return sprintf( _n( '%d week ago ', '%d weeks ago ', $weeks, 'wpjobster' ), $weeks );
		}

		/*** get the days ***/
		$days = intval( intval( $seconds ) / ( 3600 * 24 ) );

		if ( $days > 0 ) {
			$ret .= sprintf( _n( '%d day ', '%d days ', $days, 'wpjobster' ), $days );

			if ( $short ) return sprintf( __( '%dd ', 'wpjobster' ), $days );
			if ( $one_interval ) return sprintf( _n( '%d day ago ', '%d days ago ', $days, 'wpjobster' ), $days );
		}

		/*** get the hours ***/
		$hours = intval( intval( intval( $seconds ) / 3600 ) % 24 );

		if ( $hours > 0 ) {
			$ret .= sprintf( _n( '%dh ', '%dhs ', $hours, 'wpjobster' ), $hours );

			if ( $short ) return sprintf( __( '%dh ', 'wpjobster' ), $hours );
			if ( $one_interval ) return sprintf( _n( '%dh ago ', '%dhrs ago ', $hours, 'wpjobster' ), $hours );
		}

		/*** get the minutes ***/
		$minutes = intval( intval( intval( $seconds ) / 60 ) % 60 );

		if ( $minutes > 0 ) {
			$ret .= sprintf( _n( '%dmin ', '%dmins ', $minutes, 'wpjobster' ), $minutes );

			if ( $short ) return sprintf( __( '%dm ', 'wpjobster' ), $minutes );
			if ( $one_interval ) return sprintf( _n( '%dmin ago ', '%dmins ago ', $minutes, 'wpjobster' ), $minutes );
		}

		/*** get the seconds ***/
		$seconds = intval( intval( $seconds ) % 60 );

		if ( $seconds > 0 && $minutes <= 0 ) {
			$ret .= sprintf( _n( '%d second', '%d seconds', $seconds, 'wpjobster' ), $seconds );

			if ( $short ) return sprintf( __( '%ds ', 'wpjobster' ), $seconds );
			if ( $one_interval ) return sprintf( _n( '%d second ago', '%d seconds ago', $seconds, 'wpjobster' ), $seconds );
		}

		return $ret;
	}
}

// MEDIA
if ( ! function_exists( 'wpj_get_token' ) ) {
	function wpj_get_token( $length = 32 ) {
		$token = "";
		$codeAlphabet  = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
		$codeAlphabet .= "abcdefghijklmnopqrstuvwxyz";
		$codeAlphabet .= "0123456789";

		for ( $i = 0; $i < $length; $i++ ) {
			$token .= $codeAlphabet[wpj_crypto_rand_secure( 0, strlen( $codeAlphabet ) )];
		}

		return '&auth_token=' . $token;
	}
}

if ( ! function_exists( 'wpj_get_video_type' ) ) {
	function wpj_get_video_type( $url ) {
		$url = parse_url( $url );

		if ( $url['host'] == 'youtube.com'
			|| $url['host'] == 'www.youtube.com'
			|| $url['host'] == 'youtu.be'
			|| $url['host'] == 'www.youtu.be' ) {
			return 'youtube';

		} elseif ( $url['host'] == 'vimeo.com' ) {
			return 'vimeo';

		} else {
			return 'unknown';
		}
	}
}

if ( ! function_exists( 'wpj_make_links_clickable' ) ) {
	function wpj_make_links_clickable( $text, $class = '', $target = '_blank' ) {
		return preg_replace( '/\b(?<!=")(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|!:,.;]*[A-Z0-9+&@#\/%=~_|](?!.*".*>)(?!.*<\/a>)/i', '<a href="\0" rel="nofollow" target="' . $target . '" class="' . $class . '">\0</a>', $text );
	}
}

// FORM
if ( ! function_exists( 'wpj_list_select_options' ) ) {
	function wpj_list_select_options( $a, $sel = "", $def = "" ) {
		if ( ! $sel && $def ) $sel = $def;

		foreach ( $a as $k => $v ) { ?>

			<option value="<?php echo $k ?>" <?php if ( $sel == $k ) { echo "selected='selected'"; } ?>>

				<?php echo $v ?>

			</option>

		<?php }
	}
}

if ( ! function_exists( 'wpj_get_selected_value' ) ) {
	function wpj_get_selected_value( $val1, $val2 ) {
		return $val1 == $val2 ? 'selected=selected' : '';
	}
}

if ( ! function_exists( 'wpj_validate_input_content' ) ) {
	function wpj_validate_input_content( $input ) {
		return nl2br( strip_tags( htmlspecialchars( $input ) ) );
	}
}

// FUNCTION
if ( ! function_exists( 'wpj_function_has_content' ) ) {
	function wpj_function_has_content( $function_name, $args = [] ) {
		ob_start();

		if ( function_exists( $function_name ) ) {
			if ( $args ) call_user_func_array( $function_name, $args );
			else call_user_func( $function_name );
		}

		$output = ob_get_clean();

		if ( ! $output || strpos( $output, '<style>' ) !== false ) return false;
		return true;
	}
}

// CSS
if ( ! function_exists( 'wpj_minify_css' ) ) {
	function wpj_minify_css( $file ) {
		// Remove comments
		$file = preg_replace( '!/\*[^*]*\*+([^/][^*]*\*+)*/!', '', $file );

		// Minify
		$file = preg_replace( '/\/\*((?!\*\/).)*\*\//', '', $file );
		$file = preg_replace( '/\s{2,}/', ' ', $file );
		$file = preg_replace( '/\s*([:;{}])\s*/', '$1', $file );
		$file = preg_replace( '/;}/', '}', $file );

		// Minify 2
		$minified = $file;
		$minified = str_replace( "\n", "", $minified );
		$minified = str_replace( "  ", " ", $minified );
		$minified = str_replace( "  ", " ", $minified );
		$minified = str_replace( " {", "{", $minified );
		$minified = str_replace( "{ ", "{", $minified );
		$minified = str_replace( " }", "}", $minified );
		$minified = str_replace( "} ", "}", $minified );
		$minified = str_replace( ", ", ",", $minified );
		$minified = str_replace( "; ", ";", $minified );
		$minified = str_replace( ": ", ":", $minified );

		return $minified;
	}
}