<?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 backup_tables($tables = "*")
{
  global $db, $ar;
  $link = $db;
  mysqli_query($db, "SET NAMES 'utf8'");
  //get all of the tables
  if ($tables == "*") {
    $tables = [];
    $result = mysqli_query($link, "SHOW TABLES");
    while ($row = mysqli_fetch_row($result)) {
      $tables[] = $row[0];
    }
  } else {
    $tables = is_array($tables) ? $tables : explode(",", $tables);
  }

  $return = "SET NAMES utf8;
SET time_zone = '+00:00';
SET foreign_key_checks = 0;
SET sql_mode = 'NO_AUTO_VALUE_ON_ZERO';\n\n";
  //cycle through
  foreach ($tables as $table) {
    $result = mysqli_query($link, "SELECT * FROM " . $table);
    $num_fields = mysqli_num_fields($result);
    $num_rows = mysqli_num_rows($result);
    $return .= "DROP TABLE IF EXISTS `" . $table . "`;";
    $row2 = mysqli_fetch_row(
      mysqli_query($link, "SHOW CREATE TABLE " . $table)
    );
    $return .= "\n" . $row2[1] . ";\n\n";
    $counter = 1;
    //Over tables
    for ($i = 0; $i < $num_fields; $i++) {
      //Over rows
      while ($row = mysqli_fetch_row($result)) {
        $return .= "INSERT INTO `" . $table . "` VALUES(";

        //Over fields
        for ($j = 0; $j < $num_fields; $j++) {
          $row[$j] = gpc($row[$j]);
          $row[$j] = str_replace("\n", "\\n", $row[$j]);
          if (isset($row[$j])) {
            $return .= "'" . $row[$j] . "'";
          } else {
            $return .= "''";
          }
          if ($j < $num_fields - 1) {
            $return .= ",";
          }
        }

        $return .= ");\n";
        ++$counter;
      }
    }
    $return .= "\n\n";
  }
  //save file
  $fileName = $ar["sitename"] . "_db.sql";
  $handle = fopen($fileName, "w+");
  fwrite($handle, $return);
  if (fclose($handle)) {
    echo 'Done, the file name is: <a href="' .
      $ar["siteurl"] .
      "/" .
      $fileName .
      '">' .
      $ar["siteurl"] .
      "/" .
      $fileName .
      "</a>";
    exit();
  }
}

function xhr($url)
{
  global $ar, $db;
  include_once $ar["path_core"] . "dom/request.php";
  $xhr = request($url);
  return $xhr;
}

function repl_space($text)
{
  $ret = preg_replace("!\s+!", " ", $text);
  return $ret;
}

function repl_all_space($text)
{
  $ret = preg_replace("/\s|&nbsp;/", "", $text);
  return $ret;
}

//$html=preg_replace('/class=".*?"/', '', $html);

function repl_class($text)
{
  $ret = preg_replace('/ class=".*?"/', "", $text);
  $ret = preg_replace('/ style=".*?"/', "", $ret);
  $ret = preg_replace('/ dir=".*?"/', "", $ret);
  return $ret;
}

function gpc($value)
{
  $value = str_replace("\\", "", $value);
  $value = str_replace("'", "\'", $value);
  //return ((!get_magic_quotes_gpc()) ? addslashes($value) : $value);
  return $value;
}
function ugpc($value)
{
  if ($value != "") {
    //$value = preg_replace( "\\\\","\\",$value);
    $value = str_replace("\\'", "'", $value);
    $value = str_replace('\\"', '"', $value);
    return $value;
  }
  //return ((!get_magic_quotes_gpc()) ? addslashes($value) : $value);
}
function dec($l)
{
  $l = number_format($l, 2, ",", ".");
  return $l;
}
function dec1($l)
{
  $l = number_format($l, 1, ",", ".");
  return $l;
}
function dec2($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 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;
}

function to_tgl($time)
{
  if ($time > 0) {
    $tt = date("Y-m-d H:i:s", $time);
  } else {
    $tt = "";
  }
  return $tt;
}

//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);
}

# Insert Data
function Insert_v2($mysqli, $table, $data)
{
  $dt = [];
  $fields = array_keys($data);
  $values = array_map([$mysqli, "real_escape_string"], array_values($data));
  $sql =
    "INSERT INTO `$table` (`" .
    implode("`,`", $fields) .
    "`) VALUES ('" .
    implode("','", $values) .
    "')";
  $dt["sql"] = $sql;
  if (mysqli_query($mysqli, $sql)) {
    $dt["result"] = "Success";
  } else {
    $dt["result"] = "Error";
  }
  return json_encode($dt);
}

// Update Data, Where clause is left optional
function InsertUpdate_v2($mysqli, $table_name, $i_data, $u_data)
{
  $dt = [];
  $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);
  $dt["sql"] = $sql . ";";
  // run and return the query result
  // return mysqli_query($mysqli,$sql);
  if (mysqli_query($mysqli, $sql)) {
    $dt["result"] = "Success";
  } else {
    $dt["result"] = "Error";
  }
  return json_encode($dt);
}

// Update Data, Where clause is left optional
function Update_v2($mysqli, $table_name, $form_data, $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 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;

  $dt["sql"] = $sql . ";";
  // run and return the query result
  // return mysqli_query($mysqli,$sql);
  if (mysqli_query($mysqli, $sql)) {
    $dt["result"] = "Success";
  } else {
    $dt["result"] = "Error";
  }
  return json_encode($dt);
}

//Delete Data, the where clause is left optional incase the user wants to delete every row!
function Delete_v2($mysqli, $table_name, $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;

  $dt["sql"] = $sql . ";";
  // run and return the query result
  // return mysqli_query($mysqli,$sql);
  if (mysqli_query($mysqli, $sql)) {
    $dt["result"] = "Success";
  } else {
    $dt["result"] = "Error";
  }
  return json_encode($dt);
}

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 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 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 genToken($length = 10)
{
  $characters = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPRSTUVWXYZ_@!)(^%";
  $charactersLength = strlen($characters);
  $randomString = "";
  for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, $charactersLength - 1)];
  }
  return $randomString;
}

function genCode($length = 10)
{
  $characters = "abcdefghijkmnpqrstuvwxyzABCDEFGHJKLMNPRSTUVWXYZ";
  $charactersLength = strlen($characters);
  $randomString = "";
  for ($i = 0; $i < $length; $i++) {
    $randomString .= $characters[rand(0, $charactersLength - 1)];
  }
  return $randomString;
}

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;
}

function arCss($css)
{
  $cleanCss = [];

  // Remove css comments
  $clean1 = explode("/*", $css);
  foreach ($clean1 as $clean2) {
    $clean3 = explode("*/", $clean2);
    $cleanCss[] = $clean3[count($clean3) - 1];
  }
  $css = implode("", $cleanCss);
  $temp = explode("}", $css);
  $params = [];
  $type = "all";
  $nextBracketIsNotMediaEnd = false;
  foreach ($temp as $tem2) {
    $data = explode("{", $tem2);
    if (count($data) == 1) {
      if ($nextBracketIsNotMediaEnd) {
        $nextBracketIsNotMediaEnd = false;
      } else {
        $type = "all";
        continue;
      }
    }
    if (count($data) == 3) {
      $typeTemp = trim($data[0]);
      if (substr($typeTemp, 0, 6) === "@media") {
        $type = $typeTemp;
        array_shift($data);
      } else {
        $data[1] = $data[0] . $data[1];
        $nextBracketIsNotMediaEnd = true;
      }
    }
    if (count($data) == 2) {
      $rows = explode(";", $data[1]);

      $tempData = [];
      foreach ($rows as $row) {
        $paramsinline = explode(":", $row);
        if (empty($paramsinline[0]) || empty($paramsinline[1])) {
          continue;
        }
        $tempData[trim($paramsinline[0])] = trim($paramsinline[1]);
      }
      $selector = trim($data[0]);
      if (!empty($tempData)) {
        if (empty($params[$type][$selector])) {
          $params[$type][$selector] = $tempData;
        } else {
          $params[$type][$selector] = array_merge(
            $params[$type][$selector],
            $tempData
          );
        }
      }
    }
  }
  return $params;
}
?>
/home/u902783705/domains/azkapersada.com/public_html/sub/
rs2/common.function.php
si/common.function
si/dom/get.img
si/api/post_location
si/api/post_loc_v3
si/api/post_tag_v2
si/api/post_tag_v3
common.function
common.function-
footer
header
inc.app.function
inc.ar.app
index
tes_curl
ucol
api/v2/api.function
api/v2/inc.mail
api/v2/index
api/v2/php/agen
api/v2/php/armada_jalan_byday
api/v2/php/armada_perpal_byday
api/v2/php/armada_perpal_byday-
api/v2/php/beda_byday
api/v2/php/cek_rute_baru
api/v2/php/cek_rute_time
api/v2/php/cek_rute_time_v1
api/v2/php/cek_rute_time_v2
api/v2/php/city
api/v2/php/dr_time_byday
api/v2/php/dr_time_jalan_byday
api/v2/php/email_cek
api/v2/php/get_nl_byday
api/v2/php/get_nl_kelas_armada
api/v2/php/js_armada_tax_expire
api/v2/php/js_blue_armada
api/v2/php/js_blue_expire
api/v2/php/js_car_srut_blank
api/v2/php/js_img_todl
api/v2/php/js_jalurnew
api/v2/php/js_kebid
api/v2/php/js_nl_latest
api/v2/php/js_nl_min
api/v2/php/js_noken
api/v2/php/js_noken_mesin_blank
api/v2/php/js_noken_no_lambung
api/v2/php/js_noken_spionam_cek
api/v2/php/js_noken_tax_cek
api/v2/php/js_rute
api/v2/php/js_rute_bycity
api/v2/php/js_rute_min
api/v2/php/js_spionam_id
api/v2/php/js_spionam_kps
api/v2/php/kd_armada
api/v2/php/kd_armada_dr_time
api/v2/php/kd_armada_to_time
api/v2/php/naik_byday
api/v2/php/nk_pilih
api/v2/php/nl_noken_bytgl
api/v2/php/nl_pilih
api/v2/php/nl_reset
api/v2/php/noken_koreksi
api/v2/php/otw
api/v2/php/otw_not_full
api/v2/php/password_forgot
api/v2/php/post_1naik
api/v2/php/post_1turun
api/v2/php/post_blue
api/v2/php/post_dr_time_byday_local
api/v2/php/post_kebid_byday
api/v2/php/post_noken_mesin
api/v2/php/post_noken_no_lambung
api/v2/php/post_sakpol
api/v2/php/post_spionam
api/v2/php/post_spionam_cek
api/v2/php/post_spionam_update
api/v2/php/post_spnm_noken
api/v2/php/ricar
api/v2/php/rute_price
api/v2/php/selisih_bagasi
api/v2/php/signin
api/v2/php/tool
api/v2/php/tool_armada
api/v2/php/tool_lambung
api/v2/php/tool_noken
api/v2/php/turun_byday
api/v2/php/ucol
api/v2/php/uji_no
api/v2/php/update_agen
api/v2/php/update_armada_byday
api/v2/php/update_armada_v2_byday
api/v2/php/update_bagasi_byday
api/v2/php/update_bagasi_city
api/v2/php/update_jalan_byday
api/v2/php/update_penumpang_byday
api/v2/php/update_trayek_dr_time
api/v2/php/update_trayek_to_time
daily/10_tool_seq
daily/14_update_kd_armada
daily/15_update_rute_dr_to_ccd
daily/16_kdagen_to_id
daily/16_kdagen_to_id-
daily/17_update_dr_to_time
inc/inc.cp_sphp
inc/inc.filephp
inc/inc.job_kebid
inc/inc.js_pergi
inc/inc.rs4_css
inc/inc.rs4_html
inc/inc.rs4_h_page
inc/inc.rs4_h_tab
inc/inc.rs4_js
inc/inc.rs4_jsf
inc/inc.t1_css
inc/inc.t1_html
inc/inc.t1_h_page
inc/inc.t1_h_tab
inc/inc.t1_js
inc/inc.t1_jsf
xhr/inc.xhr