<?php
/**
 * Trainings Ex- und Importieren
 *
 * @package    Trainings-Ex-Import
 * @subpackage Trainings-Ex-Import/public
 * @author     Max Sternitzke <max.sternitzke@stud.th-luebeck.de>
 */
class Trainingssystem_Plugin_Module_Trainings_Ex_Import
{

    public function __construct()
    {

    }

    public function showTrainings($atts)
    {

        $heading = isset($atts['titel']) ? $atts['titel'] : 'Trainings Ex-/Import'; 

        $twig = Trainingssystem_Plugin_Twig::getInstance()->twig;

        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingseximport")) {
            ob_start();

            $current_user = wp_get_current_user();
            if (0 == $current_user->ID) {
			    return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
            }
            
            $trainings = Trainingssystem_Plugin_Database::getInstance()->TrainingDao->getAllTrainings();

            $importpath = $this::getExImportPath();
            if (!is_dir($importpath)) {
                mkdir($importpath);
            }
            $dircontent = scandir($importpath);
            $files = array();

            foreach ($dircontent as $file) {
                if (!$this::startsWith($file, ".") && $file != "index.php" && $this::endsWith($file, ".zip")) {
                    $files[] = $file;
                }
            }

            echo $twig->render('trainings-ex-import/trainings-ex-import-overview.html', ['trainings' => $trainings, 'files' => $files, 'heading' => $heading]);

            return ob_get_clean();
        } else {
            return $twig->render('modal-unauth.html', ["title" => get_bloginfo('name'), "url" => get_site_url(), "modalid" => uniqid()]);
        }
    }

    public function downloadMedien()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingseximport")) {
            if (isset($_POST['trainingid']) && is_numeric($_POST['trainingid'])) {
                $media_all = array();

                $trainingpost = get_post($_POST['trainingid'], OBJECT);
                $lektionenids = $this::getTrainingLektionen($_POST['trainingid']);

                $media_all = array_merge($media_all, $this::getMediaOfContent(do_shortcode($trainingpost->post_content)));
                $media_all = array_merge($media_all, $this::getMediaOfContent(do_shortcode($trainingpost->post_excerpt)));
                $media_all[] = get_the_post_thumbnail_url($trainingpost);

                foreach ($lektionenids as $lektionid) {
                    $lektionpost = get_post($lektionid);
                    $seitenids = $this::getLektionseiten($lektionid);

                    $media_all = array_merge($media_all, $this::getMediaOfContent(do_shortcode($lektionpost->post_content)));
                    $media_all = array_merge($media_all, $this::getMediaOfContent(do_shortcode($lektionpost->post_excerpt)));
                    $media_all[] = get_the_post_thumbnail_url($lektionpost);

                    foreach ($seitenids as $seitenid) {
                        $seitenpost = get_post($seitenid);

                        $media_all = array_merge($media_all, $this::getMediaOfContent(do_shortcode($seitenpost->post_content)));
                        $media_all = array_merge($media_all, $this::getMediaOfContent(do_shortcode($seitenpost->post_excerpt)));
                        $media_all[] = get_the_post_thumbnail_url($seitenpost);
                    }
                }

                $media = array();
                foreach ($media_all as $m) {
                    $m = $this::cleanMediaUrl($m);

                    if (!in_array($m, $media) && strlen(trim($m)) != 0 && is_file(trailingslashit((wp_get_upload_dir()['basedir'])) . $m)) {
                        $media[] = $m;
                    }
                }

                $zip = new ZipArchive;
                $filename = "Medienexport-" . current_time("d-m-Y-H-i-s") . ".zip";
                $zipfile = $this::getExImportPath() . $filename;

                if(count($media) > 0) {
                    if ($zip->open($zipfile, ZipArchive::CREATE) === true) {
                        foreach ($media as $file) {
                            $zip->addFile(trailingslashit((wp_get_upload_dir()['basedir'])) . $file, $file);
                        }
                        $zip->close();

                        header('Content-Type: application/zip');
                        header('Content-disposition: attachment; filename="' . $filename . '"');
                        header('Content-Length: ' . filesize($zipfile));
                        $handle = fopen($zipfile, 'rb');
                        $buffer = '';
                        while (!feof($handle)) {
                            $buffer = fread($handle, 4096);
                            echo $buffer;
                            ob_flush();
                            flush();
                        }
                        fclose($handle);
                        unlink($zipfile);
                    }
                }
            }
        }
        wp_die();
    }

    public function importMedien()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingseximport")) {
            if (isset($_POST['file']) && strlen(trim($_POST['file'])) > 0) {
                $importfile = $this::getExImportPath() . $_POST['file'];
                if (is_file($importfile)) {
                    $zip = new ZipArchive;
                    if ($zip->open($importfile) === true) {
                        $tmppath = trailingslashit($this::getExImportPath() . uniqid());
                        $uploaddir = trailingslashit((wp_get_upload_dir()['basedir']));

                        $zip->extractTo($tmppath);
                        $zip->close();

                        $zipfiles = $this::find_all_files($tmppath);
                        foreach ($zipfiles as $key => $file) {
                            $zipfiles[$key] = substr($file, strlen($tmppath) + 1);
                        }

                        foreach ($zipfiles as $file) {
                            if (!is_file($uploaddir . $file)) {

                                $path_exploded = explode("/", $file);
                                $dest_folder = $uploaddir;
                                for($i = 0; $i < count($path_exploded)-1; $i++) {
                                    $dest_folder .= $path_exploded[$i] . "/";
                                }
                                if(!is_dir($dest_folder)) {
                                    mkdir($dest_folder, 0777, true);
                                }

                                rename($tmppath . $file, $uploaddir . $file);
                            }
                        }

                        $this::deleteDir($tmppath);

                        // Zum Löschen/Behalten der Zip-Datei nach dem Import vom FTP-Verzeichnis die nächste Zeile aus-/einkommentieren
                        unlink($importfile);
                        echo "success";
                    } else {
                        echo "0";
                    }
                } else {
                    echo "0";
                }
            } else {
                echo "0";
            }
        }
        wp_die();
    }

    public function downloadTraining()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingseximport")) {
            if (isset($_POST['trainingid']) && is_numeric($_POST['trainingid'])) {
                
                $json = $this->exportTraining($_POST['trainingid'], "", "", "", null);

                $filename = "Trainingexport-" . current_time("d-m-Y-H-i-s") . ".json";

                header('Content-type: application/json; charset=utf-8');
                header('Content-disposition: attachment; filename="' . $filename . '"');

                echo json_encode($json);
            }
        }
        wp_die();
    }

    private function exportTraining($trainingid, $trainingAppend = " - Kopie", $lektionAppend = " - Kopie", $seitenAppend = " - Kopie", $tsformAppend = " - Kopie") {
        $ret = array();
        $code = "";

        $tsFormsModule = new Trainingssystem_Plugin_Module_TS_Forms();
        $tsExerciseModule = new Trainingssystem_Plugin_Module_Exercise();

        $trainingpost = get_post($trainingid, OBJECT);

        $code .= $trainingpost->post_ecerpt . $trainingpost->post_content;
        $ret['training']['title'] = $trainingpost->post_title . $trainingAppend;
        $ret['training']['content'] = $trainingpost->post_content;
        $ret['training']['excerpt'] = $trainingpost->post_excerpt;
        $ret['training']['postname'] = $trainingpost->post_name;
        $ret['training']['type'] = $trainingpost->post_type;
        $thumbnail = get_the_post_thumbnail_url($trainingpost);
        $ret['training']['thumbnail'] = $thumbnail == false ? "" : $this::cleanMediaUrl($thumbnail);
        $ret['training']['lektionen'] = array();
        $lektionencount = 0;
        $lektionenids = $this::getTrainingLektionen($trainingid);

        foreach ($lektionenids as $lektionid) {
            $lektionpost = get_post($lektionid);

            $code .= $lektionpost->post_ecerpt . $lektionpost->post_content;
            $ret['training']['lektionen'][$lektionencount]['title'] = $lektionpost->post_title . $lektionAppend;
            $ret['training']['lektionen'][$lektionencount]['content'] = $lektionpost->post_content;
            $ret['training']['lektionen'][$lektionencount]['excerpt'] = $lektionpost->post_excerpt;
            $ret['training']['lektionen'][$lektionencount]['postname'] = $lektionpost->post_name;
            $ret['training']['lektionen'][$lektionencount]['type'] = $lektionpost->post_type;
            $thumbnail = get_the_post_thumbnail_url($lektionpost);
            $ret['training']['lektionen'][$lektionencount]['thumbnail'] = $thumbnail == false ? "" : $this::cleanMediaUrl($thumbnail);
            $ret['training']['lektionen'][$lektionencount]['seiten'] = array();
            $seitencount = 0;
            $seitenids = $this::getLektionseiten($lektionid);

            foreach ($seitenids as $seitenid) {
                $seitenpost = get_post($seitenid);

                $code .= $seitenpost->post_ecerpt . $seitenpost->post_content;
                $ret['training']['lektionen'][$lektionencount]['seiten'][$seitencount]['title'] = $seitenpost->post_title . $seitenAppend;
                $ret['training']['lektionen'][$lektionencount]['seiten'][$seitencount]['content'] = $seitenpost->post_content;
                $ret['training']['lektionen'][$lektionencount]['seiten'][$seitencount]['excerpt'] = $seitenpost->post_excerpt;
                $ret['training']['lektionen'][$lektionencount]['seiten'][$seitencount]['postname'] = $seitenpost->post_name;
                $ret['training']['lektionen'][$lektionencount]['seiten'][$seitencount]['type'] = $seitenpost->post_type;
                $thumbnail = get_the_post_thumbnail_url($seitenpost);
                $ret['training']['lektionen'][$lektionencount]['seiten'][$seitencount]['thumbnail'] = $thumbnail == false ? "" : $this::cleanMediaUrl($thumbnail);
                $seitencount++;
            }

            $lektionencount++;
        }

        $ret['tsforms'] = array();
        $ret['exercises'] = array();

        $regex = "/\[[\wöäüßÖÄÜ0-9-_?! :.,;\/{}()=\"'…\n\r]+\]?/";
        preg_match_all($regex, $code, $matches);
        $all_shortcodes_list = array();
        $s_index = 0;
        foreach ($matches[0] as $match) {
            if (!$this::startsWith($match, "[/")) { // no closing tags here
                $all_shortcodes_list[$s_index]['original_shortcode'] = $match;
                if (strpos($match, " ") !== false) {
                    $all_shortcodes_list[$s_index]['shortcode_name'] = substr($match, 1, strpos($match, " "));
                    $parsed_shortcode_atts = shortcode_parse_atts(substr($match, 1, strlen($match) - 2));
                    if(is_array($parsed_shortcode_atts)) {
                        $all_shortcodes_list[$s_index] = array_merge($all_shortcodes_list[$s_index], array_slice($parsed_shortcode_atts, 1));
                    }
                } else {
                    $all_shortcodes_list[$s_index]['shortcode_name'] = substr($match, 1, strlen($match) - 2);
                }
                $s_index++;
            }
        }

        $replace_shortcodes = array();
        $rs_index = 0;
        foreach ($all_shortcodes_list as $shortcode) {
            switch (trim($shortcode['shortcode_name'])) {
                case "coach_output_gbu":
                case "tspv2_coach_output_gbu":
                case "coach_output_format_data":
                case "tspv2_coach_output_format_data":
                case "coach_output_list_data":
                case "tspv2_coach_output_list_data":
                case "coach_output_einzel_beurteilung1":
                case "tspv2_coach_output_einzel_beurteilung1":
                case "coach_output_einzel_beurteilung2":
                case "tspv2_coach_output_einzel_beurteilung2":
                case "coach_output_gesamt_haeufigkeit":
                case "tspv2_coach_output_gesamt_haeufigkeit":
                case "coach_output_gesamt_haeufigkeit2":
                case "tspv2_coach_output_gesamt_haeufigkeit2":
                case "coach_output_gefaerdungsbeurteilung_text":
                case "tspv2_coach_output_gefaerdungsbeurteilung_text":
                case "coach_output_tabellenset3":
                case "tspv2_coach_output_tabellenset3":
                case "coach_output_tabellenset3b":
                case "tspv2_coach_output_tabellenset3b":
                case "coach_output_gesamt_haeufigkeit_gruppen":
                case "tspv2_coach_output_gesamt_haeufigkeit_gruppen":
                case "coach_output_gesamt_haeufigkeit_gruppen2":
                case "tspv2_coach_output_gesamt_haeufigkeit_gruppen2":
                        if (isset($shortcode['id'])) {
                            if(strtolower(get_post_type($shortcode['id'])) == "formulare") { // NEW TS FORMS
                                $tsforms_valid = true;
                                if (!isset($ret['tsforms'][$shortcode['id']])) {
                                    $export = $tsFormsModule->exportForm($shortcode['id'], false, $tsformAppend);
                                    if(!empty($export)) {
                                        $ret['tsforms'][$shortcode['id']]['uid'] = bin2hex(random_bytes(32));
                                        $ret['tsforms'][$shortcode['id']]['export'] = $export;
                                    } else {
                                        $tsforms_valid = false;
                                    }
                                }
                                if($tsforms_valid) {
                                    $replace_shortcodes[$rs_index]['old'] = $shortcode['original_shortcode'];
                                    $replace_shortcodes[$rs_index]['new'] = preg_replace("/id=[\"']?" . $shortcode['id'] . "[\"']?/", "id='" . $ret['tsforms'][$shortcode['id']]['uid'] . "'", $shortcode['original_shortcode']);
                                    $rs_index++;
                                }
                            }
                        }
                    break;
                case "coach_output_mittelwert_gesamt":
                case "tspv2_coach_output_mittelwert_gesamt":
                    if (isset($shortcode['ids'])) {
                        $comg_sc = $shortcode['original_shortcode'];
                        $replace_shortcodes[$rs_index]['old'] = $shortcode['original_shortcode'];
                        $comg_ids = explode(";", $shortcode['ids']);

                        $comg_tsids_count = 0;
                        $comg_counter = 0;
                        foreach ($comg_ids as $comg_id) {
                            $comg_counter++;
                            if(strtolower(get_post_type($comg_id)) == "formulare") { // NEW TS FORMS
                                $comg_tsids_count++;
                            }
                        }

                        if($comg_counter === $comg_tsids_count) { // NEW TS FORMS
                            foreach ($comg_ids as $comg_id) {
                                $tsforms_valid = true;
                                if (!isset($ret['tsforms'][$comg_id])) {
                                    $export = $tsFormsModule->exportForm($comg_id, false, $tsformAppend);
                                    if(!empty($export)) {
                                        $ret['tsforms'][$comg_id]['uid'] = bin2hex(random_bytes(32));
                                        $ret['tsforms'][$comg_id]['export'] = $export;
                                    } else {
                                        $tsforms_valid = false;
                                    }
                                }
                                if($tsforms_valid) {
                                    $comg_sc = str_replace($comg_id, $ret['tsforms'][$comg_id]['uid'], $comg_sc);
                                }
                            }
                            $replace_shortcodes[$rs_index]['new'] = $comg_sc;
                            $rs_index++;
                        }
                    }
                    break;
                case "coach_download_csv_link":
                case "tspv2_coach_download_csv_link":
                    if (isset($shortcode['data'])) {
                        $cdcl_sc = $shortcode['original_shortcode'];
                        $replace_shortcodes[$rs_index]['old'] = $shortcode['original_shortcode'];

                        $cdcl_json = json_decode($shortcode['data'], true);
                        $cdcl_ids = array();
                        foreach ($cdcl_json as $cdcl_a) {
                            foreach ($cdcl_a as $cdcl_b) {
                                $cdcl_ids[] = $cdcl_b;
                            }
                        }

                        $cdcl_tsids_count = 0;
                        $cdcl_counter = 0;
                        foreach ($cdcl_ids as $cdcl_id) {
                            $cdcl_counter++;
                            if(strtolower(get_post_type($cdcl_id)) == "formulare") { // NEW TS FORMS
                                $cdcl_tsids_count++;
                            }
                        }

                        if($cdcl_counter === $cdcl_tsids_count) { // NEW TS FORMS
                            foreach ($cdcl_ids as $cdcl_id) {
                                $tsforms_valid = true;
                                if (!isset($ret['tsforms'][$cdcl_id])) {
                                    $export = $tsFormsModule->exportForm($cdcl_id, false, $tsformAppend);
                                    if(!empty($export)) {
                                        $ret['tsforms'][$cdcl_id]['uid'] = bin2hex(random_bytes(32));
                                        $ret['tsforms'][$cdcl_id]['export'] = $export;
                                    } else {
                                        $tsforms_valid = false;
                                    }
                                }
                                if($tsforms_valid) {
                                    $cdcl_sc = str_replace($cdcl_id, $ret['tsforms'][$cdcl_id]['uid'], $cdcl_sc);
                                }
                            }
                            $replace_shortcodes[$rs_index]['new'] = $cdcl_sc;
                            $rs_index++;
                        }
                    }
                    break;
                case "ts_forms":
                    if (isset($shortcode['id'])) {
                        $tsforms_valid = true;
                        if (!isset($ret['tsforms'][$shortcode['id']])) {
                            $export = $tsFormsModule->exportForm($shortcode['id'], false, $tsformAppend);
                            if(!empty($export)) {
                                $ret['tsforms'][$shortcode['id']]['uid'] = bin2hex(random_bytes(32));
                                $ret['tsforms'][$shortcode['id']]['export'] = $export;
                            } else {
                                $tsforms_valid = false;
                            }
                        }
                        if($tsforms_valid) {
                            $replace_shortcodes[$rs_index]['old'] = $shortcode['original_shortcode'];
                            $replace_shortcodes[$rs_index]['new'] = preg_replace("/id=[\"']?" . $shortcode['id'] . "[\"']?/", "id='" . $ret['tsforms'][$shortcode['id']]['uid'] . "'", $shortcode['original_shortcode']);
                            $rs_index++;
                        }
                    }
                    break;
                case "ts_forms_conditional":
                case "ts_forms_conditional-inner1":
                case "ts_forms_conditional-inner2":
                case "ts_forms_conditional-inner3":
                    if (isset($shortcode['tsformid'])) {
                        $tsforms_valid = true;
                        if (!isset($ret['tsforms'][$shortcode['tsformid']])) {
                            $export = $tsFormsModule->exportForm($shortcode['tsformid'], false, $tsformAppend);
                            if(!empty($export)) {
                                $ret['tsforms'][$shortcode['tsformid']]['uid'] = bin2hex(random_bytes(32));
                                $ret['tsforms'][$shortcode['tsformid']]['export'] = $export;
                            } else {
                                $tsforms_valid = false;
                            }
                        }
                        if($tsforms_valid) {
                            $replace_shortcodes[$rs_index]['old'] = $shortcode['original_shortcode'];
                            $replace_shortcodes[$rs_index]['new'] = preg_replace("/tsformid=[\"']?" . $shortcode['tsformid'] . "[\"']?/", "tsformid='" . $ret['tsforms'][$shortcode['tsformid']]['uid'] . "'", $shortcode['original_shortcode']);
                            $rs_index++;
                        }
                    }
                    break;
                case "ts_exercise":
                    if (isset($shortcode['id'])) {
                        $exerciseExport = $tsExerciseModule->exportExercise($shortcode['id'], false);
                        foreach($exerciseExport["tsforms"] as $tsformid => $tsformContent) {
                            $tsforms_valid = true;
                            if (!isset($ret['tsforms'][$tsformid])) {
                                $export = $tsFormsModule->exportForm($tsformid, false, $tsformAppend);
                                if(!empty($export)) {
                                    $ret['tsforms'][$tsformid]['uid'] = $tsformContent["uid"];
                                    $ret['tsforms'][$tsformid]['export'] = $export;
                                } else {
                                    $tsforms_valid = false;
                                }
                            } else {
                                // replace generated uid from exercise exported content with exisiting uid 
                                $exerciseExport["content"] = str_replace($tsformContent["uid"], $ret['tsforms'][$tsformid]['uid'], $exerciseExport["content"]);
                            }
                            if($tsforms_valid) {
                                $exerciseExport["content"] = preg_replace("/id=[\"']?" . $tsformid . "[\"']?/", "id='" . $ret['tsforms'][$tsformid]['uid'] . "'", $exerciseExport["content"]);
                            }
                        }
                        $exerciseExport["tsforms"] = [];
                        $ret['exercises'][$shortcode['id']]['uid'] = bin2hex(random_bytes(32));
                        $ret['exercises'][$shortcode['id']]['export'] = $exerciseExport;

                        $replace_shortcodes[$rs_index]['old'] = $shortcode['original_shortcode'];
                        $replace_shortcodes[$rs_index]['new'] = preg_replace("/id=[\"']?" . $shortcode['id'] . "[\"']?/", "id='" . $ret['exercises'][$shortcode['id']]['uid'] . "'", $shortcode['original_shortcode']);
                        $rs_index++;
                    }
                    break;
            }
        }

        $replace = array();
        $rep_index = 0;
        foreach ($replace_shortcodes as $rep_a_val) {
            $found = false;

            foreach ($replace as $rep_n_val) {
                if ($rep_a_val['old'] === $rep_n_val['old'] &&
                    $rep_a_val['new'] === $rep_n_val['new']) {
                    $found = true;
                    break;
                }
            }

            if (!$found) {
                $replace[$rep_index]['old'] = $rep_a_val['old'];
                $replace[$rep_index]['new'] = $rep_a_val['new'];
                $rep_index++;
            }
        }

        $ret['training']['content'] = $this::replaceShortcodeIds($ret['training']['content'], $replace);
        $ret['training']['excerpt'] = $this::replaceShortcodeIds($ret['training']['excerpt'], $replace);

        foreach ($ret['training']['lektionen'] as &$lektion) {
            $lektion['content'] = $this::replaceShortcodeIds($lektion['content'], $replace);
            $lektion['excerpt'] = $this::replaceShortcodeIds($lektion['excerpt'], $replace);

            foreach ($lektion['seiten'] as &$seite) {
                $seite['content'] = $this::replaceShortcodeIds($seite['content'], $replace);
                $seite['excerpt'] = $this::replaceShortcodeIds($seite['excerpt'], $replace);
            }
        }

        return $ret;
    }

    public function importTraining()
    {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingseximport")) {

            if (isset($_FILES['file']) &&
                $_FILES['file']['error'] == UPLOAD_ERR_OK &&
                is_uploaded_file($_FILES['file']['tmp_name'])) {

                $json = json_decode(file_get_contents($_FILES['file']['tmp_name']), true);

                if (json_last_error() === JSON_ERROR_NONE) {

                    if($this->importTrainingIntern($json)) {
                        echo "success";
                    }
                }
            }
        }
        wp_die();
    }

    private function importTrainingIntern($data) {
        global $wpdb;

        $lektion_table = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_TRAINING_LEKTIONEN;
        $seiten_table = $wpdb->prefix . TRAININGSSYSTEM_PLUGIN_DB_TRAINING_SEITEN;

        $replace_uid_fid = array();
        $rp_index = 0;

        $tsFormsModule = new Trainingssystem_Plugin_Module_TS_Forms();
        $tsExerciseModule = new Trainingssystem_Plugin_Module_Exercise();

        foreach($data['tsforms'] as $import_tsform) {
            $newtsid = $tsFormsModule->importForm($import_tsform['export']);

            if($newtsid != null && is_numeric($newtsid)) {
                $replace_uid_fid[$rp_index]['old'] = $import_tsform['uid'];
                $replace_uid_fid[$rp_index]['new'] = $newtsid;
                $rp_index++;
            } else {
               return false;
            }
        }

        if (count($data['tsforms']) === count($replace_uid_fid)) {

            foreach($data['exercises'] as $import_tsexercise) {
                $exportedExercise = $import_tsexercise['export'];
                $exportedExercise['content'] = $this::replaceShortcodeIds($exportedExercise["content"], $replace_uid_fid);
                $newExerciseId = $tsExerciseModule->importExercise($exportedExercise);

                if($newExerciseId != null && is_numeric($newExerciseId)) {
                    $replace_uid_fid[$rp_index]['old'] = $import_tsexercise['uid'];
                    $replace_uid_fid[$rp_index]['new'] = $newExerciseId;
                    $rp_index++;
                } else {
                   return false;
                }
            }


            $trainingid = $this::insertPost($data['training']['title'], $data['training']['content'], $data['training']['excerpt'], $data['training']['postname'], $data['training']['type'], $data['training']['thumbnail'], $replace_uid_fid);

            $lektion_index = 0;
            foreach ($data['training']['lektionen'] as $lektion) {
                $lektionid = $this::insertPost($lektion['title'], $lektion['content'], $lektion['excerpt'], $lektion['postname'], $lektion['type'], $lektion['thumbnail'], $replace_uid_fid);

                $wpdb->insert(
                    $lektion_table,
                    array(
                        'training_id' => $trainingid,
                        'lektion_id' => $lektionid,
                        'lektion_index' => $lektion_index,
                    ),
                    array(
                        '%d',
                        '%d',
                        '%d',
                    )
                );
                if ($wpdb->insert_id === false) {
                    return false;
                }

                $seiten_index = 0;
                foreach ($lektion['seiten'] as $seite) {
                    $seitenid = $this::insertPost($seite['title'], $seite['content'], $seite['excerpt'], $seite['postname'], $seite['type'], $seite['thumbnail'], $replace_uid_fid);

                    $wpdb->insert(
                        $seiten_table,
                        array(
                            'lektion_id' => $lektionid,
                            'seiten_id' => $seitenid,
                            'seiten_index' => $seiten_index,
                            'training_id' => $trainingid,
                        ),
                        array(
                            '%d',
                            '%d',
                            '%d',
                            '%d',
                        )
                    );
                    if ($wpdb->insert_id === false) {
                        return false;
                    }

                    $seiten_index++;
                }

                $lektion_index++;
            }
            return true;
        }
        return false;
    }

    public function duplicateTraining() {
        if (Trainingssystem_Plugin_Module_Berechtigung::getInstance()->accessAllowed("trainingseximport")) {
            if(isset($_POST['trainingid']) && is_numeric($_POST['trainingid']) && isset($_POST['trainingAppend']) && isset($_POST['lektionAppend']) && isset($_POST['seitenAppend']) && isset($_POST['tsformAppend'])) {

                $trainingid = $_POST['trainingid'];
                $trainingAppend = $_POST['trainingAppend'];
                $lektionAppend = $_POST['lektionAppend'];
                $seitenAppend = $_POST['seitenAppend'];
                $tsformAppend = $_POST['tsformAppend'];

                $export = $this->exportTraining($trainingid, $trainingAppend, $lektionAppend, $seitenAppend, $tsformAppend);

                if($this->importTrainingIntern($export)) {
                    echo "1";
                }
            }
        }
        wp_die();
    }

    public function insertPost($title, $content, $excerpt, $postname, $type, $thumbnail, $replace)
    {
        $content = $this::replaceShortcodeIds($content, $replace);
        $excerpt = $this::replaceShortcodeIds($excerpt, $replace);

        $array = array(
            "post_title" => $title,
            "post_content" => $content,
            "post_excerpt" => $excerpt,
            "post_name" => $postname,
            "post_status" => "publish",
            "post_type" => $type,
        );

        $postid = wp_insert_post($array);

        if (trim($thumbnail) != "" && is_file(trailingslashit((wp_get_upload_dir()['basedir'])) . $thumbnail)) {

            $filetype = wp_check_filetype(basename($thumbnail), null);

            $wp_upload_dir = wp_upload_dir();

            $attachment = array(
                'guid' => $wp_upload_dir['url'] . '/' . basename($thumbnail),
                'post_mime_type' => $filetype['type'],
                'post_title' => preg_replace('/\.[^.]+$/', '', basename($thumbnail)),
                'post_content' => '',
                'post_status' => 'inherit',
            );

            $attach_id = wp_insert_attachment($attachment, $thumbnail, $parent_post_id);

            require_once ABSPATH . 'wp-admin/includes/image.php';

            $attach_data = wp_generate_attachment_metadata($attach_id, $thumbnail);
            wp_update_attachment_metadata($attach_id, $attach_data);

            set_post_thumbnail($postid, $attach_id);
        }

        return $postid;
    }

    public function replaceShortcodeIds($text, $replacearray = array())
    {
        $ret = $text;
        if (strlen(trim($text)) > 0) {
            foreach ($replacearray as $replace) {
                $ret = str_replace($replace['old'], $replace['new'], $ret);
            }
        }
        return $ret;
    }

    public function find_all_files($dir)
    {
        $root = scandir($dir);
        foreach ($root as $value) {
            if ($value === '.' || $value === '..') {continue;}
            if (is_file("$dir/$value")) {$result[] = "$dir/$value";
                continue;}
            foreach ($this::find_all_files("$dir/$value") as $value) {
                $result[] = $value;
            }
        }
        return $result;
    }

    public function deleteDir($dirPath)
    {
        if (!is_dir($dirPath)) {
            throw new InvalidArgumentException("$dirPath must be a directory");
        }
        if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
            $dirPath .= '/';
        }
        $files = glob($dirPath . '*', GLOB_MARK);
        foreach ($files as $file) {
            if (is_dir($file)) {
                $this::deleteDir($file);
            } else {
                unlink($file);
            }
        }
        rmdir($dirPath);
    }

    public function cleanMediaUrl($mediaurl)
    {
        $ret = $mediaurl;
        $ret = substr($ret, strpos($ret, "uploads") + strlen("uploads") + 1);

        if (strpos($ret, "?") != false) {
            $ret = substr($ret, 0, strpos($ret, "?"));
        }

        return $ret;
    }

    public function getTrainingsseiten($trainingid)
    {
        global $wpdb;
        $dbprefix_seiten = $wpdb->prefix . 'md_trainingsmgr_tranings_seiten';

        $sql = $wpdb->prepare("SELECT `seiten_id` FROM $dbprefix_seiten WHERE training_id = %d", $trainingid);
        $ids = $wpdb->get_col($sql);

        return $ids;
    }

    public function getTrainingLektionen($trainingid)
    {
        global $wpdb;
        $dbprefix_lektionen = $wpdb->prefix . 'md_trainingsmgr_tranings_lektionen';

        $sql = $wpdb->prepare("SELECT `lektion_id` FROM $dbprefix_lektionen WHERE training_id = %d ORDER BY lektion_index ASC", $trainingid);
        $ids = $wpdb->get_col($sql);

        return $ids;
    }

    public function getLektionseiten($lektionid)
    {
        global $wpdb;
        $dbprefix_seiten = $wpdb->prefix . 'md_trainingsmgr_tranings_seiten';

        $sql = $wpdb->prepare("SELECT `seiten_id` FROM $dbprefix_seiten WHERE lektion_id = %d ORDER BY seiten_index ASC", $lektionid);
        $ids = $wpdb->get_col($sql);

        return $ids;
    }

    public function getMediaOfContent($content)
    {
        $ret = array();

        if (strlen(trim($content)) > 0) {
            $doc = new DOMDocument();
            // ToDo: better handling of html5 tags if supported by php in the future
            @$doc->loadHTML('<?xml encoding="utf-8" ?>' . $content);
            $imageTags = $doc->getElementsByTagName('img');

            foreach ($imageTags as $tag) {
                $ret[] = $tag->getAttribute('src');
            }

            $videoTags = $doc->getElementsByTagName('video');

            foreach ($videoTags as $tag) {
                $ret[] = $tag->getAttribute('src');
                $ret[] = $tag->getAttribute('poster');
            }

            $audioTags = $doc->getElementsByTagName('audio');

            foreach ($audioTags as $tag) {
                $ret[] = $tag->firstChild->getAttribute('src');
            }

            $aTags = $doc->getElementsByTagName('a');

            foreach ($aTags as $tag) {
                if ($this::endsWith($tag->getAttribute('href'), ".pdf")) {
                    $ret[] = $tag->getAttribute('href');
                }
            }
        }

        return $ret;
    }

    public function getExImportPath()
    {
        return trailingslashit((wp_get_upload_dir()['basedir'])) . "trainings-ex-import/";
    }

    public function startsWith($haystack, $needle)
    {
        $length = strlen($needle);
        return (substr($haystack, 0, $length) === $needle);
    }

    public function endsWith($haystack, $needle)
    {
        $length = strlen($needle);
        if ($length == 0) {
            return true;
        }

        return (substr($haystack, -$length) === $needle);
    }

}
