<?php
/**
* Tumder Project - A platform for the fun
* @copyright (c) 2016 Loois Sndr. All rights reserved.
*
* @author Loois Sndr
* @since 2016
*/

/* 
* General functions 
*/

function title_tag() {
    echo '<title>' . td_title() . '</title>' . "\n";
}


function td_title($name_display=true, $sep1='&middot;', $sep2='&raquo;') {
    global $Tumd, $lang;
    switch ($_GET['p']) {
        case 'home':
        case 'index':
            $set = $lang['page_home'];
        break;
        case 'categories':
            $set = $lang['page_categories'];
        break;
        case 'community':
            $set = $lang['page_community'];
        break;
        case 'setting':
            if (isset($_GET['section']) && !empty($_GET['section'])) {
                $page_section = $_GET['section'];
                if ($page_section == 'info') {
                    $set = $lang['page_setting'].' '.$sep2.' '.$lang['page_section_info'];
                } elseif ($page_section == 'avatar') {
                    $set = $lang['page_setting'].' '.$sep2.' '.$lang['page_section_avatar'];
                } elseif ($page_section == 'theme') {
                    $set = $lang['page_setting'].' '.$sep2.' '.$lang['page_section_theme'];
                } elseif ($page_section == 'logs') {
                    $set = $lang['page_setting'].' '.$sep2.' '.$lang['page_section_logs'];
                } elseif ($page_section == 'password') {
                    $set = $lang['page_setting'].' '.$sep2.' '.$lang['page_section_password'];
                } else {
                    $set = $lang['page_section_not_found'];
                }
            } else {
                $set = $lang['page_section_not_found'];
            }
            
        break;
        case 'profile':
            if (isset($_GET['id']) && !empty($_GET['id'])) {
                if (getData($_GET['id'], 'id') == true) {
                    $username_titled = getData($_GET['id'], 'name');
                    $set = $username_titled['name'];
                } else {
                    $set = $lang['page_user_not_found'];
                }
            } else {
                $set = $lang['page_user_not_found'];
            }
        break;
        case 'search':
            if (isset($_GET['q']) && !empty($_GET['q'])) {
                $set = $lang['page_search'].' '.$sep2.' '.$_GET['q'];
            } else {
                $set = $lang['page_search'];
            }
        break;
        case 'play':
            if (isset($_GET['id']) && !empty($_GET['id'])) {
                if (getGame($_GET['id'], 'id') == true) {
                    $gamename_titled = getGame($_GET['id'], 'name');
                    $set = $gamename_titled['name'];
                } else {
                    $set = $lang['page_game_not_found'];
                }
            } else {
                $set = $lang['page_game_not_found'];
            }
        break;
        case 'admin':
            if (isset($_GET['section']) && !empty($_GET['section'])) {
                $page_section = $_GET['section'];
                if ($page_section == 'global') {
                    $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_global'];
                } elseif ($page_section == 'addgame') {
                    $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_addgame'];
                } elseif ($page_section == 'setting') {
                    $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_setting'];
                } elseif ($page_section == 'games') {
                    if (isset($_GET['action']) && !empty($_GET['action'])) {
                        $section_page = $_GET['action'];
                        if ($section_page == 'edit') {
                            $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_games'].' &rsaquo; '.$lang['admin_game_edit'];
                        } else {
                            $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_games'].' &rsaquo; '.$lang['page_section_not_found'];
                        }
                    } else {
                        $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_games'];
                    }
                } elseif ($page_section == 'categories') {
                    if (isset($_GET['action']) && !empty($_GET['action'])) {
                        $section_page = $_GET['action'];
                        if ($section_page == 'add') {
                            $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_categories'].' &rsaquo; '.$lang['admin_category_add'];
                        } elseif ($section_page == 'edit') {
                            $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_categories'].' &rsaquo; '.$lang['admin_category_edit'];
                        } else {
                            $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_categories'].' &rsaquo; '.$lang['page_section_not_found'];
                        }
                    } else {
                        $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_categories'];
                    }
                } elseif ($page_section == 'users') {
                    if (isset($_GET['action']) && !empty($_GET['action'])) {
                        $section_page = $_GET['action'];
                        if ($section_page == 'edit') {
                            $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_users'].' &rsaquo; '.$lang['admin_user_edit'];
                        } else {
                            $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_users'].' &rsaquo; '.$lang['page_section_not_found'];
                        }
                    } else {
                        $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_users'];
                    }
                } elseif ($page_section == 'ads') {
                    $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_ads'];
                } elseif ($page_section == 'reports') {
                    $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_reports'];
                } elseif ($page_section == 'catalog') {
                    if (isset($_GET['page']) && !empty($_GET['page'])) {
                        $section_page = $_GET['page'];
                        if ($section_page == 'catalog-1') {
                            $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_catalog'].' &rsaquo; '.$lang['admin_catalog_1'];
                        } elseif ($section_page == 'catalog-2') {
                            $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_catalog'].' &rsaquo; '.$lang['admin_catalog_2'];
                        } elseif ($section_page == 'catalog-3') {
                            $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_catalog'].' &rsaquo; '.$lang['admin_catalog_3'];
                        } else {
                            $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_catalog'].' &rsaquo; '.$lang['page_section_not_found'];
                        }
                    } else {
                        $set = $lang['page_admin'].' '.$sep2.' '.$lang['page_admin_section_catalog'];
                    }
                } else {
                    $set = $lang['page_section_not_found'];
                }
            } else {
                $set = $lang['page_section_not_found'];
            }        
        break;
        case 'login':
            $set = $lang['page_login'];
        break;
        case 'signup':
            $set = $lang['page_signup'];
        break;
        case 'error':
        default:
            $set = $lang['page_error'];
        break;
    }

    if ($name_display) {
        return $Tumd['config']['setting']['site_name'].' '.$sep1.' '.$set;
    } else {
        return $set;
    }
}


function urlState($url, $type=false) {
    if ($type == true) {
        return urlencode($url);
    }
    elseif($type == false) {
        return urldecode($url);
    }
}


function siteUrl() {
    global $Tumd;
    return $Tumd['config']['setting']['site_url'];
}


function shortStr($str, $len, $pnt=true) {
    if (strlen($str) > $len) {
        if ($pnt == true) {
            $str = mb_substr($str, 0, $len, 'UTF-8')."…";
        } else {
            $str = mb_substr($str, 0, $len, 'UTF-8');
        }
    }
    return $str;
}


function incPage($page_url='') {
    global $Tumd, $Tumdconnect, $lang;
    
    $page = dirname(dirname(dirname(__FILE__))).'/templates/' . $Tumd['config']['setting']['site_theme'] . '/content/' . $page_url . '.php';
    $page_content = '';
    
    ob_start();
    include($page);
    $page_content = ob_get_contents();
    ob_end_clean();
    
    return $page_content;
}


function secureEncode($string) {
    global $Tumdconnect;
    $string = trim($string);
    if (!$Tumdconnect->connect_errno) {
    $string = mysqli_real_escape_string($Tumdconnect, $string);
    }
    $string = htmlspecialchars($string, ENT_QUOTES);
    $string = str_replace('\\r\\n', '<br>',$string);
    $string = str_replace('\\r', '<br>',$string);
    $string = str_replace('\\n\\n', '<br>',$string);
    $string = str_replace('\\n', '<br>',$string);
    $string = str_replace('\\n', '<br>',$string);
    $string = stripslashes($string);
    $string = str_replace('&amp;#', '&#',$string);
    
    return $string;
}


function decodeHTML($string) {
    return $string = htmlspecialchars_decode($string);
}


function geoIP() {
    if($_SERVER) {
        if($_SERVER["HTTP_X_FORWARDED_FOR"]) {
            $insIP = $_SERVER["HTTP_X_FORWARDED_FOR"];
        } elseif ($_SERVER["HTTP_CLIENT_IP"]) {
            $insIP = $_SERVER["HTTP_CLIENT_IP"];
        } else {
            $insIP = $_SERVER["REMOTE_ADDR"];
        }
    } else {
        if(getenv("HTTP_X_FORWARDED_FOR")) {
            $insIP = getenv("HTTP_X_FORWARDED_FOR");
        } elseif(getenv("HTTP_CLIENT_IP")) {
            $insIP = getenv("HTTP_CLIENT_IP");
        } else {
            $insIP = getenv("REMOTE_ADDR");
        }
    }
    return $insIP;
}


function addslashes__recursive($var){
    if (!is_array($var))
    return addslashes($var);
    $new_var = array();
    foreach ($var as $k => $v)$new_var[addslashes($k)]=addslashes__recursive($v);
    return $new_var;
}

$_POST=addslashes__recursive($_POST);
$_GET=addslashes__recursive($_GET);
$_REQUEST=addslashes__recursive($_REQUEST);
$_SERVER=addslashes__recursive($_SERVER);
$_COOKIE=addslashes__recursive($_COOKIE);

function gameEmbed($file_url, $type, $width, $height) {
    // Flash object
    if ($type == 'swf') {
        $game_embedcode = '
        <object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="'.$width.'" height="'.$height.'" id="ieID">
        <param name="movie" value="'.$file_url.'" />
        <!--[if !IE]>-->
        <object type="application/x-shockwave-flash" data="'.$file_url.'" width="'.$width.'" height="'.$height.'" id="eID">
        <!--<![endif]-->
        <!--[if !IE]>-->
        </object>
        <!--<![endif]-->
        </object>';
    }
    // iFrame
    else {
        $game_embedcode = '<iframe src="'.$file_url.'" width="'.$width.'" height="'.$height.'" allowfullscreen frameborder="0" scrolling="no" id="game-player"></iframe>';
    }
    return $game_embedcode;
}


function gameFileUrl($file_url, $import) {
    global $Tumd;

    if ($import == 1) {
        $game_url = siteUrl().'/data-games/'.$file_url;
    }
    else {
        $game_url = $file_url;
    }
    return $game_url;
}


function gameImageUrl($image_url, $import) {
    global $Tumd;

    if ($import == 1) {
        $url = siteUrl().'/'.$image_url;
    }
    else {
        if ($image_url == '') {
            $url = $Tumd['theme_url'].'/image/data-game/default_game-thumb.png';
        }
        else {
            $url = $image_url;
        }
    }
    return $url;
}


function gameData($row_data) {
    global $Tumd;

    $game = array('game_id' => $row_data['game_id'], 'instructions' => nl2br($row_data['instructions']), 'plays' => number_format($row_data['plays'], 0, '', '.'), 'category' => $row_data['category']);
    
    $game['name'] = $row_data['name'];
    $game['description'] = $row_data['description'];
    $game['game_url'] = siteUrl().'/play/' . $row_data['game_id'];
    $game['file_url'] = gameFileUrl($row_data['file'], $row_data['import']);
    $game['embed'] = gameEmbed($game['file_url'], $row_data['game_type'], $row_data['w'], $row_data['h']);
    $game['image_url'] = gameImageUrl($row_data['image'], $row_data['import']);

    if ($Tumd['access'] == true && $Tumd['data']['admin'] == 1) {
        $game['admin_edit'] = '<button data-href="'.siteUrl().'/admin/games/edit/'.$row_data['game_id'].'" class="stt-adm-button top-gm-btn fa fa-pencil"></button>';
    }
    else {
        $game['admin_edit'] = '';
    }

    $game['date_added'] = date('d/m/y', $row_data['date_added']);

    return $game;
}


function getGame($gid=0) {
    global $Tumdconnect;
    $gid = secureEncode($gid);
    $sql_query_game = $Tumdconnect->query("SELECT * FROM ".GAMES." WHERE game_id='{$gid}'");
    if ($sql_query_game->num_rows == 1) {
        if ($game = $sql_query_game->fetch_array()) {
            return $game;
        }
    }
}


function getAvatar($avatar_id=0, $gender=1, $avatar_size='large') {
    $userGet_media = getMedia($avatar_id);

    if ($avatar_id != 0) {
        $avatar_picture = $userGet_media[''.$avatar_size.''];
    } else {
        if ($gender == 2) {
            $avatar_picture = siteUrl()."/data-photo/data-gender/avatar-female.png";
        } else {
            $avatar_picture = siteUrl()."/data-photo/data-gender/avatar-male.png";
        }
    }

    return $avatar_picture;
}


function getInfo($user_id=0) {
    global $Tumdconnect;

    if (empty($user_id) or !is_numeric($user_id) or $user_id < 1) {
        return false;
    }

    $user_id = secureEncode($user_id);

    $user_info = "SELECT gender,about FROM ".USERS." WHERE user_id = '{$user_id}'";
    $user_info_query = $Tumdconnect->query($user_info);

    if ($user_info_query->num_rows == 1) {
        if ($user = $user_info_query->fetch_object()) {
            return $user;
        }
    }
}

function getData($user_id=0, $query_select='*') {
    global $Tumdconnect;

    if (is_numeric($user_id)) {
        $user_id_type = "id = " . $user_id;
    } elseif (preg_match('/[A-Za-z0-9_]/', $user_id)) {
        $user_id_type = "username = '{$user_id}'";
    } else {
        return false;
    }

    $user_id = secureEncode($user_id);
    $user_data = "SELECT $query_select FROM ".ACCOUNTS." WHERE " . $user_id_type;
    $user_data_query = $Tumdconnect->query($user_data);

    if ($user_data_query->num_rows == 1) {
        if ($user = $user_data_query->fetch_array()) {
            return $user;
        }
    }
}

function getMedia($file_id=0) {
    global $Tumdconnect;
    
    if (empty($file_id) or !is_numeric($file_id) or $file_id < 1) {
        return false;
    }
    
    $file_id = secureEncode($file_id);
    $query_one = "SELECT * FROM ".MEDIA." WHERE id=$file_id";
    $sql_query_one = $Tumdconnect->query($query_one);
    
    if ($sql_query_one->num_rows == 1) {
        $sql_fetch_one = mysqli_fetch_assoc($sql_query_one);
        $sql_fetch_one['complete'] = siteUrl().'/'.$sql_fetch_one['url'] . '.' . $sql_fetch_one['extension'];
        $sql_fetch_one['large'] = siteUrl().'/'.$sql_fetch_one['url'] . '_100x75.' . $sql_fetch_one['extension'];
        $sql_fetch_one['medium'] = siteUrl().'/'.$sql_fetch_one['url'] . '_100x100.' . $sql_fetch_one['extension'];
        $sql_fetch_one['thumb'] = siteUrl().'/'.$sql_fetch_one['url'] . '_thumb.' . $sql_fetch_one['extension'];

        return $sql_fetch_one;
    }
}


function uploadMedia($upload) {
    if ($GLOBALS['access'] !== true) {
        return false;
    }
    
    global $Tumdconnect;
    set_time_limit(0);
    
    if (!file_exists('data-photo/' . date('Y'))) {
        mkdir('data-photo/' . date('Y'), 0777, true);
    }
    
    if (!file_exists('data-photo/' . date('Y') . '/' . date('m'))) {
        mkdir('data-photo/' . date('Y') . '/' . date('m'), 0777, true);
    }
    
    $photo_dir = 'data-photo/' . date('Y') . '/' . date('m');
    
    if (is_uploaded_file($upload['tmp_name'])) {
        $upload['name'] = secureEncode($upload['name']);
        $name = preg_replace('/([^A-Za-z0-9_\-\.]+)/i', '', $upload['name']);
        $ext = strtolower(substr($upload['name'], strrpos($upload['name'], '.') + 1, strlen($upload['name']) - strrpos($upload['name'], '.')));
        
        if ($upload['size'] > 1024) {
            
            if (preg_match('/(jpg|jpeg|png)/', $ext)) {
                
                list($width, $height) = getimagesize($upload['tmp_name']);
                
                $query_one = "INSERT INTO " . MEDIA . " (extension, name, type) VALUES ('$ext','$name','photo')";
                $sql_query_one = mysqli_query($Tumdconnect, $query_one);
                
                if ($sql_query_one) {
                    $sql_id = mysqli_insert_id($Tumdconnect);
                    $original_file_name = $photo_dir . '/' . generateKey() . '_' . $sql_id . '_' . md5($sql_id);
                    $original_file = $original_file_name . '.' . $ext;
                    
                    if (move_uploaded_file($upload['tmp_name'], $original_file)) {
                        $min_size = $width;
                        
                        if ($width > $height) {
                            $min_size = $height;
                        }
                        
                        $min_size = floor($min_size);
                        
                        if ($min_size > 920) {
                            $min_size = 920;
                        }
                        
                        $imageSizes = array(
                            'thumb' => array(
                                'type' => 'crop',
                                'width' => 64,
                                'height' => 64,
                                'name' => $original_file_name . '_thumb'
                            ),
                            '100x100' => array(
                                'type' => 'crop',
                                'width' => $min_size,
                                'height' => $min_size,
                                'name' => $original_file_name . '_100x100'
                            ),
                            '100x75' => array(
                                'type' => 'crop',
                                'width' => $min_size,
                                'height' => floor($min_size * 0.75),
                                'name' => $original_file_name . '_100x75'
                            )
                        );
                        
                        foreach ($imageSizes as $ratio => $data) {
                            $save_file = $data['name'] . '.' . $ext;
                            processMedia($data['type'], $original_file, $save_file, $data['width'], $data['height']);
                        }
                        
                        processMedia('resize', $original_file, $original_file, $min_size, 0);
                        mysqli_query($Tumdconnect, "UPDATE " . MEDIA . " SET url='$original_file_name' WHERE id=$sql_id");
                        $get = array(
                            'id' => $sql_id,
                            'extension' => $ext,
                            'name' => $name,
                            'url' => $original_file_name
                        );
                        
                        return $get;
                    }
                }
            }
        }
    }
}


function uploadGameMedia($upload) {
    if ($GLOBALS['access'] !== true) {
        return false;
    }
    
    global $Tumdconnect, $Tumd;
    set_time_limit(0);
    
    if (!file_exists('data-photo/data-game/images/' . date('Y'))) {
        mkdir('data-photo/data-game/images/' . date('Y'), 0777, true);
    }
    
    if (!file_exists('data-photo/data-game/images/' . date('Y') . '/' . date('m'))) {
        mkdir('data-photo/data-game/images/' . date('Y') . '/' . date('m'), 0777, true);
    }
    
    $photo_dir = 'data-photo/data-game/images/' . date('Y') . '/' . date('m');
    
    if (is_uploaded_file($upload['tmp_name'])) {
        $upload['name'] = secureEncode($upload['name']);
        $name = preg_replace('/([^A-Za-z0-9_\-\.]+)/i', '', $upload['name']);
        $ext = strtolower(substr($upload['name'], strrpos($upload['name'], '.') + 1, strlen($upload['name']) - strrpos($upload['name'], '.')));
        
        if ($upload['size'] > 1024) {
            
            if (preg_match('/(jpg|jpeg|png)/', $ext)) {
                
                list($width, $height) = getimagesize($upload['tmp_name']);
                
                $query_one = "INSERT INTO " . MEDIA . " (extension, name, type) VALUES ('$ext','$name','game')";
                $sql_query_one = mysqli_query($Tumdconnect, $query_one);
                
                if ($sql_query_one) {
                    $sql_id = mysqli_insert_id($Tumdconnect);
                    $original_file_name = $photo_dir . '/' . generateKey() . '_' . $sql_id . '_' . md5($sql_id);
                    $original_file = $original_file_name . '.' . $ext;
                    
                    if (move_uploaded_file($upload['tmp_name'], $original_file)) {
                        $min_size = $width;
                        
                        if ($width > $height) {
                            $min_size = $height;
                        }
                        
                        $min_size = floor($min_size);
                        
                        if ($min_size > 920) {
                            $min_size = 920;
                        }
                        
                        $imageSizes = array(
                            'thumb' => array(
                                'type' => 'crop',
                                'width' => 64,
                                'height' => 64,
                                'name' => $original_file_name . '_thumb'
                            ),
                            '100x100' => array(
                                'type' => 'crop',
                                'width' => $min_size,
                                'height' => $min_size,
                                'name' => $original_file_name . '_100x100'
                            ),
                            '100x75' => array(
                                'type' => 'crop',
                                'width' => $min_size,
                                'height' => floor($min_size * 0.75),
                                'name' => $original_file_name . '_100x75'
                            )
                        );
                        
                        foreach ($imageSizes as $ratio => $data) {
                            $save_file = $data['name'] . '.' . $ext;
                            processMedia($data['type'], $original_file, $save_file, $data['width'], $data['height']);
                        }
                        
                        processMedia('resize', $original_file, $original_file, $min_size, 0);
                        mysqli_query($Tumdconnect, "UPDATE " . MEDIA . " SET url='$original_file_name' WHERE id=$sql_id");
                        $get = array(
                            'id' => $sql_id,
                            'extension' => $ext,
                            'name' => $name,
                            'url' => $original_file_name
                        );
                        
                        return $get;
                    }
                }
            }
        }
    }
}


function processMedia($run, $photo_src, $save_src, $width=0, $height=0, $quality=80) {
    
    if (!is_numeric($quality) or $quality < 0 or $quality > 100) {
        $quality = 80;
    }

    if (file_exists($photo_src)) {
        
        if (strrpos($photo_src, '.')) {
            $ext = substr($photo_src, strrpos($photo_src,'.') + 1, strlen($photo_src) - strrpos($photo_src, '.'));
            $fxt = (!in_array($ext, array('jpeg', 'png'))) ? "jpeg" : $ext;
        } else {
            $ext = $fxt = 0;
        }
        
        if (preg_match('/(jpg|jpeg|png)/', $ext)) {
            list($photo_width, $photo_height) = getimagesize($photo_src);
            $create_from = "imagecreatefrom" . $fxt;
            $photo_source = $create_from($photo_src);
            
            if ($run == "crop") {
                
                if ($width > 0 && $height > 0) {
                    $crop_width = $photo_width;
                    $crop_height = $photo_height;
                    $k_w = 1;
                    $k_h = 1;
                    $dst_x = 0;
                    $dst_y = 0;
                    $src_x = 0;
                    $src_y = 0;
                    
                    if ($width == 0 or $width > $photo_width) {
                        $width = $photo_width;
                    }
                    
                    if ($height == 0 or $height > $photo_height) {
                        $height = $photo_height;
                    }
                    
                    $crop_width = $width;
                    $crop_height = $height;
                    
                    if ($crop_width > $photo_width) {
                        $dst_x = ($crop_width - $photo_width) / 2;
                    }
                    
                    if ($crop_height > $photo_height) {
                        $dst_y = ($crop_height - $photo_height) / 2;
                    }
                    
                    if ($crop_width < $photo_width || $crop_height < $photo_height) {
                        $k_w = $crop_width / $photo_width;
                        $k_h = $crop_height / $photo_height;
                        
                        if ($crop_height > $photo_height) {
                            $src_x  = ($photo_width - $crop_width) / 2;
                        } elseif ($crop_width > $photo_width) {
                            $src_y  = ($photo_height - $crop_height) / 2;
                        } else {
                            
                            if ($k_h > $k_w) {
                                $src_x = round(($photo_width - ($crop_width / $k_h)) / 2);
                            } else {
                                $src_y = round(($photo_height - ($crop_height / $k_w)) / 2);
                            }
                        }
                    }
                    
                    $crop_image = @imagecreatetruecolor($crop_width, $crop_height);
                    
                    if ($ext == "png") {
                        @imagesavealpha($crop_image, true);
                        @imagefill($crop_image, 0, 0, @imagecolorallocatealpha($crop_image, 0, 0, 0, 127));
                    }
                    
                    @imagecopyresampled($crop_image, $photo_source ,$dst_x, $dst_y, $src_x, $src_y, $crop_width - 2 * $dst_x, $crop_height - 2 * $dst_y, $photo_width - 2 * $src_x, $photo_height - 2 * $src_y);

                    @imageinterlace($crop_image, true);
                    @imagejpeg($crop_image, $save_src, $quality);
                    @imagedestroy($crop_image);
                }
            } elseif ($run == "resize") {
                
                if ($width == 0 && $height == 0) {
                    return false;
                }
                
                if ($width > 0 && $height == 0) {
                    $resize_width = $width;
                    $resize_ratio = $resize_width / $photo_width;
                    $resize_height = floor($photo_height * $resize_ratio);
                } elseif ($width == 0 && $height > 0) {
                    $resize_height = $height;
                    $resize_ratio = $resize_height / $photo_height;
                    $resize_width = floor($photo_width * $resize_ratio);
                } elseif ($width > 0 && $height > 0) {
                    $resize_width = $width;
                    $resize_height = $height;
                }
                
                if ($resize_width > 0 && $resize_height > 0) {
                    $resize_image = @imagecreatetruecolor($resize_width, $resize_height);
                    
                    if ($ext == "png") {
                        @imagesavealpha($resize_image, true);
                        @imagefill($resize_image, 0, 0, @imagecolorallocatealpha($resize_image, 0, 0, 0, 127));
                    }
                    
                    @imagecopyresampled($resize_image, $photo_source, 0, 0, 0, 0, $resize_width, $resize_height, $photo_width, $photo_height);

                    @imageinterlace($resize_image, true);
                    @imagejpeg($resize_image, $save_src, $quality);
                    @imagedestroy($resize_image);
                }
            } elseif ($run == "scale") {
                
                if ($width == 0) {
                    $width = 100;
                }
                
                if ($height == 0) {
                    $height = 100;
                }
                
                $scale_width = $photo_width * ($width / 100);
                $scale_height = $photo_height * ($height / 100);
                $scale_image = @imagecreatetruecolor($scale_width, $scale_height);
                
                if ($ext == "png") {
                    @imagesavealpha($scale_image, true);
                    @imagefill($scale_image, 0, 0, imagecolorallocatealpha($scale_image, 0, 0, 0, 127));
                }
                
                @imagecopyresampled($scale_image, $photo_source, 0, 0, 0, 0, $scale_width, $scale_height, $photo_width, $photo_height);

                @imageinterlace($scale_image, true);
                @imagejpeg($scale_image, $save_src, $quality);
                @imagedestroy($scale_image);
            }
        }
    }
} 


function generateKey($minlength=5, $maxlength=5, $uselower=true, $useupper=true, $usenumbers=true, $usespecial=false) {
    $charset = '';
    
    if ($uselower) {
        $charset .= "abcdefghijklmnopqrstuvwxyz";
    }
    
    if ($useupper) {
        $charset .= "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    }
    
    if ($usenumbers) {
        $charset .= "123456789";
    }
    
    if ($usespecial) {
        $charset .= "~@#$%^*()_+-={}|][";
    }
    
    if ($minlength > $maxlength) {
        $length = mt_rand($maxlength, $minlength);
    } else {
        $length = mt_rand($minlength, $maxlength);
    }
    
    $key = '';
    
    for ($i = 0; $i < $length; $i++) {
        $key .= $charset[(mt_rand(0, strlen($charset) - 1))];
    }
    
    return $key;
}

function dateState($date, $type=1) {
    $date_state = '';
    if ($type == 1) {
        $date_state = date("j/m/y", $date);
    }
    elseif ($type == 2) {
         $date_state = date("j/m/Y", $date);
    }
    elseif ($type == 3) {
         $date_state = date("j-m-y", $date);
    }
    elseif ($type == 4) {
         $date_state = date("j-m-Y", $date);
    }
    elseif ($type == 5) {
         $date_state = date("j/m/y g:i A", $date);
    }
    elseif ($type == 6) {
         $date_state = date("j/m/Y g:i A", $date);
    }
    elseif ($type == 7) {
         $date_state = date("j-m-y g:i A", $date);
    }
    elseif ($type == 8) {
         $date_state = date("j-m-Y g:i A", $date);
    }
    return $date_state;
}

function numberFormat($num) {
    $suffixes = array('', 'k', 'M', 'G', 'T');
        $suffixIndex = 0;
    
        while(abs($num) >= 1000 && $suffixIndex < sizeof($suffixes))
        {
            $suffixIndex++;
            $num /= 1000;
        }
    
        return (
            $num > 0
                ? floor($num * 1000) / 1000
                : ceil($num * 1000) / 1000
            )
            . $suffixes[$suffixIndex];
}


function listMenu($s1, $s2) {
    if ($s1 == $s2) {
        return 'active';
    } else {
        return false;
    }
}


function getADS() {
    global $Tumdconnect, $Tumd;

    $sql_query_ads = $Tumdconnect->query("SELECT * FROM ".ADS."");
    
    if ($Tumd['config']['setting']['ads_status'] == true && $sql_query_ads->num_rows == true) {
        $ads_select = mysqli_fetch_assoc($sql_query_ads);

        $ads_select['header'] = '
            <div class="ad-box ad-mg">
                <div>'.$ads_select['header'].'</div>
            </div>';
        $ads_select['footer'] = '
            <div class="ad-box ad-mg">
                <div>'.$ads_select['footer'].'</div>
            </div>';
        $ads_select['gametop'] = '
            <div class="ad-box ad-mg">
                <div>'.$ads_select['gametop'].'</div>
            </div>';
        $ads_select['gamebottom'] = '
            <div class="ad-box ad-mg">
                <div>'.$ads_select['gamebottom'].'</div>
            </div>';
        $ads_select['gameinfo'] = '
            <div class="ad-box ad-mg">
                <div>'.$ads_select['gameinfo'].'</div>
            </div>';
        $ads_select['column_one'] = '
            <div class="ad-box">
                <div>'.$ads_select['column_one'].'</div>
            </div>';
        return $ads_select;
    } else {
        return false;
    }
}


function feedID($data, $str=4, $key='x1') {
    $pro1 = substr($data, -$str); # Select last $str digits
    $pro2 = $pro1.$key;
    return $pro2;
}


function searchGames($sch_query='') {
    global $Tumdconnect;
    $q_result = array();
    
    if (!isset($sch_query) or empty($sch_query)) {
        return $q_result;
    }
    
    $sch_query = secureEncode($sch_query);

    $sql_query = $Tumdconnect->query("SELECT * FROM ".GAMES." WHERE name LIKE '%$sch_query%' AND published='1' ORDER BY name ASC");

    if ($sql_query->num_rows > 0) {
        while ($sql_fetch = $sql_query->fetch_assoc()) {
            $q_result[] = $sql_fetch;
        }
    }
    
    return $q_result;
}


function lastUser($type='login', $limit=5) {
    global $Tumdconnect;
    $q_lb_user = array();

    if ($type == 'login') {
        $last_users_logged = $Tumdconnect->query("SELECT avatar_id,name,username,id FROM ".ACCOUNTS." ORDER BY last_logged DESC LIMIT ".$limit);
        while ($last_user = $last_users_logged->fetch_object()) {
            $q_lb_user[] = $last_user;
        }
    } elseif ($type == 'registered') {
        $last_users_registered = $Tumdconnect->query("SELECT avatar_id,name,username,id FROM ".ACCOUNTS." ORDER BY registration_date DESC LIMIT ".$limit);
        while ($last_user = $last_users_registered->fetch_object()) {
            $q_lb_user[] = $last_user;
        }
    }

    return $q_lb_user;
}


function reportsStatus() {
    global $Tumdconnect;
    $q_reports = $Tumdconnect->query("SELECT report_id FROM ".REPORTS." WHERE report_id!=0");
    return $q_reports->num_rows;
}


function getStats($type='games', $num_format=true) {
    global $Tumdconnect;

    if ($type == 'games') {
        $stats_query = $Tumdconnect->query("SELECT game_id FROM ".GAMES." WHERE game_id!=0");
    } elseif ($type == 'users') {
        $stats_query = $Tumdconnect->query("SELECT id FROM ".ACCOUNTS." WHERE id!=0");
    } elseif ($type == 'categories') {
        $stats_query = $Tumdconnect->query("SELECT id FROM ".CATEGORIES." WHERE id!=0");
    } elseif ($type == 'catalog_games') {
        $stats_query = $Tumdconnect->query("SELECT id FROM ".CATALOG." WHERE id!=0");
    }

    if ($num_format) {
        return numberFormat($stats_query->num_rows);
    } else {
        return $stats_query->num_rows;
    }
}

function incCheck($array, $entry, $type='check') {
    foreach ($array as $c_array) {
        if ($type == 'check') {
            if (stripos(strtolower($entry), strtolower($c_array)) !== false) {
                return true;
            }
        }
        elseif ($type == 'scan') {
            if ($c_array == $entry) {
                return true;
            }
        }
    }
}