<?php

/**
 * @author Pratik Dev <webmaster.pratik@gmail.com>
 */

use WebPConvert\WebPConvert;
use Intervention\Image\ImageManagerStatic as Image;
use Intervention\Image\Exception\NotReadableException;

function isLogged()
{
    if (isset($_SESSION['id']) && isset($_SESSION['username']))
        return true;
    return false;
}

function Input($val, $htmlchars = false)
{
    if (isset($_REQUEST[$val])) {
        $val = $_REQUEST[$val];
        if ($htmlchars == true) {
            return strip_tags($val, '<div><p><br><strong><b><span><font><a><li><ul>');
        }
        return filter_var($val, FILTER_SANITIZE_STRING);
    }
    return false;
}
function InputArray($str)
{
    if (isset($_REQUEST[$str])) {
        $val = $_REQUEST[$str];
        return $val;
    }
    return array();
}

function Redirect($URL)
{
    header('Location:' . $URL);
    exit;
}

function name_underscore($str)
{
    $str = str_replace(' ', '_', trim($str));
    $str = preg_replace("/[^A-Za-z0-9-_]/", "", $str);
    $str = str_replace('___', '_', $str);
    $str = str_replace('__', '_', $str);
    return $str;
}

function slug($str)
{
    if (extension_loaded('intl')) {
        $generator = new Ausi\SlugGenerator\SlugGenerator();
        return $generator->generate($str);
      }
        $str = str_replace(' ', '-', trim($str));
        $str = str_replace('_', '-', $str);
        $str = preg_replace("/[^A-Za-z0-9-]/", "", $str);
        $str = str_replace('---', '-', $str);
        $str = str_replace('--', '-', $str);
        return strtolower($str);
}

function WriteFile($Path, $string, $overwrite = true)
{
    if (file_exists($Path) && $overwrite == false)
        $overwrite = false;
    if ($overwrite == true) {
        $myfile = fopen($Path, "w") or error_log("Unable to open file! Write Permission ");
        fwrite($myfile, $string);
        fclose($myfile);
    }
}

function dtsValue()
{
    if (isset($_POST["search"]["value"]))
        return $_POST["search"]["value"];
    return false;
}

function dtOrderby($var = true)
{
    if ($var == true)
        return $_POST['order']['0']['column'];
    else
        return  $_POST['order']['0']['dir'];
}
function dtlimit($var = true)
{
    if ($var == true)
        return $_POST['start'];
    else
        return  $_POST['length'];
}


function getDateformat($val)
{
    return date('d-m-y', strtotime($val));
}

function UploadFile($val, $path)
{
    global $allowExt;
    $fileExt = pathinfo($_FILES[$val]['name'], PATHINFO_EXTENSION);
    if (in_array($fileExt, $allowExt)) {
        $file = $_FILES[$val]['tmp_name'];
        if (move_uploaded_file($file, $path)) {
            return true;
        }
    }
    return false;
}
function deleteCatThumb($thumbnailname)
{
    global $RootPath;
    if ($thumbnailname) {
        $saveTo = $RootPath . '/upload_file/folderthumb';
        $appsizes = explode(',', CATICON_SIZES);
        foreach ($appsizes as $wh) {
            $ImgDir = $saveTo . '/' . $wh;
            if (file_exists($ImgDir . '/' . $thumbnailname))
                unlink($ImgDir . '/' . $thumbnailname);
        }
        $newthumbname = pathinfo($thumbnailname, PATHINFO_FILENAME);
        $catCover = $RootPath . '/upload_file/folderthumb/' . MP3TAG_COVER . '/cover_' . $newthumbname . '.jpg';
        if (file_exists($catCover)) {
            unlink($catCover);
        }
        return true;
    }
    return false;
}

function getApi($url, $data = array())
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_POST, true);
    curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_TIMEOUT, 3000);
    $data = curl_exec($ch);
    curl_close($ch);
    return @json_decode($data, true);
}

function deleteFilesbyCat($id)
{
    global $db, $RootPath;
    $db->join("" . TABLE_CAT . " c", "f.cid=c.id", "INNER");
    $db->where("c.id", $id);
    $files = $db->get("" . TABLE_FILES . " f", null, "c.folder, f.dname,f.ext");
    if ($files) {
        foreach ($files as $file) {
            $Path = $RootPath . '/' . $file['folder'] . $file['dname'] . '.' . $file['ext'];
            if (file_exists($Path)) {
                unlink($Path);

                $parentids = array_filter(explode('/', $file['folder']));
                array_shift($parentids);
                array_pop($parentids);
                if ($parentids) {
                    $breadcrumbs = $db->orderBy('id', 'ASC')->where('id', $parentids, 'IN')->get(TABLE_CAT);
                    foreach ($breadcrumbs as $bread) {
                        $db->where('id', $bread['id'])->update(TABLE_CAT, ['totalitem' => $db->dec(1)]);
                    }
                }
            }
        }
        return true;
    }
    return false;
}

function deleteSubCat($id)
{
    global $db;
    $parentCats = $db->where('parentid', $id)->get(TABLE_CAT);
    if ($parentCats) {
        foreach ($parentCats as $cat) {
            deleteCatThumb($cat['thumb']);
            //  deleteFilesbyCat($id);
            deleteSubCat($cat['id']);
            $db->where('id', $cat['id'])->delete(TABLE_CAT);
            $db->where('cid', $cat['id'])->delete(TABLE_FILES);
        }
    }
}

function MoveFolderFiles($src, $dst)
{
    if (preg_match("/upload_file/", $src)) {
        // open the source directory 
        $dir = opendir($src);
        // Make the destination directory if not exist 
        if (!is_dir($dst)) {
            mkdir($dst);
        }
        // Loop through the files in source directory 
        foreach (scandir($src) as $file) {
            if (($file != '.') && ($file != '..')) {
                if (is_dir($src . '/' . $file)) {
                    MoveFolderFiles($src . '/' . $file, $dst . '/' . $file);
                } else {
                    @rename($src . '/' . $file, $dst . '/' . $file);
                }
            }
        }
        closedir($dir);
        @rmdir($src);
    }
}

function MoveSubFolder($id, $catinfo = array())
{
    global $db;
    if (!$catinfo) {
        $catinfo = $db->where('id', $id)->getOne(TABLE_CAT);
    }
    if (!$catinfo) {
        return false;
        exit;
    }
    $catFolder = rtrim($catinfo['folder'], '/');
    if (!$catFolder) {
        return false;
        exit;
    }
    $targetFolder = $catFolder;
    $parentCats = $db->where('parentid', $catinfo['id'])->get(TABLE_CAT);
    if ($parentCats) {
        foreach ($parentCats as $cat) {
            $newfolderpath = $targetFolder . '/' . $cat['id'] . '/';
            $db->where('id', $cat['id'])->update(TABLE_CAT, ['folder' => $newfolderpath]);
            MoveSubFolder($cat['id'], array_replace($cat, ['folder' => $newfolderpath]));
        }
    }
    return true;
}


function rmdirr($path)
{
    if (preg_match("/upload_file/", $path)) {
        $dir = opendir($path);
        while ($entry = readdir($dir)) {
            if (is_file("$path/$entry")) {
                unlink($path . '/' . $entry);
            } elseif (is_dir("$path/$entry") && $entry != '.' && $entry != '..') {
                rmdirr("$path/$entry");
            }
        }
        closedir($dir);
        return rmdir($path);
    }
}

function formatSize($size, $type = false, $round = 2)
{
    $sizes = array('byts', 'kb', 'mb', 'gb', 'tb');
    $total = count($sizes) - 1;
    for ($i = 0; $size > 1024 && $i < $total; $i++)
        $size /= 1024;
    if ($type == true)
        return array(round($size, $round), $sizes[$i]);
    return round($size, $round) . ' ' . $sizes[$i];
}

function getDuration($filename)
{
    $getID3 = new getID3;
    $ThisFileInfo = $getID3->analyze($filename);
    return gmdate("i:s", @$ThisFileInfo['playtime_seconds']);
}

function WriteTag($Filename, $cover, $data = array(), $remove_other_tags = true)
{
    if (file_exists($Filename)) {
        $TaggingFormat = 'UTF-8';
        $TagFormatsToWrite = array('id3v1', 'id3v2.4', 'ape'); //array('id3v2.4','id3v2.3','id3v2.2','ape');
        $getID3 = new getID3;
        $getID3->setOption(array('encoding' => $TaggingFormat));
        getid3_lib::IncludeDependency(GETID3_INCLUDEPATH . 'write.php', __FILE__, true);
        $tagwriter = new getid3_writetags;
        $tagwriter->filename       = $Filename;
        $tagwriter->tagformats     = $TagFormatsToWrite;
        $tagwriter->overwrite_tags = true;
        $tagwriter->tag_encoding   = $TaggingFormat;
        $tagwriter->remove_other_tags = $remove_other_tags;

        $commonkeysarray = array('Title', 'Artist', 'Album', 'Year', 'Comment');
        foreach ($commonkeysarray as $key) {
            if (!empty($data[$key])) {
                $TagData[strtolower($key)][] = $data[$key];
            }
        }

        if (file_exists($cover)) {
            if (in_array('id3v2.4', $tagwriter->tagformats) || in_array('id3v2.3', $tagwriter->tagformats) || in_array('id3v2.2', $tagwriter->tagformats)) {
                if ($fd = @fopen($cover, 'rb')) {
                    $APICdata = fread($fd, filesize($cover));
                    fclose($fd);
                    list($APIC_width, $APIC_height, $APIC_imageTypeID) = GetImageSize($cover);
                    $imagetypes = array(1 => 'gif', 2 => 'jpeg', 3 => 'png');
                    if (isset($imagetypes[$APIC_imageTypeID])) {
                        $TagData['attached_picture'][0]['data']          = $APICdata;
                        $TagData['attached_picture'][0]['picturetypeid'] = $APIC_imageTypeID;
                        $TagData['attached_picture'][0]['description']   = basename($cover);
                        $TagData['attached_picture'][0]['mime']          = 'image/' . $imagetypes[$APIC_imageTypeID];
                    }
                }
            }
        }
        $tagwriter->tag_data = $TagData;
        if ($tagwriter->WriteTags()) {
            return true;
        }
        // if ($tagwriter->WriteTags()) {
        // 	$warning =  'Successfully wrote tags<BR>';
        // 	if (!empty($tagwriter->warnings)) {
        // 		$warning.= 'There were some warnings:<blockquote style="background-color: #FFCC33; padding: 10px;">'.implode('<br><br>', $tagwriter->warnings).'</div>';
        // 	}
        //     return $warning;
        // } else {
        // 	return 'Failed to write tags!<div style="background-color: #FF9999; padding: 10px;">'.implode('<br><br>', $tagwriter->errors).'</div>';
        // }


    }
    return false;
}
function urlexpander($url)
{
    if (empty($url)) {
        return;
    }
    $dara = get_headers($url);
    foreach ($dara as $d) {
        if (strpos($d, 'Location') !== false) {
            return str_replace("Location: ", "", $d);
        }
    }
    return $url;
}

function urlCopy($source, $destination)
{
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $source);
    curl_setopt($ch, CURLOPT_HEADER, false);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLINFO_HEADER_OUT, true);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.13) Gecko/20080311 Firefox/2.0.0.13');
    set_time_limit(300);
    curl_setopt($ch, CURLOPT_TIMEOUT, 300) or exit;
    $outfile = fopen($destination, 'wb');
    curl_setopt($ch, CURLOPT_FILE, $outfile) or exit;
    curl_exec($ch);
    fclose($outfile);
    return $destination;
}
function RunUpdate()
{
    global $db, $RootPath;
    $selectData = TABLE_FILES . '.*,' . TABLE_CAT . '.name as category_name,' . TABLE_CAT . '.folder, ' . TABLE_CAT . '.thumb as category_thumb';
    $db->join(TABLE_CAT, '' . TABLE_CAT . '.id=' . TABLE_FILES . '.cid', "INNER");
    $db->where(TABLE_FILES . '.thumb', '', '!=');
    $db->where(TABLE_FILES . '.thumb', '%webp', 'NOT LIKE');
    $files = $db->get(TABLE_FILES, 200, $selectData);
    $categories = $db->where('thumb', '', '!=')->where(TABLE_CAT . '.thumb', '%webp', 'NOT LIKE')->get(TABLE_CAT, 50, 'id,thumb');
    $fileids = array();
    $catids = array();
    foreach ($files as $file) {
        if ($file['thumb']) {
            $fileThumb = $RootPath . '/' . $file['folder'] . 'thumb-' . $file['dname'] . '.' . $file['thumb'];
            if (file_exists($fileThumb)) {
                $thumbname = uniqid('thumb_');
                if (genThumb($fileThumb, $RootPath . '/' . $file['folder'], $thumbname, false, FILE_THUMB_SIZES)) {
                    unlink($fileThumb);
                    $thumbnExt = $thumbname ? $thumbname . '.webp' : '';
                    if ($db->where('id', $file['id'])->update(TABLE_FILES, ['thumb' => $thumbnExt]))
                        array_push($fileids, $file['id']);
                } else {
                    $db->where('id', $file['id'])->update(TABLE_FILES, ['thumb' => '']);
                    unlink($fileThumb);
                }
            } else {
                if ($db->where('id', $file['id'])->update(TABLE_FILES, ['thumb' => '']))
                    array_push($fileids, $file['id']);
            }
        }
    }

    foreach ($categories as $cat) {
        if ($cat['thumb']) {
            $catThumb = $RootPath . '/folderthumb/' . $cat['thumb'];
            if (file_exists($catThumb)) {
                $cthumbname = uniqid('thumb_');
                if (genThumb($catThumb, $RootPath . '/upload_file/folderthumb/', $cthumbname, false)) {
                    unlink($catThumb);
                    $thumbNameExt = $cthumbname ? $cthumbname . '.webp' : '';
                    if ($db->where('id', $cat['id'])->update(TABLE_CAT, ['thumb' => $thumbNameExt]))
                        array_push($catids, $cat['id']);
                } else {
                    $db->where('id', $cat['id'])->update(TABLE_CAT, ['thumb' => '']);
                    unlink($catThumb);
                }
            } else {
                if ($db->where('id', $cat['id'])->update(TABLE_CAT, ['thumb' => '']));
                array_push($catids, $cat['id']);
            }
        }
    }
    return array($fileids, $catids);
}

function genThumb($Source, $saveTo, $thumbname, $postion, $cover = false, $thumbsizes = CATICON_SIZES, $x = 0, $y = 0)
{
    global $RootPath;
    $thumbformat = (THUMB_FORMAT == 'webp') ? 'png' : THUMB_FORMAT;
    $appsizes = explode(',', $thumbsizes);
    foreach ($appsizes as $wh) {
        $Imgwh = explode('x', $wh);
        $ImgDir =  $saveTo . $wh;
        if (!is_dir($ImgDir))
            mkdir($ImgDir);
         else {
            if ($wh == MP3TAG_COVER || $wh == PREVIEW_THUMB) {
                try {
                    if ($wh == MP3TAG_COVER && $cover == true) {
                        Image::make($Source)->save($ImgDir . '/cover_' . $thumbname . '.jpg', THUMB_QUALITY);
                    }
                    Image::make($Source)->save($ImgDir . '/' . $thumbname . '.' . $thumbformat, THUMB_QUALITY);
                } catch (NotReadableException $e) {
                    return false;
                }
            } else {
                try {
                    Image::make($Source)->save($ImgDir . '/' . $thumbname . '.' . $thumbformat, THUMB_QUALITY);
                } catch (NotReadableException $e) {
                    return false;
                }
            }
        }
        if (THUMB_FORMAT == 'webp') {
            WebPConvert::convert($ImgDir . '/' . $thumbname . '.' . $thumbformat, $ImgDir . '/' . $thumbname . '.webp', []);
            unlink($ImgDir . '/' . $thumbname . '.' . $thumbformat);
        }
    }

    return true;
}

function unZipFile($Path, $saveTo)
{
    if (class_exists("ZipArchive")) {
        $zip = new ZipArchive;
        $res = $zip->open($Path);
        if ($res === TRUE) {
            $zip->extractTo($saveTo);
            $zip->close();
            return true;
        }
    } else {
        error_log("ZipArchive Extension not Enabled");
    }
    return false;
}

function folder_Copy($src, $dst)
{
    // open the source directory 
    $dir = opendir($src);
    // Make the destination directory if not exist 
    @mkdir($dst);
    // Loop through the files in source directory 
    foreach (scandir($src) as $file) {
        if (($file != '.') && ($file != '..')) {
            if (is_dir($src . '/' . $file)) {
                folder_Copy($src . '/' . $file, $dst . '/' . $file);
            } else {
                copy($src . '/' . $file, $dst . '/' . $file);
            }
        }
    }
    closedir($dir);
}

function SendWebPush($title, $body, $image, $link)
{
    $fields = array(
        'app_id' => WEBPUSH_SENDER_ID,
        'included_segments' => array('All'),
        'data' => array("foo" => "bar"),
        'headings' => array("en" => $title),
        'contents' => array("en" => $body),
        'url' => $link,
        'big_picture' => $image, //This Android Only
        //	'chrome_big_picture' => $image,
        'chrome_web_icon' => APP_URL . '/assets/images/android-chrome-192x192.png',
        'chrome_web_image' => $image

    );


    $fields = json_encode($fields);
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "https://onesignal.com/api/v1/notifications");
    curl_setopt($ch, CURLOPT_HTTPHEADER, array(
        'Content-Type: application/json; charset=utf-8',
        'Authorization: Basic ' . WEBPUSH_REST_KEY . ''
    ));
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    curl_setopt($ch, CURLOPT_HEADER, FALSE);
    curl_setopt($ch, CURLOPT_POST, TRUE);
    curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
    $response = curl_exec($ch);
    curl_close($ch);
    if ($response) {
        $resp = json_decode($response, true);
        if (isset($resp['id'])) {
            return true;
        }
    }
    return false;
}
function deleteTMPFiles($Path, $hour = 60 * 60 * 72)
{
    if (preg_match('/upload_file/', $Path)) {
        $files = glob($Path . '/' . "*");
        $now   = time();
        foreach ($files as $file) {
            if (is_file($file)) {
                if ($now - filemtime($file) >= $hour) {
                    unlink($file);
                }
            }
        }
    }
}

function genSlug($slug, $id = '', $type = true)
{
    global $db;
    $slug = pathinfo($slug, PATHINFO_FILENAME);
    $slug = slug($slug);

    if ($id) {
        $db->where('id', $id, '!=');
    }
    $db->where('slug', $slug);
    if ($type == true) {
        $checkExists =  $db->has(TABLE_FILES);
    } else {
        $checkExists =   $db->has(TABLE_CAT);
    }

    if ($checkExists) {
        return genSlug($slug . '-' . rand(1, 9), $id, $type);
    }

    return $slug;
}

function genArtist($str)
{

    global $db;
    $artist = explode(',', $str);
    array_filter($artist);
    $ids = array();
    foreach ($artist as $ar) {
        $name = trim($ar);
        if ($name) {
            $slug = slug($name);
            $check = $db->where('slug', $slug)->has('artist');
            if ($check != true) {
                $id = $db->insert('artist', ['name' => $name, 'slug' => $slug, 'thumb' => '', 'status' => 1, 'created_at' => $db->now()]);
                array_push($ids, $id);
            }
        }
    }
    return $ids;
}
