<?php
//master color: #46EBD5, #00D0B6; #005DE0; #3388FF
ini_set("display_errors", 1);
ini_set("display_startup_errors", 1);
ini_set("error_reporting", E_ALL & ~E_NOTICE);
date_default_timezone_set("Asia/Bangkok");
setlocale(LC_TIME, "id_ID");
function gpc($value)
{
$value = str_replace("'", "\'", $value);
//return ((!get_magic_quotes_gpc()) ? addslashes($value) : $value);
return $value;
}
function dec($l)
{
$l = number_format($l, 2, ",", ".");
return $l;
}
function nodec($l)
{
$l = number_format($l, 0, "", "");
return $l;
}
function ang($l)
{
$l = number_format($l, 0, ",", ".");
return $l;
}
function ang2($l)
{
$l = number_format($l, 0, ".", ",");
return $l;
}
function CommaToDot($grade)
{
$grade = str_replace(",", ".", $grade);
return $grade;
}
function imgdl($imageUrl, $savePath)
{
$dt = [];
// Initialize cURL session
$ch = curl_init($imageUrl);
// Open a file pointer to save the image
$fp = fopen($savePath, "wb");
// Set cURL options
curl_setopt($ch, CURLOPT_FILE, $fp); // Write the response directly to the file pointer
curl_setopt($ch, CURLOPT_HEADER, 0); // Exclude header information from being written
// Execute the cURL session
curl_exec($ch);
// Check for cURL errors
if (curl_errno($ch)) {
$dt["error"] = true;
$dt["message"] = "cURL error: " . curl_error($ch);
} else {
$dt["success"] = $dt["status"] = true;
$dt["message"] = "Image downloaded successfully";
}
// Close cURL session and file pointer
curl_close($ch);
fclose($fp);
return $dt;
}
function copyimg($file, $newfile)
{
if (copy($file, $newfile)) {
echo "<br>Copy <b>$file</b> success!<br>";
} else {
echo "<br>Copy <b>$file</b> failed.<br>";
}
}
//Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:68.0) Gecko/20100101 Firefox/68.0
//103.13.181.30
function getimg($url)
{
$headers[] = "Accept: image/gif, image/x-bitmap, image/jpeg, image/pjpeg";
$headers[] = "Connection: Keep-Alive";
$headers[] = "Content-type: application/x-www-form-urlencoded;charset=UTF-8";
$user_agent = "php";
$process = curl_init($url);
curl_setopt($process, CURLOPT_HTTPHEADER, $headers);
curl_setopt($process, CURLOPT_HEADER, 0);
curl_setopt($process, CURLOPT_USERAGENT, $user_agent); //check here
curl_setopt($process, CURLOPT_TIMEOUT, 30);
curl_setopt($process, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($process, CURLOPT_FOLLOWLOCATION, 1);
$return = curl_exec($process);
curl_close($process);
return $return;
}
function to_numeric($ang)
{
$sid = preg_replace("/[^0-9]/", "", $ang);
return $sid;
}
function NoSpace($ang)
{
$sid = preg_replace("/[^A-Za-z0-9]/", "", $ang);
return $sid;
}
function to_hp($ang)
{
$sid = preg_replace("/[^0-9]/", "", $ang);
$awalan = substr($sid, 0, 2);
if ($awalan == "08") {
$newhp = "628" . substr($sid, 2);
} else {
$newhp = $sid;
}
return $newhp;
}
//list foto by modul, by item_id
function viewImage($modul, $item_id)
{
global $db, $ar;
$sql2 =
"SELECT * FROM `files` WHERE modul='" .
$modul .
"' and item_id='" .
$item_id .
"' and `type`='image' ";
$run2 = mysqli_query($db, $sql2);
$ret = "<hr><h3>Images</h3><div class='row mb-20 pb-20'>";
while ($r2 = mysqli_fetch_assoc($run2)) {
$img_small =
$modul .
"/" .
$r2["path"] .
"/" .
$r2["seq"] .
"/image/small/" .
$r2["url"];
$img_big =
$modul .
"/" .
$r2["path"] .
"/" .
$r2["seq"] .
"/image/big/" .
$r2["url"];
$ret .= '
<div class="col-sm-3 col-lg-2 col-xs-6">
<div class="card">
';
$ret .= '<img src="' . $ar["url_img"] . "" . $img_small . '" alt="">';
$ret .= "";
$ret .= '
</div>
</div>';
}
$ret .= "</div>";
return $ret;
}
# Insert Data
function Insert($mysqli, $table, $data, $v = 0)
{
//global $mysqli;
//print_r($data);
$fields = array_keys($data);
$values = array_map([$mysqli, "real_escape_string"], array_values($data));
if ($v == 1) {
echo "INSERT INTO $table(`" .
implode("`,`", $fields) .
"`) VALUES ('" .
implode("','", $values) .
"');";
}
//exit;
mysqli_query(
$mysqli,
"INSERT INTO $table(`" .
implode("`,`", $fields) .
"`) VALUES ('" .
implode("','", $values) .
"');"
) or die(mysqli_error($mysqli));
}
// Update Data, Where clause is left optional
function InsertUpdate($mysqli, $table_name, $i_data, $u_data, $v = 0)
{
//global $mysqli;
// check for optional where clause
$i_fields = array_keys($i_data);
$i_values = array_map([$mysqli, "real_escape_string"], array_values($i_data));
$u_fields = array_keys($u_data);
$u_values = array_map([$mysqli, "real_escape_string"], array_values($u_data));
$sql =
"INSERT INTO $table_name (`" .
implode("`,`", $i_fields) .
"`) VALUES ('" .
implode("','", $i_values) .
"') ";
// start the actual SQL statement
$sql .= " on duplicate key UPDATE ";
// loop and build the column /
$sets = [];
foreach ($u_data as $column => $value) {
$sets[] = "`" . $column . "` = '" . $value . "'";
}
$sql .= implode(", ", $sets);
// append the where statement
//$sql .= $whereSQL;
// run and return the query result
//echo $sql;
if ($v == 1) {
echo $sql . ";<br>";
}
return mysqli_query($mysqli, $sql);
}
// Update Data, Where clause is left optional
function Update($mysqli, $table_name, $form_data, $where_clause = "", $v = 0)
{
//global $mysqli;
// check for optional where clause
$whereSQL = "";
if (!empty($where_clause)) {
// check to see if the 'where' keyword exists
if (substr(strtoupper(trim($where_clause)), 0, 5) != "WHERE") {
// not found, add key word
$whereSQL = " WHERE " . $where_clause;
} else {
$whereSQL = " " . trim($where_clause);
}
}
// start the actual SQL statement
$sql = "UPDATE " . $table_name . " SET ";
// loop and build the column /
$sets = [];
foreach ($form_data as $column => $value) {
$sets[] = "`" . $column . "` = '" . $value . "'";
}
$sql .= implode(", ", $sets);
// append the where statement
$sql .= $whereSQL;
// run and return the query result
if ($v == 1) {
echo $sql . "<br>";
}
return mysqli_query($mysqli, $sql);
}
//Delete Data, the where clause is left optional incase the user wants to delete every row!
function Delete($mysqli, $table_name, $where_clause = "")
{
//global $mysqli;
// check for optional where clause
$whereSQL = "";
if (!empty($where_clause)) {
// check to see if the 'where' keyword exists
if (substr(strtoupper(trim($where_clause)), 0, 5) != "WHERE") {
// not found, add keyword
$whereSQL = " WHERE " . $where_clause;
} else {
$whereSQL = " " . trim($where_clause);
}
}
// build the query
$sql = "DELETE FROM " . $table_name . $whereSQL;
// run and return the query result resource
return mysqli_query($mysqli, $sql);
}
function getDistance($latitude1, $longitude1, $latitude2, $longitude2)
{
$theta = $longitude1 - $longitude2;
$miles =
sin(deg2rad($latitude1)) * sin(deg2rad($latitude2)) +
cos(deg2rad($latitude1)) * cos(deg2rad($latitude2)) * cos(deg2rad($theta));
$miles = acos($miles);
$miles = rad2deg($miles);
$miles = $miles * 60 * 1.1515;
$feet = $miles * 5280;
$yards = $feet / 3;
$kilometers = $miles * 1.609344;
$meters = $kilometers * 1000;
//return compact('miles','feet','yards','kilometers','meters');
return $kilometers;
}
function dfjson($data)
{
if (is_array($data)) {
return json_encode($data, JSON_NUMERIC_CHECK);
}
}
function ig_get($url, $headers, $is_head = false)
{
$curl_handle = curl_init();
if ($is_head) {
curl_setopt($curl_handle, CURLOPT_CUSTOMREQUEST, "HEAD");
curl_setopt($curl_handle, CURLOPT_NOBODY, true);
}
curl_setopt_array($curl_handle, [
CURLOPT_URL => $url, // -------------------------------------------- set full target URL.
CURLOPT_CONNECTTIMEOUT => 30, // ---------------------------------------- timeout on connect, in seconds
CURLOPT_TIMEOUT => 30, // ---------------------------------------- timeout on response, in seconds
CURLOPT_BUFFERSIZE => 2048, // -------------------------------------------- smaller buffer-size for proxies.
CURLOPT_HEADER => true, // -------------------------------------------- return headers too
CURLINFO_HEADER_OUT => true, // -------------------------------------------- to use $rh = curl_getinfo($curl_handle); var_dump($rh['request_header']);
CURLOPT_RETURNTRANSFER => true, // -------------------------------------------- return as string
//, CURLOPT_FAILONERROR => true // -------------------------------------------- don't fetch error-page's content (500, 403, 404 pages etc..)
CURLOPT_SSL_VERIFYHOST => false, // ------------------------------------------- don't verify ssl
CURLOPT_SSL_VERIFYPEER => false, // ------------------------------------------- don't verify ssl
CURLOPT_IPRESOLVE => CURL_IPRESOLVE_V4, // ------------------------------- force IPv4 (instead of IPv6)
CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1, // ---------------------------- force HTTP 1.1
/* redirects */
CURLOPT_FOLLOWLOCATION => true,
CURLOPT_MAXREDIRS => 5,
CURLOPT_HTTPHEADER => $headers
]);
$response = curl_exec($curl_handle);
$info = curl_getinfo($curl_handle);
$err_num = curl_errno($curl_handle);
$err_str = curl_error($curl_handle);
@curl_close($curl_handle);
unset($curl_handle);
$num_of_redirects = isset($info["redirect_count"])
? $info["redirect_count"] + 2
: /* heuristics - try to find parts that starts with "header like" string, add +1 for body */
call_user_func(function () use ($response) {
$response = explode("\r\n\r\n", $response); //candidates
$num_of_redirects = array_reduce(
$response,
function ($value, $item) {
return $value + (0 === mb_strpos($item, "HTTP/", 0) ? 1 : 0); //starts with "HTTP/" ---> it is a redirect header.
},
0
);
return $num_of_redirects + 1 /* the +1 is for the body */;
});
$response = explode("\r\n\r\n", $response, $num_of_redirects);
unset($num_of_redirects);
$response_body = array_pop($response);
$response_header_groups = $response; //now contains just a bunch of strings.
unset($response); // *avoid confusing names..
$response_header_groups = array_map(function ($header_group) {
//reformat string to associative array for all header-groups.
$header_group = trim($header_group);
$headers = [];
$lines = explode("\r\n", $header_group);
foreach ($lines as $index => $line) {
$line = explode(": ", $line, 2); //limit to one match.
if (1 === count($line)) {
//probably lines such as "HTTP/1.1 302 Found" which does not have ": " delimiter, the key will be the [0] (index) using unshift.
array_unshift($line, $index);
} //fix "key" to be the index, in case there is no ': ' delimiter.
$key = $line[0];
$value = $line[1];
$headers[$key] = $value;
}
return $headers;
}, $response_header_groups);
$request_headers = isset($info["request_header"])
? call_user_func_array(
function ($request_headers) {
$request_headers = trim($request_headers);
$headers = [];
$lines = explode("\r\n", $request_headers);
foreach ($lines as $index => $line) {
$line = explode(": ", $line, 2); //limit to one match.
if (1 === count($line)) {
//probably lines such as "HTTP/1.1 302 Found" which does not have ": " delimiter, the key will be the [0] (index) using unshift.
array_unshift($line, $index);
} //fix "key" to be the index, in case there is no ': ' delimiter.
$key = $line[0];
$value = $line[1];
$headers[$key] = $value;
}
return $headers;
},
[$info["request_header"]]
)
: [];
return [
"info" => $info,
"request" => [
"headers" => $request_headers
],
"response" => [
"headers" => $response_header_groups,
"body" => $response_body
],
"error" => [
"num" => $err_num,
"str" => $err_str
]
];
}
function CopyUrlImage($POST, $modul)
{
global $db, $ar;
//echo "<pre>"; print_r($POST); echo "</pre>";
//echo "<pre>"; print_r($FILES); echo "</pre>";
if (isset($POST["title"]) && $POST["title"] != "") {
$title = $POST["title"];
} else {
$title = "";
}
if (isset($POST["caption"]) && $POST["caption"] != "") {
$caption = $POST["caption"];
} else {
$caption = "";
}
//get last id
$sql2 = "select id from `files` order by id desc limit 1";
$res2 = mysqli_query($db, $sql2);
$r2 = mysqli_fetch_assoc($res2);
if (isset($r2["id"]) && $r2["id"] > 0) {
$iid = $r2["id"] + 1;
} else {
$iid = 1;
}
//get last seq
$sql9 =
"select seq from `files` where item_id=" .
$POST["id"] .
" and modul='" .
$modul .
"' order by seq desc limit 1";
//echo $sql9."<br>";
$res9 = mysqli_query($db, $sql9);
$r9 = mysqli_fetch_assoc($res9);
if (isset($r9["seq"]) && $r9["seq"] > 0) {
$seq = $r9["seq"] + 1;
} else {
$seq = 1;
}
$folder_y = $ar["img_path"] . $modul . "/" . date("y");
if (!is_dir($folder_y)) {
mkdir($folder_y, 0777, true);
}
$folder_ym = $folder_y . "/" . date("m");
if (!is_dir($folder_ym)) {
mkdir($folder_ym, 0777, true);
}
$folder_ymd = $folder_ym . "/" . date("d");
if (!is_dir($folder_ymd)) {
mkdir($folder_ymd, 0777, true);
}
$folder_ymdh = $folder_ymd . "/" . date("H");
if (!is_dir($folder_ymdh)) {
mkdir($folder_ymdh, 0777, true);
}
$folder_main = $folder_ymdh . "/" . $POST["id"];
if (!is_dir($folder_main)) {
mkdir($folder_main, 0777, true);
}
$folder_seq = $folder_main . "/" . $seq;
if (!is_dir($folder_seq)) {
mkdir($folder_seq, 0777, true);
}
$folder_tmp = $folder_seq . "/tmp";
if (!is_dir($folder_tmp)) {
mkdir($folder_tmp, 0777, true);
}
/*$sub_folder=$_POST['id']."/".$seq."/";
switch($_POST['file_type']) {
case "Image";
}*/
$path =
date("y") .
"/" .
date("m") .
"/" .
date("d") .
"/" .
date("H") .
"/" .
$POST["id"];
//$e_ext=explode("/",$FILES['file']['type']);
//$file_name=date("YmdHis").".".$e_ext[1];
if ($POST["url_img_src"] != "") {
$info_img = getimagesize($POST["url_img_src"]);
$e_ext = explode("/", $info_img["mime"]);
$file_name = date("YmdHis") . "." . $e_ext[1];
$e_url = explode("/", $POST["url_img_src"]);
copyimg($POST["url_img_src"], $folder_tmp . "/" . $file_name);
//echo "Image Card Front Uploaded";
//$file_name=date("YmdHis").".jpg";
$sub_folder = $folder_seq . "/image";
$sub_folder_big = $folder_seq . "/image/big";
$sub_folder_medium = $folder_seq . "/image/medium";
$sub_folder_small = $folder_seq . "/image/small";
if (!is_dir($sub_folder)) {
mkdir($sub_folder, 0755);
}
if (!is_dir($sub_folder_big)) {
mkdir($sub_folder_big, 0755);
}
if (!is_dir($sub_folder_medium)) {
mkdir($sub_folder_medium, 0755);
}
if (!is_dir($sub_folder_small)) {
mkdir($sub_folder_small, 0755);
}
$source_image = $folder_tmp . "/" . $file_name;
$img_big = $sub_folder_big . "/" . $file_name;
$img_medium = $sub_folder_medium . "/" . $file_name;
$img_small = $sub_folder_small . "/" . $file_name;
//$destination=$ar['img_path']."".$img_url;
//resize(640, $destination, $source_image);
image_handler($source_image, $img_big, 1080, 1080, 90, false);
image_handler($source_image, $img_medium, 800, 800, 90, false);
image_handler($source_image, $img_small, 150, 150, 90, false);
echo $sub_folder_small . "<br>";
$udata2 = [
"id" => $iid,
"seq" => $seq,
"modul" => $modul,
"item_id" => $POST["id"],
"type" => "image",
"title" => gpc($title),
"caption" => gpc($caption),
"url_original" => "tmp/" . $file_name,
"create_at" => time(),
"path" => $path,
"url" => $file_name
];
Insert($db, "files", $udata2, 1);
$udt2 = [
"img" => $modul . "/" . $path . "/" . $seq . "/image/small/" . $file_name
];
Update($db, $modul, $udt2, "id=" . $POST["id"], 1);
}
}
function UploadImage($POST, $FILES, $modul)
{
global $db, $ar;
//echo "<pre>"; print_r($POST); echo "</pre>";
//echo "<pre>"; print_r($FILES); echo "</pre>";
if (isset($POST["title"]) && $POST["title"] != "") {
$title = $POST["title"];
} else {
$title = "";
}
if (isset($POST["caption"]) && $POST["caption"] != "") {
$caption = $POST["caption"];
} else {
$caption = "";
}
//get last id
$sql2 = "select id from `files` order by id desc limit 1";
$res2 = mysqli_query($db, $sql2);
$r2 = mysqli_fetch_assoc($res2);
if (isset($r2["id"]) && $r2["id"] > 0) {
$iid = $r2["id"] + 1;
} else {
$iid = 1;
}
//get last seq
$sql9 =
"select seq from `files` where item_id=" .
$POST["id"] .
" and modul='" .
$modul .
"' order by seq desc limit 1";
echo $sql9 . "<br>";
$res9 = mysqli_query($db, $sql9);
$r9 = mysqli_fetch_assoc($res9);
if (isset($r9["seq"]) && $r9["seq"] > 0) {
$seq = $r9["seq"] + 1;
} else {
$seq = 1;
}
$folder_y = $ar["img_path"] . $modul . "/" . date("y");
if (!is_dir($folder_y)) {
mkdir($folder_y, 0777, true);
}
$folder_ym = $folder_y . "/" . date("m");
if (!is_dir($folder_ym)) {
mkdir($folder_ym, 0777, true);
}
$folder_ymd = $folder_ym . "/" . date("d");
if (!is_dir($folder_ymd)) {
mkdir($folder_ymd, 0777, true);
}
$folder_ymdh = $folder_ymd . "/" . date("H");
if (!is_dir($folder_ymdh)) {
mkdir($folder_ymdh, 0777, true);
}
$folder_main = $folder_ymdh . "/" . $POST["id"];
if (!is_dir($folder_main)) {
mkdir($folder_main, 0777, true);
}
$folder_seq = $folder_main . "/" . $seq;
if (!is_dir($folder_seq)) {
mkdir($folder_seq, 0777, true);
}
$folder_tmp = $folder_seq . "/tmp";
if (!is_dir($folder_tmp)) {
mkdir($folder_tmp, 0777, true);
}
/*$sub_folder=$_POST['id']."/".$seq."/";
switch($_POST['file_type']) {
case "Image";
}*/
$path =
date("y") .
"/" .
date("m") .
"/" .
date("d") .
"/" .
date("H") .
"/" .
$POST["id"];
$e_ext = explode("/", $FILES["file"]["type"]);
$file_name = date("YmdHis") . "." . $e_ext[1];
if ($POST["file_type"] == "image") {
if (
move_uploaded_file(
$FILES["file"]["tmp_name"],
$folder_tmp . "/" . $FILES["file"]["name"]
)
) {
//echo "Image Card Front Uploaded";
//$file_name=date("YmdHis").".jpg";
$sub_folder = $folder_seq . "/image";
$sub_folder_big = $folder_seq . "/image/big";
$sub_folder_medium = $folder_seq . "/image/medium";
$sub_folder_small = $folder_seq . "/image/small";
if (!is_dir($sub_folder)) {
mkdir($sub_folder, 0755);
}
if (!is_dir($sub_folder_big)) {
mkdir($sub_folder_big, 0755);
}
if (!is_dir($sub_folder_medium)) {
mkdir($sub_folder_medium, 0755);
}
if (!is_dir($sub_folder_small)) {
mkdir($sub_folder_small, 0755);
}
$source_image = $folder_tmp . "/" . $FILES["file"]["name"];
$img_big = $sub_folder_big . "/" . $file_name;
$img_medium = $sub_folder_medium . "/" . $file_name;
$img_small = $sub_folder_small . "/" . $file_name;
//$destination=$ar['img_path']."".$img_url;
//resize(640, $destination, $source_image);
image_handler($source_image, $img_big, 1080, 1080, 90, false);
image_handler($source_image, $img_medium, 800, 800, 90, false);
image_handler($source_image, $img_small, 150, 150, 90, false);
echo $sub_folder_small . "<br>";
$udata2 = [
"id" => $iid,
"seq" => $seq,
"modul" => $modul,
"item_id" => $POST["id"],
"type" => "image",
"title" => gpc($title),
"caption" => gpc($caption),
"url_original" => "tmp/" . $FILES["file"]["name"],
"create_at" => time(),
"path" => $path,
"url" => $file_name
];
Insert($db, "files", $udata2, 1);
$udt2 = [
"img" =>
$modul . "/" . $path . "/" . $seq . "/image/small/" . $file_name
];
Update($db, $modul, $udt2, "id=" . $POST["id"], 1);
}
} else {
if (
move_uploaded_file(
$FILES["file"]["tmp_name"],
$folder_seq . "/" . $file_name
)
) {
//echo "Image Card Front Uploaded";
$udata2 = [
"id" => $iid,
"seq" => $seq,
"modul" => $modul,
"item_id" => $POST["id"],
"type" => $POST["file_type"],
"title" => gpc($title),
"caption" => gpc($caption),
"url_original" => "tmp/" . $FILES["file"]["name"],
"create_at" => time(),
"path" => $path,
"url" => $file_name
];
Insert($db, "files", $udata2, 0);
}
}
}
function image_handler(
$source_image,
$destination,
$tn_w = 100,
$tn_h = 100,
$quality = 80,
$wmsource = false
) {
// The getimagesize functions provides an "imagetype" string contstant, which can be passed to the image_type_to_mime_type function for the corresponding mime type
$info = getimagesize($source_image);
$imgtype = image_type_to_mime_type($info[2]);
// Then the mime type can be used to call the correct function to generate an image resource from the provided image
switch ($imgtype) {
case "image/jpeg":
$source = imagecreatefromjpeg($source_image);
break;
case "image/gif":
$source = imagecreatefromgif($source_image);
break;
case "image/png":
$source = imagecreatefrompng($source_image);
break;
default:
die($source_image . "Invalid image type.");
}
// Now, we can determine the dimensions of the provided image, and calculate the width/height ratio
$src_w = imagesx($source);
$src_h = imagesy($source);
$src_ratio = $src_w / $src_h;
// Now we can use the power of math to determine whether the image needs to be cropped to fit the new dimensions, and if so then whether it should be cropped vertically or horizontally. We're just going to crop from the center to keep this simple.
if ($tn_w / $tn_h > $src_ratio) {
$new_h = $tn_w / $src_ratio;
$new_w = $tn_w;
} else {
$new_w = $tn_h * $src_ratio;
$new_h = $tn_h;
}
$x_mid = $new_w / 2;
$y_mid = $new_h / 2;
// Now actually apply the crop and resize!
$newpic = imagecreatetruecolor(round($new_w), round($new_h));
imagecopyresampled(
$newpic,
$source,
0,
0,
0,
0,
$new_w,
$new_h,
$src_w,
$src_h
);
$final = imagecreatetruecolor($tn_w, $tn_h);
imagecopyresampled(
$final,
$newpic,
0,
0,
$x_mid - $tn_w / 2,
$y_mid - $tn_h / 2,
$tn_w,
$tn_h,
$tn_w,
$tn_h
);
// If a watermark source file is specified, get the information about the watermark as well. This is the same thing we did above for the source image.
if ($wmsource) {
$info = getimagesize($wmsource);
$imgtype = image_type_to_mime_type($info[2]);
switch ($imgtype) {
case "image/jpeg":
$watermark = imagecreatefromjpeg($wmsource);
break;
case "image/gif":
$watermark = imagecreatefromgif($wmsource);
break;
case "image/png":
$watermark = imagecreatefrompng($wmsource);
break;
default:
die("Invalid watermark type.");
}
// Determine the size of the watermark, because we're going to specify the placement from the top left corner of the watermark image, so the width and height of the watermark matter.
$wm_w = imagesx($watermark);
$wm_h = imagesy($watermark);
// Now, figure out the values to place the watermark in the bottom right hand corner. You could set one or both of the variables to "0" to watermark the opposite corners, or do your own math to put it somewhere else.
$wm_x = ($tn_w - $wm_w) / 2;
$wm_y = ($tn_h - $wm_h) / 2;
// Copy the watermark onto the original image
// The last 4 arguments just mean to copy the entire watermark
imagecopy($final, $watermark, $wm_x, $wm_y, 0, 0, $wm_w, $wm_h);
}
// Ok, save the output as a jpeg, to the specified destination path at the desired quality.
// You could use imagepng or imagegif here if you wanted to output those file types instead.
if (Imagejpeg($final, $destination, $quality)) {
return true;
}
// If something went wrong
return false;
}
function ResizeWithMark(
$source_image,
$destination,
$new_w,
$quality = 80,
$wmsource = false
) {
// The getimagesize functions provides an "imagetype" string contstant, which can be passed to the image_type_to_mime_type function for the corresponding mime type
$info = getimagesize($source_image);
$imgtype = image_type_to_mime_type($info[2]);
// Then the mime type can be used to call the correct function to generate an image resource from the provided image
switch ($imgtype) {
case "image/jpeg":
$source = imagecreatefromjpeg($source_image);
break;
case "image/gif":
$source = imagecreatefromgif($source_image);
break;
case "image/png":
$source = imagecreatefrompng($source_image);
break;
default:
die($source_image . "Invalid image type.");
}
// Now, we can determine the dimensions of the provided image, and calculate the width/height ratio
$src_w = imagesx($source);
$src_h = imagesy($source);
$src_ratio = $src_h / $src_w;
// Now we can use the power of math to determine whether the image needs to be cropped to fit the new dimensions, and if so then whether it should be cropped vertically or horizontally. We're just going to crop from the center to keep this simple.
/*
if ($tn_w/$tn_h > $src_ratio) {
$new_h = $tn_w/$src_ratio;
$new_w = $tn_w;
} else {
$new_w = $tn_h*$src_ratio;
$new_h = $tn_h;
}
*/
$new_h = $new_w * $src_ratio;
$tn_w = $new_w;
$tn_h = $new_h;
$x_mid = $new_w / 2;
$y_mid = $new_h / 2;
// Now actually apply the crop and resize!
$newpic = imagecreatetruecolor(round($new_w), round($new_h));
imagecopyresampled(
$newpic,
$source,
0,
0,
0,
0,
$new_w,
$new_h,
$src_w,
$src_h
);
$final = imagecreatetruecolor($tn_w, $tn_h);
imagecopyresampled(
$final,
$newpic,
0,
0,
$x_mid - $tn_w / 2,
$y_mid - $tn_h / 2,
$tn_w,
$tn_h,
$tn_w,
$tn_h
);
// If a watermark source file is specified, get the information about the watermark as well. This is the same thing we did above for the source image.
if ($wmsource) {
$info = getimagesize($wmsource);
$imgtype = image_type_to_mime_type($info[2]);
switch ($imgtype) {
case "image/jpeg":
$watermark = imagecreatefromjpeg($wmsource);
break;
case "image/gif":
$watermark = imagecreatefromgif($wmsource);
break;
case "image/png":
$watermark = imagecreatefrompng($wmsource);
break;
default:
die("Invalid watermark type.");
}
// Determine the size of the watermark, because we're going to specify the placement from the top left corner of the watermark image, so the width and height of the watermark matter.
$wm_w = imagesx($watermark);
$wm_h = imagesy($watermark);
// Now, figure out the values to place the watermark in the bottom right hand corner. You could set one or both of the variables to "0" to watermark the opposite corners, or do your own math to put it somewhere else.
$wm_x = ($tn_w - $wm_w) / 2;
$wm_y = ($tn_h - $wm_h) / 2;
// Copy the watermark onto the original image
// The last 4 arguments just mean to copy the entire watermark
imagecopy($final, $watermark, $wm_x, $wm_y, 0, 0, $wm_w, $wm_h);
}
// Ok, save the output as a jpeg, to the specified destination path at the desired quality.
// You could use imagepng or imagegif here if you wanted to output those file types instead.
if (Imagejpeg($final, $destination, $quality)) {
return true;
}
// If something went wrong
return false;
}
function resize($newWidth, $targetFile, $originalFile)
{
//$originalFile = file_get_contents($imgurl);
$info = getimagesize($originalFile);
$mime = $info["mime"];
switch ($mime) {
case "image/jpeg":
$image_create_func = "imagecreatefromjpeg";
$image_save_func = "imagejpeg";
$new_image_ext = "jpg";
break;
case "image/png":
$image_create_func = "imagecreatefrompng";
$image_save_func = "imagepng";
$new_image_ext = "png";
break;
case "image/gif":
$image_create_func = "imagecreatefromgif";
$image_save_func = "imagegif";
$new_image_ext = "gif";
break;
default:
throw new Exception("Unknown image type.");
}
$img = $image_create_func($originalFile);
[$width, $height] = getimagesize($originalFile);
$newHeight = ($height / $width) * $newWidth;
$tmp = imagecreatetruecolor($newWidth, $newHeight);
imagecopyresampled(
$tmp,
$img,
0,
0,
0,
0,
$newWidth,
$newHeight,
$width,
$height
);
if (file_exists($targetFile)) {
unlink($targetFile);
}
$image_save_func($tmp, "$targetFile");
}
function slug($text)
{
// replace non letter or digits by -
$text = preg_replace("~[^\pL\d]+~u", "-", $text);
// transliterate
$text = iconv("utf-8", "us-ascii//TRANSLIT", $text);
// remove unwanted characters
$text = preg_replace("~[^-\w]+~", "", $text);
// trim
$text = trim($text, "-");
// remove duplicate -
$text = preg_replace("~-+~", "-", $text);
// lowercase
$text = strtolower($text);
if (empty($text)) {
return "n-a";
}
return $text;
}
function paginate(
$item_per_page,
$current_page,
$total_records,
$total_pages,
$page_url
) {
/*
use bootstrap 4/5
*/
$pagination = "";
if ($total_pages > 0 && $total_pages != 1 && $current_page <= $total_pages) {
//verify total pages and current page number
$pagination .= '<ul class="pagination justify-content-center">';
$right_links = $current_page + 3;
$previous = $current_page - 3; //previous link
$next = $current_page + 1; //next link
$first_link = true; //boolean var to decide our first link
if ($current_page > 1) {
$previous_link = $previous == 0 ? 1 : $previous;
$pagination .=
'<li class="first"><a class="page-link" href="?' .
$page_url .
'&page=1" title="First">«</a></li>'; //first link
$pagination .=
'<li><a class="page-link" href="?' .
$page_url .
"&page=" .
$previous_link .
'" title="Previous"><</a></li>'; //previous link
for ($i = $current_page - 2; $i < $current_page; $i++) {
//Create left-hand side links
if ($i > 0) {
$pagination .=
'<li><a class="page-link" href="?' .
$page_url .
"&page=" .
$i .
'">' .
$i .
"</a></li>";
}
}
$first_link = false; //set first link to false
}
if ($first_link) {
//if current active page is first link
$pagination .=
'<li class="first active"><a class="page-link">' .
$current_page .
"</a></li>";
} elseif ($current_page == $total_pages) {
//if it's the last active link
$pagination .=
'<li class="last active"><a class="page-link">' .
$current_page .
"</a></li>";
} else {
//regular current link
$pagination .=
'<li class="page-item active" aria-current="page"><a class="page-link">' .
$current_page .
"</a></li>";
}
for ($i = $current_page + 1; $i < $right_links; $i++) {
//create right-hand side links
if ($i <= $total_pages) {
$pagination .=
'<li class="page-item"><a class="page-link" href="?' .
$page_url .
"&page=" .
$i .
'">' .
$i .
"</a></li>";
}
}
if ($current_page < $total_pages) {
$next_link = $i > $total_pages ? $total_pages : $i;
$pagination .=
'<li><a class="page-link" href="?' .
$page_url .
"&page=" .
$next_link .
'" >></a></li>'; //next link
$pagination .=
'<li class="last"><a class="page-link" href="?' .
$page_url .
"&page=" .
$total_pages .
'" title="Last">»</a></li>'; //last link
}
$pagination .= "</ul>";
}
return $pagination; //return pagination links
}
function emptyDir($dir)
{
if (is_dir($dir)) {
$scn = scandir($dir);
foreach ($scn as $files) {
if ($files !== ".") {
if ($files !== "..") {
if (!is_dir($dir . "/" . $files)) {
unlink($dir . "/" . $files);
} else {
emptyDir($dir . "/" . $files);
rmdir($dir . "/" . $files);
}
}
}
}
}
}
function getUserIP()
{
$client = @$_SERVER["HTTP_CLIENT_IP"];
$forward = @$_SERVER["HTTP_X_FORWARDED_FOR"];
$remote = $_SERVER["REMOTE_ADDR"];
if (filter_var($client, FILTER_VALIDATE_IP)) {
$ip = $client;
} elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
$ip = $forward;
} else {
$ip = $remote;
}
return $ip;
}
function genRandom($length = 10)
{
$characters = "1234567890abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNPQRSTUVWXYZ";
$charactersLength = strlen($characters);
$randomString = "";
for ($i = 0; $i < $length; $i++) {
$randomString .= $characters[rand(0, $charactersLength - 1)];
}
return $randomString;
}
function WAtext($text)
{
global $db2;
$search = [
"#<br\s*?/?>#i", // Strip out javascript
"#<li\s*?/?>#i",
"#<\/li\s*?/?>#i",
"#<\/ol\s*?/?>#i",
"#<\/h4\s*?/?>#i",
"#<\/h2\s*?/?>#i",
"#<h4\s*?/?>#i",
"#<h2\s*?/?>#i",
"'<[/!]*?[^<>]*?>'si" // Strip out HTML tags
]; // evaluate as php
$replace = ["\n", "- ", "\n", "\n", "*\n", "*\n", "\n*", "\n*", ""];
$ret = preg_replace($search, $replace, $text);
return $ret;
}
?>