<?php
/**
 * CMS HELPER CLASS
 *
 * @package
 * @author Rihards Silins
 * @copyright MTC Media 2013
 * @version 1.0 05/03/2014
 * @access public
 *
 * When this will be used more - it shall be more fledged out.
 *
 */
class CmsHelper {

    /**
     * Should be called in <head></head> in the frontend layout
     */
    public static function enablePdEdit() {

        echo '<script type="text/javascript" src="/admin/js/libs/tinymce/tinymce.min.js"></script>
<script type="text/javascript" src="/admin/js/libs/tinymce/jquery.tinymce.min.js"></script>
<script src="/admin/js/libs/pdedit.js"></script>
';

    }

    /**
     * Adds appropriate attributes for content container tags for inline frontend editing.
     */
    public static function pdEdit( $pagedata, $session=null ) {

        if ( $session === null ) {
            $session = $_SESSION;
        }

        $valid_editable_pagedata_types = array("text", "textarea");

        if ( !in_array($pagedata['type'], $valid_editable_pagedata_types) ) {

            return "";

        }

        if ( !isset($session['content_manager']['front_editing']) || $session['content_manager']['front_editing'] !== true ) {

            return "";

        }

        return "data-editable-pagedata-id=\"".$pagedata['id']."\" data-editable-pagedata-type=\"".$pagedata['type']."\"";

    }

    /**
     * CmsHelper::recursivelyRmdir
     * Recursively delete a directory that is not empty.
     * @param string $directory_name
     * @author Rihards Siliņs
     */
    public static function recursivelyRmdir($directory_name) {
        if (is_dir($directory_name)) {
            $objects = scandir($directory_name);
            foreach ($objects as $object) {
                if ($object != "." && $object != "..") {
                    if (filetype($directory_name."/".$object) == "dir") {
                        self::recursivelyRmdir($directory_name."/".$object);
                    } else {
                        unlink($directory_name."/".$object);
                    }
                }
            }
            reset($objects);
            rmdir($directory_name);
        }
    }

    /**
     * Check if file upload matches set rules.
     * Allows receiving settings for allowed file types.
     * By default disables harmful files.
     *
     * @param string $rules Mime regex for the (dis)allowed files
     * @param string $file Path to tmp_file of the uploaded file
     * @param string $file_name uploaded file name
     * @param bool $image whether add_fullcms_image is used (true) or add_fullcms_file (false)
     * @return bool whether file is allowed based on rules or not
     * @author Martins Fridenbergs <martins.fridenbergs@mtcmedia.co.uk>
     */
    public static function isFileMimeValid($rules = '', $file, $file_name, $image = false)
    {
        if (empty($rules)) {
            $default_rules = true;
            if ($image) {
                $rules = '/^image\/(jpeg|gif|png)$/';
            } else {
                $rules = '/((?!python|zip|compressed|x-msdownload|x-sh|php|perl|inode)[\s\S])*/';
            }
        } else {
            $rules = '/' . $rules . '/';
        }

        $file_info = finfo_open(FILEINFO_MIME_TYPE);
        $mime = finfo_file($file_info, $file);
        if (!preg_match($rules, $mime)) {
            // Mime type doesn't match rules
            return false;
        }

        // If no mime defined lets resolve to defaults
        if (!empty($default_rules)) {
            $extension = strtolower(pathinfo($file_name, PATHINFO_EXTENSION));
            if ($image) {
                $allowed_file_extensions = [
                    'jpg',
                    'jpeg',
                    'png',
                    'gif',
                ];
                if (!in_array(strtolower($extension), $allowed_file_extensions)) {
                    return false;
                }
            } else {
                $forbidden_file_extensions = [
                    'exe', // Win executable
                    'msi', // Win executable
                    'bat', // Win script
                    'php', // PHP file
                    'py',  // Python script
                    'sh',  // Shell script
                    'jar', // Java executable
                    'lnk', // Link file
                    'pl',  // Perl script
                    'ini', // INI config file
                ];
                if (in_array(strtolower($extension), $forbidden_file_extensions)) {
                    // Forbidden file type
                    return false;
                }
            }
        }
        return true;
    }

    /**
     * Calculates read time based on number of words in the article.
     * Presumably an average person can read 180 words per minute
     *
     * @param $article
     * @return int
     */
    public static function calculateArticleReadTime($article)
    {
        $word_count = 0;
        $words = explode(' ', $article->pagedata['First Paragraph'][0]['value'] ?? null);
        $word_count += count($words);

        if (is_array($article->pagedata['Extra Content'])) {
            foreach ($article->pagedata['Extra Content'] as $extra_content) {
                $words = explode(' ', $extra_content['Extra Title']['value'] ?? null);
                $word_count += count($words);
                $words = explode(' ', strip_tags($extra_content['Extra Content']['value']));
                $word_count += count($words);
            }
        }

        return round($word_count / 180) ?: 1;
    }

    /**
     * Merges articles
     *
     * @param $existing_articles
     * @param $articles_to_add
     * @return array
     */
    public static function mergeArticles($existing_articles, $articles_to_add)
    {
        foreach ($articles_to_add as $article_to_add) {
            foreach ($existing_articles as $existing_article) {
                if ($existing_article->id === $article_to_add->id) {
                    continue 2;
                }
            }
            $existing_articles[] = $article_to_add;
        }

        return $existing_articles;
    }
}
