<?php
/*$ips = array('80.12.38.36','195.132.158.230','82.127.222.225', '195.132.128.82') ;
if (! in_array($_SERVER['REMOTE_ADDR'], $ips) ) {
    header ("Location: /waiting.html");
    exit();
}*/

error_reporting(E_ALL ^E_NOTICE ^E_WARNING);
ini_set('display_errors', 1);
$forbidden = array('167.114.236.116', '167.114.234.92', '88.191.164.3', '167.114.237.221', '167.114.236.63',
                    '167.114.246.243', '167.114.236.222', '167.114.235.92', '167.114.235.0');
if ( in_array($_SERVER['REMOTE_ADDR'], $forbidden)) {
    header('HTTP/1.0 403 Forbidden');
    exit('403 Forbidden');
}

displayTimer('start script');
$www_found = strpos($_SERVER['HTTP_HOST'], 'www');
if ($www_found !== false) {header('Location: '. str_replace('www.', '', 'http://' . $_SERVER['HTTP_HOST']));exit;}

if ( substr($_SERVER['REQUEST_URI'], 0, 5) == '/http') {header ("Location: " . substr($_SERVER['REQUEST_URI'], 1, strlen($_SERVER['REQUEST_URI']))); exit;}
use Doctrine\ORM\Query\ResultSetMapping;
use Doctrine\ORM\Query\ResultSetMappingBuilder;

$twig_vars = array ();
include('../vendor/autoload.php');
include('../config/web-includes.php');
/* timer functions for debug */
function microtime_float() {
    list($usec, $sec) = explode(" ", microtime());
    return ((float)$usec + (float)$sec);
}
$time_start = microtime_float();

function displayTimer($position = '') {
    global $time_start, $time;
    $time_end = microtime_float();
    $time_since_last_call = abs(round($time - ($time_end - $time_start), 5));
    $time = $time_end - $time_start;

    if ((isset($_GET['display_timer']) && $_GET['display_timer'] == 1 && $_GET['key'] == 'tata')) { //isset($_SESSION) && $_SESSION['user'] && $_SESSION['user']->getIsAdmin() == 9
        if ($position == '') {
            echo round($time, 3) ;
        } else {
            echo '<br />' . $position . ' ' . round($time, 5) . ' -- since last call : ' . $time_since_last_call;
        }
    }
}
//error_reporting(E_ALL ^E_NOTICE ^E_WARNING ^E_DEPRECATED);
//ini_set('display_errors', 1);



$loader = new \Twig\Loader\FilesystemLoader('../templates');
/*if($_SERVER['REMOTE_ADDR'] == '83.167.39.250') {
    $debug = true;
}*/
//$debug = true;
if (isset($debug) && $debug) {
    error_reporting(E_ALL ^E_NOTICE ^E_WARNING ^E_DEPRECATED);
    ini_set('display_errors', 1);
    $twig = new \Twig\Environment($loader, array(
        'cache' => false,
        'debug' => true,
    ));
} else {
    error_reporting(0);
    ini_set('display_errors', 0);
    if ( ! isset($twig) || ! isset($twig_vars['twig_cache']) || $twig_vars['twig_cache'] != false) {
        $twig = new \Twig\Environment($loader, array(
            'cache' => '../templates_c',
            'debug' => false,
        ));
    }
}

//$escaper = new \Twig\Extension\EscaperExtension('add');
//$twig->addExtension($escaper);

//$twig->addFilter(new Twig_SimpleFilter('addslashes', 'addslashes'));
$twig->addExtension(new \Twig\Extension\DebugExtension());
$function = new \Twig\TwigFunction('getConfigParam', 'Platform::getConfigParam');
$twig->addFunction($function);
$function = new \Twig\TwigFunction('getStaticServer', 'Platform::getStaticServer');
$twig->addFunction($function);
$function = new \Twig\TwigFunction('getSessionParam', 'Platform::getSessionParam');
$twig->addFunction($function);
$function = new \Twig\TwigFunction('getTypeLabel', 'AppTweet::getTypeLabelFromTypeId');
$twig->addFunction($function);
$function = new \Twig\TwigFunction('getTypeLabelFromTypeId', 'AppTweet::getTypeLabelFromTypeId');
$twig->addFunction($function);
$function = new \Twig\TwigFunction('roundHuman', 'Platform::roundHuman');
$twig->addFunction($function);


displayTimer('avant generateCategoryDefines');

AppCategory::generateCategoryDefines();

displayTimer('avant getCategoriesByType');

$nav_categories = AppCategory::getCategoriesByType(AppCategory::TYPE_HEADER);

displayTimer('avant get all_categories');

if ($all_categories != $memcached->get('all_categories')) {
    $all_categories = $em->getRepository('Category')->findBy(array(), array("type" => 'ASC'));
    $memcached->set('all_categories', $all_categories, 3600);
}

displayTimer('apres get all_categories');

$twig_vars['all_categories'] = $all_categories;
foreach ($all_categories as $_category) {
    echo $_category->getLabel();
    if ($_category->getState() == AppCategory::STATE_ONLINE) {
        $online_categories[$_category->getCategoryId()] = $_category;
    }
    $twig_vars['online_categories'] = $online_categories;
}

/** @var $user_agent used to fix chrome webfont ugly display */
$user_agent = $_SERVER['HTTP_USER_AGENT'];
if (strpos($user_agent, 'Chrome') !== false && strpos($user_agent, 'Windows') !== false) {
    $browser_is_windows_chrome = true;
    $twig_vars['browser_is_windows_chrome'] = $browser_is_windows_chrome;
}


/**
 * get all translations
 */
displayTimer('avant getTranslations ');
$translations = AppTranslation::getAll();

$twig_vars['translations'] = $translations;
$twig->addGlobal('translations', $translations);
displayTimer('apres getTranslations ');
/**
 * handle login
 */
@session_name('limportant');
@session_start();
$twig_vars['show_register_popin'] = 1;


/**
 * get tweet themes & types
 */
$twig_vars['themes'] = Theme::getAll()['themes'];
$twig_vars['themes_array'] = Theme::getAll()['themes_array'];
$twig_vars['themes_array_by_category_id'] = Theme::getAll()['themes_array_by_category_id'];
$twig_vars['tweet_types'] = AppTweet::getTypes();
displayTimer('apres getThemes & getTypes');
$twig->addGlobal('themes', $twig_vars['themes']);
$twig->addGlobal('themes_array', $twig_vars['themes_array']);
$twig->addGlobal('themes_array_by_category_id', $twig_vars['themes_array_by_category_id']);
$twig->addGlobal('tweet_types', $twig_vars['tweet_types']);




/**
 * detect server side if device is touch device
 */
if ( ! $_SESSION['is_touch_device']) {
    $is_touch = new MobileDetect();
    $isMobile = $is_touch->isMobile();
    $isTablet = $is_touch->isTablet();
    if ($isMobile || $isTablet || $twig_vars['is_touch_device']) {
        $_SESSION['is_touch_device'] = true;
        if ($isMobile) {
            $_SESSION['show_right_column'] = false;
        } else {
            $_SESSION['show_right_column'] = true;
        }
    } else {
        $_SESSION['is_touch_device'] = false;
        $_SESSION['show_right_column'] = true;
    }
}
displayTimer('apres mobile_detect 1');
if ( ! isset($_SESSION['is_mobile']) || ! $_SESSION['is_mobile']) {
    $is_touch = new MobileDetect();
    $isMobile = $is_touch->isMobile();
    $isTablet = $is_touch->isTablet();
    $_SESSION['is_tablet'] = $isTablet;

    if ($_SESSION['is_touch_device'] === true && ($isMobile || $isTablet)) {
        $_SESSION['is_touch_device'] = true;
        $_SESSION['is_mobile'] = true;
        $_SESSION['show_right_column'] = false;
    } else {
        $_SESSION['is_mobile'] = false;
        $_SESSION['show_right_column'] = true;
    }
    if ($_SERVER['REMOTE_ADDR'] == '82.64.151.178') {
        /*echo '<pre>';
        var_dump('ici');
        var_dump($is_touch);
        var_dump($isMobile);
        var_dump($isTablet);
        var_dump($_SESSION);
        echo '</pre>';
*/
    }
}
if ($_REQUEST['set_mobile'] == true) {
    $_SESSION['is_touch_device'] = true;
    $_SESSION['is_mobile'] = true;
    $_SESSION['show_right_column'] = false;
}

$twig->addGlobal('_SESSION', $_SESSION);
displayTimer('apres mobile_detect 2');
/**
 * detect iOS device to change the way we show videos
 */
$iPod    = stripos($_SERVER['HTTP_USER_AGENT'],"iPod");
$iPhone  = stripos($_SERVER['HTTP_USER_AGENT'],"iPhone");
$iPad    = stripos($_SERVER['HTTP_USER_AGENT'],"iPad");
if ($iPad || $iPhone || $iPod) {
    $twig_vars['is_ios'] = true;
} else {
    $twig_vars['is_ios'] = false;
}
$twig->addGlobal('is_ios', $twig_vars['is_ios']);

/**
 * expires
 */
$twig_vars['meta_expires'] = date('D, d M Y H:i:s O', strtotime('+1 Week'));

try {
    if($_REQUEST['logout'] == 'true') {
        unset($_SESSION);
        session_destroy();
        setcookie("remember_me", '', time() - (3600));
        header('Location: /');
        exit();
    }
    if ($_POST['login'] == 'true') {
        $user = AppUser::loginUser($_POST['email'], $_POST['password']);
        if (! is_object($user) && $twig_vars['allow_registration']) {
            $twig_vars['error_login'] = true;
            header("Location: /?page=sign-in&error_login=true");
            exit();
        } else {
            if (strpos($_SERVER['HTTP_REFERER'], 'connexion') == true || strpos($_SERVER['HTTP_REFERER'], 'sign-in') == true) {
                header("Location: /");
                exit();
            } else {
                header("Location: " . $_SERVER['HTTP_REFERER']);
                exit();
            }

        }
    }
    /**
     * auto login / remember me
     */
    if (isset($_COOKIE['remember_me']) && strlen($_COOKIE['remember_me']) == 32 && ! is_object($_SESSION['user'])) {
        AppUser::LoginUserByToken($_COOKIE['remember_me']);
    }
    //var_dump($_COOKIE['remember_me']);
    if (! $_SESSION['user'] ) {
        /** handle global login page = site access restriction like ERDF */
        if ($twig_vars['global_login'] == true && $_GET['page'] != 'global-login'
            && $_GET['page'] != 'password-forgotten'
            && $_GET['page'] != 'twitter-auth'
            && $_GET['page'] != 'register'
        ) {

            header("Location: /?page=global-login");
            exit();
        }

        $twig_vars['categories'] = $nav_categories;
    } else {
        if ($_SESSION['user_id']) {
            $_SESSION['user'] = $em->getRepository('User')->findOneByUserId($_SESSION['user_id']);
            unset($_SESSION['user_id']);
        }
        try {
            $user_categories = AppUserPreference::getCategories($_SESSION['user']->getUserId(), 1);
        } catch (Exception $e) {
            $user_categories = AppUserPreference::getCategories($_SESSION['user']->getUserId(), 1);
        }

        if (is_array($user_categories) && count($user_categories)) {
            $twig_vars['categories'] = $user_categories;
        } else {
            $twig_vars['categories'] = $nav_categories;
        }

        /** retrieve user bookmarks **/
        if (! isset($_SESSION['user']->bookmarks)) {
            $bookmarks = AppBookmark::getUserBookmarks($_SESSION['user']);
            $_SESSION['user']->bookmarks = $bookmarks['only_tweet_id'];
        }

        /**
         * Récupération du nombre de tweets à valider pour l'afficher en haut à droite
         */
        if ($_SESSION['user'] &&
            (
                $_SESSION['user']->getIsAdmin() == Platform::USER_SUPER_ADMIN
                ||
                $_SESSION['user']->getIsAdmin() == Platform::USER_CONTRIB_NO_WORKFLOW
                ||
                $_SESSION['user']->getIsAdmin() == Platform::USER_CONTRIB_WORKFLOW_MODERATION
            )

        ) {
            $twig_vars['nb_tweets_pending_for_validation'] = AppTweet::getNbTweetsPendingForValidation();
        }
    }
    $twig_vars['_SESSION'] = $_SESSION;
    $twig_vars['_SERVER'] = $_SERVER;
    $twig_vars['_REQUEST'] = $_REQUEST;
    $twig_vars['_COOKIE'] = $_COOKIE;

    $twig_vars['baseline'] = $twig_vars['translations']['baseline'];

    /**
     * delete tweet
     */
    if ($_REQUEST['delete_tweet'] == 'true' && is_numeric($_REQUEST['tweet_id']) ) {
        $tweet_to_delete = AppTweet::cleanTweet($em->find('Tweet', $_REQUEST['tweet_id']));
        if (
            ($_SESSION['user'] != '' && $_SESSION['user']->getIsAdmin())
            OR
            ($_SESSION['user']->getPublishAllowed() && in_array($tweet_to_delete->getCategory()->getCategoryId(), $_SESSION['user']->getCategoryIds()))
            OR
            ($_SESSION['user']->getPublishAllowed() && $twig_vars['twosteps_delete'] == true)
        ) {

            if (is_object($tweet_to_delete)) {
                try {
                    /*$fh = fopen(__DIR__ . '/templates_c/delete_logs.txt', 'a');
                    if ($fh) {
                        if (is_object($tweet_to_delete->getLink()[0])) {
                            fwrite($fh, $_SESSION['user']->getName() . ';' . $tweet_to_delete->getTweetId() . ';' . strip_tags($tweet_to_delete->textCleaned) . ';' . $tweet_to_delete->getLink()[0]->getLinkId() . ";" . date('Y-m-d H:i:s')  . "\n");
                        } else {
                            fwrite($fh, $_SESSION['user']->getName() . ';' . $tweet_to_delete->getTweetId() . ';' . strip_tags($tweet_to_delete->textCleaned) . ';NO_LINK;' . date('Y-m-d H:i:s')  . "\n");
                        }

                        fclose($fh);
                    }*/
                    $tweet_to_delete->getUser()->setNbArticle(($tweet_to_delete->getUser()->getNbArticle() - 1));

                    /**
                     * log deletion
                     */
                    $tweet_log = new TweetLog();
                    $tweet_log->logDeletion($tweet_to_delete);

                    $em->persist($tweet_to_delete->getUser());
                    $rsm = new ResultSetMapping($em);
                    $rsm->addScalarResult('tweet_id', 'tweet_id');

                    $query = $em->createNativeQuery('UPDATE tweet SET category_id = NULL, is_une = NULL
                                                    WHERE tweet_id = ' . (int)$tweet_to_delete->getTweetId()
                        , $rsm);

                    $query->execute();
                    //$tweets = $query->getResult();
                    $em->flush();

                    $memcached->delete('tweets_by_category');

                    //mail ("pierredefrance@gmail.com", " LI delete tweet " . $tweet_to_delete->getTweetId(), $e->getMessage() . ' ' . $query->getSQL());
                } catch (Exception $e) {
                    //mail ("pierredefrance@gmail.com", "erreur LI delete tweet", $e->getMessage() . ' ' . $query->getSQL());
                }
                header("Location: " . $_SERVER['HTTP_REFERER'] . '/?flush_cache=true' );
                exit();

            }
        }
    }

    /*
     * delete twittos
     */
    if ($_SESSION['user'] && (
        ($_SESSION['user'] != '' && $_SESSION['user']->getIsAdmin())
        OR
        ($_SESSION['user']->getPublishAllowed())
        )
    ) {
        if ($_REQUEST['delete_toptwittos'] == 'true' && is_numeric($_REQUEST['user_id']) ) {
            if ($_SESSION['user'] != '' && $_SESSION['user']->getIsAdmin()) {
                $twittos_to_delete = $em->find('User', $_REQUEST['user_id']);
                if (is_object($twittos_to_delete)) { //&& is_object($category_to_delete)) {
                    $twittos_to_delete->setAcceptContributor(AppUser::HIDE_CONTRIBUTOR);
                    $em->persist($twittos_to_delete);
                    $em->flush($twittos_to_delete);
                }
            }
        }
    }

    displayTimer('avant getTribunes');
    $twig_vars['category_tribune'] = $em->getRepository("Category")->findOneBy(array("define" => 'TRIBUNE'));
    $twig_vars['category_humeur'] = $em->getRepository("Category")->findOneBy(array("define" => 'HUMEUR'));

    /**
     * add image to link
     */
    if ($_FILES['newImage'] != '' && is_numeric($_POST['imgUploadModalTweetId']) != ''
        &&
        (
            array_key_exists('user', $_SESSION) &&
            !is_null($_SESSION['user']) &&
            ($_SESSION['user']->getIsAdmin() || $_SESSION['user']->getPublishAllowed())
        )
    ) {

        $file_details = pathinfo($_FILES['newImage']['name']);
        if ($_FILES['newImage']['tmp_name'] != '' && (strtolower($file_details['extension']) == 'mp4' || strtolower($file_details['extension']) == 'mkv')) {

            $tweet = $em->getRepository('Tweet')->findOneByTweetId($_POST['imgUploadModalTweetId']);

            $source_video = $_FILES['newImage']['tmp_name'];
            $video_name = md5(time()) . '.mp4';
            if (strtolower($file_details['extension']) != 'mp4') {
                $destination_video = ROOT_DIRECTORY . AppTweet::VIDEO_RELATIVE_PATH . $video_name;
                $command = 'ffmpeg -i ' . $source_video . ' -c:v libx264 -preset slow -crf 18 -c:a copy ' . $destination_video;

                exec($command, $output);
            } else {
                $destination_video = ROOT_DIRECTORY . AppTweet::VIDEO_RELATIVE_PATH . $video_name;
                copy($source_video, $destination_video);
            }
            $tweet->setVideoName($video_name);
            $em->persist($tweet);
            $em->flush();
            header("Location: " . $_SERVER['HTTP_REFERER']);
            exit();
        } elseif ($_FILES['newImage']['tmp_name'] != '' && (strtolower($file_details['extension']) == 'gif') ) {

            $tweet = $em->getRepository('Tweet')->findOneByTweetId($_POST['imgUploadModalTweetId']);

            $source_gif = $_FILES['newImage']['tmp_name'];
            $video_name = md5(time()) . '.mp4';
            $destination_video = ROOT_DIRECTORY . AppTweet::VIDEO_RELATIVE_PATH . $video_name;
            $command = 'ffmpeg -f gif -i ' . $source_gif . ' ' . $destination_video;

            exec($command, $output);

            $tweet->setVideoName($video_name);
            $em->persist($tweet);
            $em->flush();
            header("Location: " . $_SERVER['HTTP_REFERER']);
            exit();
        } else {

            $tweet_to_replace_image = $em->getRepository('Tweet')->findOneByTweetId($_POST['imgUploadModalTweetId']);
            if (is_object($tweet_to_replace_image)) {
                /** if image has a link we replace the image associated to the link */
                if ($tweet_to_replace_image->getMediaUrl() != '') {
                    $tweet_to_replace_image->replaceMediaUrl();
                }
                $link_concerned = $tweet_to_replace_image->getLink()[0];
                if ($link_concerned) {
                    $link_concerned->replaceImage();
                    $memcached->delete('tweets_by_category');
                }
                header("Location: " . $_SERVER['HTTP_REFERER']);
            }
        }

    }


    /**
     * set to false in controllers that have no template (i.e. ajax)
     */
    $has_template = true;



    if (! isset($_GET['page'])) {
        /*if ($_SESSION['is_mobile']) {
            $_page = 'twitter-stream';
        } else {*/
            $_page = 'home';
        //}
    } else {
        $_page = $_GET['page'];
    }

    /**
     * by default set site layout to 2 colums, overloaded in controllers when necessary
     * $_page_layout = '2-columns';
     */
    $_page_layout = '1-column';

    if ($_pages[$_page]['layout'] == '2-columns') {
        /**
         * right column tweets
         */
            /*
        if ( ! $_SESSION['contributors_top']) {
            $contributors_top = AppUser::getContributorsAndTweetForTops();
            $_SESSION['contributors_top'] = $contributors_top;
        } else {
            $contributors_top = $_SESSION['contributors_top'];
        }*/
        ///** get contribs for right column by alpha */

        //$contributors_top = AppUser::getContributorsAndTweetForTops();

        /**
         * get latest contributors (by latest tweets registered on the platform)
         * @var  $contributors_top
         */
        /*$contributors_top = AppUser::getContributorsForTops(8);
        $twig_vars['contributors_top'] = $contributors_top;*/

        //$twig_vars['contributors_top_100'] = AppUser::getContributorsForRightColumn('', true, 30);
        displayTimer('avant video/detente');
        //$twig_vars['video']     = AppTweet::getVideo(CATEGORY_JOUR_VIDEO) ; //AppTweet::getTweetsByCategory(CATEGORY_JOUR_VIDEO,1)['tweets'];
        //if ($_page == 'home') {
        //    $twig_vars['detente']     = AppTweet::getVideo(CATEGORY_JOUR_DETENTE);
        //}
        displayTimer('apres video/detente');


        if ($twig_vars['display_top_share']) {
            if ($_page == 'home') {
                displayTimer('avant display_top_share');
            }
            $twig_vars['top_share'] = AppLink::getTopLinks();

        }
        displayTimer('apres top_clicked');
        $twig_vars['top_clicked'] = AppTweet::getMostClicked(5, true, true);
    }
    //$categ = $_SESSION['user']->getCategoryIds();

    $twig_vars['_page'] = $_page;
    $twig->addGlobal('_page', $_page);
    $twig->addGlobal('_REQUEST', $_REQUEST);
    $twig_vars['_page_layout'] = $_pages[$_page]['layout'];
    $twig_vars['_page_secure'] = $_pages[$_page]['secure'];



    displayTimer('avant include controller');
    if ($_pages[$_page]['secure']) {
        include('secure.php');
    }

    if (array_key_exists($_page, $_pages)) {
        include ($_page . '.php');
    } else {
        $_page = 'home';
        include ('home.php');
    }

    displayTimer('avant twig render');
    if ($has_template) {
        echo $twig->render(trim($_page . '.html.twig'), $twig_vars);
    }
    displayTimer('apres twig render');

} catch (Exception $e) {

    $error_body = $e->getCode();
    $error_body .= "\n exc message : " . $e->getMessage();
    $error_body .= "\n user : " . json_encode($_SESSION['user']);
    foreach ($_SERVER as $ks => $vs) {
        $error_body .= "\n ". $ks . " : " . $vs;
    }
    if ($_SERVER['REMOTE_ADDR'] == '141.255.135.105') {
        echo '<pre>';
        var_dump($e);
        var_dump($error_body); ;
        echo '</pre>';
    }
    
    //AppModel::sendLog('plantage ' . SITE_NAME . ' ' . $error_body);

    //header("Location: /?logout=true");
    if($_REQUEST && array_key_exists('reload', $_REQUEST) && $_REQUEST['reload'] !== true) {
        if (strpos($_SERVER['HTTP_REFERER'], '?') !== true) {
            header("Location: " . $_SERVER['HTTP_REFERER'] . '?reload=true');
        } else {
            header("Location: " . $_SERVER['HTTP_REFERER'] . '&reload=true');
        }
        exit();
    }
}
exit();
