Mencari Sesuatu ?

Jumat, 09 Desember 2022

Vanilla JS like jquery document.ready

 Default can use this :



document.addEventListener('DOMContentLoaded', function () {

  // do something here ...

}, false);



on fully load use this :



window.addEventListener('load', function () {

  // do something here ...

}, false);







credit to source : 

https://www.codeinwp.com/snippets/jquery-document-ready-in-vanilla-javascript/

Rabu, 07 Desember 2022

Linux Screenshot melalui remote SSH terminal

ssh root@ "runuser -l  -c 'DISPLAY=:0 import -window root /tmp/screenshot.png'" 


nama_user that running or use the display / x server
for information on running user can use this command :

$> loginctl list-sessions

Selasa, 06 Desember 2022

PHP FUNCTION Send document Telegram bot channel

 



function send_file_telegram($file,$message,$channelid,$token){  
    $curl = curl_init();
    $fh=new CURLFile(realpath($file));
    curl_setopt_array($curl, [
      CURLOPT_URL => "https://api.telegram.org/bot".urlencode($token)."/sendDocument",  
      CURLOPT_RETURNTRANSFER => true,
      CURLOPT_ENCODING => "",
      CURLOPT_MAXREDIRS => 10,
      CURLOPT_TIMEOUT => 30,
      CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
      CURLOPT_CUSTOMREQUEST => "POST",
      CURLOPT_POSTFIELDS => array(
        "document"=>$fh,
        "caption"=>$message,
        "disable_notification"=>true,
        "chat_id"=>$channelid,
      ),
      CURLOPT_HTTPHEADER => [
        "User-Agent: Telegram Bot SDK",
        "Content-Type: multipart/form-data;charset=utf-8"
      ],
    ]);
   
    $response = curl_exec($curl);
    $err = curl_error($curl);
   
    curl_close($curl);
   
    if ($err) {
      echo "cURL Error #:" . $err;
    } else {
      echo $response;
    }
   
}


Senin, 05 Desember 2022

perintah hanya untuk directory zip_log dengan umur diatas 60 hari

 #perintah hanya untuk directory zip_log dengan umur diatas 60 hari

find /var/www/html/ -type d -regex ".*zip_log.*" -mtime +60 -print -exec rm -rf "{}" \;

Rabu, 16 November 2022

linux command find and gzip file

 #perintah find untuk gzip file

find ./ -type f -regex ".*\.sql" -print -exec gzip -9 "{}" \;

Rabu, 09 November 2022

Tar backup exclude directory

tar --exclude='nama_directory' --exclude='prefix_directory' -czvf  [backup_file]

Kamis, 20 Oktober 2022

Bash Perintah hapus directory dengan find dan regex

# perintah hapus 10 hari yang lalu
find /mydir -regex ".*/backup.*" -type d -ctime +10 -print  -exec rm -rf {} \;

Jumat, 30 September 2022

PHP Script untuk Search and Replace Contents on file

 PHP Script untuk search file php dan mengganti perubahan sederhana, String Only not Binary

<?php
$target_type = '/\.php/';
$regex_target = "/date\(\'Y\-m\-d h\:i\:s\'\)/";
$regex_replace = "date('Y-m-d H:i:s')";


echo "this for string only, not binary content!\n";

$backupFolder = "backup_".date("Ymd").'/';

if(!is_dir($backupFolder)){
    mkdir($backupFolder, 0777, true);

    if ($handle = opendir('.')) {

        while (false !== ($filename = readdir($handle))) {
   
            if ($filename != "." && $filename != "..") {
   
                if(preg_match($target_type,$filename)){
                    $file_contents = file_get_contents($filename);
                    if(preg_match($regex_target,$file_contents)){
                        echo "Found and replaced :\t".$filename."\n";
                        if(!file_exists($backupFolder.$filename)){
                            copy($filename,$backupFolder.$filename);
                        }
                        $file_contents = preg_replace($regex_target,$regex_replace,$file_contents);
                        file_put_contents($filename, $file_contents);
                    }else{
                        echo "Skipped : ".$filename."\n";
                    }
                }
            }
        }
   
        closedir($handle);
    }    
}else{
    echo "Already process, Backup found!\n";
}

 

Minggu, 18 September 2022

Masalah Printer Error Failed Operation Failed Error 0x0000011b

RegEdit 

Computer\HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Print

create new DWORD 32bit Value

RpcAuthnLevelPrivacyEnabled

Set 0

Restart Service Print Spooler

Best Of Luck!

Jumat, 16 September 2022

Javascript drag scroll content vertical / horizontal ( rubik like ) PHP + HTML + CSS + Javascript

PHP + HTML + CSS + Javascript

Scroll with drag using finger touch / mouse  vertically / horizontally rubik like feel.
JQuery Based
<!DOCTYPE html>
<html>
<head>
    <link rel="icon" href="icon.png">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <title>Rubik UI Test</title> 
    <script src="js/jquery.js"></script>
    <style>
body{
    margin:0;
    padding:0;
}
.container{
    max-width: 1080px;
    margin:0 auto;
    padding:20px 50px;
}
.products_wrapper{
    overflow: auto; 
    height: 50vh;
    width: 50vh;
    box-shadow: 0 0 10px rgba(0, 0, 0, 0.2);
    background-color: darkgoldenrod;
}
.line_product {
  overflow-x: scroll;
  overflow-y: scroll;
  white-space: nowrap;
} 
.card {
    margin:0.5vh; 
    display: inline-block;
    border-radius: 1rem; 
    box-shadow: 0 2px 5px rgba(0,0,0,.2);
    width: 15vw;
    line-height: 9vh;
    text-align: center; 
}        
    </style>
    <script>
(function($) {
  $.dragScroll = function(options) {
    var settings = $.extend({
      scrollVertical: true,
      scrollHorizontal: true,
      cursor: null
    }, options);

    var clicked = false,
      clickY, clickX;

    var getCursor = function() {
      if (settings.cursor) return settings.cursor;
      if (settings.scrollVertical && settings.scrollHorizontal) return 'move';
      if (settings.scrollVertical) return 'row-resize';
      if (settings.scrollHorizontal) return 'col-resize';
    }

    var updateScrollPos = function(e, el) {
      $('html').css('cursor', getCursor());
      var $el = $(el);
      settings.scrollVertical && $el.scrollTop($el.scrollTop() + (clickY - e.pageY));
      settings.scrollHorizontal && $el.scrollLeft($el.scrollLeft() + (clickX - e.pageX));
    }

    $(document).on({
      'mousemove': function(e) {
        clicked && updateScrollPos(e, this);
      },
      'mousedown': function(e) {
        clicked = true;
        clickY = e.pageY;
        clickX = e.pageX;
      },
      'mouseup': function() {
        clicked = false;
        $('html').css('cursor', 'auto');
      }
    });
  }
}(jQuery))

$.dragScroll();        
    </script>
</head>
<body>
    <div class="container">
<?php
    echo '<div class="products_wrapper">'."\n";
    for($i=1;$i<=3;$i++){
        echo '<div class="horizontal_wrapper">'."\n";
        for($j=1;$j<=4;$j++){
            echo '<div class="line_product">'."\n";
            for($k=1;$k<=10;$k++){
                echo '<div class="card">'."\n";
                echo '<p class="card-text">'."Page $i Line $j Item $k".'</p>'."\n";
                echo '</div>'."\n";
            }
            echo '</div>'."\n";
        }
        echo '</div>'."\n";
    }
    echo '</div>'."\n";
?>         
    </div>
</body>
</html>

based on :

https://stackoverflow.com/questions/19743228/scroll-the-page-on-drag-with-jquery

Senin, 29 Agustus 2022

Mikrotik Basic Firewall Setup

 == This is a basic firewall that can be applied to any Router. ==


This script has basic rules to protect your router and avoid some unnecessary forwarding traffic. Pay attention for all comments before apply each DROP rules.


HANDS ON!

First we need to create our ADDRESS LIST with all IPs we will use most times


'''Below you need to change x.x.x.x/x for your technical subnet. This subnet will have full access to the router.'''


 /ip firewall address-list add address=x.x.x.x/x disabled=no list=support



'''Below we have the bogon list.'''

 

 /ip firewall address-list

 

 add address=0.0.0.0/8 comment="Self-Identification [RFC 3330]" disabled=no list=bogons

 add address=10.0.0.0/8 comment="Private[RFC 1918] - CLASS A # Check if you need this subnet before enable it"\

 disabled=yes list=bogons

 add address=127.0.0.0/8 comment="Loopback [RFC 3330]" disabled=no list=bogons

 add address=169.254.0.0/16 comment="Link Local [RFC 3330]" disabled=no list=bogons

 add address=172.16.0.0/12 comment="Private[RFC 1918] - CLASS B # Check if you need this subnet before enable it"\

 disabled=yes list=bogons

 add address=192.168.0.0/16 comment="Private[RFC 1918] - CLASS C # Check if you need this subnet before enable it"\

 disabled=yes list=bogons

 add address=192.0.2.0/24 comment="Reserved - IANA - TestNet1" disabled=no list=bogons

 add address=192.88.99.0/24 comment="6to4 Relay Anycast [RFC 3068]" disabled=no list=bogons

 add address=198.18.0.0/15 comment="NIDB Testing" disabled=no list=bogons

 add address=198.51.100.0/24 comment="Reserved - IANA - TestNet2" disabled=no list=bogons

 add address=203.0.113.0/24 comment="Reserved - IANA - TestNet3" disabled=no list=bogons

 add address=224.0.0.0/4 comment="MC, Class D, IANA # Check if you need this subnet before enable it"\

 disabled=yes list=bogons



'''Now we have protection against: SynFlood, ICMP Flood, Port Scan, Email Spam and much more. For more information read the comments.'''


 /ip firewall filter

 

 add action=add-src-to-address-list address-list=Syn_Flooder address-list-timeout=30m chain=input \

 comment="Add Syn Flood IP to the list" connection-limit=30,32 disabled=no protocol=tcp tcp-flags=syn

 add action=drop chain=input comment="Drop to syn flood list" disabled=no src-address-list=Syn_Flooder

 add action=add-src-to-address-list address-list=Port_Scanner address-list-timeout=1w chain=input comment="Port Scanner Detect"\

 disabled=no protocol=tcp psd=21,3s,3,1

 add action=drop chain=input comment="Drop to port scan list" disabled=no src-address-list=Port_Scanner

 add action=jump chain=input comment="Jump for icmp input flow" disabled=no jump-target=ICMP protocol=icmp

 add action=drop chain=input\

 comment="Block all access to the winbox - except to support list # DO NOT ENABLE THIS RULE BEFORE ADD YOUR SUBNET IN THE SUPPORT ADDRESS LIST"\

 disabled=yes dst-port=8291 protocol=tcp src-address-list=!support

 add action=jump chain=forward comment="Jump for icmp forward flow" disabled=no jump-target=ICMP protocol=icmp

 add action=drop chain=forward comment="Drop to bogon list" disabled=no dst-address-list=bogons

 add action=add-src-to-address-list address-list=spammers address-list-timeout=3h chain=forward comment="Add Spammers to the list for 3 hours"\

 connection-limit=30,32 disabled=no dst-port=25,587 limit=30/1m,0 protocol=tcp

 add action=drop chain=forward comment="Avoid spammers action" disabled=no dst-port=25,587 protocol=tcp src-address-list=spammers

 add action=accept chain=input comment="Accept DNS - UDP" disabled=no port=53 protocol=udp

 add action=accept chain=input comment="Accept DNS - TCP" disabled=no port=53 protocol=tcp

 add action=accept chain=input comment="Accept to established connections" connection-state=established\

 disabled=no

 add action=accept chain=input comment="Accept to related connections" connection-state=related disabled=no

 add action=accept chain=input comment="Full access to SUPPORT address list" disabled=no src-address-list=support

 add action=drop chain=input comment="Drop anything else! # DO NOT ENABLE THIS RULE BEFORE YOU MAKE SURE ABOUT ALL ACCEPT RULES YOU NEED"\

 disabled=yes

 add action=accept chain=ICMP comment="Echo request - Avoiding Ping Flood, adjust the limit as needed" disabled=no icmp-options=8:0 limit=2,5 protocol=icmp

 add action=accept chain=ICMP comment="Echo reply" disabled=no icmp-options=0:0 protocol=icmp

 add action=accept chain=ICMP comment="Time Exceeded" disabled=no icmp-options=11:0 protocol=icmp

 add action=accept chain=ICMP comment="Destination unreachable" disabled=no icmp-options=3:0-1 protocol=icmp

 add action=accept chain=ICMP comment=PMTUD disabled=no icmp-options=3:4 protocol=icmp

 add action=drop chain=ICMP comment="Drop to the other ICMPs" disabled=no protocol=icmp

 add action=jump chain=output comment="Jump for icmp output" disabled=no jump-target=ICMP protocol=icmp



'''I think this is basic. You can add or remove anything else according to your needs. I hope it helps!'''


By Guilherme Ramires


Source : https://wiki.mikrotik.com/wiki/Basic_universal_firewall_script

Jumat, 29 Juli 2022

BASH : MYSQL menghapus tables tertentu yang sudah berumur lebih dari berapa periode, contoh 6 bulan 2 bulan 3 bulan 1 bulan, 2 minggu dll

BASH : Maintenance database mysql, menghapus tables tertentu yang sudah berumur lebih dari berapa periode, contoh 6 bulan 2 bulan 3 bulan 1 bulan, 2 minggu dll
#!/usr/bin/env bash
####!/bin/sh
#set -x  

#MYSQL INFO
#change it
SQLUSER="username"
#change it
SQLPASS="password"
#change it
DB="database_name" 
DATE=`date +'%Y-%m-%d'`

#Param Info 
DAYS="6 MONTH"
#Temp name for tables
TMPFILE="/tmp/tables_list-$DATE" 
 
export MYSQL_PWD=$SQLPASS
CMD="mysql -u$SQLUSER --skip-column-names -s -e" 
echo "IT WILL DELETE tables from $DB older then $DAYS"

echo "Script Started @ $DATE "
#change the table_prefix to delete certain table only
$CMD "SELECT TABLE_NAME FROM INFORMATION_SCHEMA.TABLES WHERE table_schema = '$DB' AND (table_name LIKE '%tbl_prefix_1_%' or table_name LIKE '%tbl_prefix_1_%') AND create_time < NOW() - INTERVAL $DAYS;" | awk '{print $1}' > $TMPFILE
num=0
cat $TMPFILE | while read tables
do
num=$[$num+1]
TABLE_TO_DELETE=`echo $tables`
$CMD "use $DB; DROP TABLE \`$TABLE_TO_DELETE\`;"
#$CMD "use $DB; select count(*) FROM \`$TABLE_TO_DELETE\`;"
DATE=`date +'%Y-%m-%d'`
echo "$DB_TRIMMING deleting TABLE $TABLE_TO_DELETE FROM $DB " 
done
echo "Script ended @ $DATE "

Based on code from : https://aacable.wordpress.com/2021/07/29/mysql-delete-single-table-older-than-x-days-using-script/

BASH : Perintah find dalam linux yang di gunakan untuk maintenance, seperti menghapus, mencari, rekrusif kedalam banyak folder

BASH : Perintah find Re-edited
#menghapus log didalam folder dengan umur diatas 60 hari dengan regex filtering
find ./my_dir -regex ".*\.log" -type f -mtime +60 -delete -print   

#menghapus log didalam folder dengan umur diatas 60 hari
find ./my_dir -type f -mtime +60 -print
#find ./my_dir -type f -mtime +60 -delete

#menghapus log didalam folder dengan size diatas 100mb
find ./my_dir -type f -size +100M -print
#find ./my_dir -type f -size +100M -delete
source : https://stackoverflow.com/questions/13489398/delete-files-older-than-10-days-using-shell-script-in-unix https://www.tomshardware.com/how-to/find-large-files-linux

Kamis, 28 Juli 2022

Bash : Arsipkan folder (rekrusif) dengan exclude file type tertentu

Unix/Linux Bash command : Mengarsipkan file di folder dengan exclude file type tertentu
tar --exclude={'*.mp4','*.mov','*.psd'} -cvf [filename].tar ./
source : https://superuser.com/posts/1712870/revisions

MYSQL : SQL Mengganti string dalam sebuah record

Cara cepat mengganti sebuah kata / bagian kalimat yang tercatat dalam suatu record, biasanya record yang bersifat string panjang (ie: urlencoded json parameters )
UPDATE
    <table_name>
SET
    <column_name> = REPLACE( <column_name>, 'text to find', 'text to replace with')
WHERE
    <column_name> LIKE '%text to find%';
Source From : 
https://www.codegrepper.com/code-examples/sql/mysql+update+replace+string

Kamis, 21 Juli 2022

JS : CLI tube timestamp file txt to cue

// Based on : https://github.com/bjoreman/cuegen

// Usage Properties : For mp3Split

// https://portableapps.com/apps/music_video/mp3splt-portable


const fs = require("fs");

const { isSet } = require("util/types");


const readFile = function (fileName) {

    return fs.readFileSync(fileName, "utf-8");

};

const makeTwoDigit = function(number) {

    if (number > 9) {

        return number;

    }

    return `0${ number }`;

};



const createTimeCode = function(hhmmss, millis) {

    let hours = 0;

    let minutes = 0;

    let seconds = parseInt(hhmmss.pop(), 10);

    if (hhmmss.length > 0) {

        minutes = parseInt(hhmmss.pop(), 10);

    }

    if (hhmmss.length > 0) {

        hours = parseInt(hhmmss.pop(), 10);

    }    

    const frames = Math.floor(75 * (millis * 0.001)); 

    if(millis){

        //console.log(`${ makeTwoDigit((hours * 60) + minutes) }:${ makeTwoDigit(seconds) }:${ makeTwoDigit(frames) }`);

        return `${ makeTwoDigit((hours * 60) + minutes) }:${ makeTwoDigit(seconds) }:${ makeTwoDigit(frames) }`;

    }else{

        //console.log(`${ makeTwoDigit((hours * 60) + minutes) }:${ makeTwoDigit(seconds) }`);

        return `${ makeTwoDigit((hours * 60) + minutes) }:${ makeTwoDigit(seconds) }:00`;

    }

};



const createCue = function(input, fileName) {

    input = input.replace(/\r/g, "\n");

    input = input.replace(/\n\n/g, "\n");

    const lines = input.split("\n");

    const result = [];

    console.log("Output File : "+fileName);

    result.push(`FILE "${ fileName }.mp3" MP3`);

    lines.forEach((line, index) => {

        if (!line || line.length < 1 || line.indexOf(" ") === -1) {

            return;

        }

        result.push(`\tTRACK ${ makeTwoDigit(index + 1) } AUDIO`);

        const [time, ...rest] = line.split(" ");

        const [hhmmss, millis] = time.split(".");

        const timeParts = hhmmss.split(":");

        const title = rest.join(" ");

        result.push(`\t\tREM NAME "${ title }"`); 

        console.log(hhmmss+"\t"+title);        

        result.push(`\t\tINDEX 01 ${ createTimeCode(timeParts, parseInt(millis, 10)) }`) 

    });

    return result.join("\n");

};



const writeCue = function (fileName, output) {

    fs.writeFileSync(fileName, output);

};



const run = function (inFile, outFile) { 

    writeCue(outFile, createCue(readFile(inFile), inFile.split(".")[0]));

};



const main = function (args) {

    console.log("Pastikan filename tanpa tanda \\");

    if (args.length < 3) {

        console.log("Required argument: input file");

        console.log("Optional argument: output file")

        return;

    }

    const inputFile = args[2];    

    const outputFile = args[3] ? args[3] : `${ inputFile.split(".")[0] }.cue`;

    run(inputFile, outputFile);

}



main(process.argv);

Senin, 11 Juli 2022

PHP - Rekrusif menghitung file dalam directory dan sub-dir

 function getFileCount($path) {

    $size = 0;
    $ignore = array('.','..','cgi-bin','.DS_Store');
    $files = scandir($path);
    foreach($files as $t) {
        if(in_array($t, $ignore)) continue;
        if (is_dir(rtrim($path, '/') . '/' . $t)) {
            $size += getFileCount(rtrim($path, '/') . '/' . $t);
        } else {
            $size++;
        }   
    }
    return $size;
}

source : https://stackoverflow.com/questions/640931/recursively-counting-files-with-php