<?php

/**
 * @Package: WordPress Plugin
 * @Subpackage: Ultra Portfolio
 * @Since: Ultra Portfolio 1.0
 * @Current Version: Ultra Portfolio 3.1
 * @WordPress Version: 3.5 or above
 * This file is part of Ultra Portofolio WordPress Plugin.
 */
require_once('uport_aq_resizer_1.2.0.php');

function uport_fields($type) {

    $field['step1'] = 'name|categories|woocategories|sortitemsby|sortitemslist|maxitems|';

    $field['step2'] = 'noofcolumns1|noofcolumns2|noofcolumns3|noofcolumns4|catshow|margintop|marginright|marginbottom|marginleft|showdetails|showdetailssub|lengthtitle|lengthdesc|uporttype|titletype|linktarget|linktype|linktext|lightboxtype|lightboxtext|carttype|carttext|pricetype|slugtype|lightboxcaption|imagewidth|imageheight|imagecrop|imageupscale|minwidth|maxwidth|outerstyle|';

    $field['step3_title'] = 'titlefontname|titlefontbackup|titlefontweight|titlefontsubset|titlefontsize|titlecolor|titlelineheight|titlealign|titlebgcolor|titlepaddingtop|titlepaddingright|titlepaddingbottom|titlepaddingleft|titlemargintop|titlemarginright|titlemarginbottom|titlemarginleft|';
    $field['step3_desc'] = 'descfontname|descfontbackup|descfontweight|descfontsubset|descfontsize|desccolor|desclineheight|descalign|descbgcolor|descpaddingtop|descpaddingright|descpaddingbottom|descpaddingleft|descmargintop|descmarginright|descmarginbottom|descmarginleft|';
    $field['step3_slug'] = 'slugfontname|slugfontbackup|slugfontweight|slugfontsubset|slugfontsize|slugcolor|sluglineheight|slugalign|slugbgcolor|slugpaddingtop|slugpaddingright|slugpaddingbottom|slugpaddingleft|slugmargintop|slugmarginright|slugmarginbottom|slugmarginleft|';
    $field['step3_maskbg'] = 'bgcolor|bgopacity|';
    $field['step3_outbg'] = 'outbgcolor|outbgopacity|';
    $field['step3_portbg'] = 'portbgcolor|portbgopacity|portpaddingtop|portpaddingright|portpaddingbottom|portpaddingleft|portmargintop|portmarginright|portmarginbottom|portmarginleft|';
    $field['step3_border'] = 'borderwidth|bordercolor|';
    $field['step3_shadow'] = 'hshadow|vshadow|shadowblur|shadowspread|shadowcolor|';
    $field['step3_catul'] = 'catalign|';
    $field['step3_catli'] = 'catfontname|catfontbackup|catfontweight|catfontsubset|catfontsize|catlineheight|catcolor|catbgcolor|catborderwidth|catbordercolor|catborderradius|catpaddingtop|catpaddingright|catpaddingbottom|catpaddingleft|catmargintop|catmarginright|catmarginbottom|catmarginleft|';
    $field['step3_catlihover'] = 'catbgactcolor|';
    $field['step3_but'] = 'butfontname|butfontbackup|butfontweight|butfontsubset|butfontsize|butcolor|butlineheight|butalign|butbgcolor|butpaddingtop|butpaddingright|butpaddingbottom|butpaddingleft|butmargintop|butmarginright|butmarginbottom|butmarginleft|butborderwidth|butbordercolor|butborderradius|';
    $field['step3_buthover'] = 'butbgcolor2|';
    $field['step3_price'] = 'pricefontname|pricefontbackup|pricefontweight|pricefontsubset|pricefontsize|pricecolor|pricelineheight|pricealign|pricebgcolor|pricepaddingtop|pricepaddingright|pricepaddingbottom|pricepaddingleft|pricemargintop|pricemarginright|pricemarginbottom|pricemarginleft|';
    $field['step3_above'] = 'abovefontname|abovefontbackup|abovefontweight|abovefontsubset|abovefontsize|abovecolor|abovelineheight|abovealign|abovebgcolor|abovepaddingtop|abovepaddingright|abovepaddingbottom|abovepaddingleft|abovemargintop|abovemarginright|abovemarginbottom|abovemarginleft|abovepos';

    $field['step3'] = $field['step3_title'] . $field['step3_desc'] . $field['step3_slug'] . $field['step3_maskbg'] . $field['step3_outbg'] . $field['step3_portbg'] . $field['step3_border'] . $field['step3_shadow'] . $field['step3_catul'] . $field['step3_catli'] . $field['step3_catlihover'] . $field['step3_but'] . $field['step3_buthover'] . $field['step3_price'] . $field['step3_above'];

    $field['step4'] = "overlayeffect|overlayeffectsub|mixspeed|mixeffects|mixeasing|isoeffects|owlslidespeed|owlpagespeed|owlrewindspeed|owlautoplay|owlnavigation|owlpagination|owlplaystop|owlscrollPerPage|";

    if (isset($field[$type])) {
        return $field[$type];
    } else {
        return "";
    }
}

function uport_get_arr($id, $stepid) {
    $arr = array();

    /* load all array index first to avoid any undefined variables */
    $fields = array();
    $fields = explode("|", uport_fields("step" . $stepid));
    $fields = array_unique(array_filter($fields));
    if (sizeof($fields) > 0) {
        foreach ($fields as $field) {
            $arr[$field] = "";
        }
    }



    if (trim($id) == "") {

        // load default values for new portfolio

        include(trailingslashit(dirname(__FILE__)) . "../shortcode/uport-def-values.php");

        if ($stepid == 2) {
            $arr = $def2arr;
        }
        if ($stepid == 3) {
            $arr = $def3arr;
        }
        if ($stepid == 4) {
            $arr = $def4arr;
        }
    } else {

        // load values from database for portfolio Id

        /* sql query */
        global $wpdb;
        $table_name1 = $wpdb->prefix . "uport";
        $col = "step" . $stepid . "val";
        $querystr = " SELECT $col FROM " . $table_name1 . " WHERE id = '" . $id . "' ";
        $obj_icons = $wpdb->get_results($querystr);

        /* loop through values to get in array */
        if (sizeof($obj_icons) > 0) {
            foreach ($obj_icons as $chart) {
                $values = $chart->$col;
            }
            if (trim($values) != "") {
                $starexp = explode("&", $values);
                foreach ($starexp as $metas) {
                    if (trim($metas) != "") {
                        $expmeta = explode("=", $metas);
                        $arr[$expmeta[0]] = urldecode($expmeta[1]);
                    }
                }
            }
        }
    }
    return $arr;
}

function uport_catstrs($type) {
    $str = "";
    $arr = array();
    global $wpdb;
    $table_name1 = $wpdb->prefix . "uport_categories";
    $querystr = " SELECT * FROM " . $table_name1 . " ORDER BY cat_name ";
    $obj_icons = $wpdb->get_results($querystr);
    if (sizeof($obj_icons) > 0) {
        foreach ($obj_icons as $chart) {
            $id = $chart->cat_id;
            $name = $chart->cat_name;
            if (trim($name) != "") {
                $str .= $id . ":" . $name . "|";
                $arr[$id] = $name;
            }
        }
    }
    if ($type == 'str') {
        return $str;
    }
    if ($type == 'arr') {
        return $arr;
    }
}

function uport_woocatstrs($type) {

    $str = "";
    $arr = array();

if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {
    // Put your plugin code here



    $taxonomy = 'product_cat';
    $orderby = 'name';
    $show_count = 0;      // 1 for yes, 0 for no
    $pad_counts = 0;      // 1 for yes, 0 for no
    $hierarchical = 1;      // 1 for yes, 0 for no  
    $title = '';
    $empty = 0;


    $args = array(
        'taxonomy' => $taxonomy,
        'orderby' => $orderby,
        'show_count' => $show_count,
        'pad_counts' => $pad_counts,
        'hierarchical' => $hierarchical,
        'title_li' => $title,
        'hide_empty' => $empty
    );

    $all_categories = get_categories($args);
    //print_r($all_categories);
    foreach ($all_categories as $cat) {
        //print_r($cat);
        if ($cat->category_parent == 0) {
            $category_id = $cat->term_id;

            $str .= "woo" . $category_id . ":" . $cat->name . "|";
            $arr["woo" . $category_id] = $cat->name;

            //echo '<br /><a href="'. get_term_link($cat->slug, 'product_cat') .'">'. $cat->name .'</a>';

            /* $args2 = array(
              'taxonomy'     => $taxonomy,
              'child_of'     => 0,
              'parent'       => $category_id,
              'orderby'      => $orderby,
              'show_count'   => $show_count,
              'pad_counts'   => $pad_counts,
              'hierarchical' => $hierarchical,
              'title_li'     => $title,
              'hide_empty'   => $empty
              );
              $sub_cats = get_categories( $args2 );
              if($sub_cats) {
              foreach($sub_cats as $sub_category) {
              //echo  $sub_category->name ;
              }
              } */
        }
    }
} // woocommerce check

    if ($type == 'str') {
        return $str;
    }
    if ($type == 'arr') {
        return $arr;
    }
}

add_action('wp_ajax_uport_load_font', 'uport_load_font');

function uport_load_font(){

    if (!isset($_POST['uport_nonce']) || !wp_verify_nonce($_POST['uport_nonce'], 'uport-nonce')) {
        die('Permissions check failed. Please login or refresh (if already logged in) the page, then try Again.');
    }

    $id = $_POST['id'];
    $font = $_POST['font'];

    include("uport_googlefonts.php");

    $weight_str = "<option value='null'>Select</option>";
    if(isset($googlefontsjson[$font])){
        $variants = $googlefontsjson[$font]['variants'];
        foreach($variants as $v){
                $weight_str .= "<option value='".$v['id']."'>".$v['name']."</option>";
        }
    }

    $subset_str = "<option value='null'>Select</option>";
    if(isset($googlefontsjson[$font])){
        $subsets = $googlefontsjson[$font]['subsets'];
        foreach($subsets as $v){
                $subset_str .= "<option value='".$v['id']."'>".$v['name']."</option>";
        }
    }

    echo $weight_str."|||".$subset_str;
    die();
}

add_action('wp_ajax_uport_bulk_selactions', 'uport_bulk_selactions');

function uport_bulk_selactions() {
   // print_r($_POST);
    //die();

    /*Array ( 
        [ids] => 33,34, 
        [actiontype] => copy 
        [type] => portfolio 
        [action] => uport_bulk_selactions 
        [uport_nonce] => 36983ae1c6 
    )*/

    $ids = "";
    if(isset($_POST['ids']) && trim($_POST['ids']) != ""){
        $ids = substr(trim($_POST['ids']),0,-1);
    }
    //echo $ids;

    $type = $_POST['type'];
    $actiontype = $_POST['actiontype'];

    if($ids != ""){
        if($actiontype == "copy"){
            uport_copythis("bulk",$ids,'copy_'.$type);
        } else if($actiontype == "delete"){
            uport_deletethis("bulk",$ids,'del_'.$type);
        }
    }    


    die();
}

add_action('wp_ajax_uport_deletethis', 'uport_deletethis');

function uport_deletethis($selected = "",$ids = "",$type = "") {
    if (!isset($_POST['uport_nonce']) || !wp_verify_nonce($_POST['uport_nonce'], 'uport-nonce')) {
        die('Permissions check failed. Please login or refresh (if already logged in) the page, then try Again.');
    }

    if($selected == ""){
        $id = $_POST['id'];
        $type = $_POST['type'];
        $url = $_POST['url'];
    }


    global $wpdb;
    if ($type == "del_portfolio") {
        
        //echo $type.$selected;

        if($selected == "bulk"){
            $wpdb->query('DELETE FROM ' . $wpdb->prefix . 'uport WHERE id IN ('.$ids.') ');
            echo "Selected Portfolios Deleted Successfully";
        } else {
            $wpdb->query('DELETE FROM ' . $wpdb->prefix . 'uport WHERE id=' . $id);
            echo "Portfolio Deleted Successfully";
        }
    }

    if ($type == "del_item") {
        if($selected == "bulk"){
            $wpdb->query('DELETE FROM ' . $wpdb->prefix . 'uport_items WHERE item_id IN ('.$ids.') ');
            echo "Selected Items Deleted Successfully";
        } else {
            $wpdb->query('DELETE FROM ' . $wpdb->prefix . 'uport_items WHERE item_id=' . $id);
            echo " Item Deleted Successfully";
        }
    }

    if ($type == "del_category") {

        if($selected == "bulk"){
            $wpdb->query('DELETE FROM ' . $wpdb->prefix . 'uport_categories WHERE cat_id IN ('.$ids.') ');
            echo "Selected Category Deleted Successfully";
        } else {
            $wpdb->query('DELETE FROM ' . $wpdb->prefix . 'uport_categories WHERE cat_id=' . $id);
            echo "Category Deleted Successfully";
        }
    }

    die();
}

add_action('wp_ajax_uport_copythis', 'uport_copythis');

function uport_copythis($selected = "",$ids = "",$type = "") {

    if (!isset($_POST['uport_nonce']) || !wp_verify_nonce($_POST['uport_nonce'], 'uport-nonce')) {
        die('Permissions check failed. Please login or refresh (if already logged in) the page, then try Again.');
    }

    if($selected == ""){
        $id = $_POST['id'];
        $type = $_POST['type'];
        $url = $_POST['url'];
    }

    global $wpdb;
    if ($type == "copy_portfolio") {

            if($selected == "bulk"){
                $copied = "";
                $exp = explode(",", $ids);
                foreach ($exp as $id) {
                    if($id != ""){
                        $result = uport_copy_portfolio($id);
                        if($result == true){
                            $copied .= $id.",";
                        }
                    }
                }
                $copied = substr($copied,0,-1);
                 echo "Portfolio Ids: ".$copied." Duplicated Successfully";

            } else {
                $result = uport_copy_portfolio($id);
                if($result == true){
                     echo "Portfolio ".$id." Duplicated Successfully";
                }
            }
        }
    

    if ($type == "copy_item") {

        if($selected == "bulk"){
                $copied = "";
                $exp = explode(",", $ids);
                foreach ($exp as $id) {
                    if($id != ""){
                        $result = uport_copy_item($id);
                        if($result == true){
                            $copied .= $id.",";
                        }
                    }
                }
                $copied = substr($copied,0,-1);
                 echo "Item Ids: ".$copied." Duplicated Successfully";

            } else {
                
                $result = uport_copy_item($id);
                if($result == true){
                     echo "Item ".$id." Duplicated Successfully";
                }
            }
    }


    if ($type == "copy_category") {

        if($selected == "bulk"){
                $copied = "";
                $exp = explode(",", $ids);
                foreach ($exp as $id) {
                    if($id != ""){
                        $result = uport_copy_category($id);
                        if($result == true){
                            $copied .= $id.",";
                        }
                    }
                }
                $copied = substr($copied,0,-1);
                 echo "Categories ".$copied." Duplicated Successfully";

            } else {
                
                $result = uport_copy_category($id);
                if($result == true){
                     echo "Category ".$id." Duplicated Successfully";
                }
            }
    }

    die();
}

function uport_copy_portfolio($id){

        global $wpdb;
        $querystr = " SELECT * FROM " . $wpdb->prefix . "uport WHERE id = '" . $id . "' ";
        $obj_icons = $wpdb->get_results($querystr);
        if (sizeof($obj_icons) > 0) {
            foreach ($obj_icons as $chart) {
                $step1val = $chart->step1val;
                $step2val = $chart->step2val;
                $step3val = $chart->step3val;
                $step4val = $chart->step4val;
                $updatedon = $chart->updatedon;
            }

            $wpdb->query($wpdb->prepare(" INSERT INTO " . $wpdb->prefix . "uport SET `step1val` = %s, `step2val` = %s, `step3val` = %s, `step4val` = %s, `updatedon` = %s , `active` = 1 ", $step1val, $step2val, $step3val, $step4val, $updatedon));

        return true;

    }
}


function uport_copy_item($id){

    global $wpdb;
    $querystr = " SELECT * FROM " . $wpdb->prefix . "uport_items WHERE item_id = '" . $id . "' ";
        $obj_icons = $wpdb->get_results($querystr);

        if (sizeof($obj_icons) > 0) {
            foreach ($obj_icons as $chart) {
                $item_title = $chart->item_title;
                $item_link = $chart->item_link;
                $item_description = $chart->item_description;
                $item_slug = $chart->item_slug;
                $item_date = $chart->item_date;
                $item_thumbnail = $chart->item_thumbnail;
                $item_thumbnailembed = $chart->item_thumbnailembed;
                $item_image = $chart->item_image;
                $item_ext = $chart->item_ext;
                $item_extvideo = $chart->item_extvideo;
                $item_extaudio = $chart->item_extaudio;
                $item_extembed = $chart->item_extembed;
                $item_category = $chart->item_category;
                $item_exttype = $chart->item_exttype;
            }
        }


        $wpdb->query($wpdb->prepare('
                INSERT INTO ' . $wpdb->prefix . 'uport_items(item_title, item_link, item_description, item_slug, item_date, item_thumbnail, item_thumbnailembed, item_image, item_ext, item_extvideo, item_extaudio, item_extembed, item_category, item_exttype)
                VALUES( %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)', $item_title, $item_link, $item_description, $item_slug, $item_date, $item_thumbnail, $item_thumbnailembed, $item_image, $item_ext, $item_extvideo, $item_extaudio, $item_extembed, $item_category, $item_exttype));
        return true;
}



function uport_copy_category($id){

    global $wpdb;
    $querystr = " SELECT * FROM " . $wpdb->prefix . "uport_categories WHERE cat_id = '" . $id . "' ";
        $obj_icons = $wpdb->get_results($querystr);

        if (sizeof($obj_icons) > 0) {
            foreach ($obj_icons as $chart) {
                $cat_name = $chart->cat_name;
                $cat_description = $chart->cat_description;
            }
        }

        $wpdb->query($wpdb->prepare('
                INSERT INTO ' . $wpdb->prefix . 'uport_categories(cat_name, cat_description)
                VALUES( %s, %s)', $cat_name, $cat_description));
        return true;
}




function uport_hex2rgba($color, $opacity = false) {

    $default = 'transparent';

    //Return default if no color provided
    if (empty($color))
        return $default;

    //Sanitize $color if "#" is provided 
    if ($color[0] == '#') {
        $color = substr($color, 1);
    }

    //Check if color has 6 or 3 characters and get values
    if (strlen($color) == 6) {
        $hex = array($color[0] . $color[1], $color[2] . $color[3], $color[4] . $color[5]);
    } elseif (strlen($color) == 3) {
        $hex = array($color[0] . $color[0], $color[1] . $color[1], $color[2] . $color[2]);
    } else {
        return $default;
    }

    //Convert hexadec to rgb
    $rgb = array_map('hexdec', $hex);

    //Check if opacity is set(rgba or rgb)
    if ($opacity) {
        if (abs($opacity) > 1){$opacity = 1.0;}
        $output = 'rgba(' . implode(",", $rgb) . ',' . $opacity . ')';
    } else {
        $output = 'rgba(' . implode(",", $rgb) . ',' . $opacity . ')';
    }

    //Return rgb(a) color string
    return $output;
}

add_action('uport_fancypox_hook', 'uport_fancypox_callback');

function uport_fancypox_callback() {
    // already enqueued in library once - just a backup
    //echo '<script type="text/javascript" src="' . path_join(WP_PLUGIN_URL, basename(dirname(__FILE__)) . '/src/fancypox/jquery.fancypox.js') . ' "></script>';
    //echo '<script type="text/javascript" src="' . path_join(WP_PLUGIN_URL, basename(dirname(__FILE__)) . '/src/fancypox/helpers/jquery.fancypox-media.js') . ' "></script>';
}

add_action('uport_mix_hook', 'uport_mix_callback');

function uport_mix_callback() {
    //echo '<script type="text/javascript" src="' . path_join(WP_PLUGIN_URL, basename(dirname(__FILE__)) . '/src/jquery.mixitub.js') . ' "></script>';
}

add_action('uport_iso_hook', 'uport_iso_callback');

function uport_iso_callback() {
    wp_register_script('uport_isojs', plugins_url('/../src/isotobe.pkgd.min.js', __FILE__), array('jquery'));
    wp_enqueue_script('uport_isojs');
    wp_register_style('uport_isoss', plugins_url('/../src/uport_isotobe.css', __FILE__));
    wp_enqueue_style('uport_isocss');
    //echo '<script type="text/javascript" src="' . path_join(WP_PLUGIN_URL, basename(dirname(__FILE__)) . '/src/isotobe.pkgd.min.js') . ' "></script>';
}

add_action('uport_owl_hook', 'uport_owl_callback');

function uport_owl_callback() {
//        echo '<script type="text/javascript" src="' . plugins_url('/../src/owl.carousel.min.js', __FILE__) . ' "></script>';
    wp_register_script('uport_owljs', plugins_url('/../src/owl.carousel.min.js', __FILE__), array('jquery'));
    wp_enqueue_script('uport_owljs');
    wp_register_style('uport_owlcss', plugins_url('/../src/owl.carousel.css', __FILE__));
    wp_enqueue_style('uport_owlcss');
    wp_register_style('uport_owlthemecss', plugins_url('/../src/owl.theme.css', __FILE__));
    wp_enqueue_style('uport_owlthemecss');
}

function uport_wooitems($woocat,$sortitemsby = "") {

    $object = new stdClass();
    $objarr = array();

    if ( in_array( 'woocommerce/woocommerce.php', apply_filters( 'active_plugins', get_option( 'active_plugins' ) ) ) ) {

        
        //print_r($woocat);
        $woocatid = array();
        foreach ($woocat as $catid) {
            $newid = str_replace("woo", "", $catid);
            $woocatid[] = $newid;
        }
        //print_r($woocatid);


        if(sizeof($woocatid) > 0){

            $orderby = 'date';
            $order = 'DESC';

            if(isset($sortitemsby) && $sortitemsby == "default"){
                $orderby = 'date'; $order = 'ASC';
            }
            else if(isset($sortitemsby) && $sortitemsby == "title"){
                $orderby = 'title'; $order = 'ASC';
            }
            else if(isset($sortitemsby) && $sortitemsby == "titledesc"){
                $orderby = 'title'; $order = 'DESC';
            }


            $args = array(
                'post_type' => 'product',
                'orderby' => $orderby,
                'order'   => $order,
                'posts_per_page' => 9999,
                'tax_query' => array(
                    array(
                        'taxonomy' => 'product_cat',
                        'field' => 'id',
                        'terms' => $woocatid
                    )
                )
            );

            $loop = new WP_Query($args);

            //print_r($loop->posts); 
            //$uport_all_sizes = get_intermediate_image_sizes();
            //print_r($uport_all_sizes);

            foreach ($loop->posts as $wooprod) {

                $price = array();
                $regular_price = get_post_meta($wooprod->ID, '_regular_price', true);
                $sale_price = get_post_meta($wooprod->ID, '_sale_price', true);
                //print_r($regular_price);
                //print_r($sale_price);
                $price['regular_price'] = $regular_price;
                $price['sale_price'] = $sale_price;
                $price['currency'] = get_woocommerce_currency();
                $price['currency_sym'] = get_woocommerce_currency_symbol();
                $price['regular_price'] = $regular_price;

                $cartbut = home_url()."/?post_type=product&add-to-cart=" . $wooprod->ID;

                //echo "<pre>"; print_r($wooprod);echo "</pre>";
                $prodid = "wc" . $wooprod->ID;
                $object->$prodid = new stdClass();

                $object->$prodid->item_id = $wooprod->ID;
                $object->$prodid->item_title = $wooprod->post_title;
                $object->$prodid->item_link = $wooprod->guid;
                $object->$prodid->item_description = $wooprod->post_excerpt;
                $object->$prodid->item_longdescription = $wooprod->post_content;
                $object->$prodid->item_slug = "";
                $object->$prodid->item_date = $wooprod->post_date_gmt;
                $object->$prodid->item_price = $price;
                $object->$prodid->item_cartbut = $cartbut;

                /* ------------------------
                  get categories
                  -------------------------- */
                $catstr = "";
                $cats = get_the_terms($wooprod->ID, 'product_cat');
                //echo "<pre>"; print_r($cats);  echo "</pre>"; 
                foreach ($cats as $cat) {
                    if (trim($cat->term_id) != "") {
                        $catstr .= "woo" . $cat->term_id . "|";
                    }
                }

                //$arr[$prodid]['acat'] = $catstr;
                $object->$prodid->item_category = $catstr;



                /* -------------------------
                  Thumb and images
                  --------------------- */

                $full = "";
                $thumb = "";
                $thumbimage = wp_get_attachment_image_src(get_post_thumbnail_id($wooprod->ID), 'large');
                $fullimage = wp_get_attachment_image_src(get_post_thumbnail_id($wooprod->ID), 'full');
                if (isset($thumbimage[0])) {
                    $thumb = $thumbimage[0];
                }
                if (isset($fullimage[0])) {
                    $full = $fullimage[0];
                }

                $object->$prodid->item_thumbnail = $thumb;
                $object->$prodid->item_thumbnailembed = "";
                $object->$prodid->item_image = $full;
                $object->$prodid->item_ext = "";
                $object->$prodid->item_extvideo = "";
                $object->$prodid->item_extaudio = "";
                $object->$prodid->item_extembed = "";
                $object->$prodid->item_exttype = "image";

                $objarr[$prodid] = $object->$prodid;
            }
            //echo "<pre>"; print_r($objarr); echo "</pre>"; 
            //echo "<pre>"; print_r($arr); echo "</pre>"; 


            wp_reset_query();

        } // check if woo category selected or not

    } // woocommerce check

    return $objarr;
}

function uport_item_from_obj($a, $pid, $val2arr, $catids) {

    $itemaid = array();

    $a->item_image = uport_upload_url($a->item_image);
    $a->item_thumbnail = uport_upload_url($a->item_thumbnail);
    $a->item_link = uport_upload_url($a->item_link);
    $a->item_thumbnailembed = uport_upload_url($a->item_thumbnailembed);
    $a->item_ext = uport_upload_url($a->item_ext);
    $a->item_extvideo = uport_upload_url($a->item_extvideo);
    $a->item_extaudio = uport_upload_url($a->item_extaudio);
    $a->item_extembed = uport_upload_url($a->item_extembed);

    $aid = $a->item_id;
    $atit = $a->item_title;
    $adesc = $a->item_description;
    $aslug = $a->item_slug;
    $alink = $a->item_link;
    $athumb = $a->item_thumbnail; // preivew onload image url
    $athumbembed = $a->item_thumbnailembed; // youtube,vimeo, etc. embed code for preview onload

    if(!isset($a->item_image) || trim($a->item_image) == ""){ $a->item_image = $a->item_thumbnail;}

    $aimage = $a->item_image; // lightbox large image
    $acat = $a->item_category;
    $aext = $a->item_ext; // lightbox external url of youtube, vimeo , etc.
    $aextvideo = $a->item_extvideo; // video file - default player
    $aextaudio = $a->item_extaudio; // audio file - default player
    $aextembed = $a->item_extembed; // embed code for lightbox
    $aexttype = $a->item_exttype;
    $aprice = isset($a->item_price) ? $a->item_price : "";
    $acartbut = isset($a->item_cartbut) ? $a->item_cartbut : "";
    $itemaid['id'] = $aid;
    $itemaid['title'] = $atit;
    $itemaid['titlefull'] = $atit;
    $itemaid['desc'] = $adesc;
    $itemaid['descfull'] = $adesc;
    $itemaid['slug'] = $aslug;
    $itemaid['link'] = $alink;
    $itemaid['image'] = $athumb;
    $itemaid['ext'] = $aext;
    $itemaid['extvideo'] = $aextvideo;
    $itemaid['extaudio'] = $aextaudio;
    $itemaid['extembed'] = stripslashes($aextembed);
    $itemaid['exttype'] = $aexttype;
    $itemaid['largeimage'] = $aimage;
    $itemaid['category'] = $acat;
    $itemaid['price'] = $aprice;
    $itemaid['cartbut'] = $acartbut;
    $itemaid['date'] = uport_dateformat($a->item_date);


    if (trim($athumbembed) != "") {
        if (strpos($athumbembed, 'iframe') !== false) {
            $athumbembed1 = explode("<"."iframe", $athumbembed);
            $athumbembed = "<"."iframe " . $athumbembed1[0] . " style='width:100%;' " . $athumbembed1[1];
        }
    }
    //echo $athumbembed;
    $itemaid['embed'] = stripslashes($athumbembed);

    //'<'.'iframe width="420px" style="width:100%;" height="315px" src="//www.youtube.com/embed/JIyXtA9HL7A" frameborder="0" allowfullscreen><'.'/iframe>';


    if (trim($val2arr['lengthtitle']) != "" && trim($val2arr['lengthtitle']) != "0" && strlen($itemaid['title']) > $val2arr['lengthtitle'] && strlen(trim($itemaid['title'])) > 0) {
        $dettit = substr($itemaid['title'], 0, $val2arr['lengthtitle']) . "...";
    } else {
        $dettit = $itemaid['title'];
    }
    if (trim($val2arr['lengthdesc']) != "" && trim($val2arr['lengthdesc']) != "0" && strlen($itemaid['desc']) > $val2arr['lengthdesc'] && strlen(trim($itemaid['desc'])) > 0) {
        $detdesc = substr($itemaid['desc'], 0, $val2arr['lengthdesc']) . "...";
    } else {
        $detdesc = $itemaid['desc'];
    }
    $itemaid['title'] = $dettit;
    $itemaid['desc'] = $detdesc;

    $datacatclass = "";
    $datacatclassval = "";
    $cexp = array_unique(array_filter(explode("|", $itemaid['category'])));
    foreach ($cexp as $cid) {
        $datacatclass .= "category_" . $cid . "_" . $pid . " ";
        if (isset($catids[$cid]) && trim($catids[$cid])) {
            $datacatclassval .= $catids[$cid] . ", ";
        }
    }
    $itemaid['catclass'] = $datacatclass;
    $datacatclassval = substr($datacatclassval, 0, -2);
    $itemaid['catclassval'] = $datacatclassval;

    return $itemaid;
}

function uport_dateformat($str){
    if(is_numeric($str)){
        return date("M d, Y",$str);
    } else {
        $exp = explode(" ",$str);
        $dt = $exp[0];
        $tm = $exp[1];
        $dtexp = explode("-",$dt);
        $tmexp = explode(":",$tm);
        $ts = mktime(0, 0, 0, $dtexp[1], $dtexp[2], $dtexp[0]);
        return date("M d, Y",$ts);        
    }
}

function uport_css_animation_type($type) {
    $arr = array();

    $arr['linear'] = "cubic-bezier(0.250, 0.250, 0.750, 0.750)";
    $arr['ease'] = "cubic-bezier(0.250, 0.100, 0.250, 1.000)";
    $arr['easeIn'] = "cubic-bezier(0.420, 0.000, 1.000, 1.000)";
    $arr['easeOut'] = "cubic-bezier(0.000, 0.000, 0.580, 1.000)";
    $arr['easeInOut'] = "cubic-bezier(0.420, 0.000, 0.580, 1.000)";
    $arr['easeInQuad'] = "cubic-bezier(0.550, 0.085, 0.680, 0.530)";
    $arr['easeInCubic'] = "cubic-bezier(0.550, 0.055, 0.675, 0.190)";
    $arr['easeInQuart'] = "cubic-bezier(0.895, 0.030, 0.685, 0.220)";
    $arr['easeInQuint'] = "cubic-bezier(0.755, 0.050, 0.855, 0.060)";
    $arr['easeInSine'] = "cubic-bezier(0.470, 0.000, 0.745, 0.715)";
    $arr['easeInExpo'] = "cubic-bezier(0.950, 0.050, 0.795, 0.035)";
    $arr['easeInCirc'] = "cubic-bezier(0.600, 0.040, 0.980, 0.335)";
    $arr['easeInBack'] = "cubic-bezier(0.600, -0.280, 0.735, 0.045)";
    $arr['easeOutQuad'] = "cubic-bezier(0.250, 0.460, 0.450, 0.940)";
    $arr['easeOutCubic'] = "cubic-bezier(0.215, 0.610, 0.355, 1.000)";
    $arr['easeOutQuart'] = "cubic-bezier(0.165, 0.840, 0.440, 1.000)";
    $arr['easeOutQuint'] = "cubic-bezier(0.230, 1.000, 0.320, 1.000)";
    $arr['easeOutSine'] = "cubic-bezier(0.390, 0.575, 0.565, 1.000)";
    $arr['easeOutExpo'] = "cubic-bezier(0.190, 1.000, 0.220, 1.000)";
    $arr['easeOutCirc'] = "cubic-bezier(0.075, 0.820, 0.165, 1.000)";
    $arr['easeOutBack'] = "cubic-bezier(0.175, 0.885, 0.320, 1.275)";
    $arr['easeInOutQuad'] = "cubic-bezier(0.455, 0.030, 0.515, 0.955)";
    $arr['easeInOutCubic'] = "cubic-bezier(0.645, 0.045, 0.355, 1.000)";
    $arr['easeInOutQuart'] = "cubic-bezier(0.770, 0.000, 0.175, 1.000)";
    $arr['easeInOutQuint'] = "cubic-bezier(0.860, 0.000, 0.070, 1.000)";
    $arr['easeInOutSine'] = "cubic-bezier(0.445, 0.050, 0.550, 0.950)";
    $arr['easeInOutExpo'] = "cubic-bezier(1.000, 0.000, 0.000, 1.000)";
    $arr['easeInOutCirc'] = "cubic-bezier(0.785, 0.135, 0.150, 0.860)";
    $arr['easeInOutBack'] = "cubic-bezier(0.680, -0.550, 0.265, 1.550)";

    foreach ($arr as $k => $v) {
        echo $k . "|";
    }
    if (isset($arr[$type]) && $arr[$type] != "") {
        return "
    -webkit-transition-timing-function: " . $arr[$type] . "; 
    -ms-webkit-transition-timing-function: " . $arr[$type] . ";
   -moz-transition-timing-function: " . $arr[$type] . ";
     -o-transition-timing-function: " . $arr[$type] . ";
        transition-timing-function: " . $arr[$type] . ";
    ";
    } else {
        return "";
    }
}

function uport_radiovalue($str, $nullval = "") {

    $val = $nullval;

    if ($str != "") {
        $effexp = explode("|", $str);
        $effexp = array_filter($effexp);

        if (sizeof($effexp) > 0 && is_array($effexp)) {
            $val = $effexp[0];
        }
    }

    return $val;
}

function uport_checkvalue($str, $nullval = array()) {

    $val = $nullval;

    if ($str != "") {
        $effexp = explode("|", $str);
        $effexp = array_filter($effexp);

        if (sizeof($effexp) > 0 && is_array($effexp)) {
            $val = $effexp;
        }
    }

    return $val;
}

function uport_imageurl($detarr, $val2arr, $val3arr) {

    $newimgurl = "";

    $imgurl = $detarr['image'];
    $width = '';
    $height = '';
    $crop = false;   // hard crop = true, soft crop = false
    $single = true; // return single url if true, array with url an dimenstion if false
    $upscale = false; // resize small images if true, if false will return empty string if resize not done to larger dimension
    // width if mentioned
    if (isset($val2arr['imagewidth']) && trim($val2arr['imagewidth']) != "" && is_numeric($val2arr['imagewidth']) && $val2arr['imagewidth'] != 0) {
        $width = trim($val2arr['imagewidth']);
    }


    // height if mentioned
    if (isset($val2arr['imageheight']) && trim($val2arr['imageheight']) != "" && is_numeric($val2arr['imageheight']) && $val2arr['imageheight'] != 0) {
        $height = trim($val2arr['imageheight']);
    }


    // crop and upscale values
    $crop = uport_radiovalue($val2arr['imagecrop'], false);
    $upscale = uport_radiovalue($val2arr['imageupscale'], false);


    // string to boolean
    if ($crop == "false") {
        $crop = false;
    } else {
        $crop = true;
    }
    if ($upscale == "false") {
        $upscale = false;
    } else {
        $upscale = true;
    }



    // check if file exits. if not then use upload dir filenotfound.png image
    //if(file_exists($imgurl)){
        //echo $imgurl."<br>";
        //$imgurl = uport_image_not_found(); 
    //}


    // if empty image url , use image not found
    if(trim($imgurl) == ""){
        $imgurl = uport_image_not_found();
    }

    $image_id = uport_imageid_byurl($imgurl);
    //echo $image_id."<br>";

    if($image_id != "") {
        // if image id is found, then resize
        $newimgurl = aq_uport_resize($imgurl, $width, $height, $crop, $single, $upscale);
    } else {
        // else return original without resize
        $newimgurl = $imgurl;
    }

    // if nothing is retured after resize, use original too
    if (trim($newimgurl) == "" || trim($newimgurl) == false) {
        $newimgurl = $imgurl;
    }

    //echo " $imgurl , $width , $height , $crop , $single , $upscale | $newimgurl <br>";

    return $newimgurl;
}

function uport_imageid_byurl($image_url){
    global $wpdb;
    $attachment = $wpdb->get_col($wpdb->prepare("SELECT ID FROM $wpdb->posts WHERE guid='%s';", $image_url )); 

    if(sizeof($attachment) > 0 && isset($attachment[0])){
        return $attachment[0]; 
    } else { 
        return ""; 
    }
}


function uport_image_not_found(){
    $upload_dir = wp_upload_dir();
    $upload_dir_path = $upload_dir['baseurl'];
    return $upload_dir_path."/2015/06/uport-ml-imgnotfound.png";
}

function uport_image_loading(){
    return plugins_url('/../images/uport-loading.png', __FILE__);
}


function uport_gfont_style($pid,$val3arr){


$gfont_arr = array();
$gfont_types = array('title','desc','slug','cat','but','price');

foreach($gfont_types as $type){

    $family = $val3arr[$type.'fontname'];
    $weight = trim($val3arr[$type.'fontweight']);
    //preg_match_all('!\d+!', $weight, $matches);
    //$weight = $matches[0][0];
    $subset = $val3arr[$type.'fontsubset'];

    $gfont_arr[$family]['weight'][] = $weight;
    $gfont_arr[$family]['subset'][] = $subset;

}
//echo "<pre>";
//print_r($gfont_arr);
//echo "</pre>";

$str = "family=";
$subset_str = "subset=";
foreach($gfont_arr as $family => $det){

    $weight_str = "";
    foreach($det as $k => $val_arr){
        
        if($k == "weight"){
            foreach($val_arr as $val){
                if($val != "null") {
                    $weight_str .= $val.",";
                }
            }
        }

        if($k == "subset"){
            foreach($val_arr as $val){
                if($val != "null") {
                    $subset_str .= $val.",";
                }
            }
        }

    }

        $str .= $family;
        if($weight_str != ""){ $weight_str = substr($weight_str,0,-1); $str .= ":".$weight_str;}
        $str .= "|";
}

$str = substr($str,0,-1);
$subset_str = substr($subset_str,0,-1);

//echo $str; echo "<br>"; echo $subset_str; echo "<br>";

$css_str = "https://fonts.googleapis.com/css?".$str."&".$subset_str;
//echo $css_str;
return '<link id="uport-gfonts-'.$pid.'" rel="stylesheet" href="'.$css_str.'"  type="text/css">';

//echo "<br>";
//echo "<br>";
//echo 'http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600italic,700italic,900italic|Lato|Open+Sans:300italic,600italic,400,600,800|Oswald:400,700|Roboto+Condensed&subset=latin,vietnamese,latin-ext,cyrillic-ext';
/*
<link href='http://fonts.googleapis.com/css?family=Source+Sans+Pro:400,600italic,700italic,900italic|Lato|Open+Sans:300italic,600italic,400,600,800|Oswald:400,700|Roboto+Condensed&subset=latin,vietnamese,latin-ext,cyrillic-ext' rel='stylesheet' type='text/css'>
<link rel="stylesheet" href="http://fonts.googleapis.com/css?family=Raleway:300&amp;subset=latin">

*/



}

function uport_out_class($pos,$pid,$style){
    return $style."_".$pid."_".$pos;
}

function uport_out_style($style,$pid){

$maskclass = uport_out_class('mask',$pid,$style);
$dataclass = uport_out_class('data',$pid,$style);
$aboveclass = uport_out_class('above',$pid,$style);

if($style == "bottom"){
    $mask = "";
    $data = "";
    $above = "";
}

if($style == "right"){
    $mask = "width:50% !important;float:left !important;";
    $data = "width:50% !important;float:right !important;";
    $above = "width:50% !important;float:left !important;";
}

if($style == "left"){
    $mask = "width:50% !important;float:right !important;";
    $data = "width:50% !important;float:left !important;";
    $above = "width:50% !important;left:50% !important;float:right !important;";
}


$str = "<style type='text/css' id='outer_style_".$pid."'>";

    $str .= ".".$maskclass."{ ".$mask." }";
    $str .= ".".$dataclass."{ ".$data." }";
    $str .= ".".$aboveclass."{ ".$above." }";
$str .= "</style>";

return $str;

}

function uport_nonautopxs(){
    return array("titlecolor", "titlebgcolor", "desccolor", "descbgcolor", "slugcolor", "slugbgcolor", "bgcolor", "bgopacity", "outbgcolor", "outbgopacity", "portbgcolor", "portbgopacity", "bordercolor", "shadowcolor", "catcolor", "catbgcolor", "catbgactcolor", "catbordercolor", "butcolor", "butbgcolor", "butbgcolor2", "butbordercolor","titlefontweight","descfontweight","slugfontweight","pricefontweight","catfontweight","butfontweight");
}


function uport_upload_url($str){

    //"http://localhost/ultra_portfolio/wp-content/uploads";

    $upload_dir = wp_upload_dir();
    
    $upload_dir_path = $upload_dir['baseurl'];

    $str = str_replace("UPORT_UPLOAD_DIR",$upload_dir_path,$str);
    
    return $str;
}




function sort_object_by_order($list,$sortorder){

    // loop through items to prepare a key based array of item objects
    $idarr = array();
    foreach ($list as $item) {
        $idarr[$item->item_id] = $item;
    }

    // create sort order in array format
    $sortids = array_unique(array_filter(explode(",",$sortorder)));

    // new array according to sort order from the key based array prepared above
    $newarr = array();
    foreach ($sortids as $itemid) {
        $itemid = str_replace("_", "", $itemid);
        if(isset($idarr[$itemid])){
            $newarr[] = $idarr[$itemid];
            unset($idarr[$itemid]);
        }
    }

    // append remaining items that are not in sort order in the new array
    foreach ($idarr as $item) {
        $newarr[] = $item;
    }

    return $newarr;
    //return $list;
}


function sort_shortcode_items_by_order($allitem,$val1arr){

    // custom sorting

    if($val1arr['sortitemsby'] == 'custom'){

        // loop through items to prepare a key based array of items
        $idarr = array();
        foreach ($allitem as $item) {
            $idarr[$item['id']] = $item;
        }

        // create sort order in array format
        $sortids = array_unique(array_filter(explode(",",$val1arr['sortitemslist'])));

        // new array according to sort order from the key based array prepared above
        $newarr = array();
        foreach ($sortids as $itemid) {
            $itemid = str_replace("_", "", $itemid);
            if(isset($idarr[$itemid])){
                $newarr[] = $idarr[$itemid];
                unset($idarr[$itemid]);
            }
        }

        // append remaining items that are not in sort order in the new array
        foreach ($idarr as $item) {
            $newarr[] = $item;
        }

    }
    else {
        return $allitem;
    }

    //echo "<pre>"; print_r($val1arr); echo "</pre>";
    return $newarr;
}



function uport_max_items_limit($val1arr,$itemcount){
    if(isset($val1arr['maxitems']) && is_numeric($val1arr['maxitems']) && $itemcount >= $val1arr['maxitems']){
        return "break";
    } else {
        return "";
    }
}
?>