Merge pull request #2 from cyberperspectives/master

Update 1.3.3 base
This commit is contained in:
Cyber Perspectives, LLC 2018-07-26 08:46:50 -04:00 committed by GitHub
commit 0bccaf5838
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3230 changed files with 133313 additions and 135062 deletions

3
CHANGELOG.md Normal file
View File

@ -0,0 +1,3 @@
## v1.3.2
- Initial GitHub load
- Previous versions loaded on [SourceForge](https://sourceforge.net/projects/sagacity/)

Binary file not shown.

View File

@ -186,7 +186,7 @@
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Copyright 2018 CyberPerspectives, LLC
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.

Binary file not shown.

126
ajax.php
View File

@ -5,7 +5,7 @@
* Purpose: For AJAX queries from the UI
* Created: Mar 9, 2015
*
* Portions Copyright 2016-2017: Cyber Perspectives, LLC, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -41,6 +41,10 @@
* - Jan 15, 2018 - Updated to get formatted target notes
* - Jan 16, 2018 - Added ajax to auto update the cpe, cve, stig, and nasl loading progress.
Moved scan deletion here
* - May 2, 2018 - Added save_checklist else block to support save functionality on Catalog Mgmt page
* - May 10, 2018 - Added more fields when getting system updates
* - May 31, 2018 - Added data point for "isScanError" when getting target scan data
* - Jun 2, 2018 - Added nvd_year for status update AJAX
*/
set_time_limit(0);
@ -185,7 +189,8 @@ elseif ($action == 'add_scans') {
elseif ($action == 'auto-categorize') {
$db->auto_Catorgize_Targets($ste);
print header(JSON) . json_encode(['success' => 'Categorized Targets'
print header(JSON) . json_encode([
'success' => 'Categorized Targets'
]);
}
elseif ($action == 'delete-cat') {
@ -269,6 +274,29 @@ elseif ($action == 'checklist-add-software') {
print header(JSON) . json_encode(array('status' => 'Successfully added the software'));
}
}
elseif ($action == 'save-checklist') {
$rel_date = new DateTime(filter_input(INPUT_POST, 'rel-date', FILTER_SANITIZE_STRING));
$db->help->update("sagacity.checklist", [
'name' => filter_input(INPUT_POST, 'name', FILTER_SANITIZE_STRING),
'description' => filter_input(INPUT_POST, 'desc', FILTER_SANITIZE_STRING),
'icon' => filter_input(INPUT_POST, 'icon', FILTER_SANITIZE_STRING),
'date' => (is_a($rel_date, 'DateTime') ? $rel_date->format(MYSQL_D_FORMAT) : (new DateTime())->format(MYSQL_D_FORMAT))
], [
[
'field' => 'id',
'op' => '=',
'value' => filter_input(INPUT_POST, 'id', FILTER_VALIDATE_INT)
]
]);
if($db->help->execute()) {
print json_encode(['success' => 'Successfully updated checklist']);
}
else {
print json_encode(['error' => 'Error updating checklist']);
}
}
elseif ($action == 'export-ckl') {
$cat_id = filter_input(INPUT_POST, 'cat', FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
$tgt_id = filter_input(INPUT_POST, 'tgt', FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
@ -361,10 +389,11 @@ elseif ($action == 'save-target-notes') {
}
elseif ($action == 'get-load-status') {
$set = $db->get_Settings([
'cpe-dl-progress', 'cpe-progress',
'cve-dl-progress', 'cve-progress',
'stig-dl-progress', 'stig-progress',
'nasl-dl-progress', 'nasl-progress'
'cpe-count', 'cpe-dl-progress', 'cpe-progress',
'cve-count', 'cve-dl-progress', 'cve-progress',
'nvd-cve-count', 'nvd-cve-dl-progress', 'nvd-cve-progress', 'nvd-year',
'stig-count', 'stig-dl-progress', 'stig-progress',
'nasl-count', 'nasl-dl-progress', 'nasl-progress'
]);
print json_encode($set);
}
@ -849,6 +878,7 @@ function update_script_status()
"start_time" => $scan->get_Start_Time()->format("Y-m-d H:i:s"),
"update" => $scan->get_Last_Update()->format("Y-m-d H:i:s"),
"host_count" => $scan->get_Total_Host_Count(),
"error" => $scan->isScanError(),
"run_time" => $diff->format("%H:%I:%S")
];
}
@ -1486,7 +1516,12 @@ function get_hosts($cat_id = null)
}
foreach ($scan_srcs as $key => $src) {
$src_str .= "<img src='/img/scan_types/{$src['src']->get_Icon()}' title='{$src['src']->get_Name()}";
$icon = $src['src']->get_Icon();
if($src['scan_error']) {
$icon = strtolower($src['src']->get_Name()) . "-failed.png";
}
$src_str .= "<img src='/img/scan_types/{$icon}' title='{$src['src']->get_Name()}";
if (isset($src['count']) && $src['count']) {
$src_str .= " ({$src['count']})";
}
@ -1504,79 +1539,6 @@ function get_hosts($cat_id = null)
'data' => $tgt->get_Task_Status($tgt->get_Data_Status_ID()),
'fp' => $tgt->get_Task_Status($tgt->get_FP_Cat1_Status_ID()),
'ip' => (count($tgt->interfaces) ? array_keys($tgt->interfaces)[0] : ''),
'notes' => nl2br($tgt->get_Notes()),
'scans' => $src_str,
'chk' => $icon_str
]);
}
return json_encode($ret);
}
/**
*
* @global db $db
* @param type $cat_id
* @return type
*/
function new_get_hosts($cat_id)
{
global $db;
$ret = ['cat_id' => $cat_id];
$ste_id = filter_input(INPUT_COOKIE, 'ste', FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
$tgts = [];
if ($cat_id) {
$ste_cat = $db->get_Category($cat_id)[0];
$tgts = $db->get_Target_By_Category($cat_id);
}
elseif (is_numeric($ste_id)) {
$tgts = $db->get_Unassigned_Targets($ste_id);
}
else {
return json_encode(['error' => "Invalid info"]);
}
foreach ($tgts as $key => $tgt) {
$chks = $db->get_Target_Checklists($tgt->get_ID());
if ($cat_id) {
$exp_scan_srcs = $db->get_Expected_Category_Sources($ste_cat);
}
else {
$exp_scan_srcs = null;
}
$scan_srcs = $db->get_Target_Scan_Sources($tgt, $exp_scan_srcs);
$icons = [];
$icon_str = '';
$src_str = '';
foreach ($chks as $chk) {
if (!in_array($chk->get_Icon(), array_keys($icons))) {
$icons[$chk->get_Icon()]['icon'] = $chk->get_Icon();
$icons[$chk->get_Icon()]['name'] = '';
}
$icons[$chk->get_Icon()]['name'] .= "{$chk->get_Name()} V{$chk->get_Version()}R{$chk->get_Release()} ({$chk->get_type()})" . PHP_EOL;
}
foreach ($icons as $icon => $data) {
$icon_str .= "<img src='/img/checklist_icons/$icon' title='{$data['name']}' class='checklist_image' />";
}
foreach ($scan_srcs as $key => $src) {
$src_str .= "<img src='/img/scan_types/{$src['src']->get_Icon()}' title='{$src['src']->get_Name()}";
if (isset($src['count']) && $src['count']) {
$src_str .= " ({$src['count']})";
}
$src_str .= "' class='checklist_image' />";
}
$ret['targets'][] = array_merge([
'id' => $tgt->get_ID(),
'ste_id' => $tgt->get_STE_ID(),
'name' => $tgt->get_Name(),
'os' => $tgt->get_OS_String(),
'location' => $tgt->get_Location(),
'ip' => (count($tgt->interfaces) ? array_keys($tgt->interfaces)[0] : ''),
'notes' => $tgt->getDisplayNotes(),
'scans' => $src_str,
'chk' => $icon_str,
@ -2142,10 +2104,10 @@ function get_category_details($cat_id)
return 'no category found';
}
return json_encode(array(
return json_encode([
'id' => $cat->get_ID(),
'name' => $cat->get_Name(),
'analyst' => $cat->get_Analyst(),
'sources' => $cat->get_Sources()
));
]);
}

View File

@ -5,13 +5,14 @@
* Author: Ryan Prather
* Created: Feb 23, 2018
*
* Copyright 2018: Cyber Perspectives, All rights reserved
* Copyright 2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* See license.txt for details
*
* Change Log:
* - Feb 23, 2018 - File Created
* - Apr 29, 2018 - Added return for formatted date/time string for start and stop
*/
/**
@ -78,6 +79,16 @@ class DateTimeDiff
return $this->_dtStart->format("H:i:s");
}
/**
* Getter function for _dtStart as formatted date/time
*
* @return string
*/
public function getStartClockDateTime()
{
return $this->_dtStart->format(MYSQL_DT_FORMAT);
}
/**
* Getter function for _dtEnd
*
@ -98,6 +109,16 @@ class DateTimeDiff
return $this->_dtEnd->format("H:i:s");
}
/**
* Getter function for _dtEnd as formatted date/time
*
* @return string
*/
public function getEndClockDateTime()
{
return $this->_dtEnd->format(MYSQL_DT_FORMAT);
}
/**
* Function to stop the clock and set the ending time
*/

View File

@ -6,7 +6,7 @@
* Purpose: Represents a finding
* Created: Sep 12, 2013
*
* Portions Copyright 2016-2017: Cyber Perspectives, LLC, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -21,6 +21,7 @@
* - Nov 7, 2016 - Added finding::inc_Finding_Count function to increment counter
* - May 25, 2017 - Fixed bug of get_Category method returning empty severity (defaults to II if empty)
* - Jan 10, 2018 - Formatting
* - May 24, 2018 - Simplified get_Finding_Status_ID method
*/
/**
@ -260,10 +261,12 @@ class finding {
* @return integer
*/
public function get_Finding_Status_ID($status) {
foreach ($this->STATUS as $key => $val) {
if ($val == $status) {
return $key;
$arr_flip = array_flip($this->STATUS);
if(isset($arr_flip[$status])) {
return $arr_flip[$status];
}
else {
return $arr_flip['Not Reviewed'];
}
}
@ -527,6 +530,28 @@ class deconflict_status {
* Stores the matrix of current -> new statuses
*
* @var array:string
*
* / Finding Definitions
* Open: The finding is valid for this host - the host does not meet the requirements
* Not a Finding: The finding is not valid for this host - the host meets the requirements
* Not Applicable: The requirement does not apply to this host - prerequisites do not exist.
* Not Reviewed: The finding has not yet been reviewed.
* Exception: (A type of Open) - The finding is valid, but the system cannot comply for a valid reason
* False Positive: (A type of Not a Finding) - The scanning tool incorrectly reported Open.
* No Data: Because dissimilar checklists were merged, there is no data available for this item (Uncommon)
*
* General Precedence Order: E, FP, O, NF, NA, NR, ND
* Exception - the newest E or FP always take precedence (security engineer input)
*
* Decision Table:
* orig\new | E | FP | O | NF | NA | NR | ND
* E | E | FP | E | E | E | E | E
* FP | E | FP | FP | FP | FP | FP | FP
* O | E | FP | O | O | O | O | O
* NF | E | FP | O | NF | NF | NF | NF
* NA | E | FP | O | NF | NA | NA | NA
* NR | E | FP | O | NF | NA | NR | NR
* ND | E | FP | O | NF | NA | NR | ND
*/
static $DECONFLICTED_STATUS = [
'Exception' => [
@ -572,7 +597,7 @@ class deconflict_status {
'Not a Finding' => 'Not a Finding',
'Not Applicable' => 'Not Applicable',
'Not Reviewed' => 'Not Applicable',
'No Data' => 'Not Reviewed'
'No Data' => 'Not Applicable'
],
'Not Reviewed' => [
'Exception' => 'Exception',

View File

@ -6,7 +6,7 @@
* Purpose: Class to allow the parsing and traversing of the tmp directory to find result files to import
* Created: Sep 27, 2013
*
* Portions Copyright 2016-2017: Cyber Perspectives, LLC, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -26,6 +26,7 @@
* - Feb 21, 2017 - Fixed path issues with scripts not running
* - Jun 27, 2017 - Removed include for PHPExcel.php library
* - Oct 23, 2017 - Fixes for pdi class
* - May 24, 2018 - Added throwing error if not able to create /exec/parse_config.ini
*/
include_once 'config.inc';
include_once 'database.inc';
@ -125,7 +126,9 @@ ignore = $ignore
EOF;
file_put_contents(DOC_ROOT . "/exec/parse_config.ini", $conf);
if(!file_put_contents(DOC_ROOT . "/exec/parse_config.ini", $conf)) {
throw new Exception("Error creating the parse_config.ini");
}
$script = realpath(defined('PHP_BIN') ? PHP_BIN : PHP) .
" -c " . realpath(PHP_CONF) .

View File

@ -5,7 +5,7 @@
* Purpose: Represents an imported scan
* Created: Sep 12, 2013
*
* Portions Copyright 2016-2017: Cyber Perspectives, LLC, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -386,7 +386,7 @@ class scan
"<td>{$host->getTargetName()}</td>" .
"<td>{$host->getFindingCount()}</td>" .
"<td>{$host->getTargetIp()}</td>" .
"<td>" . ($host->getScanError() ? "<img src='/img/error.png' class='checklist_image' title='{$host->getScanError()}' />" : "") . "</td>" .
"<td>" . ($host->getScanError() ? "<img src='/img/error.png' class='checklist_image' title='{$host->getScanNotes()}' />" : "") . "</td>" .
"</tr>";
}

View File

@ -271,7 +271,7 @@ class ste_cat
}
}
$cat_sources = array();
$cat_sources = [];
if (is_array($this->sources) && count($this->sources)) {
foreach ($this->sources as $src) {
$cat_sources[] = $src->get_ID();
@ -334,7 +334,7 @@ EOC;
*
* @return string
*/
public function getSTECatRow($status_count = null)
public function getStatsCategoryRow($status_count = null)
{
$nf = "0%";
$nr = "0%";
@ -417,6 +417,14 @@ EOC;
EOC;
}
public function getTaskStatusCategoryRow()
{
$auto = 'NR';
$man = 'NR';
$data = 'NR';
$fp = 'NR';
}
/**
* Function to create vertical menu
*

View File

@ -1,4 +1,21 @@
<?php
/**
* File: config.inc
* Author: Ryan Prather <ryan.prather@cyberperspectives.com>
* Purpose: File to store config information for Sagacity
* Created: Nov 14, 2017
*
* Copyright 2017-2018: Cyber Perspective, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* See license.txt for details
*
* Change Log:
* - Nov 14, 2017 - File created
* - May 24, 2018 - Updated constants for 1.3.2 release
* - Jun 2, 2018 - Added new STIG_EXCLUSIONS constant to permanently exclude STIGs
*/
// @new
/**
* Constant defining a debug log level
@ -12,8 +29,8 @@ define('E_DEBUG', 65535);
define('DOC_ROOT', '{DOC_ROOT}');
define('PWD_FILE', '{PWD_FILE}');
define('TMP', '{TMP_PATH}');
define('VER', '1.3.1');
define('REL_DATE', '2018-02-28');
define('VER', '1.3.2');
define('REL_DATE', '2018-05-31');
define('LOG_LEVEL', '{E_ERROR}');
define('LOG_PATH', '{LOG_PATH}');
define('SALT', '{SALT}');
@ -56,6 +73,11 @@ define('SCG', '{SCG}');
define('DERIVED_ON', '{DERIVED_ON}');
define('DECLASSIFY_ON', '{DECLASSIFY_ON}');
/**
* Constant to be used to permanently exclude STIGs
*/
define('STIG_EXCLUSIONS', '');
/**
* Constant to define MySQL's DateTime format
*

117
data/catmgmt.inc Normal file
View File

@ -0,0 +1,117 @@
<?php
/**
* File: catmgmt.inc
* Author: Ryan Prather
* Purpose: For handling the catalog management page
* Created: May 2, 2018
*
* Portions Copyright 2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* See license.txt for details
*
* Change Log:
* - May 2, 2018 - File created, Moved catalog mgmt html content from index page to this for easier viewing and refined the code a little
*/
?>
<script src='/script/datatables/DataTables-1.10.9/js/jquery.dataTables.min.js'></script>
<link rel="stylesheet" href="/script/datatables/DataTables-1.10.9/css/jquery.dataTables.min.css" />
<link rel='stylesheet' href='/script/jquery-ui/jquery-ui.min.css' />
<style type='text/css'>
#availableSoftware {
height: 227px;
width: 240px;
overflow-x: scroll;
font-size: 14px;
line-height: 1.25em;
}
.swmouseover {
background-color: #1D57A0;
color: #fff;
cursor: pointer;
}
</style>
<script src='data.min.js' type='text/javascript'></script>
<script type='text/javascript'>
$(function () {
$('#catalog').DataTable({
'stripeClasses': ['odd_row', 'even_row']
});
$('.close, .backdrop').click(function () {
close_box();
});
$('#release-date').datepicker();
$('.button,.button-delete').mouseover(function(){$(this).addClass('mouseover');});
$('.button,.button-delete').mouseout(function(){$(this).removeClass('mouseover');});
});
</script>
<style type="text/css">
thead {
background-image: linear-gradient(to bottom, #ECECEC, rgba(177,177,177,0.72));
color: #4c4c4c;
}
</style>
<div>
<table id='catalog' class='display'>
<thead>
<tr>
<th>File Name</th>
<th>Status</th>
<th>Start Time</th>
<th>% Complete</th>
<th>STIG Count</th>
</tr>
</thead>
<tbody>
<?php
$cat_scripts = $db->get_Catalog_Script();
$odd = true;
foreach ($cat_scripts as $key => $cat_script) {
print <<<EOL
<tr>
<td onclick='javascript:get_cat_data("{$cat_script->file_name}");'><a href='javascript:void(0);'>{$cat_script->file_name}</a></td>
<td>{$cat_script->status}</td>
<td>{$cat_script->start_time->format("Y-m-d H:i:s")}</td>
<td>{$cat_script->perc_comp}</td>
<td>{$cat_script->stig_count}</td>
</tr>
EOL;
}
?>
</tbody>
</table>
</div>
<div id='popup' class='box'>
<div style='display:inline-block;width:49%;vertical-align:top;'>
<input type='hidden' id='id' />
Checklist ID: <span id='checklist-id'></span><br />
Name: <input type='text' id='name' /><br />
Description: <textarea id='description'></textarea><br />
Version: <span id='version'></span><br />
Release: <span id='release'></span><br />
Release Date: <input type='text' id='release-date' /><br />
Icon: <input type='text' id='icon' title='Put file in <?php print realpath(DOC_ROOT . "/img/checklist_icons") ?> and copy/paste the base filename here' /><br />
Type: <span id='type'></span><br />
<input type='button' class="button" value='Save' onclick='save_checklist();' />
<!-- <input type='button' class='button-delete' value='Delete' onclick='' /> -->
</div>
<div style='display:inline-block;width:49%;'>
<select id='software' multiple size='10' style='width:275px;' title='Double-click to remove software'></select><br />
Add CPE: <input type='text' id='cpe' onkeyup='javascript:autocomplete_software();' />&nbsp;&nbsp;
<label for='os'>OS?</label>
<input type='checkbox' id='os' /><br />
<div id="availableSoftware"></div>
</div>
</div>
<div class="backdrop"></div>

366
data/data.js Normal file
View File

@ -0,0 +1,366 @@
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
/**
* Array to store default headers in searches
*
* @type Array
*/
var default_headers = [
{'title': 'STIG ID', 'data': 'stig_id'},
{'title': 'VMS ID', 'data': 'vms_id'},
{'title': 'Checklist Name', 'data': 'name'},
{'title': 'Type', 'data': 'type'},
{'title': 'PDI', 'data': 'pdi_id'},
{'title': 'File Name', 'data': 'file'}
];
/**
* Array to store headers for CVE searches
*
* @type Array
*/
var cve_headers = [
{'title': 'PDI ID', 'data': 'pdi_id'},
{'title': 'CVE ID', 'data': 'cve_id'},
{'title': 'Description', 'data': 'desc'},
{'title': 'Status', 'data': 'status'},
{'title': 'Reference', 'data': 'ref'}
];
/**
* Array to store headers for CPE searches
*
* @type Array
*/
var cpe_headers = [
{'title': 'Man', 'data': 'man'},
{'title': 'Name', 'data': 'name'},
{'title': 'Ver', 'data': 'ver'},
{'title': 'CPE', 'data': 'cpe'},
{'title': 'String', 'data': 'sw_string'}
];
/**
* Array to store headers for IAVM searches
*
* @type Array
*/
var iavm_headers = [
{'title': 'PDI ID', 'data': 'pdi_id'},
{'title': 'IAVM Notice', 'data': 'iavm'},
{'title': 'Title', 'data': 'title'},
{'title': 'Category', 'data': 'cat'},
{'title': 'Link', 'data': 'link'}
];
var start = 0;
var table = null;
function query() {
if (!$('#q').val()) {
alert("Please enter something to search for");
return;
}
if (table) {
table.destroy();
}
if ($('#type').val() == 'cve')
headers = cve_headers;
else if ($('#type').val() == 'cpe')
headers = cpe_headers;
else if ($('#type').val() == 'iavm')
headers = iavm_headers;
else
headers = default_headers;
table = $('#results').DataTable({
pageLength: 100,
serverSide: true,
stripeClasses: ['odd_row', 'even_row'],
columns: headers,
ajax: {
beforeSend: function () {
$('body').addClass('loading');
},
url: '/search.php',
method: 'POST',
data: {
type: $('#type').val(),
q: $('#q').val()
},
complete: function () {
$('body').removeClass('loading');
}
}
});
}
function open_stig(file, id) {
$('#search_result').attr('src', '../reference/stigs/stig.php?file=' + file + '&vms=' + id);
$('#search_result').animate({'opacity': '1.00'}, 300, 'linear');
$('#search_result').css('display', 'block');
view_box();
}
function open_pdi(pdi) {
$('#search_result').attr('src', 'pdi.php?pdi=' + pdi);
$('#search_result').animate({'opacity': '1.00'}, 300, 'linear');
$('#search_result').css('display', 'block');
view_box();
}
function view_box() {
$('.backdrop').animate({
'opacity': '.5'
}, 300, 'linear');
$('.backdrop').css('display', 'block');
$('html, body').css({
'overflow': 'hidden',
'height': '100%'
});
}
function close_box() {
$('.backdrop, .box').animate({
'opacity': '0'
}, 300, 'linear', function () {
$('.backdrop, .box').css('display', 'none');
});
$('html, body').css({
'overflow': 'auto',
'height': '100%'
});
if (mydz) {
mydz.on('queuecomplete', function () {
$('.dz-complete').remove();
$('.dz-message').show();
});
}
}
function get_cat_data(fname) {
$('#popup').animate({
'opacity': '1.00'
}, 300, 'linear');
$('#popup').css('display', 'block');
view_box();
$.ajax('/ajax.php', {
data: {
action: 'get-cat-data',
'fname': fname
},
beforeSend: function () {
$('#id').val('');
$('#checklist-id').text('');
$('#name').val('');
$('#description').val('');
$('#version').text('');
$('#release').text('');
$('#icon').val('');
$('#type').text('');
$('#software option').remove();
$('#cpe').val('');
},
success: function (data) {
$('#id').val(data.id);
$('#checklist-id').text(data.checklist_id);
$('#name').val(data.name);
$('#description').val(data.description);
$('#version').text(data.ver);
$('#release').text(data.release);
$('#icon').val(data.icon);
$('#type').text(data.type);
var dt = new Date(data.date.date);
$('#release-date').val((dt.getMonth() + 1) + "/" + dt.getDate() + '/' + dt.getFullYear());
for (var x in data.sw) {
$('#software').append("<option id='" + data.sw[x].id + "'>" +
data.sw[x].man + " " + data.sw[x].name + " " + data.sw[x].ver +
"</option>");
}
$('#software option').dblclick(remove_Software);
},
error: function (xhr, status, error) {
console.error(error);
},
timeout: 3000,
method: 'post',
dataType: 'json'
});
}
function remove_Software() {
$.ajax("/ajax.php", {
data: {
action: 'checklist-remove-software',
chk_id: $('#id').val(),
sw_id: $(this).attr('id')
},
success: function (data) {
if (data.error) {
alert(data.error);
}
else if (data.success) {
alert(data.success);
}
},
error: function (xhr, status, error) {
console.error(error);
},
dataType: 'json',
timeout: 3000,
method: 'post'
});
$(this).remove();
}
function autocomplete_software() {
if ($('#cpe').val().length < 3) {
return;
}
$.ajax('/ajax.php', {
data: {
action: ($('#os').is(":checked") ? 'os_filter' : 'sw_filter'),
filter: $('#cpe').val()
},
success: function (data) {
$('#availableSoftware div').remove();
for (var x in data) {
$('#availableSoftware').append("<div sw_id='" + data[x].sw_id + "' cpe='" + data[x].cpe + "'>" + data[x].sw_string + "</div>");
}
$('#availableSoftware').show();
$('#availableSoftware div').each(function () {
$(this).on("mouseover", function () {
$(this).addClass("swmouseover");
});
$(this).on("mouseout", function () {
$(this).removeClass("swmouseover");
});
$(this).on("click", function () {
add_software($(this).attr('sw_id'));
$('#software').append("<option value='" + $(this).attr('sw_id') + "' ondblclick='remove_Software();$(this).remove();'>" + $(this).html() + "</option>");
$(this).remove();
});
});
},
error: function (xhr, status, error) {
console.error(error);
},
dataType: 'json',
method: 'post',
timeout: 5000
});
}
function add_software(sw_id) {
$.ajax('/ajax.php', {
data: {
action: 'checklist-add-software',
'sw_id': sw_id,
chk_id: $('#id').val()
},
success: function (data) {
alert(data.status);
},
error: function (xhr, status, error) {
console.error(error);
},
dataType: 'json',
method: 'post',
timeout: 3000
});
}
function save_checklist() {
$.ajax('/ajax.php', {
data: {
action: 'save-checklist',
id: $('#id').val(),
name: $('#name').val(),
desc: $('#description').val(),
'rel-date': $('#release-date').val(),
icon: $('#icon').val()
},
success: function (data) {
if (data.error) {
console.error(data.error);
}
else {
alert(data.success);
}
},
error: function (xhr, status, error) {
console.error(error);
alert(error);
},
dataType: 'json',
method: 'post',
timeout: 3000
});
}
function validate_Edit_STE() {
if ($('#action') == 'Delete STE') {
return confirm("Are you sure you want to delete this ST&E");
}
var ret = true;
if ($('#start_date').val() > $('#end_date').val()) {
alert("Your start date can't after the end date");
ret = false;
}
if (!$('#start_date').val()) {
alert("You must select a start date for this ST&E");
ret = false;
}
if (!$('#end_date').val()) {
alert("You must select an end date for this ST&E");
ret = false;
}
if ($('#system').val() == "0") {
alert("You must select a system for this ST&E");
ret = false;
}
if ($('#site').val() == "0") {
alert("You must select a site where this ST&E will be performed");
ret = false;
}
return ret;
}
function show_subsystems() {
if ($('#system').val() == '0') {
alert('Select a primary system');
$('#system').focus();
return;
}
if ($('#add_subsystems').is(':checked'))
$('#subsystem_container').show();
else
$('#subsystem_container').hide();
$('#subsystems option').each(function () {
if ($(this).val() == $('#system').val()) {
$(this).remove();
return;
}
});
}

1
data/data.min.js vendored Normal file

File diff suppressed because one or more lines are too long

View File

@ -1,5 +1,4 @@
<?php
/**
* File: reset.php
* Author: Ryan Prather
@ -19,13 +18,21 @@
* - Oct 16, 2014 - File created
* - Jun 3, 2015 - Copyright updated and added constants
* - Nov 7, 2016 - Fixed bug with resetting web user password, commented out calling Perl encrypt.pl script
* - Jun 2, 2018 - Added checkbox to allow for generation of new random SALT
*/
include_once 'config.inc';
include_once 'helper.inc';
if (isset($_REQUEST['reset'])) {
$reset = (boolean) filter_input(INPUT_POST, 'reset', FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE);
if ($reset) {
chdir(DOC_ROOT);
$db = new mysqli(DB_SERVER, $_REQUEST['uname'], $_REQUEST['pwd'], "mysql");
$uname = filter_input(INPUT_POST, 'uname', FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE);
$pwd = filter_input(INPUT_POST, 'pwd', FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE);
$web_pwd = filter_input(INPUT_POST, 'web_pwd', FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE);
$new_salt = (boolean) filter_input(INPUT_POST, 'new-salt', FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
$db = new mysqli(DB_SERVER, $uname, $pwd, "mysql");
if ($db->connect_error) {
include_once "header.inc";
die($db->connect_error);
@ -38,29 +45,42 @@ if (isset($_REQUEST['reset'])) {
$host = '%';
}
if (!$db->real_query("SET PASSWORD FOR 'web'@'$host' = PASSWORD('" . $_REQUEST['web_pwd'] . "')")) {
if (!$db->real_query("SET PASSWORD FOR 'web'@'{$host}' = PASSWORD('{$web_pwd}')")) {
include_once "header.inc";
die("DB Password change unsuccessful, ceasing further operation" . PHP_EOL . $db->error);
}
$pwd = $_REQUEST['web_pwd'];
/* ---------------------------------
* CREATE DB PASSWORD FILE
* --------------------------------- */
$enc_pwd = my_encrypt($pwd);
$salt = null;
$enc_pwd = null;
if ($new_salt) {
$salt = base64_encode(openssl_random_pseudo_bytes(32));
$enc_pwd = my_encrypt($web_pwd, $salt);
}
else {
$enc_pwd = my_encrypt($web_pwd);
}
if (!file_put_contents(DOC_ROOT . "/" . PWD_FILE, $enc_pwd)) {
die("Failed to save password");
}
die($enc_pwd);
print "Password change successful<br />";
if ($salt) {
print "Successfully updated the password, please copy the following text to the constant 'SALT' in the config.inc file, then the connection to the database will be restored<br />{$salt}<br />";
print "<a href='/'>Home</a>";
}
else {
print "Successfully updated the password, click <a href='/'>here</a> to continue";
}
}
else {
?>
<script src='/style/5grid/jquery-1.10.2.min.js' type='text/javascript'></script>
<script src='/script/jquery-3.2.1.min.js' type='text/javascript'></script>
<script type='text/javascript'>
function chk_pwd() {
if ($('#pwd').val() != $('#conf').val()) {
@ -77,6 +97,7 @@ else {
<form method='post' action='reset.php'>
MySQL Admin User Name: <input type="text" name="uname" /><br />
Password: <input type="password" name="pwd" /><br />
New Random SALT: <input type='checkbox' name='new-salt' value='1' /><br />
<br />
New Web User Password: <input type="password" name="web_pwd" id="pwd" /><br />
Confirm Password: <input type="password" name="conf_pwd" id="conf" onkeyup='javascript:chk_pwd();' /> <span id='msg'></span><br />

View File

@ -5,7 +5,7 @@
* Purpose: Allows the changing of system settings
* Created: Jan 6, 2015
*
* Portions Copyright 2016: Cyber Perspectives, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -25,13 +25,16 @@
* - May 13, 2017 - Added support for editing the default output format for E-Checklist exports
* - May 19, 2017 - Added audible notification setting
* - May 25, 2017 - Fixed typo
* - Apr 15, 2018 - Added entry for NVD CVE data and counts for each library type
*/
$db = new db();
$settings = $db->get_Settings(['cpe-load-date', 'cve-load-date', 'stig-load-date', 'nasl-load-date']);
$settings = $db->get_Settings(['cpe-load-date', 'cve-load-date', 'nvd-cve-load-date', 'stig-load-date', 'nasl-load-date', 'cpe-count', 'cve-count', 'nvd-cve-count', 'stig-count', 'nasl-count']);
$cpe_date = (isset($settings['cpe-load-date']) ? new DateTime($settings['cpe-load-date']) : null);
$cve_date = (isset($settings['cve-load-date']) ? new DateTime($settings['cve-load-date']) : null);
$nvd_date = (isset($settings['nvd-cve-load-date']) ? new DateTime($settings['nvd-cve-load-date']) : null);
$stig_date = (isset($settings['stig-load-date']) ? new DateTime($settings['stig-load-date']) : null);
$nasl_date = (isset($settings['nasl-load-date']) ? new DateTime($settings['nasl-load-date']) : null);
?>
<div style="width:49%;display:inline-block;">
@ -41,6 +44,7 @@ $nasl_date = (isset($settings['nasl-load-date']) ? new DateTime($settings['nasl-
if (isset($settings_saved)) {
print $settings_saved;
}
?>
Company: <input type="text" name="company" value="<?php print COMPANY; ?>" /><br />
Company Address: <input type="text" name="comp_add" value="<?php print COMP_ADD; ?>" /><br />
@ -78,9 +82,9 @@ $nasl_date = (isset($settings['nasl-load-date']) ? new DateTime($settings['nasl-
<!--
Nessus server: <input type="text" name="nessus_server" value="<?php print NESSUS_SVR; ?>" /><br />
NMap binary path: <input type="text" name="nmap_path" value="<?php print NMAP_PATH; ?>" /><br />
-->
<input type="button" class='button' value="Save Settings" onclick='this.form.submit();' />
-->
</form>
</div>
@ -90,24 +94,34 @@ $nasl_date = (isset($settings['nasl-load-date']) ? new DateTime($settings['nasl-
<tr>
<th>Type</th>
<th>Date</th>
<th>Count</th>
</tr>
</thead>
<tbody>
<tr>
<td>CPE's</td>
<td><?php print (is_a($cpe_date, 'DateTime') && $cpe_date != new DateTime("1970-01-01 00:00:00") ? $cpe_date->format("M j, Y") : "Not Loaded"); ?></td>
<td><?php print $settings['cpe-count']; ?></td>
</tr>
<tr>
<td>CVE's</td>
<td><?php print (is_a($cve_date, 'DateTime') && $cve_date != new DateTime("1970-01-01 00:00:00") ? $cve_date->format("M j, Y") : "Not Loaded"); ?></td>
<td><?php print $settings['cve-count']; ?></td>
</tr>
<tr>
<td>NVD CVE's</td>
<td><?php print (is_a($nvd_date, 'DateTime') && $nvd_date != new DateTime("1970-01-01 00:00:00") ? $nvd_date->format("M j, Y") : "Not Loaded"); ?></td>
<td><?php print $settings['nvd-cve-count']; ?></td>
</tr>
<tr>
<td>STIG's</td>
<td><?php print (is_a($stig_date, 'DateTime') && $stig_date != new DateTime("1970-01-01 00:00:00") ? $stig_date->format("M j, Y") : "Not Loaded"); ?></td>
<td><?php print $settings['stig-count']; ?></td>
</tr>
<tr>
<td>NASL</td>
<td><?php print (is_a($nasl_date, 'DateTime') && $nasl_date != new DateTime("1970-01-01 00:00:00") ? $nasl_date->format("M j, Y") : "Not Loaded"); ?></td>
<td><?php print $settings['nasl-count']; ?></td>
</tr>
</tbody>
</table>

View File

@ -5,7 +5,7 @@
* Purpose: For adding or editing sites
* Created: Oct 21, 2014
*
* Portions Copyright 2016-2017: Cyber Perspectives, LLC, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions

View File

@ -5,7 +5,7 @@
* Purpose: For adding or editing ST&Es
* Created: Oct 21, 2014
*
* Portions Copyright 2016-2017: Cyber Perspectives, LLC, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -21,6 +21,8 @@
* - May 19, 2017 - Migrated to filtering and changed save button to match buttons throughout
* - Jun 3, 2017 - Fixed bug #230 and changed table stripping to be consistent across the system
* - Jan 20, 2018 - Removed CKEditor fields
* - Apr 29, 2018 - Updated jQuery and jQuery UI library and remove minimum date restriction
* - May 31, 2018 - Added filtering to only show unique IP's and hostname excluding loopback and 0.0.0.0
*/
$page = filter_input(INPUT_GET, 'p', FILTER_SANITIZE_STRING);
$ste_id = filter_input(INPUT_POST, 'ste', FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE);
@ -34,7 +36,7 @@ $stes = $db->get_STE();
<script type="text/javascript" src="/script/datatables/DataTables-1.10.9/js/jquery.dataTables.min.js"></script>
<link rel="stylesheet" type="text/css" href="/script/jQueryUI/css/ui-lightness/jquery-ui-1.10.3.custom.min.css" />
<link rel="stylesheet" type="text/css" href="/script/jquery-ui/jquery-ui.min.css" />
<link type='text/css' rel='stylesheet' href="/script/datatables/DataTables-1.10.9/css/jquery.dataTables.min.css" />
<?php
@ -78,20 +80,19 @@ elseif ($page == 'EditSTE' && is_numeric($ste_id) && $ste_id > 0) {
#cke_scope, #cke_assumptions, #cke_constraints {
display:none;
}
.ui-datepicker {
width: 17em;
}
</style>
<script type='text/javascript'>
$(function () {
$('#start_date').datepicker({
dateFormat: "yy-mm-dd",
minDate: 0,
onSelect: function (date) {
var dt2 = $('#end_date');
var startDate = $(this).datepicker('getDate');
var minDate = $(this).datepicker('getDate');
startDate.setDate(startDate.getDate() + 30);
//sets dt2 maxDate to the last day of 30 days window
dt2.datepicker('option', 'maxDate', startDate);
dt2.datepicker('option', 'minDate', minDate);
//$(this).datepicker('option', 'minDate', minDate);
}
@ -122,61 +123,6 @@ elseif ($page == 'EditSTE' && is_numeric($ste_id) && $ste_id > 0) {
]});
*/ ?>
});
function validate_Edit_STE() {
if ($('#action') == 'Delete STE') {
return confirm("Are you sure you want to delete this ST&E");
}
var ret = true;
if ($('#start_date').val() > $('#end_date').val()) {
alert("Your start date can't after the end date");
ret = false;
}
if (!$('#start_date').val()) {
alert("You must select a start date for this ST&E");
ret = false;
}
if (!$('#end_date').val()) {
alert("You must select an end date for this ST&E");
ret = false;
}
if ($('#system').val() == "0") {
alert("You must select a system for this ST&E");
ret = false;
}
if ($('#site').val() == "0") {
alert("You must select a site where this ST&E will be performed");
ret = false;
}
return ret;
}
function show_subsystems() {
if ($('#system').val() == '0') {
alert('Select a primary system');
$('#system').focus();
return;
}
if ($('#add_subsystems').is(':checked'))
$('#subsystem_container').show();
else
$('#subsystem_container').hide();
$('#subsystems option').each(function () {
if ($(this).val() == $('#system').val()) {
$(this).remove();
return;
}
});
}
</script>
<form method='post' action='?p=EditSTE'>
@ -205,7 +151,6 @@ elseif ($page == 'EditSTE' && is_numeric($ste_id) && $ste_id > 0) {
<input type='text' name='start_date' id='start_date' value='<?php print $ste->get_Eval_Start_Date()->format('Y-m-d'); ?>' /><br />
Eval End Date:
<input type='text' name='end_date' id='end_date' value='<?php print $ste->get_Eval_End_Date()->format('Y-m-d'); ?>' /><br />
<?php print "<script>console.log('" . json_encode($ste->get_System()) . "');</script>"; ?>
System: <select name='system' id='system'>
<?php
foreach ($all_systems as $key => $sys) :
@ -313,28 +258,28 @@ elseif ($page == 'EditSTE' && is_numeric($ste_id) && $ste_id > 0) {
</thead>
<tbody>
<?php
$odd = true;
if (is_array($tgts) && count($tgts) && isset($tgts['id'])) {
$tgts = array(0 => $tgts);
}
if (is_array($tgts) && count($tgts) && isset($tgts[0]) && is_a($tgts[0], 'target')) {
foreach ($tgts as $key => $tgt) {
$interfaces = '';
$fqdn = '';
$odd = !$odd;
$ips = [];
$fqdn = [];
$os = $db->get_Software($tgt->get_OS_ID())[0];
foreach ($tgt->interfaces as $key2 => $int) {
$interfaces .= $int->get_IPv4() . ", ";
$fqdn .= $int->get_FQDN() . ", ";
if(!in_array($int->get_IPv4(), ['0.0.0.0', '127.0.0.1'])) {
$ips[] = $int->get_IPv4();
}
$fqdn[] = $int->get_FQDN();
}
print "<tr>" . // class='".($odd ? 'odd' : 'even')."'>".
print "<tr>" .
"<td>{$tgt->get_ID()}</td>" .
"<td>{$tgt->get_Name()}</td>" .
"<td>" . substr($interfaces, 0, -2) . "</td>" .
"<td>" . substr($fqdn, 0, -2) . "</td>" .
"<td>" . implode(", ", array_unique($ips)) . "</td>" .
"<td>" . implode(", ", array_unique($fqdn)) . "</td>" .
"<td>{$tgt->get_OS_String()}</td>" .
"</tr>";
}
@ -360,14 +305,10 @@ elseif ($page == 'EditSTE' && $ste_id == 'new') {
$(function () {
$('#start_date').datepicker({
dateFormat: "yy-mm-dd",
minDate: -30,
onSelect: function (date) {
var dt2 = $('#end_date');
var startDate = $(this).datepicker('getDate');
var minDate = $(this).datepicker('getDate');
startDate.setDate(startDate.getDate() + 30);
//sets dt2 maxDate to the last day of 30 days window
dt2.datepicker('option', 'maxDate', startDate);
dt2.datepicker('option', 'minDate', minDate);
//$(this).datepicker('option', 'minDate', minDate);
}

View File

@ -18,10 +18,22 @@
* - Oct 21, 2014 - File created
* - Sep 1, 2016 - Copyright updated and updated file purpose
* - May 19, 2017 - Migrated to filtering and changed save button to match buttons throughout
* - May 31, 2018 - Commented out CKEditor library
*/
$page = filter_input(INPUT_GET, 'p', FILTER_SANITIZE_STRING, FILTER_NULL_ON_FAILURE);
$sys_id = filter_input(INPUT_POST, 'system', FILTER_VALIDATE_INT, FILTER_NULL_ON_FAILURE);
?>
<style type="text/css">
#description {
width: 500px;
height: 150px;
}
</style>
<?php
if ($page == 'MSMgmt') {
?>
@ -58,12 +70,14 @@ elseif ($page == 'EditMS' && $sys_id) {
<script src='/script/ckeditor/ckeditor.js'></script>
<script type='text/javascript'>
$(function () {
/*
CKEDITOR.replace('description', {height: '100px', width: '950px', toolbar: [
{name: 'document', items: ['Source']},
{name: 'editor', items: ['Cut', 'Copy', 'Paste', 'PasteText', 'PastFromWord', '-', 'Undo', 'Redo']},
{name: 'basicstyles', groups: ['basicstyles', 'cleanup'], items: ['Bold', 'Italic', 'Underline', '-', 'RemoveFormat']},
{name: 'paragraph', groups: ['list', 'indent', 'blocks', 'align'], items: ['NumberedList', 'BulletedList', '-', 'Outdent', 'Indent', '-', 'JustifyLeft', 'JustifyCenter', 'JustifyRight', 'JustifyBlock']}
]});
*/
});
</script>
@ -117,7 +131,7 @@ elseif ($page == 'EditMS' && $sys_id) {
<?php print ($acred_type == accrediation_types::RMF ? ' selected' : ''); ?>>RMF</option>
</select><br />
System Description:<br />
<textarea name='description' id='description' cols='1' rows='1'><?php print $system->get_Description(); ?></textarea>
<textarea name='description' id='description' cols='1' rows='1'><?php print $system->get_Description(); ?></textarea><br />
<input type='button' class='button' name='action' value='Save System' onclick='this.form.submit();' />
</form>
@ -165,7 +179,7 @@ elseif ($page == 'EditMS' && !$sys_id) {
<option value='rmf'>RMF</option>
</select><br />
System Description:<br />
<textarea name='description' id='description' cols='1' rows='1'>[paste system description here]</textarea>
<textarea name='description' id='description' cols='1' rows='1'>[paste system description here]</textarea><br />
<input type='button' class='button' name='action' value='Save System' onclick='this.form.submit();' />
</form>

View File

@ -1025,7 +1025,7 @@
"default" : null
},
{
"name" : "check_content",
"name" : "check_contents",
"dataType" : "text",
"type" : 252,
"length" : null,

View File

@ -1,12 +1,11 @@
<?php
/**
* File: background_results.php
* Author: Ryan Prather
* Purpose: Background script file that will call appropriate function for files found
* Created: Feb 26, 2014
*
* Portions Copyright 2016-2017: Cyber Perspectives, LLC, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -29,6 +28,7 @@
* - Feb 21, 2017 - Fixed path issues with scripts not running
* - Oct 23, 2017 - Conditionally delete parse_config.ini only if not in DEBUG log level
* - Oct 27, 2017 - Fix to remove desktop.ini files if found
* - May 24, 2018 - Moved a couple code blocks because of being out of order
*/
error_reporting(E_ALL);
@ -36,15 +36,6 @@ $cmd = getopt("t::", ["help::"]);
$conf = parse_ini_file("parse_config.ini", false);
if (isset($cmd['help']) || !is_numeric($conf['ste']) || !isset($conf['doc_root'])) {
die(usage());
}
elseif (!file_exists($conf['doc_root'])) {
die("Folder {$conf['doc_root']} doesn't exist" . PHP_EOL);
}
chdir($conf['doc_root']);
set_time_limit(0);
include_once 'config.inc';
@ -52,8 +43,31 @@ include_once 'database.inc';
include_once 'helper.inc';
include_once 'vendor/autoload.php';
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
$log_level = Logger::ERROR;
switch (LOG_LEVEL) {
case E_WARNING:
$log_level = Logger::WARNING;
break;
case E_NOTICE:
$log_level = Logger::NOTICE;
break;
case E_DEBUG:
$log_level = Logger::DEBUG;
}
$log = new Logger('result_import');
$log->pushHandler(new StreamHandler(LOG_PATH . "/result_import.log", $log_level));
$debug = (LOG_LEVEL == E_DEBUG ? true : false);
if (isset($cmd['help']) || !is_numeric($conf['ste']) || !isset($conf['doc_root'])) {
die(usage());
}
chdir(TMP);
check_path(TMP . "/echecklist");
check_path(TMP . "/nessus");
check_path(TMP . "/nmap");
@ -62,8 +76,6 @@ check_path(TMP . "/stig_viewer");
check_path(TMP . "/terminated");
check_path(TMP . "/unsupported");
chdir(TMP);
$dbh = new db();
$files = glob("*.*");
@ -74,97 +86,96 @@ $threads = [];
foreach ($files as $file) {
$res = FileDetection($file);
if ($debug) {
Sagacity_Error::err_handler(print_r($res, true), E_DEBUG);
}
$log->debug("File detected", $res);
switch ($res['type']) {
case NESSUS:
$stack[] = array(
$stack[] = [
'exec' => 'nessus',
'file' => $file,
'ste' => $conf['ste'],
'source' => 'nessus'
);
];
break;
case SCC_XCCDF:
$stack[] = array(
$stack[] = [
'exec' => 'scc_xccdf',
'file' => $file,
'ste' => $conf['ste'],
'source' => 'scc_xccdf'
);
];
break;
case STIG_VIEWER_CKL:
$stack[] = array(
$stack[] = [
'exec' => 'stig_viewer',
'file' => $file,
'ste' => $conf['ste'],
'source' => 'stig_viewer'
);
];
break;
case TECH_ECHECKLIST_EXCEL:
$ignore = false;
if (isset($conf['ignore'])) {
$ignore = true;
}
$stack[] = array(
$stack[] = [
'exec' => 'excel_echecklist',
'file' => $file,
'ste' => $conf['ste'],
'ignore_hidden' => $ignore,
'source' => 'echecklist'
);
];
break;
case ECHECKLIST_CSV:
$stack[] = array(
$stack[] = [
'exec' => 'csv_echecklist',
'file' => $file,
'ste' => $conf['ste'],
'source' => 'echecklist'
);
];
break;
case PROC_ECHECKLIST_EXCEL:
$stack[] = array(
$stack[] = [
'exec' => 'proc_echecklist',
'file' => $file,
'ste' => $conf['ste']
);
];
break;
case HOST_DATA_COLLECTION:
$stack[] = array(
$stack[] = [
'exec' => 'data_collection',
'file' => $file,
'ste' => $conf['ste'],
'target' => $cmd['t'],
'source' => 'data_collection'
);
];
break;
case NMAP_GREPABLE:
case NMAP_TEXT:
case NMAP_XML:
$stack[] = array(
$stack[] = [
'exec' => 'nmap',
'file' => $file,
'ste' => $conf['ste'],
'source' => 'nmap'
);
];
break;
case MBSA_TEXT:
case MBSA_XML:
$stack[] = array(
$stack[] = [
'exec' => 'mbsa',
'file' => $file,
'ste' => $conf['ste'],
'source' => 'mbsa'
);
];
break;
case MSSQL_XML:
$stack[] = array(
$stack[] = [
'exec' => 'mssql',
'file' => $file,
'ste' => $conf['ste'],
'source' => 'mssql'
);
];
break;
case DIRECTORY:
break;
@ -176,13 +187,12 @@ foreach ($files as $file) {
}
}
if ($debug) {
Sagacity_Error::err_handler(print_r($stack, true), E_DEBUG);
}
$log->debug("Current script stack", $stack);
foreach ($stack as $key => $s) {
$existing = $dbh->get_Running_Script_Status($s['ste'], $s['file']);
if (isset($existing['status']) && $existing['status'] == 'RUNNING') {
$log->warning("Script to parse " . basename($s['file']) . " is already running");
unset($stack[$key]);
continue;
}
@ -199,10 +209,11 @@ foreach ($stack as $key => $s) {
$ignore .
($debug ? " --debug" : "");
$log->debug("Adding parser for " . basename($s['file']));
$dbh->add_Running_Script(basename($s['file']), $s['ste'], $s['source'], $conf['location']);
}
$proc = array();
$count = 0;
chdir(realpath(DOC_ROOT . "/exec"));
@ -211,10 +222,13 @@ foreach ($stack as $s) {
$threads[] = new Cocur\BackgroundProcess\BackgroundProcess($s['script']);
end($threads)->run();
$log->info("Starting parser script {$s['script']}");
sleep(3);
$count++;
while ($count >= MAX_RESULTS) {
$log->debug("Current MAX_RESULTS met at " . MAX_RESULTS);
sleep(1);
$count = $dbh->get_Running_Script_Count($conf['ste']);
}
@ -234,7 +248,8 @@ if (!$debug) {
*
* @param string $file
*/
function import_SCC_OVAL($file) {
function import_SCC_OVAL($file)
{
if (preg_match('/.*Results\_iavm\_(2009|2010)|Results\_USGCB/i', $file)) {
return;
}
@ -331,7 +346,8 @@ function import_SCC_OVAL($file) {
}
}
function usage() {
function usage()
{
print <<<EOO
Purpose: This program was written to look at all files in the /tmp directory, determine what parser is needed, then call that parser with the appropriate flags.

View File

@ -26,8 +26,10 @@
* - Apr 5, 2017 - Hard coded parsing 20 STIGs instead of using MAX_RESULTS constant
* - Jun 27, 2017 - Cleanup
* - Jul 13, 2017 - Changed STIG parsing to serial instead of parallel to fix issue with duplicate STIGs from race conditions
* - May 31, 2018 - Added deletion when files match exclusion
* - Jun 2, 2018 - Added code to check STIG_EXCLUSIONS constant to for permanently excluded STIGs
*/
$cmd = getopt("x::h::d::", ["debug::", "delete::", "ia::", "extract::", "help::"]);
$cmd = getopt("x::h::d::", ["debug::", "delete::", "ia::", "extract::", "help::", 'exclude::']);
if (isset($cmd['help']) || isset($cmd['h'])) {
die(usage());
@ -45,7 +47,7 @@ use Monolog\Handler\StreamHandler;
use Monolog\Formatter\LineFormatter;
$log_level = Logger::ERROR;
switch(LOG_LEVEL) {
switch (LOG_LEVEL) {
case E_WARNING:
$log_level = Logger::WARNING;
break;
@ -56,29 +58,32 @@ switch(LOG_LEVEL) {
$log_level = Logger::DEBUG;
}
$stream = new StreamHandler("php://output", Logger::INFO);
if (isset($cmd['debug'])) {
$log_level = Logger::DEBUG;
}
$stream = new StreamHandler("php://output", $log_level);
$stream->setFormatter(new LineFormatter("%datetime% %level_name% %message%" . PHP_EOL, "H:i:s.u"));
$log = new Logger("stig_parser");
$log->pushHandler(new StreamHandler(LOG_PATH . "/stig_parser.log", $log_level));
$log->pushHandler($stream);
$path = realpath(TMP . "/stigs");
if(isset($cmd['d']) && $cmd['d']) {
$path = $cmd['d'];
}
chdir($path);
check_path(TMP . "/stigs");
check_path(TMP . "/stigs/zip");
check_path(TMP . "/stigs/checklist");
check_path(TMP . "/stigs/xml");
check_path(DOC_ROOT . "/reference/stigs");
$path = realpath(TMP . "/stigs");
if (isset($cmd['d']) && $cmd['d']) {
$path = $cmd['d'];
}
chdir($path);
$db = new db();
$stack = [];
$zip_files = glob("*.zip");
$zip = new ZipArchive();
@ -125,12 +130,16 @@ $count = 0;
$db->help->update("settings", ['meta_value' => 0], [
[
'field' => 'meta_key',
'op' => '=',
'value' => 'stig-progress'
]
]);
$db->help->execute();
$regex = null;
if (isset($cmd['exclude'])) {
$regex = $cmd['exclude'];
}
foreach ($xml_files as $key => $file) {
// if the file has a space in the file name we need to replace it because it will cause parsing errors
if (strpos($file, ' ') !== false) {
@ -140,6 +149,17 @@ foreach ($xml_files as $key => $file) {
copy(realpath(TMP . "/stigs/xml/$file"), realpath(DOC_ROOT . "/reference/stigs") . "/$file");
}
if (!is_null($regex) && preg_match("/$regex/i", $file)) {
unlink($file);
$log->debug("Skipping $file due to matching regex");
continue;
}
elseif(!empty(STIG_EXCLUSIONS) && preg_match("/" . STIG_EXCLUSIONS . "/i", $file)) {
unlink($file);
$log->debug("Skipping $file due to matching STIG exclusion");
continue;
}
// determine the file type
$ft = FileDetection(TMP . "/stigs/xml/$file");
@ -278,11 +298,13 @@ function usage()
print <<<EOO
Purpose: This program was written to look at all files in the {doc_root}/tmp directory, determine what parser is needed, then call that parser with the appropriate flags.
Usage: background_stigs.php [-x|--extract] [-d="directory"] [--debug] [--delete] [--ia] [-h|--help]
Usage: background_stigs.php [-x|--extract] [-d="directory"] [--debug] [--regex="ex1|ex2"] [--delete] [--ia] [-h|--help]
-x|--extract Simply extract the contents of a .zip file (STIG library) to it's proper places, do not parse the contents
-d="directory" Directory to search for the zip and xml files in (optional, defaults to {doc_root}/tmp)
--regex="ex1|ex2" Insert a valid regex expression (properly escaped) to exclude specific STIGs from parsing
--ia Override any IA controls in the DB to use only the ones that are in the STIG file
--delete Delete any files once complete
--debug Debugging output

View File

@ -60,7 +60,6 @@ else {
print "Destination: $dest" . PHP_EOL;
$xml = new Array2XML();
Array2XML::$all_caps = true;
$xml->standalone = true;
$xml->formatOutput = true;

View File

@ -5,7 +5,7 @@
* Purpose: This script runs the installer processes
* Created: Nov 28, 2017
*
* Copyright 2017: Cyber Perspective, LLC, All rights reserved
* Copyright 2017-2018: Cyber Perspective, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* See license.txt for details
@ -15,12 +15,9 @@
* - Dec 27, 2017 - Fixed bug with SCG showing empty, and added download progress meta keys
* - Jan 2, 2018 - Add sleep to fix bug #357 race condition
* - Jan 10, 2018 - Formatting
* - Apr 29, 2018 - Removed settings to move to .sql file. Also, changed to pull CVEs from NVD instead of Mitre repo
*/
include_once 'helper.inc';
include_once 'vendor/autoload.php';
use Cocur\BackgroundProcess\BackgroundProcess;
set_time_limit(0);
$params = [
@ -263,10 +260,10 @@ function save_Database($params)
}
}
if (!$db->real_query("GRANT CREATE TEMPORARY TABLES, INSERT, DELETE, UPDATE, SELECT, TRIGGER ON `rmf`.* TO 'web'@'$host'")) {
if (!$db->real_query("GRANT ALL ON `rmf`.* TO 'web'@'$host'")) {
$errors[] = $db->error;
}
if (!$db->real_query("GRANT CREATE TEMPORARY TABLES, INSERT, DELETE, UPDATE, SELECT, TRIGGER ON `sagacity`.* TO 'web'@'$host'")) {
if (!$db->real_query("GRANT ALL ON `sagacity`.* TO 'web'@'$host'")) {
$errors[] = $db->error;
}
@ -306,22 +303,6 @@ function save_Database($params)
}
}
$help->extended_insert("settings", ["meta_key", "meta_value"], [
['cpe-load-date', new DateTime('1970-01-01')],
['cpe-progress', 0],
['cpe-dl-progress', 0],
['cve-load-date', new DateTime('1970-01-01')],
['cve-progress', 0],
['cve-dl-progress', 0],
['stig-load-date', new DateTime('1970-01-01')],
['stig-progress', 0],
['stig-dl-progress', 0],
['nasl-load-date', new DateTime('1970-01-01')],
['nasl-progress', 0],
['nasl-dl-progress', 0]
], true);
$help->execute();
/*
* ***********************************************************
* Load table data
@ -408,7 +389,7 @@ EOO;
}
if ($params['cve']) {
$cve = " --cve";
$cve = " --nvd";
}
if ($params['stig']) {
@ -424,11 +405,12 @@ EOO;
print json_encode(['success' => true, 'msg' => $msg]);
if (!is_null($cpe) || !is_null($cve) || !is_null($stig)) {
include_once 'vendor/autoload.php';
$script = realpath(PHP_BIN) .
" -c " . realpath(PHP_CONF) .
" -f " . realpath(DOC_ROOT . "/exec/update_db.php") .
" --{$cpe}{$cve}{$stig}{$action}";
$process = new BackgroundProcess($script);
$process = new Cocur\BackgroundProcess\BackgroundProcess($script);
$process->run();
}
}

View File

@ -1,12 +1,11 @@
<?php
/**
* File: nessus-plugin-import.php
* Author: Ryan Prather
* Purpose: Script to import all Nessus plugins from *.nasl files
* Created: Jan 5, 2015
*
* Portions Copyright 2016: Cyber Perspectives, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -22,25 +21,28 @@
* - Jan 31, 2017 - Completed testing, ready for prime time
* - Feb 15, 2017 - Store existing plugin IDs in memory for evaluation to check if we should actually run the script,
* Fixed error with PHP_BIN not being defined for some weird reason
* - May 24, 2018 - Added parsing for plugins installed on the local machine
* Added DateTimeDiff helper class
*/
include_once 'config.inc';
include_once "database.inc";
include_once "helper.inc";
$cmd = getopt("h::", array("help::"));
$cmd = getopt("h::", ["help::"]);
if (isset($cmd['h']) || isset($cmd['help'])) {
die(usage());
}
$db = new db();
$time = new DateTimeDiff();
if (!file_exists(TMP . "/nessus_plugins")) {
mkdir(TMP . "/nessus_plugins");
}
$nasl_ids = array();
$db->help->select("sagacity.nessus_plugins", array('plugin_id', 'file_date'));
$nasl_ids = [];
$db->help->select("sagacity.nessus_plugins", ['plugin_id', 'file_date']);
if ($rows = $db->help->execute()) {
foreach ($rows as $row) {
$nasl_ids[$row['plugin_id']] = DateTime::createFromFormat("U", $row['file_date']);
@ -50,70 +52,93 @@ if ($rows = $db->help->execute()) {
chdir(TMP . '/nessus_plugins');
$files = glob("*.nasl");
$start_time = new DateTime();
if (strtolower(substr(PHP_OS, 0, 3)) == 'win') {
if (file_exists(getenv("%ProgramData%") . "/Tenable/Nessus/nessus/plugins")) {
chdir(getenv("%ProgramData%") . "/Tenable/Nessus/nessus/plugins");
$files = array_merge($files, glob("*.nasl"));
}
}
elseif (strtolower(substr(PHP_OS, 0, 3)) == 'lin') {
if (file_exists("/opt/nessus/lib/nessus/plugins") && is_readable("/opt/nessus/lib/nessus/plugins")) {
chdir("/opt/nessus/lib/nessus/plugins");
$files = array_merge($files, glob("*.nasl"));
}
print "Found " . count($files) . " NASL files\nStarted at {$start_time->format("Y-m-d H:i:s")}\n";
if (file_exists("/opt/sc/data/nasl") && is_readable("/opt/sc/data/nasl")) {
chdir("/opt/sc/data/nasl");
$files = array_merge($files, glob("*.nasl"));
}
}
chdir(DOC_ROOT . '/exec');
$x = 0;
$files = array_unique($files);
print "Found " . count($files) . " NASL files\nStarted at {$time->getStartClockTime()}\n";
chdir(DOC_ROOT . "/exec");
// Query database to build an array of existing plugins to compare against on import
$existing_plugins = [];
$db->help->select("nessus_plugins", ['plugin_id', 'file_date']);
$rows = $db->help->execute();
if (is_array($rows) && count($rows)) {
foreach ($rows as $row) {
$existing_plugins[$row['plugin_id']] = DateTime::createFromFormat("U", $row['file_date']);
}
}
// Sort the files and loop over them
natsort($files);
$threads = [];
$count = 0;
$total_complete = 0;
foreach ($files as $file) {
$db->help->select("nessus_plugins", array('plugin_id', 'file_date'), [
$db->help->select("nessus_plugins", ['plugin_id', 'file_date'], [
[
'field' => 'file_name',
'op' => '=',
'value' => basename($file)
]
]);
$row = $db->help->execute();
if (!isset($row['file_name']) || is_null($row['file_date']) || filemtime(TMP . "/nessus_plugins/$file") > $row['file_date']) {
$comp = number_format(($x / count($files)) * 100, 2) . "%";
print "\r$comp";
$comp = number_format(($x / count($files)) * 100, 2);
print "\r$comp%";
$script = realpath(defined('PHP_BIN') ? PHP_BIN : PHP) .
" -c " . realpath(PHP_CONF) .
" -f " . realpath(DOC_ROOT . "/exec/nessus-plugin-to-database.php") . " --" .
" -f=\"" . realpath(TMP . "/nessus_plugins/$file") . "\"";
if (substr(strtolower(PHP_OS), 0, 3) == "win") {
$shell = new COM("WScript.Shell");
$shell->CurrentDirectory = DOC_ROOT . "/exec";
$shell->run($script, 0, false);
}
elseif (substr(strtolower(PHP_OS), 0, 3) == 'lin') {
exec("$script > /dev/null &");
$threads[] = new Cocur\BackgroundProcess\BackgroundProcess($script);
end($threads)->run();
$output = array();
exec("netstat -an | grep TIME_WAIT | wc -l", $output);
if ($output[0] > 1200) {
do {
sleep(1);
exec("netstat -an | grep TIME_WAIT | wc -l", $output);
}
while ($output[0] > 100);
}
}
//sleep(1);
$count++;
$total_complete++;
$x++;
if ($count > 1000) {
$db->set_Setting("nasl-progress", $comp);
foreach ($threads as $k => $t) {
if (!$t->isRunning()) {
unset($threads[$k]);
$count--;
}
}
}
}
}
$db->help->update("settings", ['meta_value' => 100], [
[
'field' => 'meta_key',
'op' => IN,
'value' => ['nasl-dl-progress', 'nasl-progress']
]
]);
$db->help->execute();
$db->set_Setting("nasl-dl-progress", 100);
$db->set_Setting("nasl-progress", 100);
$db->set_Setting("nasl-count", $total_complete);
$end_time = new DateTime();
$time->stopClock();
$diff = $end_time->diff($start_time);
print "\nFinished at {$time->getEndClockTime()}\nTotal Time: {$time->getTotalDiffString()}\n";
print "\nFinished at {$end_time->format("Y-m-d H:i:s")}\nTotal Time: {$diff->format("%H:%I:%S")}\n";
function usage() {
function usage()
{
print <<<EOF
Purpose: The purpose of this script is to update the CVE, CPE, and CCE databases. Script will sleep for 3 seconds between actions to allow you review the results.

View File

@ -1,12 +1,11 @@
<?php
/**
* File: nessus-plugin-to-database.php
* Author: Ryan Prather
* Purpose: Script to read .NASL files and import them to the database
* Created: Jan 15, 2017
*
* Copyright 2017: Cyber Perspectives, All rights reserved
* Copyright 2017-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* See license.txt for details
@ -15,14 +14,20 @@
* - Jan 15, 2017 - File created
* - Jan 31, 2017 - Competed testing, ready for prime time
* - Apr 5, 2017 - Delete file if error in parsing, check for TMP/nessus_plugins and LOG_PATH/nessus_plugins.log
* - Apr 29, 2018 - Updated to Monolog library and cleaned up script
*/
error_reporting(E_ALL);
include_once 'config.inc';
include_once "database.inc";
include_once "helper.inc";
include_once 'vendor/autoload.php';
$cmd = getopt("f:h::", array("help::", "debug::"));
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Monolog\Formatter\LineFormatter;
$cmd = getopt("f:h::", ["help::", "debug::"]);
if (isset($cmd['h']) || isset($cmd['help']) || !isset($cmd['f'])) {
die(usage());
@ -31,28 +36,45 @@ elseif (!file_exists($cmd['f'])) {
die("Could not find file specified {$cmd['f']}\n");
}
check_path(TMP . "/nessus_plugins", true);
check_path(LOG_PATH . "/nessus_plugins.log");
$log_level = Logger::ERROR;
switch (LOG_LEVEL) {
case E_WARNING:
$log_level = Logger::WARNING;
break;
case E_NOTICE:
$log_level = Logger::NOTICE;
break;
case E_DEBUG:
$log_level = Logger::DEBUG;
}
if (isset($cmd['debug']) && $cmd['debug']) {
$log_level = Logger::DEBUG;
}
$stream = new StreamHandler("php://output", $log_level);
$stream->setFormatter(new LineFormatter("%datetime% %level_name% %message%" . PHP_EOL, "H:i:s.u"));
$log = new Logger("nasl_plugin");
$log->pushHandler(new StreamHandler(LOG_PATH . "/nessus_plugins/{$cmd['f']}.log", $log_level));
$log->pushHandler($stream);
$db = new db();
file_put_contents("check.log", "checking plugin file {$cmd['f']}");
$nasl = new nasl($cmd['f']);
$plugin_id = 0;
$file_date = null;
if (!isset($nasl->{'id'})) {
unlink($cmd['f']);
//unlink($cmd['f']);
$log->critical("No ID available");
die;
}
if (isset($cmd['debug'])) {
print_r($nasl);
$log->debug("", [$nasl]);
}
$plugin_id = 0;
$file_date = null;
$db->help->select("sagacity.nessus_plugins", array('plugin_id', 'file_date'), [
$db->help->select("sagacity.nessus_plugins", ['plugin_id', 'file_date'], [
[
'field' => 'plugin_id',
'op' => '=',
@ -68,7 +90,7 @@ if ($row = $db->help->execute()) {
if (($plugin_id && !is_a($file_date, "DateTime")) ||
(is_a($file_date, "DateTime") && isset($nasl->last_modification) && is_a($nasl->last_modification, "DateTime") &&
$file_date->format("U") < $nasl->last_modification->format("U"))) {
file_put_contents(LOG_PATH . "/nessus_plugins.log", "Updating {$nasl->id}\n", FILE_APPEND);
$log->info("Updating {$nasl->id}");
$db->help->update("sagacity.nessus_plugins", [
'file_name' => basename($cmd['f']),
@ -84,12 +106,9 @@ if (($plugin_id && !is_a($file_date, "DateTime")) ||
throw(new Exception("Failed to update the plugin {$nasl->id}", E_WARNING));
}
}
else {
print "$db->help->sql\n";
}
}
elseif (!$plugin_id) {
file_put_contents(LOG_PATH . "/nessus_plugins.log", "Inserting {$nasl->id}\n", FILE_APPEND);
$log->info("Inserting {$nasl->id}");
$params = [
'plugin_id' => $nasl->id,
@ -108,15 +127,12 @@ elseif (!$plugin_id) {
throw(new Exception("Failed to insert a new plugin {$nasl->id}", E_WARNING));
}
}
else {
print "$db->help->sql\n";
}
}
else {
file_put_contents(LOG_PATH . "/nessus_plugins.log", "No changes to plugin {$nasl->id}\n", FILE_APPEND);
$log->info("No changes to plugin {$nasl->id}");
}
$params = array();
$params = [];
if (isset($nasl->ref)) {
foreach ($nasl->ref as $key => $refs) {
if (is_array($refs)) {
@ -172,11 +188,9 @@ else {
print $db->help->sql . PHP_EOL;
}
if (!isset($cmd['debug'])) {
unlink($cmd['f']);
}
function usage() {
function usage()
{
print <<<EOL
Purpose: This script is for reading NASL files and adding them to the database

View File

@ -225,15 +225,6 @@ if ($items->length) {
$sys->help->extended_replace("cve_web", $web_fields, $new_cve_web);
$sys->help->execute();
}
$sys->help->update("settings", ['meta_value' => 100], [
[
'field' => 'meta_key',
'op' => IN,
'value' => ['cve-dl-progress', 'cve-progress']
]
]);
$sys->help->execute();
}
function usage() {

View File

@ -5,7 +5,7 @@
* Purpose: Parse the Excel version (.xlsx or .xls) of an eChecklist
* Created: May 9, 2014
*
* Portions Copyright 2016-2017: Cyber Perspectives, LLC, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -24,6 +24,7 @@
* - May 26, 2017 - Migrated to PHPSpreadsheet library
* - Aug 28, 2017 - Fixed couple minor bugs
* - Jan 15, 2018 - Formatting, reorganized use statements, and cleaned up
* - May 24, 2018 - Attempt to fix bug #413
*/
$cmd = getopt("f:", ['debug::', 'help::']);
set_time_limit(0);
@ -48,17 +49,21 @@ include_once 'excelConditionalStyles.inc';
use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Worksheet\Worksheet;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
check_path(TMP . "/echecklist");
chdir(TMP);
$log_level = convert_log_level();
$db = new db();
$base_name = basename($cmd['f']);
$log = new Sagacity_Error($cmd['f']);
$log = new Logger("excel-echecklist");
$log->pushHandler(new StreamHandler(logify($cmd['f']), $log_level));
if (!file_exists($cmd['f'])) {
$db->update_Running_Scan($base_name, ['name' => 'status', 'value' => 'ERROR']);
$log->script_log("File not found", E_ERROR);
die($log->emergency("File not found"));
}
$db->update_Running_Scan($base_name, ['name' => 'pid', 'value' => getmypid()]);
@ -68,7 +73,7 @@ if (is_array($src) && count($src) && isset($src[0]) && is_a($src[0], 'source'))
$src = $src[0];
}
else {
$log->script_log("Could not find the source", E_ERROR);
die($log->emergency("Could not find the source"));
}
/*
@ -94,13 +99,13 @@ else {
$ste = $ste[0];
}
else {
$log->script_log("Could not retrieve the ST&E", E_ERROR);
die($log->emergency("Could not retrieve ST&E"));
}
$scan = new scan(null, $src, $ste, 1, $base_name, $dt->format('Y-m-d'));
if (!$scan_id = $db->save_Scan($scan)) {
$log->script_log("Failed to add scan for file: {$cmd['f']}", E_ERROR);
die($log->error("Failed to add scan for file: {$cmd['f']}"));
}
$scan->set_ID($scan_id);
@ -113,11 +118,11 @@ if (is_array($gen_os) && count($gen_os) && isset($gen_os[0]) && is_a($gen_os[0],
foreach ($objSS->getWorksheetIterator() as $wksht) {
if (preg_match('/Instruction|Cover Sheet/i', $wksht->getTitle())) {
$log->script_log("Skipping instruction and cover sheet", E_DEBUG);
$log->debug("Skipping instruction and cover worksheet");
continue;
}
elseif (isset($conf['ignore']) && $wksht->getSheetState() == Worksheet::SHEETSTATE_HIDDEN) {
$log->script_log("Skipping hidden worksheet {$wksht->getTitle()}");
$log->info("Skipping hidden worksheet {$wksht->getTitle()}");
continue;
}
@ -132,17 +137,17 @@ foreach ($objSS->getWorksheetIterator() as $wksht) {
if ($thread_status['status'] == 'TERMINATED') {
unset($objSS);
rename(realpath(TMP . "/{$scan->get_File_Name()}"), TMP . "/terminated/{$scan->get_File_Name()}");
$log->script_log("File parsing terminated by user");
$log->notice("File parsing terminated by user");
}
$log->script_log("Reading from {$wksht->getTitle()} worksheet");
$log->notice("Reading from {$wksht->getTitle()}");
if (!preg_match('/STIG ID/i', $wksht->getCell("A10")->getValue()) &&
!preg_match('/VMS ID/i', $wksht->getCell("B10")->getValue()) &&
!preg_match('/CAT/i', $wksht->getCell("C10")->getValue()) &&
!preg_match('/IA Controls/i', $wksht->getCell("D10")->getValue()) &&
!preg_match('/Short Title/i', $wksht->getCell("E10")->getValue())) {
$log->script_log("Invalid headers in {$wksht->getTitle()}", E_WARNING);
$log->warning("Invalid headers in {$wksht->getTitle()}");
continue;
}
@ -177,13 +182,12 @@ foreach ($objSS->getWorksheetIterator() as $wksht) {
if ($thread_status['status'] == 'TERMINATED') {
unset($objSS);
rename(realpath(TMP . "/{$scan->get_File_Name()}"), TMP . "/terminated/{$scan->get_File_Name()}");
$log->script_log("File parsing terminated by user");
die;
die($log->notice("File parsing terminated by user"));
}
if ($cell->getColumn() > $short_title_col && !preg_match('/Overall/i', $cell->getValue())) {
if (preg_match('/status/i', $cell->getValue())) {
$log->script_log("Error: Invalid host name ('status') in {$wksht->getTitle()}", E_WARNING);
$log->error("Invalid host name ('status') in {$wksht->getTitle()}");
break;
}
@ -193,7 +197,7 @@ foreach ($objSS->getWorksheetIterator() as $wksht) {
$tgt = $tgt[0];
}
else {
$log->script_log("Could not find host {$cell->getValue()}", E_ERROR);
$log->error("Could not find host {$cell->getValue()}");
}
}
else {
@ -251,7 +255,7 @@ foreach ($objSS->getWorksheetIterator() as $wksht) {
$idx['check_contents'] += count($tgts);
}
elseif (empty($tgts)) {
$log->script_log("Failed to identify targets in worksheet {$wksht->getTitle()}", E_WARNING);
$log->warning("Failed to identify targets in worksheet {$wksht->getTitle()}");
continue;
}
@ -281,7 +285,7 @@ foreach ($objSS->getWorksheetIterator() as $wksht) {
$pdi->set_Short_Title($short_title);
$pdi->set_Group_Title($short_title);
if (!($pdi_id = $db->save_PDI($pdi))) {
$log->script_log("Failed to add a new PDI for STIG ID $stig_id", E_ERROR);
die($log->error("Failed to add new PDI for STIG ID {$stig_id}"));
}
$stig = new stig($pdi_id, $stig_id, $short_title);
@ -293,14 +297,21 @@ foreach ($objSS->getWorksheetIterator() as $wksht) {
$status = $wksht->getCell(Coordinate::stringFromColumnIndex($idx['target'] + $x) . $row->getRowIndex())
->getValue();
$log->script_log("{$tgt->get_Name()} {$stig->get_ID()} ($status)\n", E_DEBUG);
$log->debug("{$tgt->get_Name()} {$stig->get_ID()} ($status)");
$finding = $db->get_Finding($tgt, $stig);
if (is_array($finding) && count($finding) && isset($finding[0]) && is_a($finding[0], 'finding')) {
$tmp = $finding[0];
if(preg_match("/Not a Finding|Not Applicable/i", $status)) {
$ds = $tmp->get_Deconflicted_Status($status);
$tmp->set_Finding_Status_By_String($ds);
}
else {
$tmp->set_Finding_Status_By_String($status);
}
$tmp->set_Notes($notes);
$tmp->set_Category($cat_lvl);

View File

@ -41,6 +41,7 @@
* - Oct 27, 2017 - Fix to convert '*' to '0.0.0.0' or '::' and validate IP's before making interface
* - Nov 25, 2017 - Fixed bug #345
* - Jan 16, 2018 - Updated to use host_list class
* - Jun 4, 2018 - Fixed bug #424 (IP address not pulled when name used for host)
*/
error_reporting(E_ALL);
@ -491,6 +492,16 @@ class nessus_parser extends scan_xml_parser
}
}
if (!empty($this->tag['host-ip']) && validation::valid_ip($this->tag['host-ip'])) {
if (!isset($this->tgt->interfaces[$this->tag['host-ip']])) {
$this->log->script_log("Adding new interface to target with IP: {$this->tag['host-ip']}");
$this->tgt->interfaces[$this->tag['host-ip']] = new interfaces(null, $this->tgt->get_ID(), null, $this->tag['host-ip'], null, $this->host->hostname, $this->host->fqdn, null);
}
else {
$this->log->script_log("Interface already exists for target: {$this->tag['host-ip']}");
}
}
$netstat_keys = preg_grep("/netstat\-established\-tcp/", array_keys($this->tag));
$this->log->script_log("Start established tcp conns...found " . count($netstat_keys) . " connections", E_DEBUG);
foreach (array_values($netstat_keys) as $key) {
@ -503,6 +514,7 @@ class nessus_parser extends scan_xml_parser
$this->log->script_log("Start listening tcp4 conns...found " . count($netstat_keys) . " connections", E_DEBUG);
if (between(count($netstat_keys), 1, PORT_LIMIT)) {
foreach (array_values($netstat_keys) as $key) {
// split into "ip:port" array
$ip_port = explode(":", $this->tag[$key]);
// skip this entry if it is not a valid IP

View File

@ -1,18 +1,19 @@
<?php
/**
* File: parse_nvd_json_cve
* Author: Ryan Prather <ryan.prather@cyberperspectives.com>
* Purpose:
* Created: Dec 30, 2017
* Created: Apr 29, 2018
*
* Copyright 2017: Cyber Perspective, LLC, All rights reserved
* Copyright 2018: Cyber Perspective, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* See license.txt for details
*
* Change Log:
* - Dec 30, 2017 - File created
* - Apr 29, 2018 - File created
* - May 10, 2018 - Formatting and fixed performance issue on Windows (bug #403)
* - Jun 5, 2018 - Fix for bug #425
*/
include_once 'config.inc';
include_once 'helper.inc';
@ -44,11 +45,7 @@ switch (LOG_LEVEL) {
break;
}
$stream = new StreamHandler("php://output", $log_level);
$stream->setFormatter(new LineFormatter("%datetime% %level_name% %message%", "H:i:s.u"));
$log = new Logger("nvd_cve");
$log->pushHandler($stream);
$log->pushHandler(new StreamHandler(LOG_PATH . "/nvd_cve.log", $log_level));
$db = new db();
@ -65,6 +62,7 @@ if (is_array($cves) && count($cves)) {
print "Currently " . count($existing_cves) . " in DB" . PHP_EOL . "Parsing: " . count($json->CVE_Items) . " items" . PHP_EOL;
$db_cpes = [];
$new_cves = [];
$new_cve_refs = [];
$new_cve_web = [];
@ -72,6 +70,12 @@ $sw_rows = [];
$new = 0;
$existing = 0;
$db->help->select("software", ['id', 'cpe']);
$rows = $db->help->execute();
foreach ($rows as $row) {
$db_cpes["{$row['cpe']}"] = $row['id'];
}
$cve_fields = [
'cve_id', 'seq', 'status', 'phase', 'phase_date', 'desc'
];
@ -132,13 +136,9 @@ foreach ($json->CVE_Items as $cve) {
}
if (count($cpes)) {
$sw_ids = $db->get_Software_Ids($cpes);
if (is_array($sw_ids) && count($sw_ids) && isset($sw_ids['id'])) {
$sw_ids = [0 => $sw_ids];
}
if (is_array($sw_ids) && count($sw_ids) && isset($sw_ids[0])) {
foreach ($sw_ids as $sw) {
$sw_rows[] = [$name, $sw];
foreach ($cpes as $cpe) {
if (isset($db_cpes["{$cpe}"])) {
$sw_rows[] = [$name, $db_cpes["{$cpe}"]];
}
}
}
@ -176,7 +176,6 @@ foreach ($json->CVE_Items as $cve) {
$db->help->update("settings", ['meta_value' => number_format((($existing + $new) / count($json->CVE_Items)) * 100, 2)], [
[
'field' => 'meta_key',
'op' => '=',
'value' => 'nvd-cve-progress'
]
]);
@ -199,36 +198,12 @@ if (count($sw_rows)) {
$db->help->execute();
}
$db->help->update("settings", ['meta_value' => 100], [
[
'field' => 'meta_key',
'op' => '=',
'value' => 'nvd-cve-progress'
]
]);
$db->help->execute();
$db->help->update("settings", ['meta_value' => 100], [
[
'field' => 'meta_key',
'op' => IN,
'value' => ['cve-dl-progress', 'cve-progress']
]
]);
$db->help->execute();
$db->help->update("settings", ['meta_value' => new DateTime()], [
[
'field' => 'meta_key',
'op' => IN,
'value' => ['cve-load-date', 'nvd-cve-load-date']
]
]);
$db->help->execute();
unlink($cmd['f']);
print PHP_EOL;
function usage() {
function usage()
{
print <<<EOF
Purpose: To import the National Vulnerability Database (NVD) CVE JSON files

View File

@ -29,6 +29,7 @@
* - Jul 23, 2017 - MAS Added comments
* - Aug 28, 2017 - Added die for draft stigs
* - Dec 27, 2017 - Added up date for load date
* - May 10, 2018 - Starting to migrate logging and fixed install status bar issues (#403)
*/
$cmd = getopt("f:", ['debug::', 'ia_reset::', 'draft::', 'help::']);
@ -670,6 +671,10 @@ foreach ($groups as $group) {
$db->update_Catalog_Script($base_name, ['name' => 'perc_comp', 'value' => ($perc_comp / $groups->length) * 100]);
}
$db->help->select_count("sagacity.stigs");
$stig_count = $db->help->execute();
$db->set_Setting('stig-count', $stig_count);
$end = new DateTime();
$diff = $end->diff($start);

View File

@ -5,7 +5,7 @@
* Author: Ryan Prather
* Created: Jan 5, 2015
*
* Portions Copyright 2016-2017: Cyber Perspectives, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -45,6 +45,9 @@
* Fixed confusion with Cygwin and Bash on Windows paths
* - Jun 27, 2017 - Matt Shuter: Fixed bug #262 & #270
* - Dec 27, 2017 - Added database field and download progress flag
* - Apr 29, 2018 - Added extract parameter to only extract nasl archive file, fixed a couple bugs
* - May 10, 2018 - Removed ping of cve.mitre.org, and added 'po' and 'do' parameters for NVD CVE
* - Jun 5, 2018 - Fixed a couple setting updates
*/
include_once 'config.inc';
include_once 'helper.inc';
@ -62,7 +65,7 @@ $total_time = null;
$total_diff = 0;
$summary_stats = [];
$cmd = getopt("h::u::p::", ['cpe::', 'cce::', 'cve::', 'nvd::', 'nasl::', 'stig::', 'do::', 'po::', 'help::']);
$cmd = getopt("h::u::p::", ['cpe::', 'cce::', 'cve::', 'nvd::', 'nasl::', 'stig::', 'do::', 'po::', 'help::', 'debug::', 'extract::', 'exclude::']);
$db = new db();
$diff = new DateTimeDiff();
@ -79,7 +82,11 @@ switch (LOG_LEVEL) {
$log_level = Logger::DEBUG;
}
$stream = new StreamHandler("php://output", Logger::INFO);
if (isset($cmd['debug']) && $cmd['debug']) {
$log_level = Logger::DEBUG;
}
$stream = new StreamHandler("php://output", $log_level);
$stream->setFormatter(new LineFormatter("%datetime% %level_name% %message%" . PHP_EOL, "H:i:s.u"));
$log = new Logger("update_db");
@ -93,7 +100,7 @@ if (isset($cmd['h'], $cmd['help']) ||
if (isset($cmd['do']) || !isset($cmd['po'])) {
if (!ping("cyberperspectives.com")) {
die("Cannot connect to internet" . PHP_EOL);
$log->emergency("Cannot connect to internet");
}
}
@ -101,8 +108,11 @@ if (isset($cmd['do']) || !isset($cmd['po'])) {
* Update CPE content downloaded from NIST
*/
if (isset($cmd['cpe'])) {
$db->set_Setting('cpe-dl-progress', 0);
$db->set_Setting('cpe-progress', 0);
$db->set_Setting_Array([
'cpe-dl-progress' => 0,
'cpe-progress' => 0,
'cpe-count' => 0
]);
$path = TMP . "/cpe";
if (isset($cmd['p']) && $cmd['p']) {
@ -112,7 +122,7 @@ if (isset($cmd['cpe'])) {
check_path($path);
$diff->resetClock();
$log->info("Started CPE ingestion ({$diff->getStartClockTime()})");
print "Started CPE ingestion ({$diff->getStartClockTime()})" . PHP_EOL;
// search for an unzip any zip files in the tmp directory
$zip_files = glob("{$path}/*cpe-dictionary*.zip");
@ -120,7 +130,7 @@ if (isset($cmd['cpe'])) {
$log->debug("Found a existing cpe-dictionary.zip file, unzipping then parsing");
$zip = new ZipArchive();
foreach ($zip_files as $file) {
$log->info("Unzipping {$file}");
$log->debug("Unzipping {$file}");
$zip->open($file);
$zip->extractTo($path);
$zip->close();
@ -135,7 +145,7 @@ if (isset($cmd['cpe'])) {
foreach ($tmp_files as $fname) {
$name = basename($fname);
if ($name == 'official-cpe-dictionary_v2.3.xml') {
$name = "cpe-dictionary-{$start_time->format("Ymd")}.xml";
$name = "cpe-dictionary-{$diff->getStartClock()->format("Ymd")}.xml";
}
rename($fname, "{$path}/{$name}");
}
@ -146,14 +156,14 @@ if (isset($cmd['cpe'])) {
$cpe_parse_fname = null;
// download the file if the do flag is used even if it already exists
if (isset($cmd['do']) && ping("nist.gov") && !isset($cmd['po'])) {
download_file($cpe_url, $cpe_fname, $db, 'cpe-dl-progress');
if (isset($cmd['do']) && !isset($cmd['po'])) {
download_file($cpe_url, $cpe_fname, $db->help, 'cpe-dl-progress');
}
// download the file only if it doesn't exist
elseif (!file_exists($cpe_fname) && ping("nist.gov") && !isset($cmd['po'])) {
download_file($cpe_url, $cpe_fname, $db, 'cpe-dl-progress');
elseif (!file_exists($cpe_fname) && !isset($cmd['po'])) {
download_file($cpe_url, $cpe_fname, $db->help, 'cpe-dl-progress');
}
elseif (!isset($cmd['po']) && !ping("nist.gov")) {
elseif (!isset($cmd['po'])) {
$log->error("Could not connect to nist.gov to download the CPE library");
die();
}
@ -185,7 +195,7 @@ if (isset($cmd['cpe'])) {
}
if (is_null($cpe_parse_fname)) {
$log->warning("Coult not find a CPE file to parse");
$log->warning("Could not find a CPE file to parse");
}
$script = realpath(defined('PHP_BIN') ? PHP_BIN : PHP) .
@ -194,14 +204,19 @@ if (isset($cmd['cpe'])) {
" -f=\"" . realpath($cpe_parse_fname) . "\"" .
" -d=\"{$dt->format("Y-m-d")}\"";
$log->info("Running parsing script");
$log->debug("Running CPE parsing script on file: $cpe_parse_fname");
passthru($script);
}
$db->help->select_count("software");
$cpe_count = $db->help->execute();
$db->set_Setting("cpe-count", $cpe_count);
$diff->stopClock();
$log->info(PHP_EOL . "Finished at {$diff->getEndClockTime()}" . PHP_EOL .
"Total time: {$diff->getDiffString()}");
print PHP_EOL . "Finished at {$diff->getEndClockTime()}" . PHP_EOL .
"Total time: {$diff->getDiffString()}" . PHP_EOL;
sleep(3);
}
@ -210,8 +225,14 @@ if (isset($cmd['cpe'])) {
* Update CVE content
*/
if (isset($cmd['cve'])) {
$db->set_Setting('cve-dl-progress', 0);
$db->set_Setting('cve-progress', 0);
$db->set_Setting_Array([
'nvd-cve-dl-progress' => 0,
'nvd-cve-progress' => 0,
'nvd-cve-count' => 0,
'cve-dl-progress' => 0,
'cve-progress' => 0,
'cve-count' => 0
]);
$path = TMP . "/cve";
if (isset($cmd['p']) && $cmd['p']) {
$path = $cmd['p'];
@ -220,12 +241,12 @@ if (isset($cmd['cve'])) {
check_path($path);
$diff->resetClock();
$log->info("Started CVE ingestion {$diff->getStartClockTime()}");
print "Started CVE ingestion {$diff->getStartClockTime()}" . PHP_EOL;
$cve_files = glob(TMP . "/allitems.xml");
if (count($cve_files)) {
foreach ($cve_files as $file) {
rename($file, "{$path}/cve-all-{$start_time->format("Ymd")}.xml");
rename($file, "{$path}/cve-all-{$diff->getStartClock()->format("Ymd")}.xml");
}
}
@ -240,13 +261,13 @@ if (isset($cmd['cve'])) {
$cve_url = "http://cve.mitre.org/data/downloads/allitems.xml";
$cve_parse_fname = null;
if (isset($cmd['do']) && ping("cve.mitre.org") && !isset($cmd['po'])) {
download_file($cve_url, $cve_fname, $db, 'cve-dl-progress');
if (isset($cmd['do']) && !isset($cmd['po'])) {
download_file($cve_url, $cve_fname, $db->help, 'cve-dl-progress');
}
elseif (!file_exists($cve_fname) && ping("cve.mitre.org") && !isset($cmd['po'])) {
download_file($cve_url, $cve_fname, $db, 'cve-dl-progress');
elseif (!file_exists($cve_fname) && !isset($cmd['po'])) {
download_file($cve_url, $cve_fname, $db->help, 'cve-dl-progress');
}
elseif (!isset($cmd['po']) && !ping("cve.mitre.org")) {
elseif (!isset($cmd['po'])) {
Sagacity_Error::err_handler("Could not connect to cve.mitre.org to download the CVE library", E_ERROR);
}
@ -271,7 +292,7 @@ if (isset($cmd['cve'])) {
}
if (is_null($cve_parse_fname)) {
$log->error("Coult not find a CVE file to parse");
$log->error("Could not find a CVE file to parse");
die;
}
@ -281,21 +302,44 @@ if (isset($cmd['cve'])) {
" -f=\"" . realpath($cve_parse_fname) . "\"" .
" -d=\"{$dt->format("Y-m-d")}\"";
$log->info("Script to run $script");
$log->debug("Script to run $script");
passthru($script);
}
$db->help->select_count("sagacity.cve_db");
$cve_count = $db->help->execute();
$db->set_Setting_Array([
'cve-dl-progress' => 100,
'cve-progress' => 100,
'cve-count' => $cve_count,
'cve-load-date' => new DateTime(),
'nvd-cve-dl-progress' => 100,
'nvd-cve-progress' => 100,
'nvd-cve-count' => $cve_count,
'nvd-cve-load-date' => new DateTime()
]);
$diff->stopClock();
$log->info("Finished at {$diff->getEndClockTime()}" . PHP_EOL .
"Total Time: {$diff->getDiffString()}");
print "Finished at {$diff->getEndClockTime()}" . PHP_EOL .
"Total Time: {$diff->getDiffString()}" . PHP_EOL;
sleep(3);
}
/**
* Update to NVD CVE content
*/
if (isset($cmd['nvd'])) {
$db->set_Setting('nvd-cve-dl-progress', 0);
$db->set_Setting('nvd-cve-progress', 0);
$db->set_Setting_Array([
'nvd-cve-dl-progress' => 0,
'nvd-cve-progress' => 0,
'nvd-cve-count' => 0,
'cve-dl-progress' => 0,
'cve-progress' => 0,
'cve-count' => 0
]);
$path = TMP . "/nvd";
if (isset($cmd['p']) && $cmd['p']) {
$path = $cmd['p'];
@ -303,13 +347,14 @@ if (isset($cmd['nvd'])) {
check_path($path);
$diff->resetClock();
$log->info("Started NVD CVE ingestion ({$diff->getStartClockTime()})");
print "Started NVD CVE ingestion ({$diff->getStartClockTime()})" . PHP_EOL;
$nvd_years = [];
for ($x = 2002; $x <= $diff->getStartClock()->format("Y"); $x++) {
$nvd_years[] = $x;
}
if (isset($cmd['do']) || !isset($cmd['po'])) {
$too_old = new DateTime();
$too_old->sub(DateInterval::createFromDateString("7 days"));
@ -317,7 +362,8 @@ if (isset($cmd['nvd'])) {
if ($load_date < $too_old) {
// More than 7 days old so have to do a full load
foreach ($nvd_years as $yr) {
download_file("https://static.nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-{$yr}.json.zip", TMP . "/nvd/nvdcve-{$yr}.json.zip");
$db->set_Setting('nvd-year', $yr);
download_file("https://static.nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-{$yr}.json.zip", TMP . "/nvd/nvdcve-{$yr}.json.zip", $db->help, 'nvd-cve-dl-progress');
$zip = new ZipArchive();
$zip->open(TMP . "/nvd/nvdcve-{$yr}.json.zip");
$zip->extractTo(TMP . "/nvd");
@ -326,37 +372,62 @@ if (isset($cmd['nvd'])) {
}
}
else {
download_file("https://static.nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-modified.json.zip", TMP . "/nvd/nvdcve-modified.json.zip");
$db->set_Setting('nvd-year', 'modified');
download_file("https://static.nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-modified.json.zip", TMP . "/nvd/nvdcve-modified.json.zip", $db->help, 'nvd-cve-dl-progress');
$zip = new ZipArchive();
$zip->open(TMP . "/nvd/nvdcve-modified.json.zip");
$zip->extractTo(TMP . "/nvd");
$zip->close();
unlink(TMP . "/nvd/nvdcve-modified.json.zip");
download_file("https://static.nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-recent.json.zip", TMP . "/nvd/nvdcve-recent.json.zip");
$db->set_Setting('nvd-year', 'recent');
download_file("https://static.nvd.nist.gov/feeds/json/cve/1.0/nvdcve-1.0-recent.json.zip", TMP . "/nvd/nvdcve-recent.json.zip", $db->help, 'nvd-cve-dl-progress');
$zip->open(TMP . "/nvd/nvdcve-recent.json.zip");
$zip->extractTo(TMP . "/nvd");
$zip->close();
unlink(TMP . "/nvd/nvdcve-recent.json.zip");
}
}
chdir(DOC_ROOT . "/exec");
if (isset($cmd['po']) || !isset($cmd['do'])) {
$json_files = glob(TMP . "/nvd/*.json");
foreach ($json_files as $j) {
$match = [];
if (preg_match("/(\d{4}|recent|modified)/", basename($j), $match)) {
$db->set_Setting('nvd-year', $match[1]);
}
else {
$db->set_Setting('nvd-year', null);
}
$script = realpath(defined('PHP_BIN') ? PHP_BIN : PHP) .
" -c " . realpath(PHP_CONF) .
" -f " . realpath(DOC_ROOT . "/exec/parse_nvd_json_cve.php") . " --" .
" -f=\"" . realpath($j) . "\"";
$log->info("Running NVD CVE parsing script");
$log->debug("Running NVD CVE parsing script on file: $j");
passthru($script);
}
}
$db->help->select_count("sagacity.cve_db");
$nvd_count = $db->help->execute();
$diff->stopClock();
$log->info("Finished at {$diff->getEndClockTime()}" . PHP_EOL .
"Total time {$diff->getTotalDiffString()}");
print "Finished at {$diff->getEndClockTime()}" . PHP_EOL .
"Total time {$diff->getTotalDiffString()}" . PHP_EOL;
$db->set_Setting("nvd-cve-load-date", $diff->getEndClock()->format(MYSQL_DT_FORMAT));
$db->set_Setting_Array([
'nvd-cve-load-date' => $diff->getEndClock()->format(MYSQL_DT_FORMAT),
'nvd-cve-count' => $nvd_count,
'nvd-cve-progress' => 100,
'nvd-cve-dl-progress' => 100,
'nvd-year' => null,
'cve-load-date' => $diff->getEndClock()->format(MYSQL_DT_FORMAT),
'cve-count' => $nvd_count,
'cve-progress' => 100,
'cve-dl-progress' => 100
]);
}
/**
@ -382,44 +453,73 @@ if (isset($cmd['cce'])) {
* Parse NASL content from NVT and/or Nessus
*/
if (isset($cmd['nasl'])) {
$db->set_Setting('nasl-dl-progress', 0);
$db->set_Setting('nasl-progress', 0);
check_path(TMP . "/nessus_plugins", true);
$db->set_Setting_Array([
'nasl-dl-progress' => 0,
'nasl-progress' => 0,
'nasl-count' => 0
]);
// Capture start time for performance monitoring
$diff->resetClock();
$log->info("Started NASL ingestion ({$diff->getStartClockTime()})");
print "Started NASL ingestion ({$diff->getStartClockTime()})" . PHP_EOL;
// Generate a unique filename for the OpenVAS feed archive using the current date
$nasl_fname = TMP . "/nessus_plugins/nasl_plugins-{$current_date->format("Ymd")}.tar.bz2";
// Download OpenVAS feed if a) it doesn't exist, b) can reach openvas.org, and c) parse only flag not set
if (!file_exists($nasl_fname) && ping("openvas.org") && !isset($cmd['po'])) {
download_file("http://www.openvas.org/openvas-nvt-feed-current.tar.bz2", $nasl_fname, $db, 'nasl-dl-progress');
$log->debug("Downloading new NASL library");
download_file("http://www.openvas.org/openvas-nvt-feed-current.tar.bz2", $nasl_fname, $db->help, 'nasl-dl-progress');
}
// Can only extract .tar.bz2 files on Linux so...
if (!isset($cmd['do']) || isset($cmd['po'])) {
if (file_exists($nasl_fname)) {
if (substr(strtolower(PHP_OS), 0, 3) == 'lin') {
$log->debug("Extracting NASL files from archive");
passthru("tar xvf $nasl_fname -C " . realpath(TMP . "/nessus_plugins") .
" --wildcards --transform='s/.*\///' '*.nasl'");
if (isset($cmd['extract'])) {
print "Completed extracting files from archive" . PHP_EOL;
}
}
}
if (isset($cmd['extract'])) {
die;
}
// ...if there are no .nasl files in the directory, die and give instructions for unzipping in Windows
$files = glob("*.nasl");
if (!count($files)) {
die("Downloaded the OpenVAS NVT plugin repository, please extract *.nasl files to " . realpath(TMP . "/nessus_plugins") . PHP_EOL .
$files = glob(TMP . "/nessus_plugins/*.nasl");
if (strtolower(substr(PHP_OS, 0, 3)) == 'win') {
if (file_exists(getenv("%ProgramData%") . "/Tenable/Nessus/nessus/plugins")) {
$log->debug("Importing local Nessus plugin files");
$files = array_merge($files, glob(getenv("%ProgramData%") . "/Tenable/Nessus/nessus/plugins/*.nasl"));
}
}
elseif (strtolower(substr(PHP_OS, 0, 3)) == 'lin') {
if (file_exists("/opt/nessus/lib/nessus/plugins") && is_readable("/opt/nessus/lib/nessus/plugins")) {
$log->debug("Importing local Nessus plugin files");
$files = array_merge($files, glob("/opt/nessus/lib/nessus/plugins/*.nasl"));
}
if (file_exists("/opt/sc/data/nasl") && is_readable("/opt/sc/data/nasl")) {
$log->debug("Importing local Nessus plugin files");
$files = array_merge($files, glob("/opt/sc/data/nasl/*.nasl"));
}
}
$files = array_unique($files);
if (!($file_count = count($files))) {
$log->emergency("Downloaded the OpenVAS NVT plugin repository, please extract *.nasl files to " . realpath(TMP . "/nessus_plugins") . PHP_EOL .
"If you have Bash on Windows ({path} = /mnt/c/xampp/www) or Cygwin ({path} = /cygdrive/c/xampp/www) installed you can run the following command on the downloaded file tweaking the paths" . PHP_EOL .
"tar xvf {path}/tmp/nessus_plugins/" . basename($nasl_fname) . " -C {path}/tmp/nessus_plugins --wildcards --transform='s/.*\///' '*.nasl'" . PHP_EOL);
die;
}
// Report how many NASL files were found in the directory
$log->info("Found " . count($files) . " NASL files" . PHP_EOL .
"Started at {$start_time->format("Y-m-d H:i:s")}");
chdir(DOC_ROOT);
print "Found {$file_count} NASL files" . PHP_EOL . "Started at {$diff->getStartClockTime()}" . PHP_EOL;
// Query database to build an array of existing plugins to compare against on import
$existing_plugins = [];
@ -430,65 +530,61 @@ if (isset($cmd['nasl'])) {
$existing_plugins[$row['plugin_id']] = DateTime::createFromFormat("U", $row['file_date']);
}
}
$log->debug("Count of existing plugins " . count($existing_plugins));
// Sort the files and loop over them
$x = 0;
natsort($files);
foreach ($files as $file) {
$abs_file_path = realpath(TMP . "/nessus_plugins/$file");
// Read the current NASL file into a nasl object
$nasl = new nasl($abs_file_path);
$nasl = new nasl($file);
// Report progress
$comp = number_format(($x / count($files)) * 100, 2) . "%";
print "\r$comp";
// calculate percent complete
$comp = number_format(($total_complete / $file_count) * 100, 2);
print "\r{$comp}%";
$log->debug("Parsing {$file} ({$comp}%)");
// If no plugin ID, delete file and continue to the next plugin
if (!isset($nasl->id)) {
unlink($abs_file_path);
$log->warning("Could not locate an ID in the plugin, skipping");
unlink($file);
continue;
}
// Only process if plugin doesn't already exist or has an older last_modificaiton date
if (!isset($existing_plugins[$nasl->id]) ||
(isset($nasl->last_modification) && $existing_plugins[$nasl->id] > $nasl->last_modification)) {
$log->info("Updating plugin {$nasl->id}");
// define command line to call script to parse the file
$script = realpath(defined('PHP_BIN') ? PHP_BIN : PHP) .
" -c " . realpath(PHP_CONF) .
" -f " . realpath(DOC_ROOT . "/exec/nessus-plugin-to-database.php") . " --" .
" -f=\"" . $abs_file_path . "\"";
" -f=\"{$file}\"";
$process = new \Cocur\BackgroundProcess\BackgroundProcess($script);
$process->run();
$threads[] = new \Cocur\BackgroundProcess\BackgroundProcess($script);
end($threads)->run();
// Call the script w/ shell or exec depending on platform
if (substr(strtolower(PHP_OS), 0, 3) == 'lin') {
$output = [];
exec("netstat -an | grep TIME_WAIT | wc -l", $output);
if ($output[0] > 2000) {
do {
$log->notice("\r$comp Sleeping till connections get below 100 {$output[0]}");
sleep(1);
$output = [];
exec("netstat -an | grep TIME_WAIT | wc -l", $output);
}
while ($output[0] > 100);
$count++;
$total_complete++;
if($total_complete % 100 == 0) {
$db->set_Setting('nasl-progress', $comp);
}
}
}
else {
unlink($abs_file_path);
}
$x++;
}
}
$db->set_Setting_Array([
'nasl-dl-progress' => 100,
'nasl-progress' => 100,
'nasl-count' => $total_complete,
'nasl-load-date' => new DateTime()
]);
$diff->stopClock();
$log->info(PHP_EOL . "Finished at {$diff->getEndClockTime()}" . PHP_EOL .
"Total Time: {$diff->getDiffString()}");
print PHP_EOL . "Finished at {$diff->getEndClockTime()}" . PHP_EOL .
"Total Time: {$diff->getDiffString()}" . PHP_EOL;
sleep(3);
}
@ -497,13 +593,16 @@ if (isset($cmd['nasl'])) {
* Update STIG library from DISA content
*/
if (isset($cmd['stig'])) {
$db->set_Setting('stig-dl-progress', 0);
$db->set_Setting('stig-progress', 0);
$db->set_Setting_Array([
'stig-dl-progress' => 0,
'stig-progress' => 0,
'stig-count' => 0
]);
$path = TMP . "/stigs";
check_path($path);
$diff->resetClock();
$log->info("Started STIG ingestion ({$diff->getStartClockTime()})");
print "Started STIG ingestion ({$diff->getStartClockTime()})" . PHP_EOL;
$mon = '01';
$prev_mon = '10';
@ -530,21 +629,21 @@ if (isset($cmd['stig'])) {
if (!file_exists($stig_fname) && ping("disa.mil") && !isset($cmd['po'])) {
if (isset($cmd['u'])) {
$url = $cmd['u'];
$log->info("Checking for $url");
$log->debug("Checking for $url");
if (url_exists($url)) {
download_file($url, $stig_fname, $db, 'stig-dl-progress');
download_file($url, $stig_fname, $db->help, 'stig-dl-progress');
}
}
else {
$log->info("Checking for $current_url");
$log->debug("Checking for $current_url");
if ($found = url_exists($current_url)) {
download_file($current_url, $stig_fname, $db, 'stig-dl-progress');
download_file($current_url, $stig_fname, $db->help, 'stig-dl-progress');
}
if (!$found) {
$log->info("Checking for $current_v2_url");
$log->debug("Checking for $current_v2_url");
if ($found = url_exists($current_v2_url)) {
download_file($current_v2_url, $stig_fname, $db, 'stig-dl-progress');
download_file($current_v2_url, $stig_fname, $db->help, 'stig-dl-progress');
}
}
@ -555,16 +654,16 @@ if (isset($cmd['stig'])) {
$prev_v2_url = "http://iasecontent.disa.mil/stigs/zip/Compilations/U_SRG-STIG_Library_{$year}_{$prev_mon}_v2.zip";
if (!$found) {
$log->info("Checking for $prev_url");
$log->debug("Checking for $prev_url");
if ($found = url_exists($prev_url)) {
download_file($prev_url, $stig_fname, $db, 'stig-dl-progress');
download_file($prev_url, $stig_fname, $db->help, 'stig-dl-progress');
}
}
if (!$found) {
$log->info("Checking for $prev_v2_url");
$log->debug("Checking for $prev_v2_url");
if (url_exists($prev_v2_url)) {
download_file($prev_v2_url, $stig_fname, $db, 'stig-dl-progress');
download_file($prev_v2_url, $stig_fname, $db->help, 'stig-dl-progress');
}
}
}
@ -581,46 +680,58 @@ if (isset($cmd['stig'])) {
$script = realpath(defined('PHP_BIN') ? PHP_BIN : PHP) .
" -c " . realpath(PHP_CONF) .
" -f " . realpath(DOC_ROOT . "/exec/background_stigs.php") . " --" .
(isset($cmd['exclude']) && $cmd['exclude'] ? " --exclude=\"{$cmd['exclude']}\"" : "") .
" --delete";
$log->info("Script to run $script");
$log->debug("Script to run $script");
passthru($script);
}
$db->help->select_count("sagacity.stigs");
$stig_count = $db->help->execute();
$db->set_Setting("stig-count", $stig_count);
$diff->stopClock();
$log->info(PHP_EOL . "Finished at {$diff->getEndClockTime()}" . PHP_EOL .
"Total Time: {$diff->getDiffString()}");
print PHP_EOL . "Finished at {$diff->getEndClockTime()}" . PHP_EOL .
"Total Time: {$diff->getDiffString()}" . PHP_EOL;
sleep(3);
}
if (is_a($diff->getTotalDiff(), 'DateInterval')) {
$log->info("Total Script Time: {$diff->getTotalDiffString()}");
print "Total Script Time: {$diff->getTotalDiffString()}" . PHP_EOL;
}
/**
*
* Usage information about the script
*/
function usage()
{
$tmp = TMP;
$tmp = realpath(TMP);
print <<<EOO
Purpose: The purpose of this script is to update the CVE, CPE, and CCE databases. Script will sleep for 3 seconds between actions to allow you review the results.
Usage: php update_db.php [--cpe] [--cve] [--nasl] [--stig] [-u={URL}] [--do] [--po] [-h|--help]
Usage: php update_db.php [--cpe] [--cve] [--nvd] [--nasl] [--stig] [-u={URL}] [--do] [--po] [-h|--help] [--debug] [--exclude="ex1"]
--cpe To download and update the CPE catalog
--cve To download and update the CVE catalog
--cve To download and update the CVE catalog using Mitre's database
--nvd To download and update the CVE catalog using the National Vulnerability Database (NVD) JSON library
--nasl To download OpenVAS NVT library and update NASL files
You can also extract *.nasl files from the Nessus library to $tmp/nessus_plugins and it will include these in the update
--stig To download and update the STIG library
--do To download the files only...do not call the parsers will overwrite any existing files
--po To parse the downloaded files only, do not download
-u={url} [optional] Used only for STIGs because sometimes DISA will use a non-standard link which makes it difficult to download the file.
--exclude="ex1" Insert a valid regex expression (properly escaped) to exclude specific STIGs from parsing (no '/' necessary)
--extract Used so script will download and extract files from archive and stop processing
-u={url} Used only for STIGs because sometimes DISA will use a non-standard link which makes it difficult to download the file.
-h|--help This screen
--debug To print verbose debugging messages to the console
EOO;
}

Binary file not shown.

Before

Width:  |  Height:  |  Size: 197 KiB

View File

@ -12,7 +12,9 @@
* - Apr 7, 2017 - Added .xlsx extension to accepted files
* - May 13, 2017 - Made this more self-sustaining
* - May 19, 2017 - Change button to match others
* - Apr 29, 2018 - Changed default message and formatting
*/
?>
<div id="import" class="box">
@ -21,6 +23,7 @@
<link type="text/css" href="/script/dropzone/basic.min.css" rel="stylesheet" />
<script type="text/javascript">
var mydz;
Dropzone.options.dropzone = {
maxFilesize: 150,
success: function (file, res) {
@ -44,7 +47,7 @@
Dropzone.autoDiscover = false;
$(function () {
var mydz = new Dropzone('#dropzone');
mydz = new Dropzone('#dropzone');
mydz.on('removedfile', function (file) {
$.ajax('/ajax.php', {
@ -102,6 +105,7 @@
</script>
<form class="dropzone" action="/upload.php" id="dropzone">
<div class="dz-message" data-dz-message><span>Click or Drop files here to upload</span></div>
<div class="fallback">
<input type="file" name="file" multiple />
</div>

1489
inc/composer.lock generated

File diff suppressed because it is too large Load Diff

View File

@ -6,7 +6,7 @@
* and for the ST&E Manager to interact with
* Created: Sep 11, 2013
*
* Portions Copyright 2016-2017: Cyber Perspectives, LLC, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -68,6 +68,11 @@
* - Jan 16, 2018 - Added include for host_list.inc, updated to use host_list class, fixed bug in delete_Scan method
Moved scan deletion here
* - Jan 20, 2018 - Fixed typo in save_STE method
* - May 24, 2018 - Added defaulting where clause operator to '='
* - May 26, 2018 - Updated autocategorization to removed any extranious spaces before or after the string
* - May 31, 2018 - Changes to support renaming sagacity.pdi_catalog.check_content field and scan error detection
* - Jun 2, 2018 - Formatting and added set_Setting_Array method
* - Jun 5, 2018 - Changed set_Setting_Array method to use SQL update instead of replace
*/
include_once 'base.inc';
include_once 'software.inc';
@ -262,7 +267,7 @@ class db_helper
if (in_array($this->query_type, [self::SELECT, self::SELECT_COUNT])) {
$this->result = $this->c->query($this->sql);
if ($this->c->error) {
$this->debug(E_ERROR, $this->c->error);
$this->debug(E_ERROR);
}
}
elseif ($this->query_type == self::DELETE) {
@ -1085,7 +1090,6 @@ class db_helper
*/
public function field_check($field_data, $check, $pks, $index)
{
$match = [];
$default = null;
$ret = null;
@ -1261,6 +1265,11 @@ class db_helper
$errmsg = $this->sql;
}
file_put_contents(realpath(LOG_PATH . '/db.log'), "{$dt->format(DATE_ISO8601)}\t" .
"$err_lvl\t" .
"Executing: $this->query_type\t" .
"SQL: {$errmsg}" . PHP_EOL, FILE_APPEND);
if ($errno == E_DEBUG && $this->result && LOG_LEVEL == E_DEBUG) {
file_put_contents(realpath(LOG_PATH . '/db.debug'), print_r($this->result, true), FILE_APPEND);
}
@ -1270,11 +1279,6 @@ class db_helper
error_log($this->c->error);
die($this->c->error);
}
file_put_contents(realpath(LOG_PATH . '/db.log'), "{$dt->format(DATE_ISO8601)}\t" .
"$err_lvl\t" .
"Executing: $this->query_type\t" .
"SQL: {$errmsg}" . PHP_EOL, FILE_APPEND);
}
/**
@ -1370,37 +1374,41 @@ class db_helper
}
$not = null;
if (in_array($w['op'], array(IS_NOT, NOT_LIKE, NOT_IN))) {
if (isset($w['op']) && in_array($w['op'], array(IS_NOT, NOT_LIKE, NOT_IN))) {
$not = ' NOT';
}
if ($w['op'] == LIKE || $w['op'] == NOT_LIKE) {
if (isset($w['op']) && ($w['op'] == LIKE || $w['op'] == NOT_LIKE)) {
$ret .= " {$field}{$not} LIKE {$w['value']}";
}
elseif (($w['op'] == IN || $w['op'] == NOT_IN) && is_string($w['value'])) {
elseif (isset($w['op']) && ($w['op'] == IN || $w['op'] == NOT_IN) && is_string($w['value'])) {
$ret .= " {$field}{$not} IN " . (strpos($w['value'], '(') !== false ? $w['value'] : "({$w['value']})");
}
elseif (($w['op'] == IN || $w['op'] == NOT_IN) && is_array($w['value'])) {
elseif (isset($w['op']) && ($w['op'] == IN || $w['op'] == NOT_IN) && is_array($w['value'])) {
$ret .= " {$field}{$not} IN (" . implode(",", array_map(array($this, '_escape'), $w['value'])) . ")";
}
elseif ($w['op'] == BETWEEN) {
elseif (isset($w['op']) && $w['op'] == BETWEEN) {
if (!isset($w['low']) && !isset($w['high'])) {
continue;
}
$ret .= " {$field} BETWEEN {$this->_escape($w['low'])} AND {$this->_escape($w['high'])}";
}
elseif ($w['op'] == IS || $w['op'] == IS_NOT) {
elseif (isset($w['op']) && ($w['op'] == IS || $w['op'] == IS_NOT)) {
$ret .= " {$field} IS{$not} {$this->_escape($w['value'])}";
}
else {
$op = "=";
if (isset($w['op'])) {
$op = $w['op'];
}
if (isset($w['case_insensitive']) && $w['case_insensitive']) {
$ret .= " LOWER({$field}) {$w['op']} LOWER({$this->_escape($w['value'])})";
$ret .= " LOWER({$field}) {$op} LOWER({$this->_escape($w['value'])})";
}
elseif (preg_match("/\(SELECT/", $w['value'])) {
$ret .= " {$field} {$w['op']} {$w['value']}";
$ret .= " {$field} {$op} {$w['value']}";
}
else {
$ret .= " {$field} {$w['op']} {$this->_escape($w['value'])}";
$ret .= " {$field} {$op} {$this->_escape($w['value'])}";
}
}
@ -1804,23 +1812,19 @@ class db
$host = ($persistent ? "p:" : "") . DB_SERVER;
if (class_exists('mysqli')) {
$pwd = self::decrypt_pwd();
$this->conn = new mysqli($host, 'web', $pwd);
$this->conn = new mysqli($host, 'web', $pwd, 'sagacity');
}
else {
die("Could not find the mysqli class");
}
//$this->conn = new mysqli($host, 'web', self::decrypt_pwd(), 'sagacity');
// if there is a problem output that
if($this->conn->connect_errno && $this->conn->connect_errno == 1045) {
if ($this->conn->connect_errno && $this->conn->connect_errno == 1045) {
die("Invalid database username and/or password");
}
elseif ($this->conn->connect_errno) {
error_log("Error connecting to " . DB_SERVER . " " . $this->conn->connect_error);
die("Error connecting to " . DB_SERVER);
}
else {
$this->conn->select_db('sagacity');
}
// set the character set and default database
$this->conn->set_charset("utf8");
@ -2012,72 +2016,68 @@ class db
*/
public function auto_Catorgize_Targets($ste_id)
{
$this->help->select("sagacity.target t", array('t.id', 't.os_string'), array(
array(
$this->help->select("sagacity.target t", ['t.id', 't.os_string'], [
[
'field' => 't.ste_id',
'op' => '=',
'value' => $ste_id
),
array(
],
[
'field' => 't.cat_id',
'op' => IS,
'value' => null,
'sql_op' => 'AND'
),
array(
],
[
'field' => 's.cpe',
'op' => '!=',
'value' => 'cpe:/o:generic:generic:-',
'sql_op' => 'AND'
)
), array(
'table_joins' => array(
]
], [
'table_joins' => [
'JOIN sagacity.software s ON t.os_id=s.id'
)
));
]
]);
$rows = $this->help->execute();
if (is_array($rows) && count($rows) && isset($rows['id'])) {
$rows = array(0 => $rows);
$rows = [0 => $rows];
}
if (is_array($rows) && count($rows) && isset($rows[0])) {
foreach ($rows as $row) {
$id = 0;
$this->help->select("sagacity.ste_cat", array('id'), array(
array(
$this->help->select("sagacity.ste_cat", ['id'], [
[
'field' => 'ste_id',
'op' => '=',
'value' => $ste_id
),
array(
],
[
'field' => 'name',
'op' => '=',
'value' => $row['os_string'],
'value' => trim($row['os_string']),
'sql_op' => 'AND'
)
));
]
]);
$tmp = $this->help->execute();
if (is_array($tmp) && count($tmp) && isset($tmp['id'])) {
$id = $tmp['id'];
}
else {
$this->help->insert("sagacity.ste_cat", array(
$this->help->insert("sagacity.ste_cat", [
'ste_id' => $ste_id,
'name' => $row['os_string']
), true);
'name' => trim($row['os_string'])
], true);
$id = $this->help->execute();
}
if ($id) {
$this->help->update("sagacity.target", array('cat_id' => $id), array(
array(
$this->help->update("sagacity.target", ['cat_id' => $id], [
[
'field' => 'id',
'op' => '=',
'value' => $row['id']
)
));
]
]);
$this->help->execute();
}
}
@ -2448,7 +2448,6 @@ class db
*/
public function get_EMASS_CCIs()
{
$ret = [];
$this->help->select("rmf.emass_cci");
$ret = $this->help->execute();
return $ret;
@ -2689,13 +2688,12 @@ class db
public function get_Checklist_By_File($fname)
{
$ret = [];
$this->help->select("sagacity.checklist", null, array(
array(
$this->help->select("sagacity.checklist", null, [
[
'field' => 'file_name',
'op' => '=',
'value' => $fname
)
));
]
]);
$rows = $this->help->execute();
if (isset($rows['id'])) {
@ -2705,25 +2703,24 @@ class db
if (is_array($rows) && count($rows) && isset($rows[0])) {
foreach ($rows as $row) {
$chk = new checklist($row['id'], $row['checklist_id'], $row['name'], $row['description'], $row['date'], $row['file_name'], $row['ver'], $row['release'], $row['type'], $row['icon']);
/*
$this->help->select("sagacity.checklist_software_lookup", array('sw_id'), array(
array(
/**/
$this->help->select("sagacity.checklist_software_lookup", ['sw_id'], [
[
'field' => 'chk_id',
'op' => '=',
'value' => $row['id']
)
));
]
]);
$sw_rows = $this->help->execute();
if (count($sw_rows)) {
if (isset($sw_rows['sw_id'])) {
$sw_rows = array(0 => $sw_rows);
$sw_rows = [0 => $sw_rows];
}
foreach ($sw_rows as $row2) {
$chk->add_SW($this->get_Software($row2['sw_id']));
}
}
*/
$ret[] = $chk;
}
}
@ -2874,46 +2871,46 @@ class db
foreach ($chklsts as $chk_key => $chk) {
foreach ($tgts as $host_key => $host) {
if ($chk != 'Orphan') {
$this->help->select_count("sagacity.target_checklist tc", array(
array(
$this->help->select_count("sagacity.target_checklist tc", [
[
'field' => 'tc.tgt_id',
'op' => '=',
'value' => $host_key
),
array(
],
[
'field' => 'tc.chk_id',
'op' => '=',
'value' => $chk_key,
'sql_op' => 'AND'
)
));
]
]);
}
else {
$this->help->select("sagacity.findings f", array("IF(COUNT(1) > 0, '1', '0')"), array(
array(
$this->help->select("sagacity.findings f", ["IF(COUNT(1) > 0, '1', '0')"], [
[
'field' => 'f.tgt_id',
'op' => '=',
'value' => $host_key
),
array(
],
[
'field' => 'c.name',
'op' => '=',
'value' => 'Orphan',
'sql_op' => 'AND'
)
), array(
'table_joins' => array(
]
], [
'table_joins' => [
"LEFT JOIN sagacity.pdi_checklist_lookup pcl ON pcl.pdi_id=f.pdi_id",
"LEFT JOIN sagacity.checklist c ON c.id=pcl.checklist_id"
)
));
]
]);
}
$summary[$chk_key][$host_key] = $this->help->execute();
}
}
return array('tgts' => $tgts, 'checklists' => $chklsts, 'summary' => $summary);
return ['tgts' => $tgts, 'checklists' => $chklsts, 'summary' => $summary];
}
/**
@ -3225,7 +3222,7 @@ class db
}
if (!isset($ret[$worksheet_name]['target_list'][$row['tgt_name']])) {
$ret[$worksheet_name]['target_list'][$row['tgt_name']] = count($ret[$worksheet_name]['target_list']) + 6;
$ret[$worksheet_name]['target_list']["{$row['tgt_name']}"] = count($ret[$worksheet_name]['target_list']) + 6;
}
if (!isset($ret[$worksheet_name]['stigs'][$row['stig_id']])) {
@ -3237,11 +3234,11 @@ class db
}
$echk = new echecklist($row['stig_id'], $row['vms_id'], (empty($row['finding_cat']) ? $row['cat'] : $row['finding_cat']), $ia, $row['short_title'], null, $row['notes'], $row['check_contents'], null);
$echk->set_PDI_ID($row['pdi_id']);
$ret[$worksheet_name]['stigs'][$row['stig_id']] = array(
$ret[$worksheet_name]['stigs'][$row['stig_id']] = [
'echecklist' => $echk,
$row['tgt_name'] => $row['finding_status'],
"{$row['tgt_name']}" => $row['finding_status'],
'chk_id' => $row['chk_id']
);
];
if (!in_array($row['stig_id'], $stigs)) {
$stigs[] = $row['stig_id'];
}
@ -4205,8 +4202,14 @@ class db
public function get_Findings_Not_in_System($ste)
{
$ret = [];
$sql = "CREATE TEMPORARY TABLE `unaccounted_for_findings` (`pdi_id` int(11) UNIQUE NOT NULL)";
$this->conn->real_query($sql);
$this->help->create_table("unaccounted_for_findings", [
[
'field' => 'pdi_id',
'datatype' => 'int(11)',
'option' => 'UNIQUE NOT NULL'
]
]);
$this->help->execute();
$sql = "INSERT IGNORE INTO `unaccounted_for_findings` (`pdi_id`) SELECT DISTINCT(f.`pdi_id`) " .
"FROM `findings` f JOIN `target` t ON t.`id` = f.`tgt_id` " .
@ -4263,133 +4266,124 @@ class db
*/
public function get_Finding_Count_By_Status($cat_id, $status, $cat = null, $ctrl = null)
{
$joins = array(
$joins = [
"LEFT JOIN sagacity.target_checklist tc ON t.id=tc.tgt_id",
"LEFT JOIN sagacity.pdi_checklist_lookup pcl ON pcl.checklist_id=tc.chk_id",
"LEFT JOIN sagacity.findings f ON f.pdi_id=pcl.pdi_id AND t.id=f.tgt_id",
"LEFT JOIN sagacity.findings_status fs ON fs.id=f.findings_status_id"
);
];
if (!is_null($ctrl)) {
$joins[] = "JOIN `sagacity`.`finding_controls` fc ON fc.`finding_id`=f.`id`";
}
$where = array(
array(
$where = [
[
'field' => 't.cat_id',
'op' => '=',
'value' => $cat_id
),
array(
],
[
'field' => 'fs.status',
'op' => '=',
'value' => $status,
'sql_op' => 'AND',
'open-paren' => true
)
);
]
];
if ($status == 'Not Reviewed') {
$where[] = array(
$where[] = [
'field' => 'fs.status',
'op' => IS,
'value' => null,
'sql_op' => 'OR',
'close-paren' => true
);
];
}
else {
$where[] = array(
$where[] = [
'close-paren' => true
);
];
}
if (!is_null($cat) && is_numeric($cat)) {
$where[] = array(
$where[] = [
'field' => 'f.cat',
'op' => '=',
'value' => $cat,
'sql_op' => 'AND'
);
];
}
if (!is_null($ctrl) && is_a($ctrl, 'proc_ia_control')) {
$where[] = array(
$where[] = [
'field' => 'fc.ia_control',
'op' => '=',
'value' => $ctrl->get_Control_ID(),
'sql_op' => 'AND'
);
];
}
$field = ($status == 'Not Reviewed' ? "COUNT(DISTINCT(pcl.pdi_id)) AS 'count'" : "COUNT(DISTINCT(f.id)) AS 'count'");
$this->help->select_count("sagacity.target t", $where, array('table_joins' => $joins));
$this->help->select_count("sagacity.target t", $where, ['table_joins' => $joins]);
$this->help->sql = str_replace("COUNT(1) AS 'count'", $field, $this->help->sql);
$cnt = $this->help->execute();
$joins = array(
$joins = [
"LEFT JOIN sagacity.pdi_checklist_lookup pcl ON pcl.checklist_id=c.id",
"LEFT JOIN sagacity.findings f ON f.pdi_id=pcl.pdi_id",
"LEFT JOIN sagacity.findings_status fs ON f.findings_status_id=fs.id",
"JOIN sagacity.target t ON t.id=f.tgt_id"
);
];
if (!is_null($ctrl) && is_a($ctrl, 'proc_ia_control')) {
$joins[] = "JOIN sagacity.finding_controls fc ON fc.finding_id=f.id";
}
$where = array(
array(
$where = [
[
'field' => 't.cat_id',
'op' => '=',
'value' => $cat_id
),
array(
],
[
'field' => 'c.name',
'op' => '=',
'value' => 'Orphan',
'sql_op' => 'AND'
),
array(
],
[
'field' => 'fs.status',
'op' => '=',
'value' => $status,
'sql_op' => 'AND',
'open-paren' => true
)
);
]
];
if ($status == 'Not Reviewed') {
$where[] = array(
$where[] = [
'field' => 'fs.status',
'op' => IS,
'value' => null,
'sql_op' => 'OR',
'close-paren' => true
);
];
}
else {
$where[] = array(
$where[] =[
'close-paren' => true
);
];
}
if (!is_null($cat) && is_numeric($cat)) {
$where[] = array(
$where[] = [
'field' => 'f.cat',
'op' => '=',
'value' => $cat,
'sql_op' => 'AND'
);
];
}
if (!is_null($ctrl) && is_a($ctrl, 'proc_ia_control')) {
$where[] = array(
$where[] = [
'field' => 'fc.ia_control',
'op' => '=',
'value' => $ctrl->get_Control_ID(),
'sql_op' => 'AND'
);
];
}
$this->help->select_count("sagacity.checklist c", $where, array('table_joins' => $joins));
@ -4816,7 +4810,6 @@ class db
$ia_controls = $finding_data[3];
$short_title = $finding_data[4];
$notes = $finding_data[self::FIRST_ECHECKLIST_HOST_COL + $host_count];
$check_content = $finding_data[self::FIRST_ECHECKLIST_HOST_COL + $host_count + 1];
if (preg_match('/SV\-.*_rule/', $stig_id)) {
$ref = $this->get_SV_Rule(null, $stig_id);
@ -7028,7 +7021,7 @@ class db
// ------------------------------ Start <registry_test> -----------------------------
// create temporary db table to combine all OVAL checks marked 'M' and not 'M'
$tmp_sql = "CREATE TEMPORARY TABLE `tmp_oval` SELECT " .
"pdi.`id`, o.`oval_id`, s.`stig_id`, vms.`vms_id`, pdi.`check_content`, pdi.`short_title` " .
"pdi.`id`, o.`oval_id`, s.`stig_id`, vms.`vms_id`, pdi.`check_contents`, pdi.`short_title` " .
"FROM `pdi_catalog` AS pdi " .
"LEFT JOIN `oval` AS o ON pdi.`id` = o.`pdi_id` " .
"LEFT JOIN `stigs` AS s ON pdi.`id` = s.`pdi_id` " .
@ -7038,7 +7031,7 @@ class db
"LEFT JOIN `software` AS sft ON sft.`id` = c.`sw_id` " .
"WHERE " .
"o.`oval_id` = 'M' AND " .
"pdi.`check_content` LIKE '%Registry Hive%' AND " .
"pdi.`check_contents` LIKE '%Registry Hive%' AND " .
"sft.`man` = 'MS' AND " .
"sft.`name` = 'Windows' AND " .
"sft.`ver` = '$os' " .
@ -7059,7 +7052,7 @@ class db
"LEFT JOIN `software` AS sft ON sft.`id` = c.`sw_id` " .
"WHERE " .
"o.`oval_id` != 'M' AND " .
"pdi.`check_content` REGEXP 'Registry Hive' AND " .
"pdi.`check_contents` REGEXP 'Registry Hive' AND " .
"sft.`man` = 'MS' AND " .
"sft.`name` = 'Windows' AND " .
"sft.`ver` = '$os' " .
@ -7068,7 +7061,7 @@ class db
$this->conn->real_query($del_sql);
$sql = "SELECT " .
"`id`, `oval_id`, `stig_id`, `vms_id`, `check_content`, `short_title` " .
"`id`, `oval_id`, `stig_id`, `vms_id`, `check_contents`, `short_title` " .
"FROM `tmp_oval`";
if ($sth = $this->conn->prepare($sql)) {
@ -7170,7 +7163,7 @@ class db
// ------------------------------ End <registry_test> -----------------------------
// ------------------------------ Start <auditeventpolicysubcategories_test> -----------------------------
$tmp_sql = "CREATE TEMPORARY TABLE `tmp_oval` SELECT " .
"pdi.`id`,o.`oval_id`,s.`stig_id`,vms.`vms_id`,pdi.`check_content`,pdi.`short_title` " .
"pdi.`id`,o.`oval_id`,s.`stig_id`,vms.`vms_id`,pdi.`check_contents`,pdi.`short_title` " .
"FROM `sagacity`.`pdi_catalog` AS pdi " .
"LEFT JOIN `sagacity`.`oval` AS o ON pdi.`id`=o.`pdi_id` " .
"LEFT JOIN `sagacity`.`stigs` AS s ON pdi.`id`=s.`pdi_id` " .
@ -7180,7 +7173,7 @@ class db
"LEFT JOIN `sagacity`.`software` AS sft ON sft.`id`=c.`sw_id` " .
"WHERE " .
"o.`oval_id`='M' AND " .
"pdi.`check_content` LIKE '%AuditPol%' AND " .
"pdi.`check_contents` LIKE '%AuditPol%' AND " .
"sft.`man`='MS' AND " .
"sft.`name`='Windows' AND " .
"sft.`ver`='$os' " .
@ -7199,7 +7192,7 @@ class db
"LEFT JOIN `sagacity`.`software` AS sft ON sft.`id`=c.`sw_id` " .
"WHERE " .
"o.`oval_id`!='M' AND " .
"pdi.`check_content` REGEXP 'AuditPol' AND " .
"pdi.`check_contents` REGEXP 'AuditPol' AND " .
"sft.`man`='MS' AND " .
"sft.`name`='Windows' AND " .
"sft.`ver`='$os' " .
@ -7207,7 +7200,7 @@ class db
$this->conn->real_query($del_sql);
$sql = "SELECT " .
"`id`,`oval_id`,`stig_id`,`vms_id`,`check_content`,`short_title` " .
"`id`,`oval_id`,`stig_id`,`vms_id`,`check_contents`,`short_title` " .
"FROM `tmp_oval`";
if ($sth = $this->conn->prepare($sql)) {
@ -7385,7 +7378,7 @@ class db
if (is_array($row) && count($row) && isset($row['id'])) {
$pdi = new pdi($row['id'], $row['cat'], $row['update']);
$pdi->set_Short_Title($row['short_title']);
$pdi->set_Check_Contents($row['check_content']);
$pdi->set_Check_Contents($row['check_contents']);
if (!is_null($chk_id)) {
$this->help->select("sagacity.pdi_checklist_lookup", null, [
@ -7591,7 +7584,7 @@ class db
'cat' => $pdi_in->get_Category_Level(),
'update' => $pdi_in->get_Last_Update(),
'short_title' => $pdi_in->get_Short_Title(),
'check_content' => $pdi_in->get_Check_Contents()
'check_contents' => $pdi_in->get_Check_Contents()
], [
[
'field' => 'id',
@ -7612,7 +7605,7 @@ class db
"cat" => $pdi_in->get_Category_Level(),
'update' => $pdi_in->get_Last_Update(),
'short_title' => $pdi_in->get_Short_Title(),
'check_content' => $pdi_in->get_Check_Contents()
'check_contents' => $pdi_in->get_Check_Contents()
]);
if (!($pdi_id = $this->help->execute())) {
@ -8135,7 +8128,6 @@ class db
$where = [
[
'field' => 's.ste_id',
'op' => '=',
'value' => $intSTE
]
];
@ -8144,7 +8136,6 @@ class db
if (is_numeric($Scan_ID)) {
$where[] = [
'field' => 's.id',
'op' => '=',
'value' => $Scan_ID,
'sql_op' => 'AND'
];
@ -8152,7 +8143,6 @@ class db
else {
$where[] = [
'field' => 's.file_name',
'op' => '=',
'value' => $Scan_ID,
'sql_op' => 'AND'
];
@ -8162,7 +8152,6 @@ class db
if (!is_null($status_in)) {
$where[] = [
'field' => 's.status',
'op' => '=',
'value' => $status_in,
'sql_op' => 'AND'
];
@ -8171,7 +8160,6 @@ class db
if (!is_null($type_in)) {
$where[] = [
'field' => 'src.name',
'op' => '=',
'value' => $type_in,
'sql_op' => 'AND'
];
@ -8216,12 +8204,9 @@ class db
$scan->set_Last_Host($row['last_host']);
$scan->set_Total_Host_Count($row['host_count']);
$this->help->select("host_list hl", ['hl.tgt_id', 't.name', 'hl.finding_count', 'hl.scanner_error'], [
$this->help->select("host_list hl", ['hl.tgt_id', 't.name', 'hl.finding_count', 'hl.scanner_error', 'hl.notes'], [
[
'field' => 'hl.scan_id',
'op' => '=',
'value' => $row['id']
]
], [
@ -8229,26 +8214,27 @@ class db
"LEFT JOIN target t ON t.id=hl.tgt_id"
]
]);
$find_rows = $this->help->execute();
if (is_array($find_rows) && count($find_rows) && isset($find_rows['tgt_id'])) {
$find_rows = [0 => $find_rows];
$hl_rows = $this->help->execute();
if (is_array($hl_rows) && count($hl_rows) && isset($hl_rows['tgt_id'])) {
$hl_rows = [0 => $hl_rows];
}
if (is_array($find_rows) && count($find_rows) && isset($find_rows[0])) {
foreach ($find_rows as $find) {
$tgt = new target($find['name']);
$tgt->set_ID($find['tgt_id']);
if (is_array($hl_rows) && count($hl_rows) && isset($hl_rows[0])) {
foreach ($hl_rows as $row) {
$tgt = new target($row['name']);
$tgt->set_ID($row['tgt_id']);
$tgt->set_STE_ID($intSTE);
$tgt->interfaces = $this->get_Interfaces($tgt->get_ID());
if ((bool) $find['scanner_error']) {
$scan->setScanError((bool) $find['scanner_error']);
if ((bool) $row['scanner_error']) {
$scan->setScanError((bool) $row['scanner_error']);
}
$hl = new host_list();
$hl->setTargetId($tgt->get_ID());
$hl->setTargetName($tgt->get_Name());
$hl->setTargetIp($tgt->getIP());
$hl->setFindingCount($find['finding_count']);
$hl->setScanError((bool) $find['scanner_error']);
$hl->setFindingCount($row['finding_count']);
$hl->setScanError((bool) $row['scanner_error']);
$hl->setScanNotes($row['notes']);
$scan->add_Target_to_Host_List($hl);
}
@ -8294,7 +8280,6 @@ class db
], [
[
'field' => 'id',
'op' => '=',
'value' => $new_Scan->get_ID()
]
]);
@ -8438,7 +8423,6 @@ class db
$this->help->delete("host_list", null, [
[
'field' => 'scan_id',
'op' => '=',
'value' => $scan->get_ID()
]
]);
@ -8454,26 +8438,28 @@ class db
$scan->get_ID(),
$host->getTargetId(),
$host->getFindingCount(),
$host->getScanError()
$host->getScanError(),
$host->getScanNotes()
];
}
}
else {
foreach ($host_list as $host) {
if(!is_a($host, 'host_list')) {
if (!is_a($host, 'host_list')) {
break;
}
$params[] = [
$scan->get_ID(),
$host->getTargetId(),
$host->getFindingCount(),
$host->getScanError()
$host->getScanError(),
$host->getScanNotes()
];
}
}
if (count($params)) {
$this->help->extended_insert("host_list", ['scan_id', 'tgt_id', 'finding_count', 'scanner_error'], $params);
$this->help->extended_insert("host_list", ['scan_id', 'tgt_id', 'finding_count', 'scanner_error', 'notes'], $params);
if (!$this->help->execute()) {
$this->help->debug(E_WARNING);
}
@ -8586,16 +8572,16 @@ class db
* Find the sources that have contained this target
*
* @param target $tgt
* @param array $exp_scan_srcs
*
* @return array:sources
*/
public function get_Target_Scan_Sources($tgt, &$exp_scan_srcs = null)
{
$ret = [];
$this->help->select("sources src", ["src.id", "src.name", "src.icon", "SUM(hl.finding_count) AS 'finding_count'"], [
$this->help->select("sources src", ["src.id", "src.name", "src.icon", "SUM(hl.finding_count) AS 'finding_count'", "hl.scanner_error", "hl.notes"], [
[
'field' => 'hl.tgt_id',
'op' => '=',
'value' => $tgt->get_ID()
]
], [
@ -8618,6 +8604,8 @@ class db
$ret[$row['id']]['src'] = new source($row['id'], $row['name']);
$ret[$row['id']]['src']->set_Icon($row['icon']);
$ret[$row['id']]['count'] = $row['finding_count'];
$ret[$row['id']]['scan_error'] = (boolean) $row['scanner_error'];
$ret[$row['id']]['notes'] = $row['notes'];
}
}
else {
@ -8625,11 +8613,15 @@ class db
if (isset($exp_scan_srcs[$row['id']])) {
$exp_scan_srcs[$row['id']]['src']->set_Icon($row['icon']);
$exp_scan_srcs[$row['id']]['count'] = $row['finding_count'];
$exp_scan_srcs[$row['id']]['scan_error'] = (boolean) $row['scanner_error'];
$exp_scan_srcs[$row['id']]['notes'] = $row['notes'];
}
else {
$exp_scan_srcs[$row['id']]['src'] = new source($row['id'], $row['name']);
$exp_scan_srcs[$row['id']]['src']->set_Icon($row['icon']);
$exp_scan_srcs[$row['id']]['count'] = $row['finding_count'];
$exp_scan_srcs[$row['id']]['scan_error'] = (boolean) $row['scanner_error'];
$exp_scan_srcs[$row['id']]['notes'] = $row['notes'];
}
}
@ -11158,6 +11150,13 @@ class db
]
]);
$this->help->execute();
$this->help->sql = "INSERT IGNORE INTO `findings` (`tgt_id`,`pdi_id`,`findings_status_id`) " .
"SELECT {$tgt['id']},pcl.pdi_id,'1' " .
"FROM target_checklist tc " .
"JOIN pdi_checklist_lookup pcl ON pcl.checklist_id = tc.chk_id " .
"WHERE tc.tgt_id = {$tgt['id']}";
$this->help->execute();
}
}
}
@ -11296,6 +11295,13 @@ class db
]
]);
$this->help->execute();
$this->help->sql = "INSERT IGNORE INTO findings (tgt_id,pdi_id,findings_status_id) " .
"SELECT {$id},pcl.pdi_id,1 " .
"FROM target_checklist tc " .
"JOIN pdi_checklist_lookup pcl ON pcl.checklist_id = tc.chk_id " .
"WHERE tc.tgt_id = {$id}";
$this->help->execute();
}
return true;
@ -12430,6 +12436,36 @@ class db
return $ret;
}
/**
* Method to update settings values using name => value pairs
*
* @param array $settings
*
* @return boolean
*/
public function set_Setting_Array($settings = [])
{
if (is_array($settings) && count($settings)) {
foreach ($settings as $key => $val) {
$this->help->update('settings', ['meta_value' => $val], [
[
'field' => 'meta_key',
'value' => $key
]
]);
if (!$this->help->execute()) {
return false;
}
}
}
else {
return false;
}
return true;
}
// }}} END META
// {{{ VARIOUS FUNCTIONS
/**

View File

@ -5,7 +5,7 @@
* Purpose: This file will contain all the standardized header information
* Created: Sep 11, 2013
*
* Portions Copyright 2016: Cyber Perspectives, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, LLC, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions
@ -25,6 +25,10 @@
* - Jan 10, 2018 - Added fontawesome CSS library
* - Jan 15, 2018 - Added jQuery UI CSS
* - Jan 16, 2018 - Added ajax to auto update the cpe, cve, stig, and nasl loading progress.
* - Apr 29, 2018 - Updated jQuery and jQuery UI libraries
* - May 10, 2018 - Fixed a couple bugs with display
* - May 24, 2018 - Fixed order of operation
* - Jun 2, 2018 - More bugs
*/
include_once 'config.inc';
include_once 'helper.inc';
@ -39,38 +43,44 @@ $db->help->select_count("software");
$cpe_count = $db->help->execute();
$cpe = $db->get_Settings(['cpe-progress', 'cpe-dl-progress']);
if (!$cpe_count) {
$msg[] = "<div id='cpe-progress'>No CPE's present in DB</div>";
}
elseif (isset($cpe['cpe-dl-progress']) && between($cpe['cpe-dl-progress'], 0.01, 99.99)) {
if (isset($cpe['cpe-dl-progress']) && between($cpe['cpe-dl-progress'], 0.01, 99.99)) {
$msg[] = "<div id='cpe-progress'>CPE Download Progress: " . number_format($cpe['cpe-dl-progress'], 0) . "%</div>";
}
elseif (isset($cpe['cpe-progress']) && between($cpe['cpe-progress'], 0.01, 99.99)) {
$msg[] = "<div id='cpe-progress'>CPE Progress: " . number_format($cpe['cpe-progress'], 0) . "%</div>";
}
elseif (!$cpe_count) {
$msg[] = "<div id='cpe-progress'>No CPE's present in DB</div>";
}
$db->help->select_count("cve_db");
$cve_count = $db->help->execute();
$cve = $db->get_Settings(['cve-progress', 'cve-dl-progress']);
$cve = $db->get_Settings([
'cve-progress', 'cve-dl-progress',
'nvd-progress', 'nvd-cve-dl-progress', 'nvd-year'
]);
if (!$cve_count) {
$msg[] = "<div id='cve-progress'>No CVE's present in DB</div>";
}
elseif (isset($cve['cve-dl-progress']) && between($cve['cve-dl-progress'], 0.01, 99.99)) {
if (isset($cve['cve-dl-progress']) && between($cve['cve-dl-progress'], 0.01, 99.99)) {
$msg[] = "<div id='cve-progress'>CVE Download Progress: " . number_format($cve['cve-dl-progress'], 0) . "%</div>";
}
elseif (isset($cve['nvd-cve-dl-progress']) && between($cve['nvd-cve-dl-progress'], 0.01, 99.99)) {
$msg[] = "<div id='cve-progress'>NVD CVE Download {$cve['nvd-year']} Progress: " . number_format($cve['nvd-cve-dl-progress'], 0) . "%</div>";
}
elseif (isset($cve['cve-progress']) && between($cve['cve-progress'], 0.01, 99.99)) {
$msg[] = "<div id='cve-progress'>CVE Progress: " . number_format($cve['cve-progress'], 0) . "%</div>";
}
elseif (isset($cve['nvd-cve-progress']) && between($cve['nvd-cve-progress'], 0.01, 99.99)) {
$msg[] = "<div id='cve-progress'>NVD CVE {$cve['nvd-year']} Progress: " . number_format($cve['cve-progress'], 0) . "%</div>";
}
elseif (!$cve_count) {
$msg[] = "<div id='cve-progress'>No CVE's present in DB</div>";
}
$db->help->select_count("stigs");
$stig_count = $db->help->execute();
$stig = $db->get_Settings(['stig-progress', 'stig-dl-progress']);
if (!$stig_count) {
$msg[] = "<div id='stig-progress'>No STIG's present in DB</div>";
}
elseif (isset($stig['stig-dl-progress']) && between($stig['stig-dl-progress'], 0.01, 99.99)) {
if (isset($stig['stig-dl-progress']) && between($stig['stig-dl-progress'], 0.01, 99.99)) {
$msg[] = "<div id='stig-progress'>STIG Download Progress: " . number_format($stig['stig-dl-progress'], 0) . "%</div>";
}
elseif (isset($stig['stig-progress']) && between($stig['stig-progress'], 0.01, 99.99)) {
@ -78,12 +88,13 @@ elseif (isset($stig['stig-progress']) && between($stig['stig-progress'], 0.01, 9
"<span id='stig-overall-progress'>" . number_format($stig['stig-progress'], 0) . "%</span>" .
"</div>";
}
elseif (!$stig_count) {
$msg[] = "<div id='stig-progress'>No STIG's present in DB</div>";
}
$db->help->select_count("nessus_plugins");
$nessus_count = $db->help->execute();
$nasl_progress = $db->get_Settings(['nasl-progress', 'nasl-dl-progress']);
$nasl = $db->get_Settings(['nasl-progress', 'nasl-dl-progress', 'nasl-count']);
if (!$nessus_count) {
if (!$nasl['nasl-count']) {
if (isset($nasl['nasl-dl-progress']) && between($nasl['nasl-dl-progress'], 0.01, 99.99)) {
$msg[] = "<div id='nasl-progress'>NASL Download Progress: {$nasl['nasl-dl-progress']}%</div>";
}
@ -104,12 +115,11 @@ if (!$nessus_count) {
<link href='/style/fonts/fonts.css' rel='stylesheet' type='text/css' />
<!--[if IE 9]><link rel="stylesheet" href="style/style-ie9.css" /><![endif]-->
<script src="/style/5grid/jquery-1.11.3.min.js"></script>
<script src="/script/jquery-3.2.1.min.js"></script>
<script src="/style/5grid/jquery.browser.min.js"></script>
<script type="text/javascript" src="/script/jquery-ui-1.11.4/jquery-ui.min.js"></script>
<script type="text/javascript" src="/script/jquery-ui/jquery-ui.min.js"></script>
<script src="/style/5grid/init.js?use=mobile,desktop,1000px&amp;mobileUI=1&amp;mobileUI.theme=none"></script>
<script type="text/javascript" src="/script/default.js"></script>
<script type="text/javascript" src="/script/highcharts-custom.js"></script>
<script type="text/javascript" src="/script/spin/spin.min.js"></script>
<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
@ -128,8 +138,8 @@ if (!$nessus_count) {
<link rel="icon" type="image/png" href="/favicon-96x96.png" sizes="96x96">
<link rel="icon" type="image/png" href="/favicon-16x16.png" sizes="16x16">
<link rel="icon" type="image/png" href="/favicon-32x32.png" sizes="32x32">
<link rel='stylesheet' href='/script/fontawesome-free-5.0.3/web-fonts-with-css/css/fontawesome-all.min.css' />
<link rel='stylesheet' href='/script/jquery-ui-1.11.4/jquery-ui.theme.min.css' />
<link rel='stylesheet' href='/script/fontawesome/web-fonts-with-css/css/fontawesome-all.min.css' />
<link rel='stylesheet' href='/script/jquery-ui/jquery-ui.min.css' />
<meta name="msapplication-TileColor" content="#da532c">
<meta name="msapplication-TileImage" content="/mstile-144x144.png">
@ -140,7 +150,6 @@ if (!$nessus_count) {
getLoadStatus();
}
});
function getLoadStatus() {
$.ajax("/ajax.php", {
data: {
@ -148,26 +157,37 @@ if (!$nessus_count) {
},
success: function (data) {
var reload = false;
if($('#cpe-progress').length) {
$('#cpe-progress').html(loadValue('cpe-progress', data['cpe-dl-progress'], data['cpe-progress'], 'CPE'));
if ($('#cpe-progress').length) {
var cpe = loadValue('cpe-progress', data['cpe-dl-progress'], data['cpe-progress'], data['cpe-count'], 'CPE');
if (cpe) {
$('#cpe-progress').html(cpe);
reload = true;
}
if($('#cve-progress').length) {
$('#cve-progress').html(loadValue('cve-progress', data['cve-dl-progress'], data['cve-progress'], 'CVE'));
reload = true;
}
if($('#stig-progress').length) {
$('#stig-progress').html(loadValue('stig-progress', data['stig-dl-progress'], data['stig-progress'], 'STIG'));
if ($('#cve-progress').length) {
var cve = loadValue('cve-progress', data['nvd-cve-dl-progress'], data['nvd-cve-progress'], data['nvd-cve-count'], 'NVD CVE', data['nvd-year']);
if (cve) {
$('#cve-progress').html(cve);
reload = true;
}
}
if($('#nasl-progress').length) {
$('#nasl-progress').html(loadValue('nasl-progress', data['nasl-dl-progress'], data['nasl-progress'], 'NASL'));
if ($('#stig-progress').length) {
var stig = loadValue('stig-progress', data['stig-dl-progress'], data['stig-progress'], data['stig-count'], 'STIG');
if (stig) {
$('#stig-progress').html(stig);
reload = true;
}
}
if ($('#nasl-progress').length) {
var nasl = loadValue('nasl-progress', data['nasl-dl-progress'], data['nasl-progress'], data['nasl-count'], 'NASL');
if (nasl) {
$('#nasl-progress').html(nasl);
reload = true;
}
}
if (reload) {
setTimeout(getLoadStatus, 1000);
@ -184,16 +204,20 @@ if (!$nessus_count) {
});
}
function loadValue(id, dl, prog, msg) {
if(dl < 100 && prog == 0) {
return msg + ' Download Progress ' + parseInt(dl) + "%";
function loadValue(id, dl, prog, count, msg, nvd_year) {
if (parseFloat(dl) < 100 && parseFloat(dl) > 0 && parseFloat(prog) === 0) {
return msg + (typeof nvd_year !== 'undefined' && parseInt(nvd_year) ? ' ' + nvd_year : '') + ' Download Progress ' + parseInt(dl) + "%";
}
else if(prog < 100) {
return msg + ' Progress ' + parseInt(prog) + "%";
else if (parseFloat(prog) < 100 && parseFloat(prog) > 0) {
return msg + (typeof nvd_year !== 'undefined' && parseInt(nvd_year) ? ' ' + nvd_year : '') + ' Progress ' + parseInt(prog) + "%";
}
else if (!parseInt(count)) {
return "No " + msg + "'s present in DB";
}
else {
$('#' + id).remove();
}
return false;
}
</script>
@ -213,7 +237,7 @@ if (!$nessus_count) {
<div class="row">
<div class="12u">
<!-- Nav -->
<?php include_once 'menu.inc'; ?>
<?php include_once 'menu.inc'; ?>
<!-- Logo -->
<span class="mobileUI-site-name">
<img src='/img/Sagacity-Logo.png' style='width:210px;float:right;' />

View File

@ -1,5 +1,4 @@
<?php
/**
* File: helper.inc
* Author: Ryan Prather
@ -39,6 +38,7 @@
* - Oct 2, 2017 - Fixed error with file downloads showing as moved and return largest content-size from http header
* - Oct 27, 2017 - Added UNSUPPORTED_INI constant and file detection for desktop.ini files
* - Dec 27, 2017 - Expanded download_file method to allow for download progress meta key
* - Jun 2, 2018 - Added $salt parameter to my_encrypt method to support changing passwords
*/
include_once 'error.inc';
include_once 'validation.inc';
@ -58,7 +58,8 @@ include_once 'validation.inc';
* @return mixed
* Will a DOMElement if $keep is true, a string if a single element, or an array:string if there are multiple elements
*/
function getValue($xml, $path, $starting = null, $keep = false) {
function getValue($xml, $path, $starting = null, $keep = false)
{
$xpath = new DOMXPath($xml);
$ns = $xml->lookupNamespaceUri($xml->namespaceURI);
@ -119,7 +120,8 @@ function getValue($xml, $path, $starting = null, $keep = false) {
* <p><i>msg</i> - string notice</p>
* <p><i>base_name</i> - string file name alone</p>
*/
function FileDetection($filename) {
function FileDetection($filename)
{
$name['base_name'] = basename($filename);
// print "\tCheck if exists".PHP_EOL;
if (!file_exists($filename)) {
@ -294,7 +296,8 @@ function FileDetection($filename) {
* @return integer
* Returns the amount of member in bytes being
*/
function return_bytes($val) {
function return_bytes($val)
{
$val = trim($val);
$measurement = strtolower(substr($val, -1));
$val = (int) substr($val, 0, -1);
@ -327,7 +330,8 @@ function return_bytes($val) {
* @return integer
* The target ID for any targets found or created
*/
function get_a_tgt_id($db, $steid, $hostname, $ip) {
function get_a_tgt_id($db, $steid, $hostname, $ip)
{
# gets a target ID for the hostname/ip combo
$tgt_id = $db->check_Target($steid, $hostname);
if (!$tgt_id) {
@ -365,7 +369,8 @@ function get_a_tgt_id($db, $steid, $hostname, $ip) {
*
* @return string
*/
function textCleanup($string) {
function textCleanup($string)
{
return htmlentities(preg_replace('/\n+/', '\n', preg_replace('/\r|\t|^\n$/', "", $string)));
}
@ -386,7 +391,8 @@ function textCleanup($string) {
* @return DOMElement
* The returned element (can be passed into appendChild)
*/
function xml_helper(&$xml, $element_name, $element_value = null, $is_cdata = false, $attrs = array()) {
function xml_helper(&$xml, $element_name, $element_value = null, $is_cdata = false, $attrs = array())
{
if (false) {
$xml = new DOMDocument();
}
@ -419,7 +425,8 @@ function xml_helper(&$xml, $element_name, $element_value = null, $is_cdata = fal
* @param string $msg
* Message to send to the file
*/
function time_log_diff($fh, $msg) {
function time_log_diff($fh, $msg)
{
global $last_time;
//$now = new DateTime();
$now = microtime(true);
@ -442,7 +449,8 @@ function time_log_diff($fh, $msg) {
* @param db_helper $db [optional]
* @param string $db_meta [optional]
*/
function download_file($url, $newname = null, &$db = null, $db_meta = null) {
function download_file($url, $newname = null, &$db = null, $db_meta = null)
{
if (!url_exists($url)) {
Sagacity_Error::err_handler("Could not find the URL $url", E_WARNING);
return;
@ -499,7 +507,8 @@ function download_file($url, $newname = null, &$db = null, $db_meta = null) {
*
* @return string
*/
function human_filesize($bytes, $decimals = 2) {
function human_filesize($bytes, $decimals = 2)
{
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
@ -512,7 +521,8 @@ function human_filesize($bytes, $decimals = 2) {
*
* @return boolean|int
*/
function remote_filesize($url) {
function remote_filesize($url)
{
error_reporting(E_ERROR);
try {
if ($size = filesize($url)) {
@ -550,7 +560,8 @@ function remote_filesize($url) {
*
* @return string
*/
function str_replace_first($search, $replace, $subject) {
function str_replace_first($search, $replace, $subject)
{
return implode($replace, explode($search, $subject, 2));
}
@ -560,7 +571,8 @@ function str_replace_first($search, $replace, $subject) {
* @param string $path
* @param boolean $chdir
*/
function check_path($path, $chdir = false) {
function check_path($path, $chdir = false)
{
if (!file_exists($path)) {
try {
// come in 4 characters from the end and check to see if it is a . (period), which signifies a file was passed in
@ -589,7 +601,8 @@ function check_path($path, $chdir = false) {
*
* @return bool
*/
function bzip2($in, $out) {
function bzip2($in, $out)
{
if (!file_exists($in) || !is_readable($in))
return false;
if ((!file_exists($out) && !is_writeable(dirname($out)) || (file_exists($out) && !is_writable($out))))
@ -619,7 +632,8 @@ function bzip2($in, $out) {
*
* @return bool
*/
function bunzip2($in, $out) {
function bunzip2($in, $out)
{
if (!file_exists($in) || !is_readable($in))
return false;
if ((!file_exists($out) && !is_writeable(dirname($out)) || (file_exists($out) && !is_writable($out))))
@ -649,7 +663,10 @@ function bunzip2($in, $out) {
*
* @return boolean
*/
function ping($host, $port = 80, $timeout = 6) {
function ping($host, $port = 80, $timeout = 6)
{
//$e = new Exception("Test");
//die($e->getTraceAsString());
$errno = null;
$errstr = null;
$fsock = @fsockopen($host, $port, $errno, $errstr, $timeout);
@ -671,7 +688,8 @@ function ping($host, $port = 80, $timeout = 6) {
*
* @return boolean
*/
function between($val, $low, $high) {
function between($val, $low, $high)
{
if (is_numeric($val) && is_numeric($low) && is_numeric($high)) {
if ($val >= $low && $val <= $high) {
return true;
@ -688,7 +706,8 @@ function between($val, $low, $high) {
*
* @return boolean
*/
function url_exists($url) {
function url_exists($url)
{
$file_headers = get_headers($url);
foreach ($file_headers as $header) {
if (preg_match("/HTTP\/[\d\.]+ 200 OK/", $header)) {
@ -705,7 +724,8 @@ function url_exists($url) {
* @param type $end
* @return type
*/
function microtime_diff($start, $end = null) {
function microtime_diff($start, $end = null)
{
list($start_usec, $start_sec) = explode(" ", $start);
list($end_usec, $end_sec) = explode(" ", $end);
@ -719,12 +739,19 @@ function microtime_diff($start, $end = null) {
* Sagacity encryption algorithm
*
* @param string $data
* @param string $salt
*
* @return string
*/
function my_encrypt($data) {
function my_encrypt($data, $salt = null)
{
// Remove the base64 encoding from our key
if (is_null($salt)) {
$encryption_key = base64_decode(SALT);
}
else {
$encryption_key = base64_decode($salt);
}
// Generate an initialization vector
$iv = openssl_random_pseudo_bytes(openssl_cipher_iv_length(ALGORITHM));
// Encrypt the data using AES 256 encryption in CBC mode using our encryption key and initialization vector.
@ -741,7 +768,8 @@ function my_encrypt($data) {
*
* @return string
*/
function my_decrypt($data) {
function my_decrypt($data)
{
// Remove the base64 encoding from our key
$encryption_key = base64_decode(SALT);
// To decrypt, split the encrypted data from our IV - our unique separator used was "::"
@ -756,7 +784,8 @@ function my_decrypt($data) {
* @param string $replace
* @param string &$subject
*/
function my_str_replace($search, $replace, &$subject) {
function my_str_replace($search, $replace, &$subject)
{
$subject = str_replace($search, $replace, $subject);
}
@ -768,7 +797,8 @@ function my_str_replace($search, $replace, &$subject) {
*
* @return DateInterval
*/
function add_intervals($i1, $i2) {
function add_intervals($i1, $i2)
{
$a = new DateTime("00:00");
$b = clone $a;
@ -782,3 +812,39 @@ function add_intervals($i1, $i2) {
return $b->diff($a);
}
/**
* Helper method to convert a file name to a .log file
*
* @param string $fname
*
* @return string New filename with the prepended LOG_PATH
*/
function logify($fname)
{
$fname = preg_replace("/[\.][^\.]+$/", '', basename($fname));
if (!file_exists(LOG_PATH . "/{$fname}.log")) {
touch(LOG_PATH . "/{$fname}.log");
}
return LOG_PATH . "/{$fname}.log";
}
/**
* Helper method to convert LOG_LEVEL to Logger PSR log level
*
* @return string
*/
function convert_log_level()
{
switch (LOG_LEVEL) {
case E_DEBUG:
return Logger::DEBUG;
case E_NOTICE:
return Logger::NOTICE;
case E_WARNING:
return Logger::WARNING;
default:
return Logger::ERROR;
}
}

View File

@ -5,7 +5,7 @@
* Purpose: Display the top nav menu
* Created: Sep 11, 2013
*
* Portions Copyright 2016: Cyber Perspectives, All rights reserved
* Portions Copyright 2016-2018: Cyber Perspectives, All rights reserved
* Released under the Apache v2.0 License
*
* Portions Copyright (c) 2012-2015, Salient Federal Solutions

View File

@ -38,7 +38,7 @@ if (isset($target_filter_width)) {
$stes = $db->get_STE_List();
if (!$ste_id) {
if (!isset($ste_id) || !$ste_id) {
$ste_id = filter_input(INPUT_POST, 'ste', FILTER_VALIDATE_INT);
if (!$ste_id) {
$ste_id = filter_input(INPUT_COOKIE, 'ste', FILTER_VALIDATE_INT);

View File

@ -18,6 +18,7 @@
* Change Log:
* - Oct 14, 2013 - File created
* - Jun 5, 2017 - Removed unnecessary elements and added validation for IPv4 addresses
* - Jun 2, 2018 - Changed IP validation to use filter_var PHP method
*/
/**
@ -254,11 +255,11 @@ class validation {
* Returns TRUE if it is a valid IPv4 address, otherwise FALSE
*/
public static function valid_ip($ip) {
if (!preg_match("/((^\s*((([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5]))\s*$)|(^\s*((([0-9A-Fa-f]{1,4}:){7}([0-9A-Fa-f]{1,4}|:))|(([0-9A-Fa-f]{1,4}:){6}(:[0-9A-Fa-f]{1,4}|((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){5}(((:[0-9A-Fa-f]{1,4}){1,2})|:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3})|:))|(([0-9A-Fa-f]{1,4}:){4}(((:[0-9A-Fa-f]{1,4}){1,3})|((:[0-9A-Fa-f]{1,4})?:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){3}(((:[0-9A-Fa-f]{1,4}){1,4})|((:[0-9A-Fa-f]{1,4}){0,2}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){2}(((:[0-9A-Fa-f]{1,4}){1,5})|((:[0-9A-Fa-f]{1,4}){0,3}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(([0-9A-Fa-f]{1,4}:){1}(((:[0-9A-Fa-f]{1,4}){1,6})|((:[0-9A-Fa-f]{1,4}){0,4}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:))|(:(((:[0-9A-Fa-f]{1,4}){1,7})|((:[0-9A-Fa-f]{1,4}){0,5}:((25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)(\.(25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)){3}))|:)))(%.+)?\s*$))|(^\s*((?=.{1,255}$)(?=.*[A-Za-z].*)[0-9A-Za-z](?:(?:[0-9A-Za-z]|\b-){0,61}[0-9A-Za-z])?(?:\.[0-9A-Za-z](?:(?:[0-9A-Za-z]|\b-){0,61}[0-9A-Za-z])?)*)\s*$)/", $ip)) {
return false;
}
if (filter_var($ip, FILTER_VALIDATE_IP) && !in_array($ip, ['0.0.0.0', '127.0.0.1'])) {
return true;
}
return false;
}
}

View File

@ -4,4 +4,4 @@
require_once __DIR__ . '/composer/autoload_real.php';
return ComposerAutoloaderInit1fa72dab7423f549dd6a0578a12d3ab4::getLoader();
return ComposerAutoloaderInit69a0c53551ee5f4e61c53efb549e5e72::getLoader();

View File

@ -21,8 +21,8 @@ use RuntimeException;
* @license http://opensource.org/licenses/MIT The MIT License
* @link https://florian.ec/articles/running-background-processes-in-php/ Running background processes in PHP
*/
class BackgroundProcess
{
class BackgroundProcess {
const OS_WINDOWS = 1;
const OS_NIX = 2;
const OS_OTHER = 3;
@ -47,8 +47,7 @@ class BackgroundProcess
*
* @codeCoverageIgnore
*/
public function __construct($command = null)
{
public function __construct($command = null) {
$this->command = $command;
$this->serverOS = $this->getOS();
}
@ -60,9 +59,8 @@ class BackgroundProcess
* currently $outputFile has no effect when used in conjunction with a Windows server
* @param bool $append - set to true if output should be appended to $outputfile
*/
public function run($outputFile = '/dev/null', $append = false)
{
if($this->command === null) {
public function run($outputFile = '/dev/null', $append = false) {
if ($this->command === null) {
return;
}
@ -72,7 +70,8 @@ class BackgroundProcess
$shell = new \COM("WScript.Shell");
$shell->CurrentDirectory = realpath(DOC_ROOT . "/exec");
$shell->run("cmd /C \"{$this->command}\"", 0, false);
} else {
}
else {
shell_exec(sprintf('"cd ' . realpath(DOC_ROOT . "/exec") . ' && %s %s %s"', $this->command, ($append ? '>>' : '>'), $outputFile));
}
break;
@ -80,10 +79,11 @@ class BackgroundProcess
$script = "cd " . realpath(DOC_ROOT . "/exec") . " && " .
sprintf('%s %s %s 2>&1 &', $this->command, ($append ? ">>" : ">"), $outputFile);
pclose(popen($script, "r"));
//$this->pid = (int) shell_exec("cd " . realpath(DOC_ROOT . "/exec") . " && " . sprintf('%s %s %s 2>&1 & echo $!', $this->command, ($append ? '>>' : '>'), $outputFile));
break;
default:
throw new RuntimeException(sprintf(
'Could not execute command "%s" because operating system "%s" is not supported by '.
'Could not execute command "%s" because operating system "%s" is not supported by ' .
'Cocur\BackgroundProcess.', $this->command, PHP_OS
));
}
@ -94,9 +94,8 @@ class BackgroundProcess
*
* @return bool TRUE if the process is running, FALSE if not.
*/
public function isRunning()
{
$this->checkSupportingOS('Cocur\BackgroundProcess can only check if a process is running on *nix-based '.
public function isRunning() {
$this->checkSupportingOS('Cocur\BackgroundProcess can only check if a process is running on *nix-based ' .
'systems, such as Unix, Linux or Mac OS X. You are running "%s".');
try {
@ -104,7 +103,9 @@ class BackgroundProcess
if (count(preg_split("/\n/", $result)) > 2 && !preg_match('/ERROR: Process ID out of range/', $result)) {
return true;
}
} catch (Exception $e) {
}
catch (Exception $e) {
}
return false;
@ -115,9 +116,8 @@ class BackgroundProcess
*
* @return bool `true` if the processes was stopped, `false` otherwise.
*/
public function stop()
{
$this->checkSupportingOS('Cocur\BackgroundProcess can only stop a process on *nix-based systems, such as '.
public function stop() {
$this->checkSupportingOS('Cocur\BackgroundProcess can only stop a process on *nix-based systems, such as ' .
'Unix, Linux or Mac OS X. You are running "%s".');
try {
@ -125,7 +125,9 @@ class BackgroundProcess
if (!preg_match('/No such process/', $result)) {
return true;
}
} catch (Exception $e) {
}
catch (Exception $e) {
}
return false;
@ -136,9 +138,8 @@ class BackgroundProcess
*
* @return int The ID of the process
*/
public function getPid()
{
$this->checkSupportingOS('Cocur\BackgroundProcess can only return the PID of a process on *nix-based systems, '.
public function getPid() {
$this->checkSupportingOS('Cocur\BackgroundProcess can only return the PID of a process on *nix-based systems, ' .
'such as Unix, Linux or Mac OS X. You are running "%s".');
return $this->pid;
@ -149,21 +150,20 @@ class BackgroundProcess
*
* @param $pid
*/
protected function setPid($pid)
{
protected function setPid($pid) {
$this->pid = $pid;
}
/**
* @return int
*/
protected function getOS()
{
protected function getOS() {
$os = strtoupper(PHP_OS);
if (substr($os, 0, 3) === 'WIN') {
return self::OS_WINDOWS;
} elseif ($os === 'LINUX' || $os === 'FREEBSD' || $os === 'DARWIN') {
}
else if ($os === 'LINUX' || $os === 'FREEBSD' || $os === 'DARWIN') {
return self::OS_NIX;
}
@ -177,8 +177,7 @@ class BackgroundProcess
*
* @codeCoverageIgnore
*/
protected function checkSupportingOS($message)
{
protected function checkSupportingOS($message) {
if ($this->getOS() !== self::OS_NIX) {
throw new RuntimeException(sprintf($message, PHP_OS));
}
@ -195,4 +194,5 @@ class BackgroundProcess
return $process;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,858 @@
**********************************************************************
* TCPDF LICENSE
**********************************************************************
TCPDF is free software: you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
**********************************************************************
**********************************************************************
GNU LESSER GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
This version of the GNU Lesser General Public License incorporates
the terms and conditions of version 3 of the GNU General Public
License, supplemented by the additional permissions listed below.
0. Additional Definitions.
As used herein, "this License" refers to version 3 of the GNU Lesser
General Public License, and the "GNU GPL" refers to version 3 of the GNU
General Public License.
"The Library" refers to a covered work governed by this License,
other than an Application or a Combined Work as defined below.
An "Application" is any work that makes use of an interface provided
by the Library, but which is not otherwise based on the Library.
Defining a subclass of a class defined by the Library is deemed a mode
of using an interface provided by the Library.
A "Combined Work" is a work produced by combining or linking an
Application with the Library. The particular version of the Library
with which the Combined Work was made is also called the "Linked
Version".
The "Minimal Corresponding Source" for a Combined Work means the
Corresponding Source for the Combined Work, excluding any source code
for portions of the Combined Work that, considered in isolation, are
based on the Application, and not on the Linked Version.
The "Corresponding Application Code" for a Combined Work means the
object code and/or source code for the Application, including any data
and utility programs needed for reproducing the Combined Work from the
Application, but excluding the System Libraries of the Combined Work.
1. Exception to Section 3 of the GNU GPL.
You may convey a covered work under sections 3 and 4 of this License
without being bound by section 3 of the GNU GPL.
2. Conveying Modified Versions.
If you modify a copy of the Library, and, in your modifications, a
facility refers to a function or data to be supplied by an Application
that uses the facility (other than as an argument passed when the
facility is invoked), then you may convey a copy of the modified
version:
a) under this License, provided that you make a good faith effort to
ensure that, in the event an Application does not supply the
function or data, the facility still operates, and performs
whatever part of its purpose remains meaningful, or
b) under the GNU GPL, with none of the additional permissions of
this License applicable to that copy.
3. Object Code Incorporating Material from Library Header Files.
The object code form of an Application may incorporate material from
a header file that is part of the Library. You may convey such object
code under terms of your choice, provided that, if the incorporated
material is not limited to numerical parameters, data structure
layouts and accessors, or small macros, inline functions and templates
(ten or fewer lines in length), you do both of the following:
a) Give prominent notice with each copy of the object code that the
Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the object code with a copy of the GNU GPL and this license
document.
4. Combined Works.
You may convey a Combined Work under terms of your choice that,
taken together, effectively do not restrict modification of the
portions of the Library contained in the Combined Work and reverse
engineering for debugging such modifications, if you also do each of
the following:
a) Give prominent notice with each copy of the Combined Work that
the Library is used in it and that the Library and its use are
covered by this License.
b) Accompany the Combined Work with a copy of the GNU GPL and this license
document.
c) For a Combined Work that displays copyright notices during
execution, include the copyright notice for the Library among
these notices, as well as a reference directing the user to the
copies of the GNU GPL and this license document.
d) Do one of the following:
0) Convey the Minimal Corresponding Source under the terms of this
License, and the Corresponding Application Code in a form
suitable for, and under terms that permit, the user to
recombine or relink the Application with a modified version of
the Linked Version to produce a modified Combined Work, in the
manner specified by section 6 of the GNU GPL for conveying
Corresponding Source.
1) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (a) uses at run time
a copy of the Library already present on the user's computer
system, and (b) will operate properly with a modified version
of the Library that is interface-compatible with the Linked
Version.
e) Provide Installation Information, but only if you would otherwise
be required to provide such information under section 6 of the
GNU GPL, and only to the extent that such information is
necessary to install and execute a modified version of the
Combined Work produced by recombining or relinking the
Application with a modified version of the Linked Version. (If
you use option 4d0, the Installation Information must accompany
the Minimal Corresponding Source and Corresponding Application
Code. If you use option 4d1, you must provide the Installation
Information in the manner specified by section 6 of the GNU GPL
for conveying Corresponding Source.)
5. Combined Libraries.
You may place library facilities that are a work based on the
Library side by side in a single library together with other library
facilities that are not Applications and are not covered by this
License, and convey such a combined library under terms of your
choice, if you do both of the following:
a) Accompany the combined library with a copy of the same work based
on the Library, uncombined with any other library facilities,
conveyed under the terms of this License.
b) Give prominent notice with the combined library that part of it
is a work based on the Library, and explaining where to find the
accompanying uncombined form of the same work.
6. Revised Versions of the GNU Lesser General Public License.
The Free Software Foundation may publish revised and/or new versions
of the GNU Lesser General Public License from time to time. Such new
versions will be similar in spirit to the present version, but may
differ in detail to address new problems or concerns.
Each version is given a distinguishing version number. If the
Library as you received it specifies that a certain numbered version
of the GNU Lesser General Public License "or any later version"
applies to it, you have the option of following the terms and
conditions either of that published version or of any later version
published by the Free Software Foundation. If the Library as you
received it does not specify a version number of the GNU Lesser
General Public License, you may choose any version of the GNU Lesser
General Public License ever published by the Free Software Foundation.
If the Library as you received it specifies that a proxy can decide
whether future versions of the GNU Lesser General Public License shall
apply, that proxy's public statement of acceptance of any version is
permanent authorization for you to choose that version for the
Library.
**********************************************************************
**********************************************************************
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program 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. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.
**********************************************************************
**********************************************************************

View File

@ -0,0 +1,84 @@
# TCPDF
*PHP PDF Library*
[![Donate via PayPal](https://img.shields.io/badge/donate-paypal-87ceeb.svg)](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&currency_code=GBP&business=paypal@tecnick.com&item_name=donation%20for%20TCPDF%20project)
*Please consider supporting this project by making a donation via [PayPal](https://www.paypal.com/cgi-bin/webscr?cmd=_donations&currency_code=GBP&business=paypal@tecnick.com&item_name=donation%20for%20TCPDF%20project)*
* **category** Library
* **author** Nicola Asuni <info@tecnick.com>
* **copyright** 2002-2018 Nicola Asuni - Tecnick.com LTD
* **license** http://www.gnu.org/copyleft/lesser.html GNU-LGPL v3 (see LICENSE.TXT)
* **link** http://www.tcpdf.org
* **source** https://github.com/tecnickcom/TCPDF
## IMPORTANT
A new version of this library is under development at https://github.com/tecnickcom/tc-lib-pdf and as a consequence this version will not receive any additional development or support.
This version should be considered obsolete, new projects should use the new version as soon it will become stable.
## Description
PHP library for generating PDF documents on-the-fly.
### Main Features:
* no external libraries are required for the basic functions;
* all standard page formats, custom page formats, custom margins and units of measure;
* UTF-8 Unicode and Right-To-Left languages;
* TrueTypeUnicode, OpenTypeUnicode v1, TrueType, OpenType v1, Type1 and CID-0 fonts;
* font subsetting;
* methods to publish some XHTML + CSS code, Javascript and Forms;
* images, graphic (geometric figures) and transformation methods;
* supports JPEG, PNG and SVG images natively, all images supported by GD (GD, GD2, GD2PART, GIF, JPEG, PNG, BMP, XBM, XPM) and all images supported via ImagMagick (http://www.imagemagick.org/script/formats.php)
* 1D and 2D barcodes: CODE 39, ANSI MH10.8M-1983, USD-3, 3 of 9, CODE 93, USS-93, Standard 2 of 5, Interleaved 2 of 5, CODE 128 A/B/C, 2 and 5 Digits UPC-Based Extension, EAN 8, EAN 13, UPC-A, UPC-E, MSI, POSTNET, PLANET, RMS4CC (Royal Mail 4-state Customer Code), CBC (Customer Bar Code), KIX (Klant index - Customer index), Intelligent Mail Barcode, Onecode, USPS-B-3200, CODABAR, CODE 11, PHARMACODE, PHARMACODE TWO-TRACKS, Datamatrix, QR-Code, PDF417;
* JPEG and PNG ICC profiles, Grayscale, RGB, CMYK, Spot Colors and Transparencies;
* automatic page header and footer management;
* document encryption up to 256 bit and digital signature certifications;
* transactions to UNDO commands;
* PDF annotations, including links, text and file attachments;
* text rendering modes (fill, stroke and clipping);
* multiple columns mode;
* no-write page regions;
* bookmarks, named destinations and table of content;
* text hyphenation;
* text stretching and spacing (tracking);
* automatic page break, line break and text alignments including justification;
* automatic page numbering and page groups;
* move and delete pages;
* page compression (requires php-zlib extension);
* XOBject Templates;
* Layers and object visibility.
* PDF/A-1b support.
### Third party fonts:
This library may include third party font files released with different licenses.
All the PHP files on the fonts directory are subject to the general TCPDF license (GNU-LGPLv3),
they do not contain any binary data but just a description of the general properties of a particular font.
These files can be also generated on the fly using the font utilities and TCPDF methods.
All the original binary TTF font files have been renamed for compatibility with TCPDF and compressed using the gzcompress PHP function that uses the ZLIB data format (.z files).
The binary files (.z) that begins with the prefix "free" have been extracted from the GNU FreeFont collection (GNU-GPLv3).
The binary files (.z) that begins with the prefix "pdfa" have been derived from the GNU FreeFont, so they are subject to the same license.
For the details of Copyright, License and other information, please check the files inside the directory fonts/freefont-20120503
Link : http://www.gnu.org/software/freefont/
The binary files (.z) that begins with the prefix "dejavu" have been extracted from the DejaVu fonts 2.33 (Bitstream) collection.
For the details of Copyright, License and other information, please check the files inside the directory fonts/dejavu-fonts-ttf-2.33
Link : http://dejavu-fonts.org
The binary files (.z) that begins with the prefix "ae" have been extracted from the Arabeyes.org collection (GNU-GPLv2).
Link : http://projects.arabeyes.org/
### ICC profile:
TCPDF includes the sRGB.icc profile from the icc-profiles-free Debian package:
https://packages.debian.org/source/stable/icc-profiles-free
## Developer(s) Contact
* Nicola Asuni <info@tecnick.com>

View File

@ -0,0 +1,47 @@
{
"name": "tecnickcom/tcpdf",
"version": "6.2.17",
"homepage": "http://www.tcpdf.org/",
"type": "library",
"description": "TCPDF is a PHP class for generating PDF documents and barcodes.",
"keywords": [
"PDF",
"tcpdf",
"PDFD32000-2008",
"qrcode",
"datamatrix",
"pdf417",
"barcodes"
],
"license": "LGPL-3.0",
"authors": [
{
"name": "Nicola Asuni",
"email": "info@tecnick.com",
"role": "lead"
}
],
"require": {
"php": ">=5.3.0"
},
"autoload": {
"classmap": [
"config",
"include",
"tcpdf.php",
"tcpdf_parser.php",
"tcpdf_import.php",
"tcpdf_barcodes_1d.php",
"tcpdf_barcodes_2d.php",
"include/tcpdf_colors.php",
"include/tcpdf_filters.php",
"include/tcpdf_font_data.php",
"include/tcpdf_fonts.php",
"include/tcpdf_images.php",
"include/tcpdf_static.php",
"include/barcodes/datamatrix.php",
"include/barcodes/pdf417.php",
"include/barcodes/qrcode.php"
]
}
}

View File

@ -0,0 +1,227 @@
<?php
//============================================================+
// File name : tcpdf_config.php
// Begin : 2004-06-11
// Last Update : 2014-12-11
//
// Description : Configuration file for TCPDF.
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2004-2014 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
//============================================================+
/**
* Configuration file for TCPDF.
* @author Nicola Asuni
* @package com.tecnick.tcpdf
* @version 4.9.005
* @since 2004-10-27
*/
// IMPORTANT:
// If you define the constant K_TCPDF_EXTERNAL_CONFIG, all the following settings will be ignored.
// If you use the tcpdf_autoconfig.php, then you can overwrite some values here.
/**
* Installation path (/var/www/tcpdf/).
* By default it is automatically calculated but you can also set it as a fixed string to improve performances.
*/
//define ('K_PATH_MAIN', '');
/**
* URL path to tcpdf installation folder (http://localhost/tcpdf/).
* By default it is automatically set but you can also set it as a fixed string to improve performances.
*/
//define ('K_PATH_URL', '');
/**
* Path for PDF fonts.
* By default it is automatically set but you can also set it as a fixed string to improve performances.
*/
//define ('K_PATH_FONTS', K_PATH_MAIN.'fonts/');
/**
* Default images directory.
* By default it is automatically set but you can also set it as a fixed string to improve performances.
*/
//define ('K_PATH_IMAGES', '');
/**
* Deafult image logo used be the default Header() method.
* Please set here your own logo or an empty string to disable it.
*/
//define ('PDF_HEADER_LOGO', '');
/**
* Header logo image width in user units.
*/
//define ('PDF_HEADER_LOGO_WIDTH', 0);
/**
* Cache directory for temporary files (full path).
*/
//define ('K_PATH_CACHE', '/tmp/');
/**
* Generic name for a blank image.
*/
define ('K_BLANK_IMAGE', '_blank.png');
/**
* Page format.
*/
define ('PDF_PAGE_FORMAT', 'A4');
/**
* Page orientation (P=portrait, L=landscape).
*/
define ('PDF_PAGE_ORIENTATION', 'P');
/**
* Document creator.
*/
define ('PDF_CREATOR', 'TCPDF');
/**
* Document author.
*/
define ('PDF_AUTHOR', 'TCPDF');
/**
* Header title.
*/
define ('PDF_HEADER_TITLE', 'TCPDF Example');
/**
* Header description string.
*/
define ('PDF_HEADER_STRING', "by Nicola Asuni - Tecnick.com\nwww.tcpdf.org");
/**
* Document unit of measure [pt=point, mm=millimeter, cm=centimeter, in=inch].
*/
define ('PDF_UNIT', 'mm');
/**
* Header margin.
*/
define ('PDF_MARGIN_HEADER', 5);
/**
* Footer margin.
*/
define ('PDF_MARGIN_FOOTER', 10);
/**
* Top margin.
*/
define ('PDF_MARGIN_TOP', 27);
/**
* Bottom margin.
*/
define ('PDF_MARGIN_BOTTOM', 25);
/**
* Left margin.
*/
define ('PDF_MARGIN_LEFT', 15);
/**
* Right margin.
*/
define ('PDF_MARGIN_RIGHT', 15);
/**
* Default main font name.
*/
define ('PDF_FONT_NAME_MAIN', 'helvetica');
/**
* Default main font size.
*/
define ('PDF_FONT_SIZE_MAIN', 10);
/**
* Default data font name.
*/
define ('PDF_FONT_NAME_DATA', 'helvetica');
/**
* Default data font size.
*/
define ('PDF_FONT_SIZE_DATA', 8);
/**
* Default monospaced font name.
*/
define ('PDF_FONT_MONOSPACED', 'courier');
/**
* Ratio used to adjust the conversion of pixels to user units.
*/
define ('PDF_IMAGE_SCALE_RATIO', 1.25);
/**
* Magnification factor for titles.
*/
define('HEAD_MAGNIFICATION', 1.1);
/**
* Height of cell respect font height.
*/
define('K_CELL_HEIGHT_RATIO', 1.25);
/**
* Title magnification respect main font size.
*/
define('K_TITLE_MAGNIFICATION', 1.3);
/**
* Reduction factor for small font.
*/
define('K_SMALL_RATIO', 2/3);
/**
* Set to true to enable the special procedure used to avoid the overlappind of symbols on Thai language.
*/
define('K_THAI_TOPCHARS', true);
/**
* If true allows to call TCPDF methods using HTML syntax
* IMPORTANT: For security reason, disable this feature if you are printing user HTML content.
*/
define('K_TCPDF_CALLS_IN_HTML', false);
/**
* If true and PHP version is greater than 5, then the Error() method throw new exception instead of terminating the execution.
*/
define('K_TCPDF_THROW_EXCEPTION_ERROR', false);
/**
* Default timezone for datetime functions
*/
define('K_TIMEZONE', 'UTC');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_1d_html.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.000
*/
// include 1D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_1d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDFBarcode('http://www.tcpdf.org', 'C128');
// output the barcode as HTML object
echo $barcodeobj->getBarcodeHTML(2, 30, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_1d_png.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.000
*/
// include 1D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_1d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDFBarcode('http://www.tcpdf.org', 'C128');
// output the barcode as PNG image
$barcodeobj->getBarcodePNG(2, 30, array(0,0,0));
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_1d_svg.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.000
*/
// include 1D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_1d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDFBarcode('http://www.tcpdf.org', 'C128');
// output the barcode as SVG image
$barcodeobj->getBarcodeSVG(2, 30, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_1d_svgi.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.000
*/
// include 1D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_1d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDFBarcode('http://www.tcpdf.org', 'C128');
// output the barcode as SVG inline code
echo $barcodeobj->getBarcodeSVGcode(2, 40, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_html.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'DATAMATRIX');
// output the barcode as HTML object
echo $barcodeobj->getBarcodeHTML(6, 6, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_png.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'DATAMATRIX');
// output the barcode as PNG image
$barcodeobj->getBarcodePNG(6, 6, array(0,0,0));
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_svg.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'DATAMATRIX');
// output the barcode as SVG image
$barcodeobj->getBarcodeSVG(6, 6, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_svgi.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'DATAMATRIX');
// output the barcode as SVG inline code
echo $barcodeobj->getBarcodeSVGcode(6, 6, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_html.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'PDF417');
// output the barcode as HTML object
echo $barcodeobj->getBarcodeHTML(4, 4, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_png.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'PDF417');
// output the barcode as PNG image
$barcodeobj->getBarcodePNG(4, 4, array(0,0,0));
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_svg.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'PDF417');
// output the barcode as SVG image
$barcodeobj->getBarcodeSVG(4, 4, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_svgi.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'PDF417');
// output the barcode as SVG inline code
echo $barcodeobj->getBarcodeSVGcode(4, 4, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_html.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'QRCODE,H');
// output the barcode as HTML object
echo $barcodeobj->getBarcodeHTML(6, 6, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_png.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'QRCODE,H');
// output the barcode as PNG image
$barcodeobj->getBarcodePNG(6, 6, array(0,0,0));
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_svg.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'QRCODE,H');
// output the barcode as SVG image
$barcodeobj->getBarcodeSVG(6, 6, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,53 @@
<?php
//============================================================+
// File name : example_2d_svgi.php
// Version : 1.0.000
// Begin : 2011-07-21
// Last Update : 2013-03-19
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2009-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
// -------------------------------------------------------------------
//
// Description : Example for tcpdf_barcodes_2d.php class
//
//============================================================+
/**
* @file
* Example for tcpdf_barcodes_2d.php class
* @package com.tecnick.tcpdf
* @author Nicola Asuni
* @version 1.0.009
*/
// include 2D barcode class (search for installation path)
require_once(dirname(__FILE__).'/tcpdf_barcodes_2d_include.php');
// set the barcode content and type
$barcodeobj = new TCPDF2DBarcode('http://www.tcpdf.org', 'QRCODE,H');
// output the barcode as SVG inline code
echo $barcodeobj->getBarcodeSVGcode(6, 6, 'black');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,37 @@
<?php
//============================================================+
// File name : tcpdf_barcodes_1d_include.php
// Begin : 2013-05-19
// Last Update : 2013-05-19
//
// Description : Search and include the TCPDF Barcode 1D class.
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Search and include the TCPDF Barcode 1D class.
* @package com.tecnick.tcpdf
* @abstract TCPDF - Include the main class.
* @author Nicola Asuni
* @since 2013-05-19
*/
// Include the TCPDF 1D barcode class (search the class on the following directories).
$tcpdf_barcodes_1d_include_dirs = array(realpath('../../tcpdf_barcodes_1d.php'), '/usr/share/php/tcpdf/tcpdf_barcodes_1d.php', '/usr/share/tcpdf/tcpdf_barcodes_1d.php', '/usr/share/php-tcpdf/tcpdf_barcodes_1d.php', '/var/www/tcpdf/tcpdf_barcodes_1d.php', '/var/www/html/tcpdf/tcpdf_barcodes_1d.php', '/usr/local/apache2/htdocs/tcpdf/tcpdf_barcodes_1d.php');
foreach ($tcpdf_barcodes_1d_include_dirs as $tcpdf_barcodes_1d_include_path) {
if (@file_exists($tcpdf_barcodes_1d_include_path)) {
require_once($tcpdf_barcodes_1d_include_path);
break;
}
}
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,37 @@
<?php
//============================================================+
// File name : tcpdf_barcodes_2d_include.php
// Begin : 2013-05-19
// Last Update : 2013-05-19
//
// Description : Search and include the TCPDF Barcode 1D class.
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Search and include the TCPDF Barcode 2D class.
* @package com.tecnick.tcpdf
* @abstract TCPDF - Include the main class.
* @author Nicola Asuni
* @since 2013-05-19
*/
// Include the TCPDF 2D barcode class (search the class on the following directories).
$tcpdf_barcodes_2d_include_dirs = array(realpath('../../tcpdf_barcodes_2d.php'), '/usr/share/php/tcpdf/tcpdf_barcodes_2d.php', '/usr/share/tcpdf/tcpdf_barcodes_2d.php', '/usr/share/php-tcpdf/tcpdf_barcodes_2d.php', '/var/www/tcpdf/tcpdf_barcodes_2d.php', '/var/www/html/tcpdf/tcpdf_barcodes_2d.php', '/usr/local/apache2/htdocs/tcpdf/tcpdf_barcodes_2d.php');
foreach ($tcpdf_barcodes_2d_include_dirs as $tcpdf_barcodes_2d_include_path) {
if (@file_exists($tcpdf_barcodes_2d_include_path)) {
require_once($tcpdf_barcodes_2d_include_path);
break;
}
}
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,222 @@
<?php
//============================================================+
// File name : tcpdf_config.php
// Begin : 2004-06-11
// Last Update : 2013-05-16
//
// Description : Example of alternative configuration file for TCPDF.
// Author : Nicola Asuni - Tecnick.com LTD - www.tecnick.com - info@tecnick.com
// License : GNU-LGPL v3 (http://www.gnu.org/copyleft/lesser.html)
// -------------------------------------------------------------------
// Copyright (C) 2004-2013 Nicola Asuni - Tecnick.com LTD
//
// This file is part of TCPDF software library.
//
// TCPDF is free software: you can redistribute it and/or modify it
// under the terms of the GNU Lesser General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// TCPDF 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.
// See the GNU Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public License
// along with TCPDF. If not, see <http://www.gnu.org/licenses/>.
//
// See LICENSE.TXT file for more information.
//============================================================+
/**
* Example of alternative configuration file for TCPDF.
* @author Nicola Asuni
* @package com.tecnick.tcpdf
* @version 4.9.005
* @since 2004-10-27
*/
/**
* Define the following constant to ignore the default configuration file.
*/
define ('K_TCPDF_EXTERNAL_CONFIG', true);
/**
* Installation path (/var/www/tcpdf/).
* By default it is automatically calculated but you can also set it as a fixed string to improve performances.
*/
//define ('K_PATH_MAIN', '');
/**
* URL path to tcpdf installation folder (http://localhost/tcpdf/).
* By default it is automatically set but you can also set it as a fixed string to improve performances.
*/
//define ('K_PATH_URL', '');
/**
* Path for PDF fonts.
* By default it is automatically set but you can also set it as a fixed string to improve performances.
*/
//define ('K_PATH_FONTS', K_PATH_MAIN.'fonts/');
/**
* Default images directory.
* By default it is automatically set but you can also set it as a fixed string to improve performances.
*/
define ('K_PATH_IMAGES', dirname(__FILE__).'/../images/');
/**
* Deafult image logo used be the default Header() method.
* Please set here your own logo or an empty string to disable it.
*/
define ('PDF_HEADER_LOGO', 'tcpdf_logo.jpg');
/**
* Header logo image width in user units.
*/
define ('PDF_HEADER_LOGO_WIDTH', 30);
/**
* Cache directory for temporary files (full path).
*/
define ('K_PATH_CACHE', sys_get_temp_dir().'/');
/**
* Generic name for a blank image.
*/
define ('K_BLANK_IMAGE', '_blank.png');
/**
* Page format.
*/
define ('PDF_PAGE_FORMAT', 'A4');
/**
* Page orientation (P=portrait, L=landscape).
*/
define ('PDF_PAGE_ORIENTATION', 'P');
/**
* Document creator.
*/
define ('PDF_CREATOR', 'TCPDF');
/**
* Document author.
*/
define ('PDF_AUTHOR', 'TCPDF');
/**
* Header title.
*/
define ('PDF_HEADER_TITLE', 'TCPDF Example');
/**
* Header description string.
*/
define ('PDF_HEADER_STRING', "by Nicola Asuni - Tecnick.com\nwww.tcpdf.org");
/**
* Document unit of measure [pt=point, mm=millimeter, cm=centimeter, in=inch].
*/
define ('PDF_UNIT', 'mm');
/**
* Header margin.
*/
define ('PDF_MARGIN_HEADER', 5);
/**
* Footer margin.
*/
define ('PDF_MARGIN_FOOTER', 10);
/**
* Top margin.
*/
define ('PDF_MARGIN_TOP', 27);
/**
* Bottom margin.
*/
define ('PDF_MARGIN_BOTTOM', 25);
/**
* Left margin.
*/
define ('PDF_MARGIN_LEFT', 15);
/**
* Right margin.
*/
define ('PDF_MARGIN_RIGHT', 15);
/**
* Default main font name.
*/
define ('PDF_FONT_NAME_MAIN', 'helvetica');
/**
* Default main font size.
*/
define ('PDF_FONT_SIZE_MAIN', 10);
/**
* Default data font name.
*/
define ('PDF_FONT_NAME_DATA', 'helvetica');
/**
* Default data font size.
*/
define ('PDF_FONT_SIZE_DATA', 8);
/**
* Default monospaced font name.
*/
define ('PDF_FONT_MONOSPACED', 'courier');
/**
* Ratio used to adjust the conversion of pixels to user units.
*/
define ('PDF_IMAGE_SCALE_RATIO', 1.25);
/**
* Magnification factor for titles.
*/
define('HEAD_MAGNIFICATION', 1.1);
/**
* Height of cell respect font height.
*/
define('K_CELL_HEIGHT_RATIO', 1.25);
/**
* Title magnification respect main font size.
*/
define('K_TITLE_MAGNIFICATION', 1.3);
/**
* Reduction factor for small font.
*/
define('K_SMALL_RATIO', 2/3);
/**
* Set to true to enable the special procedure used to avoid the overlappind of symbols on Thai language.
*/
define('K_THAI_TOPCHARS', true);
/**
* If true allows to call TCPDF methods using HTML syntax
* IMPORTANT: For security reason, disable this feature if you are printing user HTML content.
*/
define('K_TCPDF_CALLS_IN_HTML', true);
/**
* If true and PHP version is greater than 5, then the Error() method throw new exception instead of terminating the execution.
*/
define('K_TCPDF_THROW_EXCEPTION_ERROR', false);
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,40 @@
Bag Attributes
localKeyID: 7B AB 1B 7A BE 4C 85 C0 1A A6 DC 59 3F 79 48 C3 93 38 68 9C
subject=/CN=TCPDF DEMO/O=TCPDF/OU=DEMO/emailAddress=you@example.com/C=IT
issuer=/CN=TCPDF DEMO/O=TCPDF/OU=DEMO/emailAddress=you@example.com/C=IT
-----BEGIN CERTIFICATE-----
MIIC1TCCAj6gAwIBAgIKkehOL/XGkB5cjjANBgkqhkiG9w0BAQUFADBhMRMwEQYD
VQQDEwpUQ1BERiBERU1PMQ4wDAYDVQQKEwVUQ1BERjENMAsGA1UECxMEREVNTzEe
MBwGCSqGSIb3DQEJARYPeW91QGV4YW1wbGUuY29tMQswCQYDVQQGEwJJVDAeFw0w
OTA4MjExMjU0NDhaFw0xNDA4MjExMjU0NDhaMGExEzARBgNVBAMTClRDUERGIERF
TU8xDjAMBgNVBAoTBVRDUERGMQ0wCwYDVQQLEwRERU1PMR4wHAYJKoZIhvcNAQkB
Fg95b3VAZXhhbXBsZS5jb20xCzAJBgNVBAYTAklUMIGfMA0GCSqGSIb3DQEBAQUA
A4GNADCBiQKBgQDAqIL0uGKmTR98Lxx2vEEE1OGKkMXFo0JViitALe7Onhxxqx0H
XMUDKF5mvEVu1rcvh7/oAnAfrCuEpL/up3u1mQCgBE7WXBnFFE/AE3jCksh9OkS0
Z0Xj9woN5bzxRDsGoPiOu/4xzk5qSEXt8jf2Ep90QuNkqLIRT4swAzpDbwIDAQAB
o4GTMIGQMDcGA1UdEgQwMC6gEQYDVQQDDApUQ1BERiBERU1PoAwGA1UECgwFVENQ
REagCwYDVQQLDARERU1PMDcGA1UdEQQwMC6gEQYDVQQDDApUQ1BERiBERU1PoAwG
A1UECgwFVENQREagCwYDVQQLDARERU1PMA8GCSqGSIb3LwEBCgQCBQAwCwYDVR0P
BAQDAgSQMA0GCSqGSIb3DQEBBQUAA4GBAEhTQfqX3ZNdHmpTLDbIj22RHXii2roE
OavCbu9WsHoWpva0qSd+yIoD594VHvYAd29sfzDfiN+7W0aiZfDhq5jpaSQMVlN8
RGYMupbHY/+a9Gz1wqxnR84mlTtIkZVRYAhsfPwy6M1BEjdMqfdh9h40JIdkdjtb
8faTCfXPePWQ
-----END CERTIFICATE-----
Bag Attributes
localKeyID: 7B AB 1B 7A BE 4C 85 C0 1A A6 DC 59 3F 79 48 C3 93 38 68 9C
Key Attributes: <No Attributes>
-----BEGIN RSA PRIVATE KEY-----
MIICXQIBAAKBgQDAqIL0uGKmTR98Lxx2vEEE1OGKkMXFo0JViitALe7Onhxxqx0H
XMUDKF5mvEVu1rcvh7/oAnAfrCuEpL/up3u1mQCgBE7WXBnFFE/AE3jCksh9OkS0
Z0Xj9woN5bzxRDsGoPiOu/4xzk5qSEXt8jf2Ep90QuNkqLIRT4swAzpDbwIDAQAB
AoGAXc+wNMmz/5Z+RlIKYia44klmqbplEx+0JULqXI4BQsrqvs67i+I4bJkznoL+
rEIRYSuQ3sCRKFsFtckjTGpxadnxkB+uwGKc6pZChv99BFX6HFR4hgBlT/BBRAQA
hMDlM2JIRr4S4SMVXR7MHwGMUf9mUeanGLR3ZWtU3aXJrIECQQD7OaYUVYNEEnM9
uXyjm22CuHyqyEf5gb13sK0uQty67547yJTMUQZd/sQc9KGwhzBbhrob2LO2jAhh
S+f+NSRnAkEAxFHm3fMI5RgXmswxlGm4QW07a/Ueo7ZJG6xjTkFXluJhd+XHswRD
dQIO3zG9nGjNUoeMrPhXhPvKqFc2F9RDuQJAQBEGin74N77gxqfr4ik79y8nE8J5
oGZ2s/RJZdfFRKLg3mwbjjNHhWb4Ck5UgZkoOt8TzRApXG8/n9hktE5HFwJBALur
M5AueO1Pl5kB489lNJ9OxUQRYUXMxpxuscuoCQwSwmv0O2+0/qtG2WKhUQnI4aYo
L+FV0YwtivBb1jj3T/kCQQDIWOxq8eRowdaMzvJpRUHFgMcf1AVZExKyrugwYOWd
KNsDxC4KaQOsPt8iT/Ulo4g/MJC0HolCOhWibKmR9Ayl
-----END RSA PRIVATE KEY-----

View File

@ -0,0 +1,19 @@
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed imperdiet lectus. Phasellus quis velit velit, non condimentum quam. Sed neque urna, ultrices ac volutpat vel, laoreet vitae augue. Sed vel velit erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras eget velit nulla, eu sagittis elit. Nunc ac arcu est, in lobortis tellus. Praesent condimentum rhoncus sodales. In hac habitasse platea dictumst. Proin porta eros pharetra enim tincidunt dignissim nec vel dolor. Cras sapien elit, ornare ac dignissim eu, ultricies ac eros. Maecenas augue magna, ultrices a congue in, mollis eu nulla. Nunc venenatis massa at est eleifend faucibus. Vivamus sed risus lectus, nec interdum nunc.
Fusce et felis vitae diam lobortis sollicitudin. Aenean tincidunt accumsan nisi, id vehicula quam laoreet elementum. Phasellus egestas interdum erat, et viverra ipsum ultricies ac. Praesent sagittis augue at augue volutpat eleifend. Cras nec orci neque. Mauris bibendum posuere blandit. Donec feugiat mollis dui sit amet pellentesque. Sed a enim justo. Donec tincidunt, nisl eget elementum aliquam, odio ipsum ultrices quam, eu porttitor ligula urna at lorem. Donec varius, eros et convallis laoreet, ligula tellus consequat felis, ut ornare metus tellus sodales velit. Duis sed diam ante. Ut rutrum malesuada massa, vitae consectetur ipsum rhoncus sed. Suspendisse potenti. Pellentesque a congue massa.
Integer non sem eget neque mattis accumsan. Maecenas eu nisl mauris, sit amet interdum ipsum. In pharetra erat vel lectus venenatis elementum. Nulla non elit ligula, sit amet mollis urna. Morbi ut gravida est. Mauris tincidunt sem et turpis molestie malesuada. Curabitur vel nulla risus, sed mollis erat. Suspendisse vehicula accumsan purus nec varius. Donec fermentum lorem id felis sodales dictum. Quisque et dolor ipsum. Nam luctus consectetur dui vitae fermentum. Curabitur sodales consequat augue, id ultricies augue tempor ac. Aliquam ac magna id ipsum vehicula bibendum. Sed elementum congue tristique. Phasellus vel lorem eu lectus porta sodales. Etiam neque tortor, sagittis id pharetra quis, laoreet vel arcu.
Cras quam mi, ornare laoreet laoreet vel, vehicula at lacus. Maecenas a lacus accumsan augue convallis sagittis sed quis odio. Morbi sit amet turpis diam, dictum convallis urna. Cras eget interdum augue. Cras eu nisi sit amet dolor faucibus porttitor. Suspendisse potenti. Nunc vitae dolor risus, at cursus libero. Suspendisse bibendum tellus non nibh hendrerit tristique. Mauris eget orci elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam porta libero non ante laoreet semper. Proin volutpat sodales mi, ac fermentum erat sagittis in. Vivamus at viverra felis. Ut pretium facilisis ante et pharetra.
Nulla facilisi. Cras varius quam eget libero aliquam vitae tincidunt leo rutrum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque a nisl massa, quis pretium urna. Proin vel porttitor tortor. Cras rhoncus congue velit in bibendum. Donec pharetra semper augue id lacinia. Quisque magna quam, hendrerit eu aliquam et, pellentesque ut tellus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Maecenas nulla quam, rutrum eu feugiat at, elementum eu libero. Maecenas ullamcorper leo et turpis rutrum ac laoreet eros faucibus. Phasellus condimentum lorem quis neque imperdiet quis molestie enim iaculis. Phasellus risus est, vestibulum ut convallis ultrices, dignissim nec erat. Etiam congue lobortis laoreet. Nulla ut neque sed velit dapibus semper. Quisque nec dolor id nibh eleifend iaculis. Vivamus vitae fermentum odio. Etiam malesuada quam in nulla aliquam sed convallis dui feugiat.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed imperdiet lectus. Phasellus quis velit velit, non condimentum quam. Sed neque urna, ultrices ac volutpat vel, laoreet vitae augue. Sed vel velit erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras eget velit nulla, eu sagittis elit. Nunc ac arcu est, in lobortis tellus. Praesent condimentum rhoncus sodales. In hac habitasse platea dictumst. Proin porta eros pharetra enim tincidunt dignissim nec vel dolor. Cras sapien elit, ornare ac dignissim eu, ultricies ac eros. Maecenas augue magna, ultrices a congue in, mollis eu nulla. Nunc venenatis massa at est eleifend faucibus. Vivamus sed risus lectus, nec interdum nunc.
Fusce et felis vitae diam lobortis sollicitudin. Aenean tincidunt accumsan nisi, id vehicula quam laoreet elementum. Phasellus egestas interdum erat, et viverra ipsum ultricies ac. Praesent sagittis augue at augue volutpat eleifend. Cras nec orci neque. Mauris bibendum posuere blandit. Donec feugiat mollis dui sit amet pellentesque. Sed a enim justo. Donec tincidunt, nisl eget elementum aliquam, odio ipsum ultrices quam, eu porttitor ligula urna at lorem. Donec varius, eros et convallis laoreet, ligula tellus consequat felis, ut ornare metus tellus sodales velit. Duis sed diam ante. Ut rutrum malesuada massa, vitae consectetur ipsum rhoncus sed. Suspendisse potenti. Pellentesque a congue massa.
Integer non sem eget neque mattis accumsan. Maecenas eu nisl mauris, sit amet interdum ipsum. In pharetra erat vel lectus venenatis elementum. Nulla non elit ligula, sit amet mollis urna. Morbi ut gravida est. Mauris tincidunt sem et turpis molestie malesuada. Curabitur vel nulla risus, sed mollis erat. Suspendisse vehicula accumsan purus nec varius. Donec fermentum lorem id felis sodales dictum. Quisque et dolor ipsum. Nam luctus consectetur dui vitae fermentum. Curabitur sodales consequat augue, id ultricies augue tempor ac. Aliquam ac magna id ipsum vehicula bibendum. Sed elementum congue tristique. Phasellus vel lorem eu lectus porta sodales. Etiam neque tortor, sagittis id pharetra quis, laoreet vel arcu.
Cras quam mi, ornare laoreet laoreet vel, vehicula at lacus. Maecenas a lacus accumsan augue convallis sagittis sed quis odio. Morbi sit amet turpis diam, dictum convallis urna. Cras eget interdum augue. Cras eu nisi sit amet dolor faucibus porttitor. Suspendisse potenti. Nunc vitae dolor risus, at cursus libero. Suspendisse bibendum tellus non nibh hendrerit tristique. Mauris eget orci elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam porta libero non ante laoreet semper. Proin volutpat sodales mi, ac fermentum erat sagittis in. Vivamus at viverra felis. Ut pretium facilisis ante et pharetra.
Nulla facilisi. Cras varius quam eget libero aliquam vitae tincidunt leo rutrum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque a nisl massa, quis pretium urna. Proin vel porttitor tortor. Cras rhoncus congue velit in bibendum. Donec pharetra semper augue id lacinia. Quisque magna quam, hendrerit eu aliquam et, pellentesque ut tellus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Maecenas nulla quam, rutrum eu feugiat at, elementum eu libero. Maecenas ullamcorper leo et turpis rutrum ac laoreet eros faucibus. Phasellus condimentum lorem quis neque imperdiet quis molestie enim iaculis. Phasellus risus est, vestibulum ut convallis ultrices, dignissim nec erat. Etiam congue lobortis laoreet. Nulla ut neque sed velit dapibus semper. Quisque nec dolor id nibh eleifend iaculis. Vivamus vitae fermentum odio. Etiam malesuada quam in nulla aliquam sed convallis dui feugiat.

View File

@ -0,0 +1,23 @@
<p><strong>Lorem ipsum</strong> dolor sit amet, consectetur adipiscing elit. In sed imperdiet lectus. Phasellus quis velit velit, non condimentum quam. Sed neque urna, ultrices ac volutpat vel, laoreet vitae augue. Sed vel velit erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras eget velit nulla, eu sagittis elit. Nunc ac arcu est, in lobortis tellus. Praesent condimentum rhoncus sodales. In hac habitasse platea dictumst. Proin porta eros pharetra enim tincidunt dignissim nec vel dolor. Cras sapien elit, ornare ac dignissim eu, ultricies ac eros. Maecenas augue magna, ultrices a congue in, mollis eu nulla. Nunc venenatis massa at est eleifend faucibus. Vivamus sed risus lectus, nec interdum nunc.</p>
<img src="images/image_demo.jpg" width="54mm" height="80mm" />
<p style="background-color:yellow;"><i>Fusce et felis vitae diam lobortis sollicitudin. Aenean tincidunt accumsan nisi, id vehicula quam laoreet elementum. Phasellus egestas interdum erat, et viverra ipsum ultricies ac. Praesent sagittis augue at augue volutpat eleifend. Cras nec orci neque. Mauris bibendum posuere blandit. Donec feugiat mollis dui sit amet pellentesque. Sed a enim justo. Donec tincidunt, nisl eget elementum aliquam, odio ipsum ultrices quam, eu porttitor ligula urna at lorem. Donec varius, eros et convallis laoreet, ligula tellus consequat felis, ut ornare metus tellus sodales velit. Duis sed diam ante. Ut rutrum malesuada massa, vitae consectetur ipsum rhoncus sed. Suspendisse potenti. Pellentesque a congue massa.</i></p>
<p>Integer non sem eget neque mattis accumsan. Maecenas eu nisl mauris, sit amet interdum ipsum. In pharetra erat vel lectus venenatis elementum. Nulla non elit ligula, sit amet mollis urna. Morbi ut gravida est. Mauris tincidunt sem et turpis molestie malesuada. Curabitur vel nulla risus, sed mollis erat. Suspendisse vehicula accumsan purus nec varius. Donec fermentum lorem id felis sodales dictum. Quisque et dolor ipsum. Nam luctus consectetur dui vitae fermentum. Curabitur sodales consequat augue, id ultricies augue tempor ac. Aliquam ac magna id ipsum vehicula bibendum. Sed elementum congue tristique. Phasellus vel lorem eu lectus porta sodales. Etiam neque tortor, sagittis id pharetra quis, laoreet vel arcu.</p>
<p style="color:navy;">Cras quam mi, ornare laoreet laoreet vel, vehicula at lacus. Maecenas a lacus accumsan augue convallis sagittis sed quis odio. Morbi sit amet turpis diam, dictum convallis urna. Cras eget interdum augue. Cras eu nisi sit amet dolor faucibus porttitor. Suspendisse potenti. Nunc vitae dolor risus, at cursus libero. Suspendisse bibendum tellus non nibh hendrerit tristique. Mauris eget orci elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam porta libero non ante laoreet semper. Proin volutpat sodales mi, ac fermentum erat sagittis in. Vivamus at viverra felis. Ut pretium facilisis ante et pharetra.</p>
<p>Nulla facilisi. Cras varius quam eget libero aliquam vitae tincidunt leo rutrum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque a nisl massa, quis pretium urna. Proin vel porttitor tortor. Cras rhoncus congue velit in bibendum. Donec pharetra semper augue id lacinia. Quisque magna quam, hendrerit eu aliquam et, pellentesque ut tellus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Maecenas nulla quam, rutrum eu feugiat at, elementum eu libero. Maecenas ullamcorper leo et turpis rutrum ac laoreet eros faucibus. Phasellus condimentum lorem quis neque imperdiet quis molestie enim iaculis. Phasellus risus est, vestibulum ut convallis ultrices, dignissim nec erat. Etiam congue lobortis laoreet. Nulla ut neque sed velit dapibus semper. Quisque nec dolor id nibh eleifend iaculis. Vivamus vitae fermentum odio. Etiam malesuada quam in nulla aliquam sed convallis dui feugiat.</p>
<p><strong>Lorem ipsum</strong> dolor sit amet, consectetur adipiscing elit. In sed imperdiet lectus. Phasellus quis velit velit, non condimentum quam. Sed neque urna, ultrices ac volutpat vel, laoreet vitae augue. Sed vel velit erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras eget velit nulla, eu sagittis elit. Nunc ac arcu est, in lobortis tellus. Praesent condimentum rhoncus sodales. In hac habitasse platea dictumst. Proin porta eros pharetra enim tincidunt dignissim nec vel dolor. Cras sapien elit, ornare ac dignissim eu, ultricies ac eros. Maecenas augue magna, ultrices a congue in, mollis eu nulla. Nunc venenatis massa at est eleifend faucibus. Vivamus sed risus lectus, nec interdum nunc.</p>
<img src="images/image_demo.jpg" width="54mm" height="80mm" />
<p style="background-color:yellow;"><i>Fusce et felis vitae diam lobortis sollicitudin. Aenean tincidunt accumsan nisi, id vehicula quam laoreet elementum. Phasellus egestas interdum erat, et viverra ipsum ultricies ac. Praesent sagittis augue at augue volutpat eleifend. Cras nec orci neque. Mauris bibendum posuere blandit. Donec feugiat mollis dui sit amet pellentesque. Sed a enim justo. Donec tincidunt, nisl eget elementum aliquam, odio ipsum ultrices quam, eu porttitor ligula urna at lorem. Donec varius, eros et convallis laoreet, ligula tellus consequat felis, ut ornare metus tellus sodales velit. Duis sed diam ante. Ut rutrum malesuada massa, vitae consectetur ipsum rhoncus sed. Suspendisse potenti. Pellentesque a congue massa.</i></p>
<p>Integer non sem eget neque mattis accumsan. Maecenas eu nisl mauris, sit amet interdum ipsum. In pharetra erat vel lectus venenatis elementum. Nulla non elit ligula, sit amet mollis urna. Morbi ut gravida est. Mauris tincidunt sem et turpis molestie malesuada. Curabitur vel nulla risus, sed mollis erat. Suspendisse vehicula accumsan purus nec varius. Donec fermentum lorem id felis sodales dictum. Quisque et dolor ipsum. Nam luctus consectetur dui vitae fermentum. Curabitur sodales consequat augue, id ultricies augue tempor ac. Aliquam ac magna id ipsum vehicula bibendum. Sed elementum congue tristique. Phasellus vel lorem eu lectus porta sodales. Etiam neque tortor, sagittis id pharetra quis, laoreet vel arcu.</p>
<p style="color:navy;">Cras quam mi, ornare laoreet laoreet vel, vehicula at lacus. Maecenas a lacus accumsan augue convallis sagittis sed quis odio. Morbi sit amet turpis diam, dictum convallis urna. Cras eget interdum augue. Cras eu nisi sit amet dolor faucibus porttitor. Suspendisse potenti. Nunc vitae dolor risus, at cursus libero. Suspendisse bibendum tellus non nibh hendrerit tristique. Mauris eget orci elit. Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nam porta libero non ante laoreet semper. Proin volutpat sodales mi, ac fermentum erat sagittis in. Vivamus at viverra felis. Ut pretium facilisis ante et pharetra.</p>
<p>Nulla facilisi. Cras varius quam eget libero aliquam vitae tincidunt leo rutrum. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Pellentesque a nisl massa, quis pretium urna. Proin vel porttitor tortor. Cras rhoncus congue velit in bibendum. Donec pharetra semper augue id lacinia. Quisque magna quam, hendrerit eu aliquam et, pellentesque ut tellus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Maecenas nulla quam, rutrum eu feugiat at, elementum eu libero. Maecenas ullamcorper leo et turpis rutrum ac laoreet eros faucibus. Phasellus condimentum lorem quis neque imperdiet quis molestie enim iaculis. Phasellus risus est, vestibulum ut convallis ultrices, dignissim nec erat. Etiam congue lobortis laoreet. Nulla ut neque sed velit dapibus semper. Quisque nec dolor id nibh eleifend iaculis. Vivamus vitae fermentum odio. Etiam malesuada quam in nulla aliquam sed convallis dui feugiat.</p>

View File

@ -0,0 +1,15 @@
Austria;Vienna;83859;8075
Belgium;Brussels;30518;10192
Denmark;Copenhagen;43094;5295
Finland;Helsinki;304529;5147
France;Paris;543965;58728
Germany;Berlin;357022;82057
Greece;Athens;131625;10511
Ireland;Dublin;70723;3694
Italy;Roma;301316;57563
Luxembourg;Luxembourg;2586;424
Netherlands;Amsterdam;41526;15654
Portugal;Lisbon;91906;9957
Spain;Madrid;504790;39348
Sweden;Stockholm;410934;8839
United Kingdom;London;243820;58862

View File

@ -0,0 +1,128 @@
Sentences that contain all letters commonly used in a language
--------------------------------------------------------------
This file is UTF-8 encoded.
Czech (cz)
---------
Příšerně žluťoučký kůň úpěl ďábelské ódy.
Hleď, toť přízračný kůň v mátožné póze šíleně úpí.
Zvlášť zákeřný učeň s ďolíčky běží podél zóny úlů.
Loď čeří kýlem tůň obzvlášť v Grónské úžině.
Ó, náhlý déšť již zvířil prach a čilá laň teď běží s houfcem gazel k úkrytům.
Danish (da)
---------
Quizdeltagerne spiste jordbær med fløde, mens cirkusklovnen
Wolther spillede på xylofon.
(= Quiz contestants were eating strawbery with cream while Wolther
the circus clown played on xylophone.)
German (de)
-----------
Falsches Üben von Xylophonmusik quält jeden größeren Zwerg
(= Wrongful practicing of xylophone music tortures every larger dwarf)
Zwölf Boxkämpfer jagten Eva quer über den Sylter Deich
(= Twelve boxing fighters hunted Eva across the dike of Sylt)
Heizölrückstoßabdämpfung
(= fuel oil recoil absorber)
(jqvwxy missing, but all non-ASCII letters in one word)
English (en)
------------
The quick brown fox jumps over the lazy dog
Spanish (es)
------------
El pingüino Wenceslao hizo kilómetros bajo exhaustiva lluvia y
frío, añoraba a su querido cachorro.
(Contains every letter and every accent, but not every combination
of vowel + acute.)
French (fr)
-----------
Portez ce vieux whisky au juge blond qui fume sur son île intérieure, à
côté de l'alcôve ovoïde, où les bûches se consument dans l'âtre, ce
qui lui permet de penser à la cænogenèse de l'être dont il est question
dans la cause ambiguë entendue à Moÿ, dans un capharnaüm qui,
pense-t-il, diminue çà et là la qualité de son œuvre.
l'île exiguë
Où l'obèse jury mûr
Fête l'haï volapük,
Âne ex aéquo au whist,
Ôtez ce vœu déçu.
Le cœur déçu mais l'âme plutôt naïve, Louÿs rêva de crapaüter en
canoë au delà des îles, près du mälström où brûlent les novæ.
Irish Gaelic (ga)
-----------------
D'fhuascail Íosa, Úrmhac na hÓighe Beannaithe, pór Éava agus Ádhaimh
Hungarian (hu)
--------------
Árvíztűrő tükörfúrógép
(= flood-proof mirror-drilling machine, only all non-ASCII letters)
Icelandic (is)
--------------
Kæmi ný öxi hér ykist þjófum nú bæði víl og ádrepa
Sævör grét áðan því úlpan var ónýt
(some ASCII letters missing)
Greek (el)
-------------
Γαζέες καὶ μυρτιὲς δὲν θὰ βρῶ πιὰ στὸ χρυσαφὶ ξέφωτο
(= No more shall I see acacias or myrtles in the golden clearing)
Ξεσκεπάζω τὴν ψυχοφθόρα βδελυγμία
(= I uncover the soul-destroying abhorrence)
Hebrew (iw)
-----------
? דג סקרן שט בים מאוכזב ולפתע מצא לו חברה איך הקליטה
Polish (pl)
-----------
Pchnąć w tę łódź jeża lub osiem skrzyń fig
(= To push a hedgehog or eight bins of figs in this boat)
Zażółć gęślą jaźń
Russian (ru)
------------
В чащах юга жил бы цитрус? Да, но фальшивый экземпляр!
(= Would a citrus live in the bushes of south? Yes, but only a fake one!)
Thai (th)
---------
[--------------------------|------------------------]
๏ เป็นมนุษย์สุดประเสริฐเลิศคุณค่า กว่าบรรดาฝูงสัตว์เดรัจฉาน
จงฝ่าฟันพัฒนาวิชาการ อย่าล้างผลาญฤๅเข่นฆ่าบีฑาใคร
ไม่ถือโทษโกรธแช่งซัดฮึดฮัดด่า หัดอภัยเหมือนกีฬาอัชฌาสัย
ปฏิบัติประพฤติกฎกำหนดใจ พูดจาให้จ๊ะๆ จ๋าๆ น่าฟังเอย ฯ
[The copyright for the Thai example is owned by The Computer
Association of Thailand under the Royal Patronage of His Majesty the
King.]
Please let me know if you find others! Special thanks to the people
from all over the world who contributed these sentences.

View File

@ -0,0 +1,106 @@
<?php
//============================================================+
// File name : example_001.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 001 for TCPDF class
// Default Header and Footer
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Default Header and Footer
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 001');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 001', PDF_HEADER_STRING, array(0,64,255), array(0,64,128));
$pdf->setFooterData(array(0,64,0), array(0,64,128));
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set default font subsetting mode
$pdf->setFontSubsetting(true);
// Set font
// dejavusans is a UTF-8 Unicode font, if you only need to
// print standard ASCII chars, you can use core fonts like
// helvetica or times to reduce file size.
$pdf->SetFont('dejavusans', '', 14, '', true);
// Add a page
// This method has several options, check the source code documentation for more information.
$pdf->AddPage();
// set text shadow effect
$pdf->setTextShadow(array('enabled'=>true, 'depth_w'=>0.2, 'depth_h'=>0.2, 'color'=>array(196,196,196), 'opacity'=>1, 'blend_mode'=>'Normal'));
// Set some content to print
$html = <<<EOD
<h1>Welcome to <a href="http://www.tcpdf.org" style="text-decoration:none;background-color:#CC0000;color:black;">&nbsp;<span style="color:black;">TC</span><span style="color:white;">PDF</span>&nbsp;</a>!</h1>
<i>This is the first example of TCPDF library.</i>
<p>This text is printed using the <i>writeHTMLCell()</i> method but you can also use: <i>Multicell(), writeHTML(), Write(), Cell() and Text()</i>.</p>
<p>Please check the source code documentation and other examples for further information.</p>
<p style="color:#CC0000;">TO IMPROVE AND EXPAND TCPDF I NEED YOUR SUPPORT, PLEASE <a href="http://sourceforge.net/donate/index.php?group_id=128076">MAKE A DONATION!</a></p>
EOD;
// Print text using writeHTMLCell()
$pdf->writeHTMLCell(0, 0, '', '', $html, 0, 1, 0, true, '', true);
// ---------------------------------------------------------
// Close and output PDF document
// This method has several options, check the source code documentation for more information.
$pdf->Output('example_001.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,87 @@
<?php
//============================================================+
// File name : example_002.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 002 for TCPDF class
// Removing Header and Footer
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Removing Header and Footer
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 002');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// remove default header/footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('times', 'BI', 20);
// add a page
$pdf->AddPage();
// set some text to print
$txt = <<<EOD
TCPDF Example 002
Default page header and footer are disabled using setPrintHeader() and setPrintFooter() methods.
EOD;
// print a block of text using Write()
$pdf->Write(0, $txt, '', 0, 'C', true, 0, false, false, 0);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_002.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,118 @@
<?php
//============================================================+
// File name : example_003.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 003 for TCPDF class
// Custom Header and Footer
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Custom Header and Footer
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// Extend the TCPDF class to create custom Header and Footer
class MYPDF extends TCPDF {
//Page header
public function Header() {
// Logo
$image_file = K_PATH_IMAGES.'logo_example.jpg';
$this->Image($image_file, 10, 10, 15, '', 'JPG', '', 'T', false, 300, '', false, false, 0, false, false, false);
// Set font
$this->SetFont('helvetica', 'B', 20);
// Title
$this->Cell(0, 15, '<< TCPDF Example 003 >>', 0, false, 'C', 0, '', 0, false, 'M', 'M');
}
// Page footer
public function Footer() {
// Position at 15 mm from bottom
$this->SetY(-15);
// Set font
$this->SetFont('helvetica', 'I', 8);
// Page number
$this->Cell(0, 10, 'Page '.$this->getAliasNumPage().'/'.$this->getAliasNbPages(), 0, false, 'C', 0, '', 0, false, 'T', 'M');
}
}
// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 003');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE, PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('times', 'BI', 12);
// add a page
$pdf->AddPage();
// set some text to print
$txt = <<<EOD
TCPDF Example 003
Custom page header and footer are defined by extending the TCPDF class and overriding the Header() and Footer() methods.
EOD;
// print a block of text using Write()
$pdf->Write(0, $txt, '', 0, 'C', true, 0, false, false, 0);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_003.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,121 @@
<?php
//============================================================+
// File name : example_004.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 004 for TCPDF class
// Cell stretching
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Cell stretching
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 004');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 004', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('times', '', 11);
// add a page
$pdf->AddPage();
//Cell($w, $h=0, $txt='', $border=0, $ln=0, $align='', $fill=0, $link='', $stretch=0, $ignore_min_height=false, $calign='T', $valign='M')
// test Cell stretching
$pdf->Cell(0, 0, 'TEST CELL STRETCH: no stretch', 1, 1, 'C', 0, '', 0);
$pdf->Cell(0, 0, 'TEST CELL STRETCH: scaling', 1, 1, 'C', 0, '', 1);
$pdf->Cell(0, 0, 'TEST CELL STRETCH: force scaling', 1, 1, 'C', 0, '', 2);
$pdf->Cell(0, 0, 'TEST CELL STRETCH: spacing', 1, 1, 'C', 0, '', 3);
$pdf->Cell(0, 0, 'TEST CELL STRETCH: force spacing', 1, 1, 'C', 0, '', 4);
$pdf->Ln(5);
$pdf->Cell(45, 0, 'TEST CELL STRETCH: scaling', 1, 1, 'C', 0, '', 1);
$pdf->Cell(45, 0, 'TEST CELL STRETCH: force scaling', 1, 1, 'C', 0, '', 2);
$pdf->Cell(45, 0, 'TEST CELL STRETCH: spacing', 1, 1, 'C', 0, '', 3);
$pdf->Cell(45, 0, 'TEST CELL STRETCH: force spacing', 1, 1, 'C', 0, '', 4);
$pdf->AddPage();
// example using general stretching and spacing
for ($stretching = 90; $stretching <= 110; $stretching += 10) {
for ($spacing = -0.254; $spacing <= 0.254; $spacing += 0.254) {
// set general stretching (scaling) value
$pdf->setFontStretching($stretching);
// set general spacing value
$pdf->setFontSpacing($spacing);
$pdf->Cell(0, 0, 'Stretching '.$stretching.'%, Spacing '.sprintf('%+.3F', $spacing).'mm, no stretch', 1, 1, 'C', 0, '', 0);
$pdf->Cell(0, 0, 'Stretching '.$stretching.'%, Spacing '.sprintf('%+.3F', $spacing).'mm, scaling', 1, 1, 'C', 0, '', 1);
$pdf->Cell(0, 0, 'Stretching '.$stretching.'%, Spacing '.sprintf('%+.3F', $spacing).'mm, force scaling', 1, 1, 'C', 0, '', 2);
$pdf->Cell(0, 0, 'Stretching '.$stretching.'%, Spacing '.sprintf('%+.3F', $spacing).'mm, spacing', 1, 1, 'C', 0, '', 3);
$pdf->Cell(0, 0, 'Stretching '.$stretching.'%, Spacing '.sprintf('%+.3F', $spacing).'mm, force spacing', 1, 1, 'C', 0, '', 4);
$pdf->Ln(2);
}
}
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_004.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,158 @@
<?php
//============================================================+
// File name : example_005.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 005 for TCPDF class
// Multicell
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Multicell
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 005');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 005', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('times', '', 10);
// add a page
$pdf->AddPage();
// set cell padding
$pdf->setCellPaddings(1, 1, 1, 1);
// set cell margins
$pdf->setCellMargins(1, 1, 1, 1);
// set color for background
$pdf->SetFillColor(255, 255, 127);
// MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0)
// set some text for example
$txt = 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.';
// Multicell test
$pdf->MultiCell(55, 5, '[LEFT] '.$txt, 1, 'L', 1, 0, '', '', true);
$pdf->MultiCell(55, 5, '[RIGHT] '.$txt, 1, 'R', 0, 1, '', '', true);
$pdf->MultiCell(55, 5, '[CENTER] '.$txt, 1, 'C', 0, 0, '', '', true);
$pdf->MultiCell(55, 5, '[JUSTIFY] '.$txt."\n", 1, 'J', 1, 2, '' ,'', true);
$pdf->MultiCell(55, 5, '[DEFAULT] '.$txt, 1, '', 0, 1, '', '', true);
$pdf->Ln(4);
// set color for background
$pdf->SetFillColor(220, 255, 220);
// Vertical alignment
$pdf->MultiCell(55, 40, '[VERTICAL ALIGNMENT - TOP] '.$txt, 1, 'J', 1, 0, '', '', true, 0, false, true, 40, 'T');
$pdf->MultiCell(55, 40, '[VERTICAL ALIGNMENT - MIDDLE] '.$txt, 1, 'J', 1, 0, '', '', true, 0, false, true, 40, 'M');
$pdf->MultiCell(55, 40, '[VERTICAL ALIGNMENT - BOTTOM] '.$txt, 1, 'J', 1, 1, '', '', true, 0, false, true, 40, 'B');
$pdf->Ln(4);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// set color for background
$pdf->SetFillColor(215, 235, 255);
// set some text for example
$txt = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed imperdiet lectus. Phasellus quis velit velit, non condimentum quam. Sed neque urna, ultrices ac volutpat vel, laoreet vitae augue. Sed vel velit erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras eget velit nulla, eu sagittis elit. Nunc ac arcu est, in lobortis tellus. Praesent condimentum rhoncus sodales. In hac habitasse platea dictumst. Proin porta eros pharetra enim tincidunt dignissim nec vel dolor. Cras sapien elit, ornare ac dignissim eu, ultricies ac eros. Maecenas augue magna, ultrices a congue in, mollis eu nulla. Nunc venenatis massa at est eleifend faucibus. Vivamus sed risus lectus, nec interdum nunc.
Fusce et felis vitae diam lobortis sollicitudin. Aenean tincidunt accumsan nisi, id vehicula quam laoreet elementum. Phasellus egestas interdum erat, et viverra ipsum ultricies ac. Praesent sagittis augue at augue volutpat eleifend. Cras nec orci neque. Mauris bibendum posuere blandit. Donec feugiat mollis dui sit amet pellentesque. Sed a enim justo. Donec tincidunt, nisl eget elementum aliquam, odio ipsum ultrices quam, eu porttitor ligula urna at lorem. Donec varius, eros et convallis laoreet, ligula tellus consequat felis, ut ornare metus tellus sodales velit. Duis sed diam ante. Ut rutrum malesuada massa, vitae consectetur ipsum rhoncus sed. Suspendisse potenti. Pellentesque a congue massa.';
// print a blox of text using multicell()
$pdf->MultiCell(80, 5, $txt."\n", 1, 'J', 1, 1, '' ,'', true);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// AUTO-FITTING
// set color for background
$pdf->SetFillColor(255, 235, 235);
// Fit text on cell by reducing font size
$pdf->MultiCell(55, 60, '[FIT CELL] '.$txt."\n", 1, 'J', 1, 1, 125, 145, true, 0, false, true, 60, 'M', true);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// CUSTOM PADDING
// set color for background
$pdf->SetFillColor(255, 255, 215);
// set font
$pdf->SetFont('helvetica', '', 8);
// set cell padding
$pdf->setCellPaddings(2, 4, 6, 8);
$txt = "CUSTOM PADDING:\nLeft=2, Top=4, Right=6, Bottom=8\nLorem ipsum dolor sit amet, consectetur adipiscing elit. In sed imperdiet lectus. Phasellus quis velit velit, non condimentum quam. Sed neque urna, ultrices ac volutpat vel, laoreet vitae augue.\n";
$pdf->MultiCell(55, 5, $txt, 1, 'J', 1, 2, 125, 210, true);
// move pointer to last page
$pdf->lastPage();
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_005.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,330 @@
<?php
//============================================================+
// File name : example_006.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 006 for TCPDF class
// WriteHTML and RTL support
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: WriteHTML and RTL support
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 006');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 006', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('dejavusans', '', 10);
// add a page
$pdf->AddPage();
// writeHTML($html, $ln=true, $fill=false, $reseth=false, $cell=false, $align='')
// writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true)
// create some HTML content
$html = '<h1>HTML Example</h1>
Some special characters: &lt; &euro; &#8364; &amp; è &egrave; &copy; &gt; \\slash \\\\double-slash \\\\\\triple-slash
<h2>List</h2>
List example:
<ol>
<li><img src="images/logo_example.png" alt="test alt attribute" width="30" height="30" border="0" /> test image</li>
<li><b>bold text</b></li>
<li><i>italic text</i></li>
<li><u>underlined text</u></li>
<li><b>b<i>bi<u>biu</u>bi</i>b</b></li>
<li><a href="http://www.tecnick.com" dir="ltr">link to http://www.tecnick.com</a></li>
<li>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo.<br />Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.</li>
<li>SUBLIST
<ol>
<li>row one
<ul>
<li>sublist</li>
</ul>
</li>
<li>row two</li>
</ol>
</li>
<li><b>T</b>E<i>S</i><u>T</u> <del>line through</del></li>
<li><font size="+3">font + 3</font></li>
<li><small>small text</small> normal <small>small text</small> normal <sub>subscript</sub> normal <sup>superscript</sup> normal</li>
</ol>
<dl>
<dt>Coffee</dt>
<dd>Black hot drink</dd>
<dt>Milk</dt>
<dd>White cold drink</dd>
</dl>
<div style="text-align:center">IMAGES<br />
<img src="images/logo_example.png" alt="test alt attribute" width="100" height="100" border="0" /><img src="images/tcpdf_box.svg" alt="test alt attribute" width="100" height="100" border="0" /><img src="images/logo_example.jpg" alt="test alt attribute" width="100" height="100" border="0" />
</div>';
// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
// output some RTL HTML content
$html = '<div style="text-align:center">The words &#8220;<span dir="rtl">&#1502;&#1494;&#1500; [mazel] &#1496;&#1493;&#1489; [tov]</span>&#8221; mean &#8220;Congratulations!&#8221;</div>';
$pdf->writeHTML($html, true, false, true, false, '');
// test some inline CSS
$html = '<p>This is just an example of html code to demonstrate some supported CSS inline styles.
<span style="font-weight: bold;">bold text</span>
<span style="text-decoration: line-through;">line-trough</span>
<span style="text-decoration: underline line-through;">underline and line-trough</span>
<span style="color: rgb(0, 128, 64);">color</span>
<span style="background-color: rgb(255, 0, 0); color: rgb(255, 255, 255);">background color</span>
<span style="font-weight: bold;">bold</span>
<span style="font-size: xx-small;">xx-small</span>
<span style="font-size: x-small;">x-small</span>
<span style="font-size: small;">small</span>
<span style="font-size: medium;">medium</span>
<span style="font-size: large;">large</span>
<span style="font-size: x-large;">x-large</span>
<span style="font-size: xx-large;">xx-large</span>
</p>';
$pdf->writeHTML($html, true, false, true, false, '');
// reset pointer to the last page
$pdf->lastPage();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Print a table
// add a page
$pdf->AddPage();
// create some HTML content
$subtable = '<table border="1" cellspacing="6" cellpadding="4"><tr><td>a</td><td>b</td></tr><tr><td>c</td><td>d</td></tr></table>';
$html = '<h2>HTML TABLE:</h2>
<table border="1" cellspacing="3" cellpadding="4">
<tr>
<th>#</th>
<th align="right">RIGHT align</th>
<th align="left">LEFT align</th>
<th>4A</th>
</tr>
<tr>
<td>1</td>
<td bgcolor="#cccccc" align="center" colspan="2">A1 ex<i>amp</i>le <a href="http://www.tcpdf.org">link</a> column span. One two tree four five six seven eight nine ten.<br />line after br<br /><small>small text</small> normal <sub>subscript</sub> normal <sup>superscript</sup> normal bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla bla<ol><li>first<ol><li>sublist</li><li>sublist</li></ol></li><li>second</li></ol><small color="#FF0000" bgcolor="#FFFF00">small small small small small small small small small small small small small small small small small small small small</small></td>
<td>4B</td>
</tr>
<tr>
<td>'.$subtable.'</td>
<td bgcolor="#0000FF" color="yellow" align="center">A2 &euro; &#8364; &amp; è &egrave;<br/>A2 € &euro; &#8364; &amp; è &egrave;</td>
<td bgcolor="#FFFF00" align="left"><font color="#FF0000">Red</font> Yellow BG</td>
<td>4C</td>
</tr>
<tr>
<td>1A</td>
<td rowspan="2" colspan="2" bgcolor="#FFFFCC">2AA<br />2AB<br />2AC</td>
<td bgcolor="#FF0000">4D</td>
</tr>
<tr>
<td>1B</td>
<td>4E</td>
</tr>
<tr>
<td>1C</td>
<td>2C</td>
<td>3C</td>
<td>4F</td>
</tr>
</table>';
// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
// Print some HTML Cells
$html = '<span color="red">red</span> <span color="green">green</span> <span color="blue">blue</span><br /><span color="red">red</span> <span color="green">green</span> <span color="blue">blue</span>';
$pdf->SetFillColor(255,255,0);
$pdf->writeHTMLCell(0, 0, '', '', $html, 'LRTB', 1, 0, true, 'L', true);
$pdf->writeHTMLCell(0, 0, '', '', $html, 'LRTB', 1, 1, true, 'C', true);
$pdf->writeHTMLCell(0, 0, '', '', $html, 'LRTB', 1, 0, true, 'R', true);
// reset pointer to the last page
$pdf->lastPage();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Print a table
// add a page
$pdf->AddPage();
// create some HTML content
$html = '<h1>Image alignments on HTML table</h1>
<table cellpadding="1" cellspacing="1" border="1" style="text-align:center;">
<tr><td><img src="images/logo_example.png" border="0" height="41" width="41" /></td></tr>
<tr style="text-align:left;"><td><img src="images/logo_example.png" border="0" height="41" width="41" align="top" /></td></tr>
<tr style="text-align:center;"><td><img src="images/logo_example.png" border="0" height="41" width="41" align="middle" /></td></tr>
<tr style="text-align:right;"><td><img src="images/logo_example.png" border="0" height="41" width="41" align="bottom" /></td></tr>
<tr><td style="text-align:left;"><img src="images/logo_example.png" border="0" height="41" width="41" align="top" /></td></tr>
<tr><td style="text-align:center;"><img src="images/logo_example.png" border="0" height="41" width="41" align="middle" /></td></tr>
<tr><td style="text-align:right;"><img src="images/logo_example.png" border="0" height="41" width="41" align="bottom" /></td></tr>
</table>';
// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
// reset pointer to the last page
$pdf->lastPage();
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Print all HTML colors
// add a page
$pdf->AddPage();
$textcolors = '<h1>HTML Text Colors</h1>';
$bgcolors = '<hr /><h1>HTML Background Colors</h1>';
foreach(TCPDF_COLORS::$webcolor as $k => $v) {
$textcolors .= '<span color="#'.$v.'">'.$v.'</span> ';
$bgcolors .= '<span bgcolor="#'.$v.'" color="#333333">'.$v.'</span> ';
}
// output the HTML content
$pdf->writeHTML($textcolors, true, false, true, false, '');
$pdf->writeHTML($bgcolors, true, false, true, false, '');
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Test word-wrap
// create some HTML content
$html = '<hr />
<h1>Various tests</h1>
<a href="#2">link to page 2</a><br />
<font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font> <font face="courier"><b>thisisaverylongword</b></font> <font face="helvetica"><i>thisisanotherverylongword</i></font> <font face="times"><b>thisisaverylongword</b></font> thisisanotherverylongword <font face="times">thisisaverylongword</font>';
// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
// Test fonts nesting
$html1 = 'Default <font face="courier">Courier <font face="helvetica">Helvetica <font face="times">Times <font face="dejavusans">dejavusans </font>Times </font>Helvetica </font>Courier </font>Default';
$html2 = '<small>small text</small> normal <small>small text</small> normal <sub>subscript</sub> normal <sup>superscript</sup> normal';
$html3 = '<font size="10" color="#ff7f50">The</font> <font size="10" color="#6495ed">quick</font> <font size="14" color="#dc143c">brown</font> <font size="18" color="#008000">fox</font> <font size="22"><a href="http://www.tcpdf.org">jumps</a></font> <font size="22" color="#a0522d">over</font> <font size="18" color="#da70d6">the</font> <font size="14" color="#9400d3">lazy</font> <font size="10" color="#4169el">dog</font>.';
$html = $html1.'<br />'.$html2.'<br />'.$html3.'<br />'.$html3.'<br />'.$html2;
// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// test pre tag
// add a page
$pdf->AddPage();
$html = <<<EOF
<div style="background-color:#880000;color:white;">
Hello World!<br />
Hello
</div>
<pre style="background-color:#336699;color:white;">
int main() {
printf("HelloWorld");
return 0;
}
</pre>
<tt>Monospace font</tt>, normal font, <tt>monospace font</tt>, normal font.
<br />
<div style="background-color:#880000;color:white;">DIV LEVEL 1<div style="background-color:#008800;color:white;">DIV LEVEL 2</div>DIV LEVEL 1</div>
<br />
<span style="background-color:#880000;color:white;">SPAN LEVEL 1 <span style="background-color:#008800;color:white;">SPAN LEVEL 2</span> SPAN LEVEL 1</span>
EOF;
// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// test custom bullet points for list
// add a page
$pdf->AddPage();
$html = <<<EOF
<h1>Test custom bullet image for list items</h1>
<ul style="font-size:14pt;list-style-type:img|png|4|4|images/logo_example.png">
<li>test custom bullet image</li>
<li>test custom bullet image</li>
<li>test custom bullet image</li>
<li>test custom bullet image</li>
<ul>
EOF;
// output the HTML content
$pdf->writeHTML($html, true, false, true, false, '');
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// reset pointer to the last page
$pdf->lastPage();
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_006.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,113 @@
<?php
//============================================================+
// File name : example_007.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 007 for TCPDF class
// Two independent columns with WriteHTMLCell()
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Two independent columns with WriteHTMLCell()
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 007');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 007', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('times', '', 12);
// add a page
$pdf->AddPage();
// create columns content
$left_column = '<b>LEFT COLUMN</b> left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column';
$right_column = '<b>RIGHT COLUMN</b> right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column';
// writeHTMLCell($w, $h, $x, $y, $html='', $border=0, $ln=0, $fill=0, $reseth=true, $align='', $autopadding=true)
// get current vertical position
$y = $pdf->getY();
// set color for background
$pdf->SetFillColor(255, 255, 200);
// set color for text
$pdf->SetTextColor(0, 63, 127);
// write the first column
$pdf->writeHTMLCell(80, '', '', $y, $left_column, 1, 0, 1, true, 'J', true);
// set color for background
$pdf->SetFillColor(215, 235, 255);
// set color for text
$pdf->SetTextColor(127, 31, 0);
// write the second column
$pdf->writeHTMLCell(80, '', '', '', $right_column, 1, 1, 1, true, 'J', true);
// reset pointer to the last page
$pdf->lastPage();
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_007.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,97 @@
<?php
//============================================================+
// File name : example_008.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 008 for TCPDF class
// Include external UTF-8 text file
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Include external UTF-8 text file
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 008');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 008', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set default font subsetting mode
$pdf->setFontSubsetting(true);
// set font
$pdf->SetFont('freeserif', '', 12);
// add a page
$pdf->AddPage();
// get esternal file content
$utf8text = file_get_contents('data/utf8test.txt', false);
// set color for text
$pdf->SetTextColor(0, 63, 127);
//Write($h, $txt, $link='', $fill=0, $align='', $ln=false, $stretch=0, $firstline=false, $firstblock=false, $maxh=0)
// write the text
$pdf->Write(5, $utf8text, '', 0, '', false, 0, false, false, 0);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_008.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,146 @@
<?php
//============================================================+
// File name : example_009.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 009 for TCPDF class
// Test Image
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Test Image
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 009');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 009', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// -------------------------------------------------------------------
// add a page
$pdf->AddPage();
// set JPEG quality
$pdf->setJPEGQuality(75);
// Image method signature:
// Image($file, $x='', $y='', $w=0, $h=0, $type='', $link='', $align='', $resize=false, $dpi=300, $palign='', $ismask=false, $imgmask=false, $border=0, $fitbox=false, $hidden=false, $fitonpage=false)
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Example of Image from data stream ('PHP rules')
$imgdata = base64_decode('iVBORw0KGgoAAAANSUhEUgAAABwAAAASCAMAAAB/2U7WAAAABlBMVEUAAAD///+l2Z/dAAAASUlEQVR4XqWQUQoAIAxC2/0vXZDrEX4IJTRkb7lobNUStXsB0jIXIAMSsQnWlsV+wULF4Avk9fLq2r8a5HSE35Q3eO2XP1A1wQkZSgETvDtKdQAAAABJRU5ErkJggg==');
// The '@' character is used to indicate that follows an image data stream and not an image file name
$pdf->Image('@'.$imgdata);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Image example with resizing
$pdf->Image('images/image_demo.jpg', 15, 140, 75, 113, 'JPG', 'http://www.tcpdf.org', '', true, 150, '', false, false, 1, false, false, false);
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// test fitbox with all alignment combinations
$horizontal_alignments = array('L', 'C', 'R');
$vertical_alignments = array('T', 'M', 'B');
$x = 15;
$y = 35;
$w = 30;
$h = 30;
// test all combinations of alignments
for ($i = 0; $i < 3; ++$i) {
$fitbox = $horizontal_alignments[$i].' ';
$x = 15;
for ($j = 0; $j < 3; ++$j) {
$fitbox[1] = $vertical_alignments[$j];
$pdf->Rect($x, $y, $w, $h, 'F', array(), array(128,255,128));
$pdf->Image('images/image_demo.jpg', $x, $y, $w, $h, 'JPG', '', '', false, 300, '', false, false, 0, $fitbox, false, false);
$x += 32; // new column
}
$y += 32; // new row
}
$x = 115;
$y = 35;
$w = 25;
$h = 50;
for ($i = 0; $i < 3; ++$i) {
$fitbox = $horizontal_alignments[$i].' ';
$x = 115;
for ($j = 0; $j < 3; ++$j) {
$fitbox[1] = $vertical_alignments[$j];
$pdf->Rect($x, $y, $w, $h, 'F', array(), array(128,255,255));
$pdf->Image('images/image_demo.jpg', $x, $y, $w, $h, 'JPG', '', '', false, 300, '', false, false, 0, $fitbox, false, false);
$x += 27; // new column
}
$y += 52; // new row
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
// Stretching, position and alignment example
$pdf->SetXY(110, 200);
$pdf->Image('images/image_demo.jpg', '', '', 40, 40, '', '', 'T', false, 300, '', false, false, 1, false, false, false);
$pdf->Image('images/image_demo.jpg', '', '', 40, 40, '', '', '', false, 300, '', false, false, 1, false, false, false);
// -------------------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_009.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,150 @@
<?php
//============================================================+
// File name : example_010.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 010 for TCPDF class
// Text on multiple columns
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Text on multiple columns
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
/**
* Extend TCPDF to work with multiple columns
*/
class MC_TCPDF extends TCPDF {
/**
* Print chapter
* @param $num (int) chapter number
* @param $title (string) chapter title
* @param $file (string) name of the file containing the chapter body
* @param $mode (boolean) if true the chapter body is in HTML, otherwise in simple text.
* @public
*/
public function PrintChapter($num, $title, $file, $mode=false) {
// add a new page
$this->AddPage();
// disable existing columns
$this->resetColumns();
// print chapter title
$this->ChapterTitle($num, $title);
// set columns
$this->setEqualColumns(3, 57);
// print chapter body
$this->ChapterBody($file, $mode);
}
/**
* Set chapter title
* @param $num (int) chapter number
* @param $title (string) chapter title
* @public
*/
public function ChapterTitle($num, $title) {
$this->SetFont('helvetica', '', 14);
$this->SetFillColor(200, 220, 255);
$this->Cell(180, 6, 'Chapter '.$num.' : '.$title, 0, 1, '', 1);
$this->Ln(4);
}
/**
* Print chapter body
* @param $file (string) name of the file containing the chapter body
* @param $mode (boolean) if true the chapter body is in HTML, otherwise in simple text.
* @public
*/
public function ChapterBody($file, $mode=false) {
$this->selectColumn();
// get esternal file content
$content = file_get_contents($file, false);
// set font
$this->SetFont('times', '', 9);
$this->SetTextColor(50, 50, 50);
// print content
if ($mode) {
// ------ HTML MODE ------
$this->writeHTML($content, true, false, true, false, 'J');
} else {
// ------ TEXT MODE ------
$this->Write(0, $content, '', 0, 'J', true, 0, false, true, 0);
}
$this->Ln();
}
} // end of extended class
// ---------------------------------------------------------
// EXAMPLE
// ---------------------------------------------------------
// create new PDF document
$pdf = new MC_TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 010');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 010', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// print TEXT
$pdf->PrintChapter(1, 'LOREM IPSUM [TEXT]', 'data/chapter_demo_1.txt', false);
// print HTML
$pdf->PrintChapter(2, 'LOREM IPSUM [HTML]', 'data/chapter_demo_2.txt', true);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_010.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,138 @@
<?php
//============================================================+
// File name : example_011.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 011 for TCPDF class
// Colored Table (very simple table)
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Colored Table
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// extend TCPF with custom functions
class MYPDF extends TCPDF {
// Load table data from file
public function LoadData($file) {
// Read file lines
$lines = file($file);
$data = array();
foreach($lines as $line) {
$data[] = explode(';', chop($line));
}
return $data;
}
// Colored table
public function ColoredTable($header,$data) {
// Colors, line width and bold font
$this->SetFillColor(255, 0, 0);
$this->SetTextColor(255);
$this->SetDrawColor(128, 0, 0);
$this->SetLineWidth(0.3);
$this->SetFont('', 'B');
// Header
$w = array(40, 35, 40, 45);
$num_headers = count($header);
for($i = 0; $i < $num_headers; ++$i) {
$this->Cell($w[$i], 7, $header[$i], 1, 0, 'C', 1);
}
$this->Ln();
// Color and font restoration
$this->SetFillColor(224, 235, 255);
$this->SetTextColor(0);
$this->SetFont('');
// Data
$fill = 0;
foreach($data as $row) {
$this->Cell($w[0], 6, $row[0], 'LR', 0, 'L', $fill);
$this->Cell($w[1], 6, $row[1], 'LR', 0, 'L', $fill);
$this->Cell($w[2], 6, number_format($row[2]), 'LR', 0, 'R', $fill);
$this->Cell($w[3], 6, number_format($row[3]), 'LR', 0, 'R', $fill);
$this->Ln();
$fill=!$fill;
}
$this->Cell(array_sum($w), 0, '', 'T');
}
}
// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 011');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 011', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('helvetica', '', 12);
// add a page
$pdf->AddPage();
// column titles
$header = array('Country', 'Capital', 'Area (sq km)', 'Pop. (thousands)');
// data loading
$data = $pdf->LoadData('data/table_data_demo.txt');
// print colored table
$pdf->ColoredTable($header, $data);
// ---------------------------------------------------------
// close and output PDF document
$pdf->Output('example_011.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,205 @@
<?php
//============================================================+
// File name : example_012.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 012 for TCPDF class
// Graphic Functions
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Graphic Functions
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 012');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// disable header and footer
$pdf->setPrintHeader(false);
$pdf->setPrintFooter(false);
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('helvetica', '', 10);
// add a page
$pdf->AddPage();
$style = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => '10,20,5,10', 'phase' => 10, 'color' => array(255, 0, 0));
$style2 = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(255, 0, 0));
$style3 = array('width' => 1, 'cap' => 'round', 'join' => 'round', 'dash' => '2,10', 'color' => array(255, 0, 0));
$style4 = array('L' => 0,
'T' => array('width' => 0.25, 'cap' => 'butt', 'join' => 'miter', 'dash' => '20,10', 'phase' => 10, 'color' => array(100, 100, 255)),
'R' => array('width' => 0.50, 'cap' => 'round', 'join' => 'miter', 'dash' => 0, 'color' => array(50, 50, 127)),
'B' => array('width' => 0.75, 'cap' => 'square', 'join' => 'miter', 'dash' => '30,10,5,10'));
$style5 = array('width' => 0.25, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 64, 128));
$style6 = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => '10,10', 'color' => array(0, 128, 0));
$style7 = array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(255, 128, 0));
// Line
$pdf->Text(5, 4, 'Line examples');
$pdf->Line(5, 10, 80, 30, $style);
$pdf->Line(5, 10, 5, 30, $style2);
$pdf->Line(5, 10, 80, 10, $style3);
// Rect
$pdf->Text(100, 4, 'Rectangle examples');
$pdf->Rect(100, 10, 40, 20, 'DF', $style4, array(220, 220, 200));
$pdf->Rect(145, 10, 40, 20, 'D', array('all' => $style3));
// Curve
$pdf->Text(5, 34, 'Curve examples');
$pdf->Curve(5, 40, 30, 55, 70, 45, 60, 75, null, $style6);
$pdf->Curve(80, 40, 70, 75, 150, 45, 100, 75, 'F', $style6);
$pdf->Curve(140, 40, 150, 55, 180, 45, 200, 75, 'DF', $style6, array(200, 220, 200));
// Circle and ellipse
$pdf->Text(5, 79, 'Circle and ellipse examples');
$pdf->SetLineStyle($style5);
$pdf->Circle(25,105,20);
$pdf->Circle(25,105,10, 90, 180, null, $style6);
$pdf->Circle(25,105,10, 270, 360, 'F');
$pdf->Circle(25,105,10, 270, 360, 'C', $style6);
$pdf->SetLineStyle($style5);
$pdf->Ellipse(100,103,40,20);
$pdf->Ellipse(100,105,20,10, 0, 90, 180, null, $style6);
$pdf->Ellipse(100,105,20,10, 0, 270, 360, 'DF', $style6);
$pdf->SetLineStyle($style5);
$pdf->Ellipse(175,103,30,15,45);
$pdf->Ellipse(175,105,15,7.50, 45, 90, 180, null, $style6);
$pdf->Ellipse(175,105,15,7.50, 45, 270, 360, 'F', $style6, array(220, 200, 200));
// Polygon
$pdf->Text(5, 129, 'Polygon examples');
$pdf->SetLineStyle(array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
$pdf->Polygon(array(5,135,45,135,15,165));
$pdf->Polygon(array(60,135,80,135,80,155,70,165,50,155), 'DF', array($style6, $style7, $style7, 0, $style6), array(220, 200, 200));
$pdf->Polygon(array(120,135,140,135,150,155,110,155), 'D', array($style6, 0, $style7, $style6));
$pdf->Polygon(array(160,135,190,155,170,155,200,160,160,165), 'DF', array('all' => $style6), array(220, 220, 220));
// Polygonal Line
$pdf->SetLineStyle(array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 164)));
$pdf->PolyLine(array(80,165,90,160,100,165,110,160,120,165,130,160,140,165), 'D', array(), array());
// Regular polygon
$pdf->Text(5, 169, 'Regular polygon examples');
$pdf->SetLineStyle($style5);
$pdf->RegularPolygon(20, 190, 15, 6, 0, 1, 'F');
$pdf->RegularPolygon(55, 190, 15, 6);
$pdf->RegularPolygon(55, 190, 10, 6, 45, 0, 'DF', array($style6, 0, $style7, 0, $style7, $style7));
$pdf->RegularPolygon(90, 190, 15, 3, 0, 1, 'DF', array('all' => $style5), array(200, 220, 200), 'F', array(255, 200, 200));
$pdf->RegularPolygon(125, 190, 15, 4, 30, 1, null, array('all' => $style5), null, null, $style6);
$pdf->RegularPolygon(160, 190, 15, 10);
// Star polygon
$pdf->Text(5, 209, 'Star polygon examples');
$pdf->SetLineStyle($style5);
$pdf->StarPolygon(20, 230, 15, 20, 3, 0, 1, 'F');
$pdf->StarPolygon(55, 230, 15, 12, 5);
$pdf->StarPolygon(55, 230, 7, 12, 5, 45, 0, 'DF', array('all' => $style7), array(220, 220, 200), 'F', array(255, 200, 200));
$pdf->StarPolygon(90, 230, 15, 20, 6, 0, 1, 'DF', array('all' => $style5), array(220, 220, 200), 'F', array(255, 200, 200));
$pdf->StarPolygon(125, 230, 15, 5, 2, 30, 1, null, array('all' => $style5), null, null, $style6);
$pdf->StarPolygon(160, 230, 15, 10, 3);
$pdf->StarPolygon(160, 230, 7, 50, 26);
// Rounded rectangle
$pdf->Text(5, 249, 'Rounded rectangle examples');
$pdf->SetLineStyle(array('width' => 0.5, 'cap' => 'butt', 'join' => 'miter', 'dash' => 0, 'color' => array(0, 0, 0)));
$pdf->RoundedRect(5, 255, 40, 30, 3.50, '1111', 'DF');
$pdf->RoundedRect(50, 255, 40, 30, 6.50, '1000');
$pdf->RoundedRect(95, 255, 40, 30, 10.0, '1111', null, $style6);
$pdf->RoundedRect(140, 255, 40, 30, 8.0, '0101', 'DF', $style6, array(200, 200, 200));
// Arrows
$pdf->Text(185, 249, 'Arrows');
$pdf->SetLineStyle($style5);
$pdf->SetFillColor(255, 0, 0);
$pdf->Arrow(200, 280, 185, 266, 0, 5, 15);
$pdf->Arrow(200, 280, 190, 263, 1, 5, 15);
$pdf->Arrow(200, 280, 195, 261, 2, 5, 15);
$pdf->Arrow(200, 280, 200, 260, 3, 5, 15);
// - . - . - . - . - . - . - . - . - . - . - . - . - . - . -
// ellipse
// add a page
$pdf->AddPage();
$pdf->Cell(0, 0, 'Arc of Ellipse');
// center of ellipse
$xc=100;
$yc=100;
// X Y axis
$pdf->SetDrawColor(200, 200, 200);
$pdf->Line($xc-50, $yc, $xc+50, $yc);
$pdf->Line($xc, $yc-50, $xc, $yc+50);
// ellipse axis
$pdf->SetDrawColor(200, 220, 255);
$pdf->Line($xc-50, $yc-50, $xc+50, $yc+50);
$pdf->Line($xc-50, $yc+50, $xc+50, $yc-50);
// ellipse
$pdf->SetDrawColor(200, 255, 200);
$pdf->Ellipse($xc, $yc, 30, 15, 45, 0, 360, 'D', array(), array(), 2);
// ellipse arc
$pdf->SetDrawColor(255, 0, 0);
$pdf->Ellipse($xc, $yc, 30, 15, 45, 45, 90, 'D', array(), array(), 2);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_012.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,229 @@
<?php
//============================================================+
// File name : example_013.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 013 for TCPDF class
// Graphic Transformations
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Graphic Transformations
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 013');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 013', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('helvetica', 'B', 20);
// add a page
$pdf->AddPage();
$pdf->Write(0, 'Graphic Transformations', '', 0, 'C', 1, 0, false, false, 0);
// set font
$pdf->SetFont('helvetica', '', 10);
// --- Scaling ---------------------------------------------
$pdf->SetDrawColor(200);
$pdf->SetTextColor(200);
$pdf->Rect(50, 70, 40, 10, 'D');
$pdf->Text(50, 66, 'Scale');
$pdf->SetDrawColor(0);
$pdf->SetTextColor(0);
// Start Transformation
$pdf->StartTransform();
// Scale by 150% centered by (50,80) which is the lower left corner of the rectangle
$pdf->ScaleXY(150, 50, 80);
$pdf->Rect(50, 70, 40, 10, 'D');
$pdf->Text(50, 66, 'Scale');
// Stop Transformation
$pdf->StopTransform();
// --- Translation -----------------------------------------
$pdf->SetDrawColor(200);
$pdf->SetTextColor(200);
$pdf->Rect(125, 70, 40, 10, 'D');
$pdf->Text(125, 66, 'Translate');
$pdf->SetDrawColor(0);
$pdf->SetTextColor(0);
// Start Transformation
$pdf->StartTransform();
// Translate 7 to the right, 5 to the bottom
$pdf->Translate(7, 5);
$pdf->Rect(125, 70, 40, 10, 'D');
$pdf->Text(125, 66, 'Translate');
// Stop Transformation
$pdf->StopTransform();
// --- Rotation --------------------------------------------
$pdf->SetDrawColor(200);
$pdf->SetTextColor(200);
$pdf->Rect(70, 100, 40, 10, 'D');
$pdf->Text(70, 96, 'Rotate');
$pdf->SetDrawColor(0);
$pdf->SetTextColor(0);
// Start Transformation
$pdf->StartTransform();
// Rotate 20 degrees counter-clockwise centered by (70,110) which is the lower left corner of the rectangle
$pdf->Rotate(20, 70, 110);
$pdf->Rect(70, 100, 40, 10, 'D');
$pdf->Text(70, 96, 'Rotate');
// Stop Transformation
$pdf->StopTransform();
// --- Skewing ---------------------------------------------
$pdf->SetDrawColor(200);
$pdf->SetTextColor(200);
$pdf->Rect(125, 100, 40, 10, 'D');
$pdf->Text(125, 96, 'Skew');
$pdf->SetDrawColor(0);
$pdf->SetTextColor(0);
// Start Transformation
$pdf->StartTransform();
// skew 30 degrees along the x-axis centered by (125,110) which is the lower left corner of the rectangle
$pdf->SkewX(30, 125, 110);
$pdf->Rect(125, 100, 40, 10, 'D');
$pdf->Text(125, 96, 'Skew');
// Stop Transformation
$pdf->StopTransform();
// --- Mirroring horizontally ------------------------------
$pdf->SetDrawColor(200);
$pdf->SetTextColor(200);
$pdf->Rect(70, 130, 40, 10, 'D');
$pdf->Text(70, 126, 'MirrorH');
$pdf->SetDrawColor(0);
$pdf->SetTextColor(0);
// Start Transformation
$pdf->StartTransform();
// mirror horizontally with axis of reflection at x-position 70 (left side of the rectangle)
$pdf->MirrorH(70);
$pdf->Rect(70, 130, 40, 10, 'D');
$pdf->Text(70, 126, 'MirrorH');
// Stop Transformation
$pdf->StopTransform();
// --- Mirroring vertically --------------------------------
$pdf->SetDrawColor(200);
$pdf->SetTextColor(200);
$pdf->Rect(125, 130, 40, 10, 'D');
$pdf->Text(125, 126, 'MirrorV');
$pdf->SetDrawColor(0);
$pdf->SetTextColor(0);
// Start Transformation
$pdf->StartTransform();
// mirror vertically with axis of reflection at y-position 140 (bottom side of the rectangle)
$pdf->MirrorV(140);
$pdf->Rect(125, 130, 40, 10, 'D');
$pdf->Text(125, 126, 'MirrorV');
// Stop Transformation
$pdf->StopTransform();
// --- Point reflection ------------------------------------
$pdf->SetDrawColor(200);
$pdf->SetTextColor(200);
$pdf->Rect(70, 160, 40, 10, 'D');
$pdf->Text(70, 156, 'MirrorP');
$pdf->SetDrawColor(0);
$pdf->SetTextColor(0);
// Start Transformation
$pdf->StartTransform();
// point reflection at the lower left point of rectangle
$pdf->MirrorP(70,170);
$pdf->Rect(70, 160, 40, 10, 'D');
$pdf->Text(70, 156, 'MirrorP');
// Stop Transformation
$pdf->StopTransform();
// --- Mirroring against a straigth line described by a point (120, 120) and an angle -20°
$angle=-20;
$px=120;
$py=170;
// just for visualisation: the straight line to mirror against
$pdf->SetDrawColor(200);
$pdf->Line($px-1,$py-1,$px+1,$py+1);
$pdf->Line($px-1,$py+1,$px+1,$py-1);
$pdf->StartTransform();
$pdf->Rotate($angle, $px, $py);
$pdf->Line($px-5, $py, $px+60, $py);
$pdf->StopTransform();
$pdf->SetDrawColor(200);
$pdf->SetTextColor(200);
$pdf->Rect(125, 160, 40, 10, 'D');
$pdf->Text(125, 156, 'MirrorL');
$pdf->SetDrawColor(0);
$pdf->SetTextColor(0);
//Start Transformation
$pdf->StartTransform();
//mirror against the straight line
$pdf->MirrorL($angle, $px, $py);
$pdf->Rect(125, 160, 40, 10, 'D');
$pdf->Text(125, 156, 'MirrorL');
//Stop Transformation
$pdf->StopTransform();
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_013.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,194 @@
<?php
//============================================================+
// File name : example_014.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 014 for TCPDF class
// Javascript Form and user rights (only works on Adobe Acrobat)
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Javascript Form and user rights (only works on Adobe Acrobat)
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 014');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 014', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// IMPORTANT: disable font subsetting to allow users editing the document
$pdf->setFontSubsetting(false);
// set font
$pdf->SetFont('helvetica', '', 10, '', false);
// add a page
$pdf->AddPage();
/*
It is possible to create text fields, combo boxes, check boxes and buttons.
Fields are created at the current position and are given a name.
This name allows to manipulate them via JavaScript in order to perform some validation for instance.
*/
// set default form properties
$pdf->setFormDefaultProp(array('lineWidth'=>1, 'borderStyle'=>'solid', 'fillColor'=>array(255, 255, 200), 'strokeColor'=>array(255, 128, 128)));
$pdf->SetFont('helvetica', 'BI', 18);
$pdf->Cell(0, 5, 'Example of Form', 0, 1, 'C');
$pdf->Ln(10);
$pdf->SetFont('helvetica', '', 12);
// First name
$pdf->Cell(35, 5, 'First name:');
$pdf->TextField('firstname', 50, 5);
$pdf->Ln(6);
// Last name
$pdf->Cell(35, 5, 'Last name:');
$pdf->TextField('lastname', 50, 5);
$pdf->Ln(6);
// Gender
$pdf->Cell(35, 5, 'Gender:');
$pdf->ComboBox('gender', 30, 5, array(array('', '-'), array('M', 'Male'), array('F', 'Female')));
$pdf->Ln(6);
// Drink
$pdf->Cell(35, 5, 'Drink:');
//$pdf->RadioButton('drink', 5, array('readonly' => 'true'), array(), 'Water');
$pdf->RadioButton('drink', 5, array(), array(), 'Water');
$pdf->Cell(35, 5, 'Water');
$pdf->Ln(6);
$pdf->Cell(35, 5, '');
$pdf->RadioButton('drink', 5, array(), array(), 'Beer', true);
$pdf->Cell(35, 5, 'Beer');
$pdf->Ln(6);
$pdf->Cell(35, 5, '');
$pdf->RadioButton('drink', 5, array(), array(), 'Wine');
$pdf->Cell(35, 5, 'Wine');
$pdf->Ln(6);
$pdf->Cell(35, 5, '');
$pdf->RadioButton('drink', 5, array(), array(), 'Milk');
$pdf->Cell(35, 5, 'Milk');
$pdf->Ln(10);
// Newsletter
$pdf->Cell(35, 5, 'Newsletter:');
$pdf->CheckBox('newsletter', 5, true, array(), array(), 'OK');
$pdf->Ln(10);
// Address
$pdf->Cell(35, 5, 'Address:');
$pdf->TextField('address', 60, 18, array('multiline'=>true, 'lineWidth'=>0, 'borderStyle'=>'none'), array('v'=>'Lorem ipsum dolor sit amet, consectetur adipiscing elit.', 'dv'=>'Lorem ipsum dolor sit amet, consectetur adipiscing elit.'));
$pdf->Ln(19);
// Listbox
$pdf->Cell(35, 5, 'List:');
$pdf->ListBox('listbox', 60, 15, array('', 'item1', 'item2', 'item3', 'item4', 'item5', 'item6', 'item7'), array('multipleSelection'=>'true'));
$pdf->Ln(20);
// E-mail
$pdf->Cell(35, 5, 'E-mail:');
$pdf->TextField('email', 50, 5);
$pdf->Ln(6);
// Date of the day
$pdf->Cell(35, 5, 'Date:');
$pdf->TextField('date', 30, 5, array(), array('v'=>date('Y-m-d'), 'dv'=>date('Y-m-d')));
$pdf->Ln(10);
$pdf->SetX(50);
// Button to validate and print
$pdf->Button('print', 30, 10, 'Print', 'Print()', array('lineWidth'=>2, 'borderStyle'=>'beveled', 'fillColor'=>array(128, 196, 255), 'strokeColor'=>array(64, 64, 64)));
// Reset Button
$pdf->Button('reset', 30, 10, 'Reset', array('S'=>'ResetForm'), array('lineWidth'=>2, 'borderStyle'=>'beveled', 'fillColor'=>array(128, 196, 255), 'strokeColor'=>array(64, 64, 64)));
// Submit Button
$pdf->Button('submit', 30, 10, 'Submit', array('S'=>'SubmitForm', 'F'=>'http://localhost/printvars.php', 'Flags'=>array('ExportFormat')), array('lineWidth'=>2, 'borderStyle'=>'beveled', 'fillColor'=>array(128, 196, 255), 'strokeColor'=>array(64, 64, 64)));
// Form validation functions
$js = <<<EOD
function CheckField(name,message) {
var f = getField(name);
if(f.value == '') {
app.alert(message);
f.setFocus();
return false;
}
return true;
}
function Print() {
if(!CheckField('firstname','First name is mandatory')) {return;}
if(!CheckField('lastname','Last name is mandatory')) {return;}
if(!CheckField('gender','Gender is mandatory')) {return;}
if(!CheckField('address','Address is mandatory')) {return;}
print();
}
EOD;
// Add Javascript code
$pdf->IncludeJS($js);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_014.pdf', 'D');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,161 @@
<?php
//============================================================+
// File name : example_015.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 015 for TCPDF class
// Bookmarks (Table of Content)
// and Named Destinations.
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Bookmarks (Table of Content)
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 015');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 015', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// Bookmark($txt, $level=0, $y=-1, $page='', $style='', $color=array(0,0,0))
// set font
$pdf->SetFont('times', 'B', 20);
// add a page
$pdf->AddPage();
// set a bookmark for the current position
$pdf->Bookmark('Chapter 1', 0, 0, '', 'B', array(0,64,128));
// print a line using Cell()
$pdf->Cell(0, 10, 'Chapter 1', 0, 1, 'L');
$pdf->SetFont('times', 'I', 14);
$pdf->Write(0, 'You can set PDF Bookmarks using the Bookmark() method.
You can set PDF Named Destinations using the setDestination() method.');
$pdf->SetFont('times', 'B', 20);
// add other pages and bookmarks
$pdf->AddPage();
$pdf->Bookmark('Paragraph 1.1', 1, 0, '', '', array(0,0,0));
$pdf->Cell(0, 10, 'Paragraph 1.1', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Paragraph 1.2', 1, 0, '', '', array(0,0,0));
$pdf->Cell(0, 10, 'Paragraph 1.2', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Sub-Paragraph 1.2.1', 2, 0, '', 'I', array(0,0,0));
$pdf->Cell(0, 10, 'Sub-Paragraph 1.2.1', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Paragraph 1.3', 1, 0, '', '', array(0,0,0));
$pdf->Cell(0, 10, 'Paragraph 1.3', 0, 1, 'L');
$pdf->AddPage();
// add a named destination so you can open this document at this page using the link: "example_015.pdf#chapter2"
$pdf->setDestination('chapter2', 0, '');
// add a bookmark that points to a named destination
$pdf->Bookmark('Chapter 2', 0, 0, '', 'BI', array(128,0,0), -1, '#chapter2');
$pdf->Cell(0, 10, 'Chapter 2', 0, 1, 'L');
$pdf->SetFont('times', 'I', 14);
$pdf->Write(0, 'Once saved, you can open this document at this page using the link: "example_015.pdf#chapter2".');
$pdf->AddPage();
$pdf->setDestination('chapter3', 0, '');
$pdf->SetFont('times', 'B', 20);
$pdf->Bookmark('Chapter 3', 0, 0, '', 'B', array(0,64,128));
$pdf->Cell(0, 10, 'Chapter 3', 0, 1, 'L');
$pdf->AddPage();
$pdf->setDestination('chapter4', 0, '');
$pdf->SetFont('times', 'B', 20);
$pdf->Bookmark('Chapter 4', 0, 0, '', 'B', array(0,64,128));
$pdf->Cell(0, 10, 'Chapter 4', 0, 1, 'L');
$pdf->AddPage();
$pdf->Bookmark('Chapter 5', 0, 0, '', 'B', array(0,128,0));
$pdf->Cell(0, 10, 'Chapter 5', 0, 1, 'L');
$txt = 'Example of File Attachment.
Double click on the icon to open the attached file.';
$pdf->SetFont('helvetica', '', 10);
$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);
// attach an external file TXT file
$pdf->Annotation(20, 50, 5, 5, 'TXT file', array('Subtype'=>'FileAttachment', 'Name' => 'PushPin', 'FS' => 'data/utf8test.txt'));
// attach an external file
$pdf->Annotation(50, 50, 5, 5, 'PDF file', array('Subtype'=>'FileAttachment', 'Name' => 'PushPin', 'FS' => 'example_012.pdf'));
// add a bookmark that points to an embedded file
// NOTE: prefix the file name with the * character for generic file and with % character for PDF file
$pdf->Bookmark('TXT file', 0, 0, '', 'B', array(128,0,255), -1, '*utf8test.txt');
// add a bookmark that points to an embedded file
// NOTE: prefix the file name with the * character for generic file and with % character for PDF file
$pdf->Bookmark('PDF file', 0, 0, '', 'B', array(128,0,255), -1, '%example_012.pdf');
// add a bookmark that points to an external URL
$pdf->Bookmark('External URL', 0, 0, '', 'B', array(0,0,255), -1, 'http://www.tcpdf.org');
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_015.pdf', 'D');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,134 @@
<?php
//============================================================+
// File name : example_016.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 016 for TCPDF class
// Document Encryption / Security
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Document Encryption / Security
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// *** Set PDF protection (encryption) *********************
/*
The permission array is composed of values taken from the following ones (specify the ones you want to block):
- print : Print the document;
- modify : Modify the contents of the document by operations other than those controlled by 'fill-forms', 'extract' and 'assemble';
- copy : Copy or otherwise extract text and graphics from the document;
- annot-forms : Add or modify text annotations, fill in interactive form fields, and, if 'modify' is also set, create or modify interactive form fields (including signature fields);
- fill-forms : Fill in existing interactive form fields (including signature fields), even if 'annot-forms' is not specified;
- extract : Extract text and graphics (in support of accessibility to users with disabilities or for other purposes);
- assemble : Assemble the document (insert, rotate, or delete pages and create bookmarks or thumbnail images), even if 'modify' is not set;
- print-high : Print the document to a representation from which a faithful digital copy of the PDF content could be generated. When this is not set, printing is limited to a low-level representation of the appearance, possibly of degraded quality.
- owner : (inverted logic - only for public-key) when set permits change of encryption and enables all other permissions.
If you don't set any password, the document will open as usual.
If you set a user password, the PDF viewer will ask for it before displaying the document.
The master (owner) password, if different from the user one, can be used to get full document access.
Possible encryption modes are:
0 = RSA 40 bit
1 = RSA 128 bit
2 = AES 128 bit
3 = AES 256 bit
NOTES:
- To create self-signed signature: openssl req -x509 -nodes -days 365000 -newkey rsa:1024 -keyout tcpdf.crt -out tcpdf.crt
- To export crt to p12: openssl pkcs12 -export -in tcpdf.crt -out tcpdf.p12
- To convert pfx certificate to pem: openssl pkcs12 -in tcpdf.pfx -out tcpdf.crt -nodes
*/
$pdf->SetProtection(array('print', 'copy'), '', null, 0, null);
// Example with public-key
// To open the document you need to install the private key (tcpdf.p12) on the Acrobat Reader. The password is: 1234
//$pdf->SetProtection($permissions=array('print', 'copy'), $user_pass='', $owner_pass=null, $mode=1, $pubkeys=array(array('c' => 'file://../config/cert/tcpdf.crt', 'p' => array('print'))));
// *********************************************************
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 016');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 016', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array('helvetica', '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array('helvetica', '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('times', '', 16);
// add a page
$pdf->AddPage();
// set some text to print
$txt = <<<EOD
Encryption Example
Consult the source code documentation for the SetProtection() method.
EOD;
// print a block of text using Write()
$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_016.pdf', 'D');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,117 @@
<?php
//============================================================+
// File name : example_017.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 017 for TCPDF class
// Two independent columns with MultiCell
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Two independent columns with MultiCell
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 017');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 017', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('helvetica', '', 20);
// add a page
$pdf->AddPage();
$pdf->Write(0, 'Example of independent Multicell() columns', '', 0, 'L', true, 0, false, false, 0);
$pdf->Ln(5);
$pdf->SetFont('times', '', 12);
// create columns content
// create columns content
$left_column = '[LEFT COLUMN] left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column left column'."\n";
$right_column = '[RIGHT COLUMN] right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column right column'."\n";
// MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0, $ishtml=false, $autopadding=true, $maxh=0)
// set color for background
$pdf->SetFillColor(255, 255, 200);
// set color for text
$pdf->SetTextColor(0, 63, 127);
// write the first column
$pdf->MultiCell(80, 0, $left_column, 1, 'J', 1, 0, '', '', true, 0, false, true, 0);
// set color for background
$pdf->SetFillColor(215, 235, 255);
// set color for text
$pdf->SetTextColor(127, 31, 0);
// write the second column
$pdf->MultiCell(80, 0, $right_column, 1, 'J', 1, 1, '', '', true, 0, false, true, 0);
// reset pointer to the last page
$pdf->lastPage();
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_017.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,128 @@
<?php
//============================================================+
// File name : example_018.php
// Begin : 2008-03-06
// Last Update : 2013-05-14
//
// Description : Example 018 for TCPDF class
// RTL document with Persian language
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: RTL document with Persian language
* @author Nicola Asuni
* @since 2008-03-06
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 018');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 018', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language dependent data:
$lg = Array();
$lg['a_meta_charset'] = 'UTF-8';
$lg['a_meta_dir'] = 'rtl';
$lg['a_meta_language'] = 'fa';
$lg['w_page'] = 'page';
// set some language-dependent strings (optional)
$pdf->setLanguageArray($lg);
// ---------------------------------------------------------
// set font
$pdf->SetFont('dejavusans', '', 12);
// add a page
$pdf->AddPage();
// Persian and English content
$htmlpersian = '<span color="#660000">Persian example:</span><br />سلام بالاخره مشکل PDF فارسی به طور کامل حل شد. اینم یک نمونش.<br />مشکل حرف \"ژ\" در بعضی کلمات مانند کلمه ویژه نیز بر طرف شد.<br />نگارش حروف لام و الف پشت سر هم نیز تصحیح شد.<br />با تشکر از "Asuni Nicola" و محمد علی گل کار برای پشتیبانی زبان فارسی.';
$pdf->WriteHTML($htmlpersian, true, 0, true, 0);
// set LTR direction for english translation
$pdf->setRTL(false);
$pdf->SetFontSize(10);
// print newline
$pdf->Ln();
// Persian and English content
$htmlpersiantranslation = '<span color="#0000ff">Hi, At last Problem of Persian PDF Solved completely. This is a example for it.<br />Problem of "jeh" letter in some word like "ویژه" (=special) fix too.<br />The joining of laa and alf letter fix now.<br />Special thanks to "Nicola Asuni" and "Mohamad Ali Golkar" for Persian support.</span>';
$pdf->WriteHTML($htmlpersiantranslation, true, 0, true, 0);
// Restore RTL direction
$pdf->setRTL(true);
// set font
$pdf->SetFont('aefurat', '', 18);
// print newline
$pdf->Ln();
// Arabic and English content
$pdf->Cell(0, 12, 'بِسْمِ اللهِ الرَّحْمنِ الرَّحِيمِ',0,1,'C');
$htmlcontent = 'تمَّ بِحمد الله حلّ مشكلة الكتابة باللغة العربية في ملفات الـ<span color="#FF0000">PDF</span> مع دعم الكتابة <span color="#0000FF">من اليمين إلى اليسار</span> و<span color="#009900">الحركَات</span> .<br />تم الحل بواسطة <span color="#993399">صالح المطرفي و Asuni Nicola</span> . ';
$pdf->WriteHTML($htmlcontent, true, 0, true, 0);
// set LTR direction for english translation
$pdf->setRTL(false);
// print newline
$pdf->Ln();
$pdf->SetFont('aealarabiya', '', 18);
// Arabic and English content
$htmlcontent2 = '<span color="#0000ff">This is Arabic "العربية" Example With TCPDF.</span>';
$pdf->WriteHTML($htmlcontent2, true, 0, true, 0);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_018.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,98 @@
<?php
//============================================================+
// File name : example_019.php
// Begin : 2008-03-07
// Last Update : 2013-05-14
//
// Description : Example 019 for TCPDF class
// Non unicode with alternative config file
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Non unicode with alternative config file
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, false, 'ISO-8859-1', false);
// Set document information dictionary in unicode mode
$pdf->SetDocInfoUnicode(true);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni [€]');
$pdf->SetTitle('TCPDF Example 019');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 019', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language dependent data:
$lg = Array();
$lg['a_meta_charset'] = 'ISO-8859-1';
$lg['a_meta_dir'] = 'ltr';
$lg['a_meta_language'] = 'en';
$lg['w_page'] = 'page';
// set some language-dependent strings (optional)
$pdf->setLanguageArray($lg);
// ---------------------------------------------------------
// set font
$pdf->SetFont('helvetica', '', 12);
// add a page
$pdf->AddPage();
// set color for background
$pdf->SetFillColor(200, 255, 200);
$txt = 'An alternative configuration file is used on this example.
Check the definition of the K_TCPDF_EXTERNAL_CONFIG constant on the source code.';
// print some text
$pdf->MultiCell(0, 0, $txt."\n", 1, 'J', 1, 1, '', '', true, 0, false, true, 0);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_019.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,146 @@
<?php
//============================================================+
// File name : example_020.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 020 for TCPDF class
// Two columns composed by MultiCell of different
// heights
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Two columns composed by MultiCell of different heights
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// extend TCPF with custom functions
class MYPDF extends TCPDF {
public function MultiRow($left, $right) {
// MultiCell($w, $h, $txt, $border=0, $align='J', $fill=0, $ln=1, $x='', $y='', $reseth=true, $stretch=0)
$page_start = $this->getPage();
$y_start = $this->GetY();
// write the left cell
$this->MultiCell(40, 0, $left, 1, 'R', 1, 2, '', '', true, 0);
$page_end_1 = $this->getPage();
$y_end_1 = $this->GetY();
$this->setPage($page_start);
// write the right cell
$this->MultiCell(0, 0, $right, 1, 'J', 0, 1, $this->GetX() ,$y_start, true, 0);
$page_end_2 = $this->getPage();
$y_end_2 = $this->GetY();
// set the new row position by case
if (max($page_end_1,$page_end_2) == $page_start) {
$ynew = max($y_end_1, $y_end_2);
} elseif ($page_end_1 == $page_end_2) {
$ynew = max($y_end_1, $y_end_2);
} elseif ($page_end_1 > $page_end_2) {
$ynew = $y_end_1;
} else {
$ynew = $y_end_2;
}
$this->setPage(max($page_end_1,$page_end_2));
$this->SetXY($this->GetX(),$ynew);
}
}
// create new PDF document
$pdf = new MYPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 020');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 020', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('helvetica', '', 20);
// add a page
$pdf->AddPage();
$pdf->Write(0, 'Example of text layout using Multicell()', '', 0, 'L', true, 0, false, false, 0);
$pdf->Ln(5);
$pdf->SetFont('times', '', 9);
//$pdf->SetCellPadding(0);
//$pdf->SetLineWidth(2);
// set color for background
$pdf->SetFillColor(255, 255, 200);
$text = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In sed imperdiet lectus. Phasellus quis velit velit, non condimentum quam. Sed neque urna, ultrices ac volutpat vel, laoreet vitae augue. Sed vel velit erat. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Cras eget velit nulla, eu sagittis elit. Nunc ac arcu est, in lobortis tellus. Praesent condimentum rhoncus sodales. In hac habitasse platea dictumst. Proin porta eros pharetra enim tincidunt dignissim nec vel dolor. Cras sapien elit, ornare ac dignissim eu, ultricies ac eros. Maecenas augue magna, ultrices a congue in, mollis eu nulla. Nunc venenatis massa at est eleifend faucibus. Vivamus sed risus lectus, nec interdum nunc.
Fusce et felis vitae diam lobortis sollicitudin. Aenean tincidunt accumsan nisi, id vehicula quam laoreet elementum. Phasellus egestas interdum erat, et viverra ipsum ultricies ac. Praesent sagittis augue at augue volutpat eleifend. Cras nec orci neque. Mauris bibendum posuere blandit. Donec feugiat mollis dui sit amet pellentesque. Sed a enim justo. Donec tincidunt, nisl eget elementum aliquam, odio ipsum ultrices quam, eu porttitor ligula urna at lorem. Donec varius, eros et convallis laoreet, ligula tellus consequat felis, ut ornare metus tellus sodales velit. Duis sed diam ante. Ut rutrum malesuada massa, vitae consectetur ipsum rhoncus sed. Suspendisse potenti. Pellentesque a congue massa.';
// print some rows just as example
for ($i = 0; $i < 10; ++$i) {
$pdf->MultiRow('Row '.($i+1), $text."\n");
}
// reset pointer to the last page
$pdf->lastPage();
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_020.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,91 @@
<?php
//============================================================+
// File name : example_021.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 021 for TCPDF class
// WriteHTML text flow
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: WriteHTML text flow.
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 021');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 021', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('helvetica', '', 9);
// add a page
$pdf->AddPage();
// create some HTML content
$html = '<h1>Example of HTML text flow</h1>Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit, sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt. Neque porro quisquam est, qui dolorem ipsum quia dolor sit amet, consectetur, adipisci velit, sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem. <em>Ut enim ad minima veniam, quis nostrum exercitationem ullam corporis suscipit laboriosam, nisi ut aliquid ex ea commodi consequatur?</em> <em>Quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae consequatur, vel illum qui dolorem eum fugiat quo voluptas nulla pariatur?</em><br /><br /><b>A</b> + <b>B</b> = <b>C</b> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>B</i> = <i>A</i> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>A</i> = <i>B</i> -&gt; &nbsp;&nbsp; <b>A</b> + <b>B</b> = <b>C</b> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>B</i> = <i>A</i> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>A</i> = <i>B</i> -&gt; &nbsp;&nbsp; <b>A</b> + <b>B</b> = <b>C</b> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>B</i> = <i>A</i> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>A</i> = <i>B</i> -&gt; &nbsp;&nbsp; <b>A</b> + <b>B</b> = <b>C</b> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>B</i> = <i>A</i> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>A</i> = <i>B</i> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <b>A</b> + <b>B</b> = <b>C</b> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>B</i> = <i>A</i> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>A</i> = <i>B</i> -&gt; &nbsp;&nbsp; <b>A</b> + <b>B</b> = <b>C</b> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>B</i> = <i>A</i> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>A</i> = <i>B</i> -&gt; &nbsp;&nbsp; <b>A</b> + <b>B</b> = <b>C</b> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>B</i> = <i>A</i> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>A</i> = <i>B</i> -&gt; &nbsp;&nbsp; <b>A</b> + <b>B</b> = <b>C</b> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>B</i> = <i>A</i> &nbsp;&nbsp; -&gt; &nbsp;&nbsp; <i>C</i> - <i>A</i> = <i>B</i><br /><br /><b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u> <b>Bold</b><i>Italic</i><u>Underlined</u>';
// output the HTML content
$pdf->writeHTML($html, true, 0, true, 0);
// reset pointer to the last page
$pdf->lastPage();
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_021.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,146 @@
<?php
//============================================================+
// File name : example_022.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 022 for TCPDF class
// CMYK colors
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: CMYK colors.
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 022');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 022', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// check also the following methods:
// SetDrawColorArray()
// SetFillColorArray()
// SetTextColorArray()
// set font
$pdf->SetFont('helvetica', 'B', 18);
// add a page
$pdf->AddPage();
$pdf->Write(0, 'Example of CMYK, RGB and Grayscale colours', '', 0, 'L', true, 0, false, false, 0);
// define style for border
$border_style = array('all' => array('width' => 2, 'cap' => 'square', 'join' => 'miter', 'dash' => 0, 'phase' => 0));
// --- CMYK ------------------------------------------------
$pdf->SetDrawColor(50, 0, 0, 0);
$pdf->SetFillColor(100, 0, 0, 0);
$pdf->SetTextColor(100, 0, 0, 0);
$pdf->Rect(30, 60, 30, 30, 'DF', $border_style);
$pdf->Text(30, 92, 'Cyan');
$pdf->SetDrawColor(0, 50, 0, 0);
$pdf->SetFillColor(0, 100, 0, 0);
$pdf->SetTextColor(0, 100, 0, 0);
$pdf->Rect(70, 60, 30, 30, 'DF', $border_style);
$pdf->Text(70, 92, 'Magenta');
$pdf->SetDrawColor(0, 0, 50, 0);
$pdf->SetFillColor(0, 0, 100, 0);
$pdf->SetTextColor(0, 0, 100, 0);
$pdf->Rect(110, 60, 30, 30, 'DF', $border_style);
$pdf->Text(110, 92, 'Yellow');
$pdf->SetDrawColor(0, 0, 0, 50);
$pdf->SetFillColor(0, 0, 0, 100);
$pdf->SetTextColor(0, 0, 0, 100);
$pdf->Rect(150, 60, 30, 30, 'DF', $border_style);
$pdf->Text(150, 92, 'Black');
// --- RGB -------------------------------------------------
$pdf->SetDrawColor(255, 127, 127);
$pdf->SetFillColor(255, 0, 0);
$pdf->SetTextColor(255, 0, 0);
$pdf->Rect(30, 110, 30, 30, 'DF', $border_style);
$pdf->Text(30, 142, 'Red');
$pdf->SetDrawColor(127, 255, 127);
$pdf->SetFillColor(0, 255, 0);
$pdf->SetTextColor(0, 255, 0);
$pdf->Rect(70, 110, 30, 30, 'DF', $border_style);
$pdf->Text(70, 142, 'Green');
$pdf->SetDrawColor(127, 127, 255);
$pdf->SetFillColor(0, 0, 255);
$pdf->SetTextColor(0, 0, 255);
$pdf->Rect(110, 110, 30, 30, 'DF', $border_style);
$pdf->Text(110, 142, 'Blue');
// --- GRAY ------------------------------------------------
$pdf->SetDrawColor(191);
$pdf->SetFillColor(127);
$pdf->SetTextColor(127);
$pdf->Rect(30, 160, 30, 30, 'DF', $border_style);
$pdf->Text(30, 192, 'Gray');
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_022.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,113 @@
<?php
//============================================================+
// File name : example_023.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 023 for TCPDF class
// Page Groups
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Page Groups.
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 023');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 023', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('times', 'BI', 14);
// Start First Page Group
$pdf->startPageGroup();
// add a page
$pdf->AddPage();
// set some text to print
$txt = <<<EOD
Example of page groups.
Check the page numbers on the page footer.
This is the first page of group 1.
EOD;
// print a block of text using Write()
$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);
// add second page
$pdf->AddPage();
$pdf->Cell(0, 10, 'This is the second page of group 1', 0, 1, 'L');
// Start Second Page Group
$pdf->startPageGroup();
// add some pages
$pdf->AddPage();
$pdf->Cell(0, 10, 'This is the first page of group 2', 0, 1, 'L');
$pdf->AddPage();
$pdf->Cell(0, 10, 'This is the second page of group 2', 0, 1, 'L');
$pdf->AddPage();
$pdf->Cell(0, 10, 'This is the third page of group 2', 0, 1, 'L');
$pdf->AddPage();
$pdf->Cell(0, 10, 'This is the fourth page of group 2', 0, 1, 'L');
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_023.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,140 @@
<?php
//============================================================+
// File name : example_024.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 024 for TCPDF class
// Object Visibility and Layers
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Object Visibility and Layers
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 024');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 024', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('times', '', 18);
// add a page
$pdf->AddPage();
/*
* setVisibility() allows to restrict the rendering of some
* elements to screen or printout. This can be useful, for
* instance, to put a background image or color that will
* show on screen but won't print.
*/
$txt = 'You can limit the visibility of PDF objects to screen or printer by using the setVisibility() method.
Check the print preview of this document to display the alternative text.';
$pdf->Write(0, $txt, '', 0, '', true, 0, false, false, 0);
// change font size
$pdf->SetFontSize(40);
// change text color
$pdf->SetTextColor(0,63,127);
// set visibility only for screen
$pdf->setVisibility('screen');
// write something only for screen
$pdf->Write(0, '[This line is for display]', '', 0, 'C', true, 0, false, false, 0);
// set visibility only for print
$pdf->setVisibility('print');
// change text color
$pdf->SetTextColor(127,0,0);
// write something only for print
$pdf->Write(0, '[This line is for printout]', '', 0, 'C', true, 0, false, false, 0);
// restore visibility
$pdf->setVisibility('all');
// ---------------------------------------------------------
// LAYERS
// start a new layer
$pdf->startLayer('layer1', true, true);
// change font size
$pdf->SetFontSize(18);
// change text color
$pdf->SetTextColor(0,127,0);
$txt = 'Using the startLayer() method you can group PDF objects into layers.
This text is on "layer1".';
// write something
$pdf->Write(0, $txt, '', 0, 'L', true, 0, false, false, 0);
// close the current layer
$pdf->endLayer();
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_024.pdf', 'D');
//============================================================+
// END OF FILE
//============================================================+

View File

@ -0,0 +1,118 @@
<?php
//============================================================+
// File name : example_025.php
// Begin : 2008-03-04
// Last Update : 2013-05-14
//
// Description : Example 025 for TCPDF class
// Object Transparency
//
// Author: Nicola Asuni
//
// (c) Copyright:
// Nicola Asuni
// Tecnick.com LTD
// www.tecnick.com
// info@tecnick.com
//============================================================+
/**
* Creates an example PDF TEST document using TCPDF
* @package com.tecnick.tcpdf
* @abstract TCPDF - Example: Object Transparency
* @author Nicola Asuni
* @since 2008-03-04
*/
// Include the main TCPDF library (search for installation path).
require_once('tcpdf_include.php');
// create new PDF document
$pdf = new TCPDF(PDF_PAGE_ORIENTATION, PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
// set document information
$pdf->SetCreator(PDF_CREATOR);
$pdf->SetAuthor('Nicola Asuni');
$pdf->SetTitle('TCPDF Example 025');
$pdf->SetSubject('TCPDF Tutorial');
$pdf->SetKeywords('TCPDF, PDF, example, test, guide');
// set default header data
$pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, PDF_HEADER_TITLE.' 025', PDF_HEADER_STRING);
// set header and footer fonts
$pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
// set default monospaced font
$pdf->SetDefaultMonospacedFont(PDF_FONT_MONOSPACED);
// set margins
$pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
// set auto page breaks
$pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
// set image scale factor
$pdf->setImageScale(PDF_IMAGE_SCALE_RATIO);
// set some language-dependent strings (optional)
if (@file_exists(dirname(__FILE__).'/lang/eng.php')) {
require_once(dirname(__FILE__).'/lang/eng.php');
$pdf->setLanguageArray($l);
}
// ---------------------------------------------------------
// set font
$pdf->SetFont('helvetica', '', 12);
// add a page
$pdf->AddPage();
$txt = 'You can set the transparency of PDF objects using the setAlpha() method.';
$pdf->Write(0, $txt, '', 0, '', true, 0, false, false, 0);
/*
* setAlpha() gives transparency support. You can set the
* alpha channel from 0 (fully transparent) to 1 (fully
* opaque). It applies to all elements (text, drawings,
* images).
*/
$pdf->SetLineWidth(2);
// draw opaque red square
$pdf->SetFillColor(255, 0, 0);
$pdf->SetDrawColor(127, 0, 0);
$pdf->Rect(30, 40, 60, 60, 'DF');
// set alpha to semi-transparency
$pdf->SetAlpha(0.5);
// draw green square
$pdf->SetFillColor(0, 255, 0);
$pdf->SetDrawColor(0, 127, 0);
$pdf->Rect(50, 60, 60, 60, 'DF');
// draw blue square
$pdf->SetFillColor(0, 0, 255);
$pdf->SetDrawColor(0, 0, 127);
$pdf->Rect(70, 80, 60, 60, 'DF');
// draw jpeg image
$pdf->Image('images/image_demo.jpg', 90, 100, 60, 60, '', 'http://www.tcpdf.org', '', true, 72);
// restore full opacity
$pdf->SetAlpha(1);
// ---------------------------------------------------------
//Close and output PDF document
$pdf->Output('example_025.pdf', 'I');
//============================================================+
// END OF FILE
//============================================================+

Some files were not shown because too many files have changed in this diff Show More