<commit_before><?php
/**
 * @file          export.queries.php
 * @author        <NAME>
 * @version       2.1.22
 * @copyright     (c) 2009-2014 <NAME>
 * @licensing     GNU AFFERO GPL 3.0
 * @link          http://www.teampass.net
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

require_once('sessions.php');
session_start();
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
    die('Hacking attempt...');
}

global $k, $settings;
include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
header("Content-type: text/html; charset=utf-8");
error_reporting(E_ERROR);
require_once $_SESSION['settings']['cpassman_dir'].'/sources/main.functions.php';
require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';

// connect to DB
require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
DB::$host = $server;
DB::$user = $user;
DB::$password = $<PASSWORD>;
DB::$dbName = $database;
DB::$port = $port;
DB::$error_handler = 'db_error_handler';
$link = mysqli_connect($server, $user, $pass, $database, $port);

//Build tree
$tree = new SplClassLoader('Tree\NestedTree', $_SESSION['settings']['cpassman_dir'].'/includes/libraries');
$tree->register();
$tree = new Tree\NestedTree\NestedTree($pre.'nested_tree', 'id', 'parent_id', 'title');

//User's language loading
$k['langage'] = @$_SESSION['user_language'];
require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
;
//Manage type of action asked
switch ($_POST['type']) {
    case "initialize_export_table":
        DB::query("TRUNCATE TABLE ".$pre."export");
        break;

    //CASE export to PDF format
    case "export_to_pdf_format":
        $id = $_POST['id'];
        if (!in_array($id, $_SESSION['forbiden_pfs']) && in_array($id, $_SESSION['groupes_visibles'])) {
            // get path
            $tree->rebuild();
            $folders = $tree->getPath($id, true);
            $path = "";
            foreach ($folders as $val) {
                if ($path) {
                    $path .= " » ";
                }
                $path .= $val->title;
            }

            // send query
            $rows = DB::query(
                "SELECT i.id as id, i.restricted_to as restricted_to, i.perso as perso, i.label as label, i.description as description, i.pw as pw, i.login as login,
                    l.date as date,
                    n.renewal_period as renewal_period,
                    k.rand_key
                    FROM ".$pre."items as i
                    INNER JOIN ".$pre."nested_tree as n ON (i.id_tree = n.id)
                    INNER JOIN ".$pre."log_items as l ON (i.id = l.id_item)
                    INNER JOIN ".$pre."keys as k ON (i.id = k.id)
                    WHERE i.inactif = %i
                    AND i.id_tree= %i
                    AND (l.action = %s OR (l.action = %s AND l.raison LIKE %s))
                    ORDER BY i.label ASC, l.date DESC",
                "0",
                intval($id),
                "at_creation",
                "at_modification",
                "at_pw :%"
            );

            $id_managed = '';
            $i = 0;
            $items_id_list = array();
            foreach ($rows as $record) {
                $restricted_users_array = explode(';', $record['restricted_to']);
                //exclude all results except the first one returned by query
                if (empty($id_managed) || $id_managed != $record['id']) {
                    if (
                        (in_array($id, $_SESSION['personal_visible_groups']) && !($record['perso'] == 1 && $_SESSION['user_id'] == $record['restricted_to']) && !empty($record['restricted_to']))
                        ||
                        (!empty($record['restricted_to']) && !in_array($_SESSION['user_id'], $restricted_users_array))
                    ) {
                        //exclude this case
                    } else {
                        //encrypt PW
                        if (!empty($_POST['salt_key']) && isset($_POST['salt_key'])) {
                            $pw = decrypt($record['pw'], mysqli_escape_string($link, stripslashes($_POST['salt_key'])));
                        } else {
                            $pw = decrypt($record['pw']);
                        }
                        if ($record['perso'] != 1) {
                            $pw = stripslashes($pw);
                            $pw = substr(addslashes($pw), strlen($record['rand_key']));
                        }
                        // store
                        DB::insert(
                            $pre.'export',
                            array(
                                'id' => $record['id'],
                                'description' => addslashes($record['description']),
                                'label' => addslashes($record['label']),
                                'pw' => ($pw),
                                'login' => $record['login'],
                                'path' => $path
                            )
                        );
                    }
                }
                $id_managed = $record['id'];
                $folder_title = $record['folder_title'];
            }
        }
        echo '[{}]';
        break;

    case "finalize_export_pdf":
        // query
        $rows = DB::query("SELECT * FROM ".$pre."export");
        $counter = DB::count();
        if ($counter > 0) {
            // print
            //Some variables
            $table_full_width = 190;
            $table_col_width = array(45, 40, 45, 60);

            //Prepare the PDF file
            include $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Pdf/Tfpdf/fpdf.php';
            $pdf=new FPDF_Protection();
            $pdf->SetProtection(array('print'), $_POST['pdf_password']);

            //Add font for regular text
            $pdf->AddFont('DejaVu', '', 'DejaVuSansCondensed.ttf', true);
            //Add monospace font for passwords
            $pdf->AddFont('LiberationMono', '');

            $pdf->aliasNbPages();
            $pdf->addPage();
            $pdf->SetFont('DejaVu', '', 16);
            $pdf->Cell(0, 10, $LANG['print_out_pdf_title'], 0, 1, 'C', false);
            $pdf->SetFont('DejaVu', '', 12);
            $pdf->Cell(0, 10, $LANG['pdf_del_date']." ".date($_SESSION['settings']['date_format']." ".$_SESSION['settings']['time_format'], time()).' '.$LANG['by'].' '.$_SESSION['login'], 0, 1, 'C', false);

            $prev_path = "";
            $table = array('label', 'login', 'pw', 'description');
            foreach ($rows as $record) {
                $printed_ids[] = $record['id'];
                if ($prev_path != $record['path']) {
                    $pdf->SetFont('DejaVu', '', 10);
                    $pdf->SetFillColor(192, 192, 192);
                    error_log('key: '.$key.' - paths: '.$record['path']);
                    $pdf->cell(0, 6, $record['path'], 1, 1, "L", 1);
                    $pdf->SetFillColor(222, 222, 222);
                    $pdf->cell(45, 6, $LANG['label'], 1, 0, "C", 1);
                    $pdf->cell(40, 6, $LANG['login'], 1, 0, "C", 1);
                    $pdf->cell(45, 6, $LANG['pw'], 1, 0, "C", 1);
                    $pdf->cell(60, 6, $LANG['description'], 1, 1, "C", 1);
                }
                $prev_path = $record['path'];
                $record['pw'] = stripslashes($record['pw']);
                $record['description'] = html_entity_decode(htmlspecialchars_decode(str_replace("<br />", "\n", $record['description']), ENT_QUOTES));
                //row height calculation
                $nb = 0;
                $nb = max($nb, nbLines($table_col_width[0], $record['label']));
                $nb = max($nb, nbLines($table_col_width[3], $record['description']));
                $nb = max($nb, nbLines($table_col_width[2], $record['pw']));

                $h=5*$nb;
                //Page break needed?
                checkPageBreak($h);
                //Draw cells
                $pdf->SetFont('DejaVu', '', 9);
                for ($i=0; $i<count($table); $i++) {
                    $w=$table_col_width[$i];
                    $a='L';
                    //actual position<commit_msg>Export to PDF - fix for non utf8 strings<commit_after><?php
/**
 * @file          export.queries.php
 * @author        <NAME>
 * @version       2.1.22
 * @copyright     (c) 2009-2014 <NAME>
 * @licensing     GNU AFFERO GPL 3.0
 * @link          http://www.teampass.net
 *
 * This library is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
 */

require_once('sessions.php');
session_start();
if (!isset($_SESSION['CPM']) || $_SESSION['CPM'] != 1 || !isset($_SESSION['key']) || empty($_SESSION['key'])) {
    die('Hacking attempt...');
}

global $k, $settings;
include $_SESSION['settings']['cpassman_dir'].'/includes/settings.php';
header("Content-type: text/html; charset=utf-8");
error_reporting(E_ERROR);
require_once $_SESSION['settings']['cpassman_dir'].'/sources/main.functions.php';
require_once $_SESSION['settings']['cpassman_dir'].'/sources/SplClassLoader.php';

// connect to DB
require_once $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Database/Meekrodb/db.class.php';
DB::$host = $server;
DB::$user = $user;
DB::$password = $<PASSWORD>;
DB::$dbName = $database;
DB::$port = $port;
DB::$error_handler = 'db_error_handler';
$link = mysqli_connect($server, $user, $pass, $database, $port);

//Build tree
$tree = new SplClassLoader('Tree\NestedTree', $_SESSION['settings']['cpassman_dir'].'/includes/libraries');
$tree->register();
$tree = new Tree\NestedTree\NestedTree($pre.'nested_tree', 'id', 'parent_id', 'title');

//User's language loading
$k['langage'] = @$_SESSION['user_language'];
require_once $_SESSION['settings']['cpassman_dir'].'/includes/language/'.$_SESSION['user_language'].'.php';
;
//Manage type of action asked
switch ($_POST['type']) {
    case "initialize_export_table":
        DB::query("TRUNCATE TABLE ".$pre."export");
        break;

    //CASE export to PDF format
    case "export_to_pdf_format":
        $id = $_POST['id'];
        if (!in_array($id, $_SESSION['forbiden_pfs']) && in_array($id, $_SESSION['groupes_visibles'])) {
            // get path
            $tree->rebuild();
            $folders = $tree->getPath($id, true);
            $path = "";
            foreach ($folders as $val) {
                if ($path) {
                    $path .= " » ";
                }
                $path .= $val->title;
            }

            // send query
            $rows = DB::query(
                "SELECT i.id as id, i.restricted_to as restricted_to, i.perso as perso, i.label as label, i.description as description, i.pw as pw, i.login as login,
                    l.date as date,
                    n.renewal_period as renewal_period,
                    k.rand_key
                    FROM ".$pre."items as i
                    INNER JOIN ".$pre."nested_tree as n ON (i.id_tree = n.id)
                    INNER JOIN ".$pre."log_items as l ON (i.id = l.id_item)
                    INNER JOIN ".$pre."keys as k ON (i.id = k.id)
                    WHERE i.inactif = %i
                    AND i.id_tree= %i
                    AND (l.action = %s OR (l.action = %s AND l.raison LIKE %s))
                    ORDER BY i.label ASC, l.date DESC",
                "0",
                intval($id),
                "at_creation",
                "at_modification",
                "at_pw :%"
            );

            $id_managed = '';
            $i = 0;
            $items_id_list = array();
            foreach ($rows as $record) {
                $restricted_users_array = explode(';', $record['restricted_to']);
                //exclude all results except the first one returned by query
                if (empty($id_managed) || $id_managed != $record['id']) {
                    if (
                        (in_array($id, $_SESSION['personal_visible_groups']) && !($record['perso'] == 1 && $_SESSION['user_id'] == $record['restricted_to']) && !empty($record['restricted_to']))
                        ||
                        (!empty($record['restricted_to']) && !in_array($_SESSION['user_id'], $restricted_users_array))
                    ) {
                        //exclude this case
                    } else {
                        //encrypt PW
                        if (!empty($_POST['salt_key']) && isset($_POST['salt_key'])) {
                            $pw = decrypt($record['pw'], mysqli_escape_string($link, stripslashes($_POST['salt_key'])));
                        } else {
                            $pw = decrypt($record['pw']);
                        }
                        if ($record['perso'] != 1) {
                            $pw = stripslashes($pw);
                            $pw = substr(addslashes($pw), strlen($record['rand_key']));
                        }
                        // store
                        DB::insert(
                            $pre.'export',
                            array(
                                'id' => $record['id'],
                                'description' => addslashes($record['description']),
                                'label' => addslashes($record['label']),
                                'pw' => ($pw),
                                'login' => $record['login'],
                                'path' => $path
                            )
                        );
                    }
                }
                $id_managed = $record['id'];
                $folder_title = $record['folder_title'];
            }
        }
        echo '[{}]';
        break;

    case "finalize_export_pdf":
        // query
        $rows = DB::query("SELECT * FROM ".$pre."export");
        $counter = DB::count();
        if ($counter > 0) {
            // print
            //Some variables
            $table_full_width = 190;
            $table_col_width = array(45, 40, 45, 60);

            //Prepare the PDF file
            include $_SESSION['settings']['cpassman_dir'].'/includes/libraries/Pdf/Tfpdf/fpdf.php';
            $pdf=new FPDF_Protection();
            $pdf->SetProtection(array('print'), $_POST['pdf_password']);

            //Add font for regular text
            $pdf->AddFont('DejaVu', '', 'DejaVuSansCondensed.ttf', true);
            //Add monospace font for passwords
            $pdf->AddFont('LiberationMono', '');

            $pdf->aliasNbPages();
            $pdf->addPage();
            $pdf->SetFont('DejaVu', '', 16);
            $pdf->Cell(0, 10, $LANG['print_out_pdf_title'], 0, 1, 'C', false);
            $pdf->SetFont('DejaVu', '', 12);
            $pdf->Cell(0, 10, $LANG['pdf_del_date']." ".date($_SESSION['settings']['date_format']." ".$_SESSION['settings']['time_format'], time()).' '.$LANG['by'].' '.$_SESSION['login'], 0, 1, 'C', false);

            $prev_path = "";
            $table = array('label', 'login', 'pw', 'description');
            foreach ($rows as $record) {
                $printed_ids[] = $record['id'];
                if ($prev_path != $record['path']) {
                    $pdf->SetFont('DejaVu', '', 10);
                    $pdf->SetFillColor(192, 192, 192);
                    error_log('key: '.$key.' - paths: '.$record['path']);
                    $pdf->cell(0, 6, $record['path'], 1, 1, "L", 1);
                    $pdf->SetFillColor(222, 222, 222);
                    $pdf->cell(45, 6, $LANG['label'], 1, 0, "C", 1);
                    $pdf->cell(40, 6, $LANG['login'], 1, 0, "C", 1);
                    $pdf->cell(45, 6, $LANG['pw'], 1, 0, "C", 1);
                    $pdf->cell(60, 6, $LANG['description'], 1, 1, "C", 1);
                }
                $prev_path = $record['path'];
                if (!isutf8($record['pw'])) $record['pw'] = "";
                $record['description'] = html_entity_decode(htmlspecialchars_decode(str_replace("<br />", "\n", $record['description']), ENT_QUOTES));
                //row height calculation
                $nb = 0;
                $nb = max($nb, nbLines($table_col_width[0], $record['label']));
                $nb = max($nb, nbLines($table_col_width[3], $record['description']));
                $nb = max($nb, nbLines($table_col_width[2], $record['pw']));

                $h=5*$nb;
                //Page break needed?
                checkPageBreak($h);
                //Draw cells
                $pdf->SetFont('DejaVu', '', 9);
                for ($i=0; $i<count($table); $i++) {
                    $w=$table_col_width[$i];
                    $a='L';
                    //actual position
{'fraction_non_alphanumeric': 0.1727496772679263, 'fraction_numerical': 0.012087783124046474, 'mean_word_length': 1.6713166144200626, 'pattern_counts': {'":': 6, '<': 15, '<?xml version=': 0, '>': 69, 'https://': 0, 'lorem ipsum': 0, 'www.': 2, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '893890', 'n_tokens_mistral': 5222, 'n_tokens_neox': 4792, 'n_words': 1015}