<?php

class Cf {
    
    public function get_timezone_offset($remote_tz, $origin_tz = null) {
        date_default_timezone_set('UTC');
        if ($origin_tz === null) {
            if (!is_string($origin_tz = date_default_timezone_get())) {
                return false; // A UTC timestamp was returned -- bail out!
            }
        }
        $origin_dtz = new DateTimeZone($origin_tz);
        $remote_dtz = new DateTimeZone($remote_tz);
        $origin_dt = new DateTime("now", $origin_dtz);
        $remote_dt = new DateTime("now", $remote_dtz);
        $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
        return $offset;
    }    
    
    public function get_tinymce_description_value($description1) {
        $description = '';
        for ($i = 0; $i < count($description1); $i++) {
            if ($description1[$i] != '') {
                $description = $description1[$i];
                break;
            }
        }
        return $description;
    }

    public function get_tinymce_description_value_for_edit($description, $old_description) {
        $counter = 0;
        for ($i = 0; $i < count($description); $i++) {
            if ($description[$i] == $old_description) {
                $counter++;
            }
        }
        if ($counter == 4) {
            return $old_description;
        } else {
            return $this->get_tinymce_description_value_for_edit1($description, $old_description);
        }
    }

    public function get_tinymce_description_value_for_edit1($description, $old_description) {
        $description1 = '';
        for ($i = 0; $i < count($description); $i++) {
            if ($description[$i] != $old_description) {
                $description1 = $description[$i];
                break;
            }
        }
        return $description1;
    }

    /**
     * Created date     : 2016-01-16
     * Name             : Mahabub-A-Mawla
     * Modified date    : 
     * Modifier name    : 
     * Work             : create subtitle 
     * call from        : user_video controller -> view_video() function
     */
    public function create_subtitle($save_path, $upload_video_transcript, $video_duration) {
        /*
         * special character  !@#$ % ^* ()_- += {}[] ' "  : ; <,> ? < div> <script> 
         */
        if ($upload_video_transcript) {
            $subtitle_sentence = array();
            $upload_video_transcript = str_replace('<p>', '', $upload_video_transcript);
            $upload_video_transcript = str_replace('</p>', '', $upload_video_transcript);
            $upload_video_transcript = str_replace('&', '', $upload_video_transcript);
            $upload_video_transcript = preg_replace("/\r|\n/", "", $upload_video_transcript);
            $subtitle_sentence = explode('. ', $upload_video_transcript);
            if ($subtitle_sentence[count($subtitle_sentence) - 1] == '') {
                array_pop($subtitle_sentence);
            }
            $total_sentence = count($subtitle_sentence);

            $upload_video_transcript = str_replace('.', '', $upload_video_transcript);
            $subtitle_word = explode(' ', $upload_video_transcript);
            $total_words = count($subtitle_word);
            $word_duration = $video_duration / $total_words;

            $i = 0;
            $sentence_duration = array();
            foreach ($subtitle_sentence as $v_sentence) {
                $v_sentence = trim($v_sentence);
                $sentence_words = explode(' ', $v_sentence);
                $sentence_total_word = count($sentence_words);
                $sentence_duration[$i] = $sentence_total_word * $word_duration;
                $i++;
            }
            if ($subtitle_sentence[count($subtitle_sentence) - 1] == '') {
                array_pop($subtitle_sentence);
            }
        }
        $xml = new DOMDocument();
        $xml->load('content-library/subtitle.xml');
        $placeing_tag = $xml->getElementsByTagName('body')->item(0);

        $div = $xml->createElement('div');
        $div->setAttribute('xml:lang', 'en');
        $div->setAttribute('id', 'subtitle');

        if ($subtitle_sentence) {
            $i = 0;
            $begin = '00:00:01';
            $next_begin = 0;
            $now_duration = $sentence_duration[$i];
            $duration = date('H:i:s', $sentence_duration[$i]);
            foreach ($subtitle_sentence as $v_sentence) {
                $p = $xml->createElement('p', $v_sentence);
                $p->setAttribute('begin', "$begin.00");
                $p->setAttribute('dur', "$duration.00");
                $p->setAttribute('style', 'subtitle');

                $next_begin = $next_begin + $sentence_duration[$i];

                $i++;
                $begin = date('H:i:s', $next_begin);
                $duration = date('H:i:s', $sentence_duration[$i]);

                $div->appendChild($p);
            }
        }

        $placeing_tag->appendChild($div);

        $string = $xml->saveXML();
        $xml->save("$save_path");
    }

    public function array_msort($array, $cols) {
        $colarr = array();
        foreach ($cols as $col => $order) {
            $colarr[$col] = array();
            foreach ($array as $k => $row) {
                $colarr[$col]['_' . $k] = strtolower($row[$col]);
            }
        }
        $eval = 'array_multisort(';
        foreach ($cols as $col => $order) {
            $eval .= '$colarr[\'' . $col . '\'],' . $order . ',';
        }
        $eval = substr($eval, 0, -1) . ');';
        eval($eval);
        $ret = array();
        foreach ($colarr as $col => $arr) {
            foreach ($arr as $k => $v) {
                $k = substr($k, 1);
                if (!isset($ret[$k]))
                    $ret[$k] = $array[$k];
                $ret[$k][$col] = $array[$k][$col];
            }
        }
        return $ret;
    }

    function format_interval(DateInterval $interval) {
        $result = "";
        if ($interval->y) {
            $result .= $interval->format("%y years ");
        }
        if ($interval->m) {
            $result .= $interval->format("%m months ");
        }
        if ($interval->d) {
            $result .= $interval->format("%d days ");
        }
        if ($interval->h) {
            $result .= $interval->format("%h hours ");
        }
        if ($interval->i) {
            $result .= $interval->format("%i minutes ");
        }
        if ($interval->s) {
            $result .= $interval->format("%s seconds ");
        }

        return $result;
    }    

    public function make_word_array($string) {
        //Lower case everything
        $string = strtolower($string);
        //Make alphanumeric (removes all other characters)
        $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
        //Clean up multiple dashes or whitespaces
        $string = preg_replace("/[\s-]+/", " ", $string);
        //Convert whitespaces and underscore to dash
        $string = preg_replace("/[\s_]/", "-", $string);
        return $string;
    }

    public function convert_file_folder_name($string) {
        //Lower case everything
        $string = strtolower($string);
        //Make alphanumeric (removes all other characters)
        $string = preg_replace("/[^a-z0-9_\s-]/", "", $string);
        //Clean up multiple dashes or whitespaces
        $string = preg_replace("/[\s-]+/", " ", $string);
        //Convert whitespaces and underscore to dash
        $string = preg_replace("/[\s_]/", "-", $string);
        return $string;
    }

    public function folderSize($dir) {
        $size = 0;
        foreach (glob(rtrim($dir, '/') . '/*', GLOB_NOSORT) as $each) {
            $size += is_file($each) ? filesize($each) : $this->folderSize($each);
        }
        return $size;
    }

    public function create_folder($profile_url) {
        if (!file_exists('content-library/' . $profile_url)) {
            $folder_Data = array('assignment-file', 'my-image', 'my-video', 'my-work-file', 'tt-content');
            for ($i = 0; $i < count($folder_Data); $i++) {
                $folder = 'content-library/' . $profile_url . '/' . $folder_Data[$i] . '/';
                mkdir($folder, 0777, true);
            }
        }
    }

    function view_emoticons($message) {
        $chars = array(
            ":)",
            ":(",
            ":D",
            "(y)",
            "<3",
            ":o",
            ":'(",
            ":p",
            ":v",
            ":@",
            "angel",
            "(n)",
            "(y-n)",
            "(cool)",
            "(:|)",
            ":|",
            "|-)",
            "think",
            "idea"
        );
        $icons = array(
            '<img src="' . base_url() . 'image/emoticons/smile.gif" alt="smile" width="30">',
            '<img src="' . base_url() . 'image/emoticons/sad.gif" alt="sad" width="30">',
            '<img src="' . base_url() . 'image/emoticons/laugh.gif" alt="laugh" width="30">',
            '<img src="' . base_url() . 'image/emoticons/like.gif" alt="like" width="30">',
            '<img src="' . base_url() . 'image/emoticons/heart.png" alt="heart" width="17">',
            '<img src="' . base_url() . 'image/emoticons/surprise.gif" alt="surprise" width="30">',
            '<img src="' . base_url() . 'image/emoticons/crying.gif" alt="crying" width="30">',
            '<img src="' . base_url() . 'image/emoticons/winking.png" alt="winking" width="17">',
            '<img src="' . base_url() . 'image/emoticons/laughing.png" alt="laughing" width="17">',
            '<img src="' . base_url() . 'image/emoticons/angry.gif" alt="angry" width="30">',
            '<img src="' . base_url() . 'image/emoticons/angel.gif" alt="angel" width="30">',
            '<img src="' . base_url() . 'image/emoticons/no.gif" alt="no" width="30">',
            '<img src="' . base_url() . 'image/emoticons/yes-no.gif" alt="yes-no" width="30">',
            '<img src="' . base_url() . 'image/emoticons/cool.gif" alt="cool" width="30">',
            '<img src="' . base_url() . 'image/emoticons/sweating.gif" alt="sweating" width="30">',
            '<img src="' . base_url() . 'image/emoticons/speechless.gif" alt="speechless" width="30">',
            '<img src="' . base_url() . 'image/emoticons/sleepy.gif" alt="sleepy" width="30">',
            '<img src="' . base_url() . 'image/emoticons/think.gif" alt="think" width="30">',
            '<img src="' . base_url() . 'image/emoticons/idea.gif" alt="idea" width="30">'
        );

        $combine_array = array_combine($chars, $icons);
        $view_message = $message;
        $i = 0;
        while (count($combine_array) > $i) {
            $view_message = str_replace($chars[$i], $icons[$i], $view_message);
            $i++;
        }
        return $view_message;
    }

    function time_format_for_read_write($user_time, $offset) {
        $current_date = date('Y-m-d H:i:s', (time() - $offset));
        $formated_current_date = new DateTime($current_date);
        $formated_user_date = new DateTime($user_time);
        $interval = $formated_user_date->diff($formated_current_date);
        if ($interval->format("%d")) {
            echo ' ' . $interval->format("%d days");
        }
        if ($interval->format("%h")) {
            echo ' ' . $interval->format("%h hours");
        }
        if ($interval->format("%i")) {
            echo ' ' . $interval->format("%i minutes");
        }
        echo ' ' . $interval->format("%s seconds");
        echo ' Ago ';
    }

    function read_write_status($user_id, $post_like_id, $id) {
        if ($post_like_id == '') {
            echo 'you first read this';
        } else {
            $liked_person_id = array_filter(explode(",", $post_like_id));
            if (count($liked_person_id) > 1) {
                if (in_array($user_id, $liked_person_id)) {
                    echo 'you and <a href="javascript:void(0)"  data-toggle="modal" data-target="#viewLikeModal_' . $id . '">' . (count($liked_person_id) - 1) . 'people</a>  read this';
                } else {
                    echo '<a href="javascript:void(0)"  data-toggle="modal" data-target="#viewLikeModal_' . $id . '">' . count($liked_person_id) . ' people</a> read this';
                }
            } else {
                if (in_array($user_id, $liked_person_id)) {
                    echo 'you read this';
                } else {
                    echo '<a href="javascript:void(0)"  data-toggle="modal" data-target="#viewLikeModal_' . $id . '">' . count($liked_person_id) . ' people</a> read this';
                }
            }
        }
    }    

        public function sec2view($seconds) {
        /**
         * Convert number of seconds into years, days, hours, minutes and seconds
         * and return an string containing those values
         *
         * @param integer $seconds Number of seconds to parse
         * @return string
         */
        $y = floor($seconds / (86400 * 365.25));
        $d = floor(($seconds - ($y * (86400 * 365.25))) / 86400);
        $h = gmdate('H', $seconds);
        $m = gmdate('i', $seconds);
        $s = gmdate('s', $seconds);

        $string = '';

        if ($y > 0) {
            $yw = $y > 1 ? ' years ' : ' year ';
            $string .= $y . $yw;
        }

        if ($d > 0) {
            $dw = $d > 1 ? ' days ' : ' day ';
            $string .= $d . $dw;
        }

        if ($h > 0) {
            $hw = $h > 1 ? ' hours ' : ' hour ';
            $string .= $h . $hw;
        }

        if ($m > 0) {
            $mw = $m > 1 ? ' minutes ' : ' minute ';
            $string .= $m . $mw;
        }

        if ($s > 0) {
            $sw = $s > 1 ? ' seconds ' : ' second ';
            $string .= $s . $sw;
        }

        return preg_replace('/\s+/', ' ', $string);
    }
    
    function dateDifference($date_1, $date_2, $differenceFormat = '%a') {
        $datetime1 = date_create($date_1);
        $datetime2 = date_create($date_2);
        $interval = date_diff($datetime1, $datetime2);
        return $interval->format($differenceFormat);
    }
    public $key = '1234567890123456';
    public $mode = MCRYPT_MODE_CBC;

    function decrypt_data($data) {
        $decode = base64_decode($data);
        return mcrypt_decrypt(
                MCRYPT_RIJNDAEL_128, $this->key, $decode, $this->mode, "\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0\0"
        );
    }
    function get_meta_url($data, $url) {
        $headers = array();
        $tags = array();
        $validhost = filter_var(gethostbyname(parse_url($url,PHP_URL_HOST)), FILTER_VALIDATE_IP);
        if($validhost){
            // get headers only when Domain is valid
            $headers = get_headers($url, 1);
            if(substr($headers[0], 9, 3)){
                // read Metatags only when Statuscode OK
                $tags = get_meta_tags($url);
                if(isset($tags['author'])){
                    if ($tags['author'] != '') {
                        $data['author'] = $tags['author'];     
                    }
                }else {
                    $data['author'] = '';     
                }
                if(isset($tags['description'])){
                    if ($tags['description'] != '') {
                        $data['description'] = $tags['description'];     
                    }
                }else {
                    $data['description'] = '';     
                }
                //$html = $this->file_get_contents_curl($url);
                $html = file_get_contents($url);
                
                //parsing begins here:
                libxml_use_internal_errors(true);
                $doc = new DOMDocument();
                $doc->loadHTML($html);
                $nodes = $doc->getElementsByTagName('title');
                //get and display what you need:
                $title = $nodes->item(0)->nodeValue;
                $description = '';
                $metas = $doc->getElementsByTagName('meta');
                for ($i = 0; $i < $metas->length; $i++) {
                    $meta = $metas->item($i);
                    if ($meta->getAttribute('name') == 'description'){
                        $description = $meta->getAttribute('content');
                    }
                }
                $data['title'] = $title;
                $data['description'] = $description;
                $data['author'] = '';
                libxml_clear_errors();
                
                return $data;
            }
        }
        else{
            $data['title'] = '';
            $data['description'] = '';
            $data['author'] = '';
            $data['invalide_url'] = 'Please Type Valid Url';
            return $data;
        }
    }
    
    function get_topic_status_modal($topic_id, $status) {
        echo '<div class="modal-dialog">
                            <div class="modal-content" style="top: 180px;border: 5px solid #80c12c;border-top: 20px solid #80c12c !important;margin: 0 auto;max-width: 400px">           
                                <div class="modal-body text-center" style="padding-bottom: 0px;">
                                    <span class="text-center">Are you sure you want to ' .$status. ' this Topic?</span>
                                </div>
                                <div class="modal-footer">
                                    <div  class="col-sm-12 text-center">  
					<span class="col-sm-3 col-sm-offset-3">
                                            <button  type="button" class="btn btn-danger  col-sm-12" data-dismiss="modal" style="font-size: 14px;">No</button>
                                        </span>		
					<span class="col-sm-3">
                                            <button onclick="changeTopicStatus(&quot;' . base_url() . 'admin/change-topic-status&quot;,' . $topic_id . ',&quot;' . $status . '&quot;)" class="btn btn-success  col-sm-12" data-dismiss="modal">Yes</button>
                                        </span>										
                                       
                                    </div>
                                </div>            
                            </div>
                        </div>';
    }   

    function get_status_modal($function_name, $message) {
        echo "<div class='modal-dialog'>
                            <div class='modal-content' style='top: 180px;border: 5px solid #80c12c;border-top: 20px solid #80c12c !important;margin: 0 auto;max-width: 400px'>           
                                <div class='modal-body text-center' style='padding-bottom: 0px;'>
                                    <span class='text-center'>$message</span>
                                </div>
                                <div class='modal-footer'>
                                    <div  class='col-sm-12 text-center'>  
					<span class='col-sm-3 col-sm-offset-3'>
                                            <button  type='button' class='btn btn-danger  col-sm-12' data-dismiss='modal' style='font-size: 14px;'>No</button>
                                        </span>		
					<span class='col-sm-3'>
                                            <button onclick='$function_name' class='btn btn-success  col-sm-12' data-dismiss='modal'>Yes</button>
                                        </span>										
                                       
                                    </div>
                                </div>            
                            </div>
                        </div>";
    }

    function view_modal($id, $message) {
        echo "<div class='modal-dialog'>
                            <div class='modal-content' style='top: 180px;border: 5px solid #80c12c;border-top: 20px solid #80c12c !important;margin: 0 auto; max-width: 400px'>           
                                <div class='modal-body text-center' style='padding-bottom: 0px;'>
                                    <span class='text-center'>$message</span>
                                </div>
                                <div class='modal-footer'>
                                    <div  class='col-sm-12 text-center'>
                                        <span class='col-sm-3 col-sm-offset-3'>
                                            <button  id='modalNoButton$id' class='btn btn-danger  col-sm-12' data-dismiss='modal' style='font-size: 14px;'>No</button>
                                        </span>                                        
                                        <span class='col-sm-3'>
                                            <button id='modalYesButton$id' class='btn btn-success col-sm-12' data-dismiss='modal'>Yes</button>
                                        </span>
                                    </div>
                                </div>            
                            </div>
                        </div>";
    }
    
    function view_single_modal($id, $message) {
        echo "<div class='modal-dialog'>
                            <div class='modal-content' style='top: 180px;border: 5px solid #80c12c;border-top: 20px solid #80c12c !important;margin: 0 auto; max-width: 370px'>           
                                <div class='modal-body text-center'>
                                    <p>$message</p>
                                </div>
                                <div class='modal-footer'>
                                    <div  class='col-sm-12 col-sm-offset-5'>               
                                        <button id='modalOkButton$id' type='button' class='btn btn-success col-sm-2' data-dismiss='modal'>OK</button>
                                    </div>
                                </div>            
                            </div>
                        </div>";
    }
    
    
 /*
 * @Function            : dd (die and dump)
 * @Description         : Takes variable / array and print it
                          This function is only for testing variables and arrays
 * @Developed By        : Md Mashqur Ul Alam
 * @Start DateTime      : 26-02-17
 * @Parameter           : $var        
 * @Status              : Available       
 */
    function dd($var){
        echo '<pre>';
        print_r($var);
        echo '</pre>';
        exit();
    }

}
