<?php

class Common
{
    private $con_dist;

    public function __construct()
    {
        $dbs = new Database();

        $dist = $dbs->conDist();

        if ($dist instanceof mysqli) {
            $this->con_dist = $dist;
        } else {
            $this->common->logErrorFatal('', 'mysql:', 'dist mysql connection object is unusable'.print_r($dist, true), print_r(error_get_last(), true));
        }
    }

    public function getSetting($setting)
    {
        $get_setting = "SELECT setting FROM settings WHERE name='".$setting."'";
        $this->chkEmptyVar($setting);
        if ($chk = mysqli_query($this->con_dist, $get_setting)) {
            if (mysqli_num_rows($chk)) {
                $value = mysqli_fetch_row($chk);
                $this->chkEmptyVar($value[0]);

                return $value[0];
            } else {
                $this->logErrorFatal('', 'settings:', 'key: '.$setting.', dont exist', print_r(error_get_last(), true));
            }
        } else {
            $this->logErrorFatal('', "mysql:$get_setting", mysqli_error($this->con_dist), print_r(error_get_last(), true));
        }

        return false;
    }



    /**
     * [calculate_grade description]
     * @param  [type] $page_errors [description]
     * @return [type]              [description]
     */
    public function calculateGrade($url_grade_errors) {
        $gradeSum = 0;
        foreach ($url_grade_errors as $ugkey => $ugvalue) {
            $err_weight = strtoupper($ugkey)."_WEIGHT";

            $gradeSum += constant($err_weight);
        }
        if($gradeSum <= T_GRADE_A)
            return "A";
        if($gradeSum >= T_GRADE_A && $gradeSum <= T_GRADE_B)
            return "B";
        if($gradeSum >= T_GRADE_B && $gradeSum <= T_GRADE_C)
            return "C";
        if($gradeSum >= T_GRADE_C && $gradeSum <= T_GRADE_D)
            return "D";
        if($gradeSum >= T_GRADE_E && $gradeSum <= T_GRADE_F)
            return "E";
        if($gradeSum >= T_GRADE_F)
            return "F";
        return "F";

    }


    public function rel2abs($rel, $base)
    {
        /* return if already absolute URL */
        if (parse_url($rel, PHP_URL_SCHEME) != '') return $rel;

        /* queries and anchors */
        if ($rel[0]=='#' || $rel[0]=='?') return $base.$rel;

        /* parse base URL and convert to local variables:
           $scheme, $host, $path */
        extract(parse_url($base));

        /* remove non-directory element from path */
        $path = preg_replace('#/[^/]*$#', '', $path);

        /* destroy path if relative url points to root */
        if ($rel[0] == '/') $path = '';

        /* dirty absolute URL */
        $abs = "$host$path/$rel";

        /* replace '//' or '/./' or '/foo/../' with '/' */
        $re = array('#(/\.?/)#', '#/(?!\.\.)[^/]+/\.\./#');
        for($n=1; $n>0; $abs=preg_replace($re, '/', $abs, -1, $n)) {}

        /* absolute URL is ready! */
        return $scheme.'://'.$abs;
    }


    public function get_error_desc($err, $errval, $no_pages)
    {
        $show_err = "";
        $show_err_more = "";
        $more_details = 0;

        $errval['url'] = urldecode(urldecode(urldecode($errval['url'])));
        $link_id = "see_more_link";

        //minor
        if($err == 'spc')
        {
            $show_err = "You have <b>".$errval['espl']['spc']."</b> spelling errors on the URL <i>".$errval['url']."</i>. Please click <a href='javascript:void(0);' id='".$link_id."'><b>here</b></a> to see all corrections.";
            $show_err_more = "";
            // $more_details = 1;
        }
        if($err == "big")
        {
            if(empty($errval['epage']['hsi']))
                $errval['epage']['hsi'] = "300000";
            $show_err = "Your URL <i>".$errval['url']."</i> is too large with the size at <b>".round($errval['epage']['hsi']/1000)." KBs.</b> ";
            $show_err_more = "";
            // $more_details = 1;
        }
        if($err == 't')
        {
            $show_err = "Your URL <i>".$errval['url']."</i> has taken <b>".round($errval['t'])." sec</b> to load which is slower than the industry standards.";
            $show_err_more = "The speed of a page is made up of both Front-end and Server-side components. Currently, the load speed of the URL ".$errval['url']." is  is slow. As per industry standards the load speed of a URL should be less than 30 seconds. ";
            // $more_details = 1;
        }
        if($err == 'frm')
        {
            $show_err = "Your page has iframes in it.";
            $show_err_more = "";
        }
        if($err == 'fls')
        {
            $show_err = "Your page has flash content in it.";
            $show_err_more = "";
        }
        if($err == 'spu')
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> has unsafe/special characters.";
            $show_err_more = "unsafe/special characters are restricted by the Internet Engineering Task Force (IETF) who have clearly defined these specifications. Unsafe characters are classified as blank/empty spaces and ' < > # % { } | \ ^ ~ [ ] `";
        }
        if($err == 'ent')
        {
            $show_err = "Your URL has <a href='javascript:void(0);' id='".$link_id."'><b>".$errval['eln']['int']."</b></a> links.";
            $show_err_more = "";
            // $more_details = 1;
        }
        if($err == 'eex')
        {
            $show_err = "Your URL has <a href='javascript:void(0);' id='".$link_id."'><b>".$errval['eln']['ext']."</b></a> external links.";
            $show_err_more = "";
            // $more_details = 1;
        }
        if($err == 'nfc')
        {
            $show_err = "Your Page has <b>".$errval['eln']['nfc']."</b> nofollow links in it.";
            $show_err_more = "";
        }
        if($err == "eim")
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> has <a href='javascript:void(0);' id='".$link_id."'><b>".$errval['eimg']['count']."</b></a> images.";
            $show_err_more = "If your images are too large they will create numerous problems and issues on your site. First, your website will be slow. Second, your site visitors will become frustrated with the slow speed of the website Third, large images can take up a lot of space on your server";
            // $more_details = 1;
        }
        elseif($err == 'mst')
        {
                $show_err = "Your URL is linking <a href='javascript:void(0);' id='".$link_id."'><b>".count($errval['esht']['sts'])."</b></a> stylesheets.";
            $show_err_more = "";
            // $more_details = 1;
        }
        elseif($err == 'mlg')
        {
            $show_err = "This page has missing Language Decelaration.";
            $show_err_more = "";
        }
        elseif($err == 'mkw')
        {
            $show_err = "Meta Keywords are missing from your webpage.";
            $show_err_more = "Not the most important element of a web page. But it is advisable to include Meta Keywords on your webpage as it gives structure to the page.";
        }
        elseif($err == 'skw')
        {
            $show_err = "Your Meta Keyword <i>'".$errval['emet']['kws']."'</i> is <b>".mb_strlen(html_entity_decode($errval['emet']['kws'], ENT_QUOTES))."</b> characters long.";
            $show_err_more = "According to Google's Guidelines it should not be less than <b>".T_META_LOW."</b> characters. Meta keywords are distinguished from regular keywords because they appear “behind the scenes,” in the source code of your page, rather than on the live, visible page itself.";
            // $more_details = 1;
        }
        elseif($err == 'sti')
        {
            $show_err = "Your Title Tag <i>'".$errval['etit']['tit']."'</i> is <b>".mb_strlen(html_entity_decode($errval['etit']['tit'], ENT_QUOTES))."</b> characters long.";
            $show_err_more = "According to Google's Guidelines it should not be less than 25 characters. Making your title tags close to 70 characters is a good way to get the most out of your title tags and optimize your chances of showing up for different keyword searches.";
        }

        // medium
        elseif($err == 'mds')
        {
            $show_err = "The Meta Description is missing from the webpage.";
            $show_err_more = "Meta descriptions are HTML attributes that provide concise explanations of the contents of web pages. Meta descriptions are commonly used on search engine result pages (SERPs) to display preview snippets for a given page.";
        }
        elseif($err == 'unu')
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> has underscore ( _ ) in it.";
            $show_err_more = "Search engines treat dashes and underscores differently from one another. Google has clearly stated that when it comes to URL structure, using hyphens rather than underscores makes it much easier for them to identify what the page is about. Read more here- https://support.google.com/webmasters/answer/76329?hl=en";
        }
        elseif($err == 'mh2')
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> does not have the H2 Tag.";
            $show_err_more = "Unlike the H1 tag, you may have multiple H2, H3, H4, H5, and H6 sub-headings. Think of these sub-headings as ways of organizing the content on your page for your readers more than for the search engines.";
        }
        elseif($err == 'upu')
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> has upper case characters in it.";
            $show_err_more = "It is considered bad SEO practice if you have capitals in your URL as different servers handle capitalizations differently and those pages will be seen as two different pages. Consequently, if the different pages (URL's) lead to the same page it is bad for your search rankings.";
        }
        elseif($err == 'mnf')
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> uses meta nofollow tag.";
            $show_err_more = "";
        }
        elseif($err == 'mre')
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> uses meta refresh redirect";
            $show_err_more = "";
        }
        elseif($err == 'mrf')
        {
                $show_err = "Meta Refresh tag was found on this page. ";
            $show_err_more = "";
        }

        elseif($err == 'sds')
        {
            $show_err = "Your Meta Description <i>'".$errval['emet']['desc']."'</i> is <b>".mb_strlen(html_entity_decode($errval['emet']['desc'], ENT_QUOTES))."</b> characters long.";
            $show_err_more = "According to Google's Guidelines it should not be less than <b>".T_DESC_LOW."</b> characters. Ideally, the Meta Description should be between 140-160 characters.The meta description is used by search engines to describe the Web page in their results.";
            // $more_details = 1;
        }
        elseif($err == 'lds')
        {
            $show_err = "Your Meta Description <i>'".$errval['emet']['desc']."'</i> is <b>".mb_strlen(html_entity_decode($errval['emet']['desc'], ENT_QUOTES))."</b> characters long.";
            $show_err_more = "According to Google's Guidelines it should not be greater than 200 characters as Google starts cutting off descriptions after 155-160 characters. The meta description is a meta tag that is used to describe the current Web page. It provides a short summary of the page so that readers can decide whether the page is what they are looking for.";
            // $more_details = 1;
        }
        elseif($err == "low")
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> has low Text-to-HTML Ratio at <b>".round($errval['etth']['ratio'])."</b>.";
            $show_err_more = "Every website has a certain amount of backend code and a certain amount of regular text in the front-end. The text to HTML ratio refers to the amount of text on a web page versus the HTML code on the same web page.";
        }

        // major
        elseif($err == "eti")
        {
            $show_err = "The Title Tag is missing from your webpage.";
            $show_err_more = "The title tag is the single most important on-page SEO element. It is critical to both user experience and search engine optimization as it defines the title of the document.";
        }
        elseif($err == 'can')
        {
            $show_err = "rel='can' tag was found on this page. ";
            $show_err_more = "";
        }
        elseif($err == 'nin')
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> is blocked by meta no index tag.";
            $show_err_more = "";
        }
        elseif($err == 'eh2')
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> has <a href='javascript:void(0);' id='".$link_id."'><b>".count($errval['eh2s']['h2t'])."</b></a> H2 Tags.";
            $show_err_more = "Ideally, there should be a maximum number of <b>".T_H2_NO."</b> H2 tags on your webpage.";
        }
        elseif($err == 'eh1')
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> has <a href='javascript:void(0);' id='".$link_id."'><b>".count($errval['eh1s']['h1t'])."</b></a> H1 Tags.";
            $show_err_more = "Ideally, there should be a maximum number of <b>".T_H1_NO."</b> H1 tags on your webpage.";
        }
        elseif($err == 'mh1')
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> does not have the H1 Tag.";
            $show_err_more = "The proportion of the H1 Tag's  influence on rankings compared to the overall picture has diminished over time, but is still an important ranking factor.";
        }
        elseif($err == 'lu')
        {
            $show_err = "Your URL is <b>".mb_strlen($errval['url'])."</b> characters long.";
            $show_err_more = "According to Google's Guidelines it should not be less than 50 characters. Ideally, the Meta Description should be between 140-160 characters.The meta description is used by search engines to describe the Web page in their results. ";
        }
        elseif($err == 'dde')
        {
            $show_err = "Your Meta Description <i>'".$errval['emet']['desc']."'</i> is used on <a href='javascript:void(0);' id='".$link_id."'><b>".$no_pages."</b></a> other pages.";
            $show_err_more = "As suggested by Matt Cutts himself, it is better to have unique meta descriptions and even no meta descriptions at all, than to show duplicate meta descriptions across pages.";
            // $more_details = 1;
        }

        elseif($err == 'lt')
        {
            $show_err = "Your Title Tag <i>'".$errval['etit']['tit']."'</i> is <b>".mb_strlen(html_entity_decode($errval['etit']['tit'], ENT_QUOTES))."</b> characters long.";
            $show_err_more = "According to Google's Guidelines it should not be greater than 100 characters. Search engines display only the first 70 characters of a web page’s title tag. The rest gets chopped off and replaced with ellipses.";
            // $more_details = 1;
        }
        elseif($err == 'dkw')
        {
            $show_err = "Your Meta Keyword <i>'".$errval['emet']['kws']."'</i> is used on <a href='javascript:void(0);' id='".$link_id."'><b>".$no_pages."</b></a> other pages.";
            $show_err_more = "Having duplicate Meta Keywords will be considered as 'Keyword Stuffing'. The most important thing to keep in mind when selecting or optimizing your meta keywords is to be sure that each keyword accurately reflects the content of your page.";
            // $more_details = 1;
        }

        elseif($err == 'dti')
        {
            $show_err = "Your Title Tag is used on <a href='javascript:void(0);' id='".$link_id."'><b>".$no_pages."</b></a> other pages.";
            $show_err_more = "Having duplicate title tags may result in only 1 of your pages getting indexed or your website ranking on only 1 keyword. Google is all about original content and anything you can do to make the content fresh and different will help Google, you and your visitors.";
            // $more_details = 1;
        }
        elseif($err == "mal")
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> has missing Alt-Tags.<br /> Click <a href='javascript:void(0);' id='".$link_id."'><b>Here</b></a> to see the complete list of missing alt tags.";
            $show_err_more = "The alt attribute is used to describe the contents of an image file. It's important for several reasons: 1) It provides Google with useful information about the subject matter of the image. Google uses this information to help determine the best image to return for a user's query. 2) It helps users with visual impairments, or people using screen readers or who have low-bandwidth connections—may not be able to see images on web pages. Descriptive alt text provides these users with important information.<br /> Click below to see complete list of missing alt tags.";
            // $more_details = 1;

        }
        elseif($err == 'lkw')
        {
            $show_err = "Your Meta <i>'".$errval['emet']['kws']."'</i> Keyword is <b>".mb_strlen(html_entity_decode($errval['emet']['kws'], ENT_QUOTES))."</b> characters long.";
            $show_err_more = "According to Google's Guidelines it should not be greater than 250 characters. Meta Keywords are a specific type of meta tag that appear in the HTML code of a Web page and help tell search engines what the topic of the page is.";
            // $more_details = 1;
        }
        elseif($err == 'tu')
        {
            $show_err = "You have <b>".$errval['dup_perc']." %</b> of duplicate content on <a href='javascript:void(0);' id='".$link_id."'><b>".$errval['tu']."</b></a> page(s) of your website.";
            $show_err_more = "Duplicate content generally refers to substantive blocks of content within or across domains that either completely match other content or are appreciably similar. To see the full list of URL's with duplicate content please click below.";
            // $more_details = 1;
        }
        elseif($err == 'thn')
        {
            $show_err = "Your URL <i>'".$errval['url']."'</i> has <b>'".$errval['epage']['wrd']."'</b> words and is categorised as having thin content.";
            $show_err_more = "Thin content is a webpage with little or no original content. According to Google Guidelines, a web page has thin content if it has less than 200 words. One of the most important steps in improving your site's ranking in Google search results is to ensure that it contains plenty of rich information that includes relevant keywords, used appropriately, that  indicate the subject matter of your content.";
        }
        return array($show_err, $show_err_more, $more_details);
    }
















    public function chkEmptyVar($var_arr)
    {
        if (empty($var_arr) && $var_arr !== 0 && $var_arr !== '0') {
            $this->logErrorFatal('', 'variable:important variable empty', '', print_r(error_get_last(), true));
        }
        if (is_array($var_arr) && !empty($var_arr)) {
            foreach ($var_arr as $value) {
                if (empty($value) && $value !== 0 && $value !== '0') {
                    $this->logErrorFatal('', 'variable:important variable empty', trim(preg_replace('/\s+/', ' ', print_r($value, true))), print_r(error_get_last(), true));
                }
            }
        }
    }

    public function logErrorFile($err)
    {
        $dir = '/var/www/html/logs/';
        $file = '/var/www/html/logs/error.log';

        if (!is_dir($dir)) {
            mkdir($dir);
        }
        $error = $err.print_r(error_get_last(), true).print_r(debug_backtrace(0), true);
        $fhn = fopen($file, 'a+');
        fwrite($fhn, $error."\n");
        fclose($fhn);
    }

    /**
     *  Function: logs custom erros in DB and provides front end error managment.
     *
     *  @param $uid: logged in user id
     *  @param $section: section where error occured, (file,mysql,etc)
     *  @param $cause: detaild error reporting, mostly error_get_last() output
     *  @param $mongoDB: mongoDB connection resource
     */
    public function logErrorFatal($pid, $section, $cause, $detail = '')
    {
        $log = "INSERT INTO log_fatal VALUES('', '".$pid."','".addslashes($section)."','".addslashes($cause)."', NOW(), '".addslashes(trim(preg_replace('/\s+/', ' ', $detail)))."','".MY_IP."', '".addslashes(trim(preg_replace('/\s+/', ' ', print_r(debug_backtrace(0), true))))."')";

        if (mysqli_query($this->con_dist, $log)) {
            return true;
        } else {
            $this->logErrorFile(print_r(array($pid, $section, $cause, $detail, mysqli_error($this->con_dist)), true));

            return mysqli_error($this->con_dist);
        }
    }

    /**
     *  Function: logs custom erros in DB and provides front end error managment.
     *
     *  @param $uid: logged in user id
     *  @param $section: section where error occured, (file,mysql,etc)
     *  @param $cause: detaild error reporting, mostly error_get_last() output
     *  @param $mongoDB: mongoDB connection resource
     */
    public function logErrorFix($pid, $section, $cause, $detail = '')
    {
        $log = "INSERT INTO log_fix VALUES('', '".$pid."','".addslashes($section)."','".addslashes($cause)."', NOW(), '".addslashes(trim(preg_replace('/\s+/', ' ', $detail)))."','".MY_IP."', '".addslashes(trim(preg_replace('/\s+/', ' ', print_r(debug_backtrace(0), true))))."')";
        if (mysqli_query($this->con_dist, $log)) {
            return true;
            $this->logErrorFile(print_r(array($pid, $section, $cause, $detail, mysqli_error($this->con_dist)), true));
        } else {
            return mysqli_error($this->con_dist);
        }
    }


}
