2016-04-05 20:43:46 +02:00
< ? php
/**
* EGroupware - Document merge print
*
* @ link http :// www . egroupware . org
* @ author Ralf Becker < RalfBecker - AT - outdoor - training . de >
* @ package api
* @ subpackage storage
* @ copyright ( c ) 2007 - 16 by Ralf Becker < RalfBecker - AT - outdoor - training . de >
* @ license http :// opensource . org / licenses / gpl - license . php GPL - GNU General Public License
* @ version $Id $
*/
namespace EGroupware\Api\Storage ;
2020-03-25 03:34:04 +01:00
use DOMDocument ;
2016-04-05 20:43:46 +02:00
use EGroupware\Api ;
2021-06-23 19:19:36 +02:00
use EGroupware\Api\Vfs ;
2021-09-29 01:00:55 +02:00
use EGroupware\Collabora\Conversion ;
2016-04-05 20:43:46 +02:00
use EGroupware\Stylite ;
use tidy ;
2020-03-25 03:34:04 +01:00
use uiaccountsel ;
use XSLTProcessor ;
2016-04-05 20:43:46 +02:00
use ZipArchive ;
// explicit import old, non-namespaced phpgwapi classes
/**
* Document merge print
*
* @ todo move apply_styles call into merge_string to run for each entry merged and not all together to lower memory requirements
*/
abstract class Merge
{
2021-10-07 18:22:45 +02:00
/**
* Preference , path where we look for merge templates
*/
public const PREF_TEMPLATE_DIR = 'document_dir' ;
/**
* Preference , path to special documents that are listed first
*/
public const PREF_DEFAULT_TEMPLATE = 'default_document' ;
2021-10-06 19:58:39 +02:00
/**
* Preference , path where we will put the generated document
*/
2021-09-30 20:01:37 +02:00
const PREF_STORE_LOCATION = " merge_store_path " ;
2021-10-06 19:58:39 +02:00
/**
* Preference , placeholders for creating the filename of the generated document
*/
const PREF_DOCUMENT_FILENAME = " document_download_name " ;
/**
* List of placeholders
*/
const DOCUMENT_FILENAME_OPTIONS = [
'$$document$$' => 'Template name' ,
'$$link_title$$' => 'Entry link-title' ,
'$$contact_title$$' => 'Contact link-title' ,
'$$current_date$$' => 'Current date' ,
];
2016-04-05 20:43:46 +02:00
/**
* Instance of the addressbook_bo class
*
* @ var addressbook_bo
*/
var $contacts ;
/**
* Datetime format according to user preferences
*
* @ var string
*/
var $datetime_format = 'Y-m-d H:i' ;
/**
* Fields that are to be treated as datetimes , when merged into spreadsheets
*/
2021-10-05 14:11:11 +02:00
var $date_fields = [];
/**
* Fields that are numeric , for special numeric handling
*/
protected $numeric_fields = [];
2016-04-05 20:43:46 +02:00
/**
* Mimetype of document processed by merge
*
* @ var string
*/
var $mimetype ;
/**
* Plugins registered by extending class to create a table with multiple rows
*
* $$table / $plugin $ $ ... $$endtable $ $
*
* Callback returns replacements for row $n ( stringing with 0 ) or null if no further rows
*
* @ var array $plugin => array callback ( $plugin , $id , $n )
*/
var $table_plugins = array ();
/**
* Export limit in number of entries or some non - numerical value , if no export allowed at all , empty means no limit
*
* Set by constructor to $GLOBALS [ egw_info ][ server ][ export_limit ]
*
* @ var int | string
*/
public $export_limit ;
2021-06-23 19:19:36 +02:00
public $public_functions = array (
2021-10-07 18:22:45 +02:00
" merge_entries " => true
2021-06-23 19:19:36 +02:00
);
2021-10-05 14:11:11 +02:00
2016-04-05 20:43:46 +02:00
/**
* Configuration for HTML Tidy to clean up any HTML content that is kept
*/
public static $tidy_config = array (
2021-10-07 18:22:45 +02:00
'output-xml' => true , // Entity encoding
'show-body-only' => true ,
'output-encoding' => 'utf-8' ,
'input-encoding' => 'utf-8' ,
'quote-ampersand' => false , // Prevent double encoding
'quote-nbsp' => true , // XSLT can handle spaces easier
'preserve-entities' => true ,
'wrap' => 0 , // Wrapping can break output
2016-04-05 20:43:46 +02:00
);
/**
* Parse HTML styles into target document style , if possible
*
* Apps not using html in there own data should set this with Customfields :: use_html ( $app )
* to avoid memory and time consuming html processing .
*/
protected $parse_html_styles = true ;
/**
* Enable this to report memory_usage to error_log
*
* @ var boolean
*/
public $report_memory_usage = false ;
2018-10-01 19:16:17 +02:00
/**
* Save sent emails . Used when merge template is an email . Default is true ,
* to save sent emails in your sent folder .
*
* @ var boolean
*/
public $keep_emails = true ;
2016-04-05 20:43:46 +02:00
/**
* Constructor
*/
function __construct ()
{
// Common messages are in preferences
Api\Translation :: add_app ( 'preferences' );
// All contact fields are in addressbook
Api\Translation :: add_app ( 'addressbook' );
$this -> contacts = new Api\Contacts ();
2021-10-07 18:22:45 +02:00
$this -> datetime_format = $GLOBALS [ 'egw_info' ][ 'user' ][ 'preferences' ][ 'common' ][ 'dateformat' ] . ' ' .
( $GLOBALS [ 'egw_info' ][ 'user' ][ 'preferences' ][ 'common' ][ 'timeformat' ] == 12 ? 'h:i a' : 'H:i' );
2016-04-05 20:43:46 +02:00
$this -> export_limit = self :: getExportLimit ();
}
/**
* Hook returning options for export_limit_excepted groups
*
* @ param array $config
*/
public static function hook_export_limit_excepted ( $config )
{
$accountsel = new uiaccountsel ();
2021-10-07 18:22:45 +02:00
return '<input type="hidden" value="" name="newsettings[export_limit_excepted]" />' .
$accountsel -> selection ( 'newsettings[export_limit_excepted]' , 'export_limit_excepted' , $config [ 'export_limit_excepted' ], 'both' , 4 );
2016-04-05 20:43:46 +02:00
}
/**
* Get all replacements , must be implemented in extending class
*
* Can use eg . the following high level methods :
* - contact_replacements ( $contact_id , $prefix = '' )
* - format_datetime ( $time , $format = null )
*
* @ param int $id id of entry
2021-10-07 18:22:45 +02:00
* @ param string & $content = null content to create some replacements only if they are use
2016-04-05 20:43:46 +02:00
* @ return array | boolean array with replacements or false if entry not found
*/
2021-10-07 18:22:45 +02:00
abstract protected function get_replacements ( $id , & $content = null );
2016-04-05 20:43:46 +02:00
/**
* Return if merge - print is implemented for given mime - type ( and / or extension )
*
* @ param string $mimetype eg . text / plain
* @ param string $extension only checked for applications / msword and . rtf
*/
2021-10-07 18:22:45 +02:00
static public function is_implemented ( $mimetype , $extension = null )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
static $zip_available = null ;
if ( is_null ( $zip_available ))
2016-04-05 20:43:46 +02:00
{
$zip_available = check_load_extension ( 'zip' ) &&
2021-10-07 18:22:45 +02:00
class_exists ( 'ZipArchive' ); // some PHP has zip extension, but no ZipArchive (eg. RHEL5!)
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
switch ( $mimetype )
2016-04-05 20:43:46 +02:00
{
case 'application/msword' :
2021-10-07 18:22:45 +02:00
if ( strtolower ( $extension ) != '.rtf' )
{
break ;
}
2016-04-05 20:43:46 +02:00
case 'application/rtf' :
case 'text/rtf' :
2021-10-07 18:22:45 +02:00
return true ; // rtf files
case 'application/vnd.oasis.opendocument.text' : // oo text
case 'application/vnd.oasis.opendocument.spreadsheet' : // oo spreadsheet
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.presentation' :
case 'application/vnd.oasis.opendocument.text-template' :
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
case 'application/vnd.oasis.opendocument.presentation-template' :
2021-10-07 18:22:45 +02:00
if ( ! $zip_available )
{
break ;
}
return true ; // open office write xml files
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' : // ms word 2007 xml format
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.d' : // mimetypes in vfs are limited to 64 chars
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-word.document.macroenabled.12' :
2021-10-07 18:22:45 +02:00
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : // ms excel 2007 xml format
2016-04-05 20:43:46 +02:00
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.shee' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-excel.sheet.macroenabled.12' :
2021-10-07 18:22:45 +02:00
if ( ! $zip_available )
{
break ;
}
return true ; // ms word xml format
2016-04-05 20:43:46 +02:00
case 'application/xml' :
2021-10-07 18:22:45 +02:00
return true ; // alias for text/xml, eg. ms office 2003 word format
2016-04-05 20:43:46 +02:00
case 'message/rfc822' :
return true ; // ToDo: check if you are theoretical able to send mail
case 'application/x-yaml' :
2021-10-07 18:22:45 +02:00
return true ; // yaml file, plain text with marginal syntax support for multiline replacements
2016-04-05 20:43:46 +02:00
default :
2021-10-07 18:22:45 +02:00
if ( substr ( $mimetype , 0 , 5 ) == 'text/' )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
return true ; // text files
2016-04-05 20:43:46 +02:00
}
break ;
}
return false ;
// As browsers not always return correct mime types, one could use a negative list instead
//return !($mimetype == Api\Vfs::DIR_MIME_TYPE || substr($mimetype,0,6) == 'image/');
}
/**
* Return replacements for a contact
*
* @ param int | string | array $contact contact - array or id
* @ param string $prefix = '' prefix like eg . 'user'
* @ param boolean $ignore_acl = false true : no acl check
* @ return array
*/
2021-10-07 18:22:45 +02:00
public function contact_replacements ( $contact , $prefix = '' , $ignore_acl = false , & $content = '' )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if ( ! is_array ( $contact ))
2016-04-05 20:43:46 +02:00
{
$contact = $this -> contacts -> read ( $contact , $ignore_acl );
}
2021-10-07 18:22:45 +02:00
if ( ! is_array ( $contact ))
{
return array ();
}
2016-04-05 20:43:46 +02:00
$replacements = array ();
foreach ( array_keys ( $this -> contacts -> contact_fields ) as $name )
{
2021-10-06 19:58:39 +02:00
$value = $contact [ $name ] ? ? '' ;
if ( ! $value )
{
continue ;
}
2016-04-05 20:43:46 +02:00
switch ( $name )
{
2021-10-06 19:58:39 +02:00
case 'created' :
case 'modified' :
if ( $value )
{
$value = Api\DateTime :: to ( $value );
}
2016-04-05 20:43:46 +02:00
break ;
case 'bday' :
2021-10-06 19:58:39 +02:00
if ( $value )
2016-04-05 20:43:46 +02:00
{
2021-10-06 19:58:39 +02:00
try
{
2016-06-06 10:09:05 +02:00
$value = Api\DateTime :: to ( $value , true );
}
2021-10-06 19:58:39 +02:00
catch ( \Exception $e )
{
unset ( $e ); // ignore exception caused by wrongly formatted date
2016-06-06 10:09:05 +02:00
}
2016-04-05 20:43:46 +02:00
}
break ;
2021-10-06 19:58:39 +02:00
case 'owner' :
case 'creator' :
case 'modifier' :
2016-04-05 20:43:46 +02:00
$value = Api\Accounts :: username ( $value );
break ;
case 'cat_id' :
2021-10-06 19:58:39 +02:00
if ( $value )
2016-04-05 20:43:46 +02:00
{
// if cat-tree is displayed, we return a full category path not just the name of the cat
$use = $GLOBALS [ 'egw_info' ][ 'server' ][ 'cat_tab' ] == 'Tree' ? 'path' : 'name' ;
$cats = array ();
2021-10-06 19:58:39 +02:00
foreach ( is_array ( $value ) ? $value : explode ( ',' , $value ) as $cat_id )
2016-04-05 20:43:46 +02:00
{
2021-10-06 19:58:39 +02:00
$cats [] = $GLOBALS [ 'egw' ] -> categories -> id2name ( $cat_id , $use );
2016-04-05 20:43:46 +02:00
}
2021-10-06 19:58:39 +02:00
$value = implode ( ', ' , $cats );
2016-04-05 20:43:46 +02:00
}
break ;
2021-10-06 19:58:39 +02:00
case 'jpegphoto' : // returning a link might make more sense then the binary photo
if ( $contact [ 'photo' ])
2016-04-05 20:43:46 +02:00
{
2021-10-06 19:58:39 +02:00
$value = Api\Framework :: getUrl ( Api\Framework :: link ( '/index.php' , $contact [ 'photo' ]));
2016-04-05 20:43:46 +02:00
}
break ;
case 'tel_prefer' :
2021-10-06 19:58:39 +02:00
if ( $value && $contact [ $value ])
2016-04-05 20:43:46 +02:00
{
$value = $contact [ $value ];
}
break ;
case 'account_id' :
2021-09-21 22:06:24 +02:00
if ( $value )
2016-04-05 20:43:46 +02:00
{
2021-09-21 22:06:24 +02:00
$replacements [ '$$' . ( $prefix ? $prefix . '/' : '' ) . 'account_lid$$' ] = $GLOBALS [ 'egw' ] -> accounts -> id2name ( $value );
2016-04-05 20:43:46 +02:00
}
break ;
}
2021-09-21 22:06:24 +02:00
if ( $name != 'photo' )
{
$replacements [ '$$' . ( $prefix ? $prefix . '/' : '' ) . $name . '$$' ] = $value ;
}
2016-04-05 20:43:46 +02:00
}
2021-09-21 22:06:24 +02:00
// Formatted address, according to preference or country
foreach ([ 'one' , 'two' ] as $adr )
{
switch ( $this -> contacts -> addr_format_by_country ( $contact [ " adr_ { $adr } _countryname " ]))
{
case 'city_state_postcode' :
$formatted_placeholder = $contact [ " adr_ { $adr } _locality " ] . " " .
$contact [ " adr_ { $adr } _region " ] . " " . $contact [ " adr_ { $adr } _postalcode " ];
break ;
case 'postcode_city' :
default :
$formatted_placeholder = $contact [ " adr_ { $adr } _postalcode " ] . ' ' . $contact [ " adr_ { $adr } _locality " ];
break ;
}
$replacements [ '$$adr_' . $adr . '_formatted$$' ] = $formatted_placeholder ;
}
2016-04-05 20:43:46 +02:00
// set custom fields, should probably go to a general method all apps can use
// need to load all cfs for $ignore_acl=true
foreach ( $ignore_acl ? Customfields :: get ( 'addressbook' , true ) : $this -> contacts -> customfields as $name => $field )
{
2021-09-21 22:06:24 +02:00
$name = '#' . $name ;
2021-03-05 17:13:12 +01:00
if ( ! array_key_exists ( $name , $contact ) || ! $contact [ $name ])
2019-02-07 17:59:38 +01:00
{
2021-09-21 22:06:24 +02:00
$replacements [ '$$' . ( $prefix ? $prefix . '/' : '' ) . $name . '$$' ] = '' ;
2019-02-07 17:59:38 +01:00
continue ;
}
// Format date cfs per user Api\Preferences
if ( $this -> mimetype !== 'application/x-yaml' && $contact [ $name ] &&
2021-10-07 18:22:45 +02:00
( $field [ 'type' ] == 'date' || $field [ 'type' ] == 'date-time' ))
2019-02-07 17:59:38 +01:00
{
2021-10-07 18:22:45 +02:00
$this -> date_fields [] = '#' . $name ;
$replacements [ '$$' . ( $prefix ? $prefix . '/' : '' ) . $name . '$$' ] = Api\DateTime :: to ( $contact [ $name ], $field [ 'type' ] == 'date' ? true : '' );
2019-02-07 17:59:38 +01:00
}
2021-10-07 18:22:45 +02:00
$replacements [ '$$' . ( $prefix ? $prefix . '/' : '' ) . $name . '$$' ] =
2016-04-05 20:43:46 +02:00
// use raw data for yaml, no user-preference specific formatting
2019-02-07 17:59:38 +01:00
$this -> mimetype == 'application/x-yaml' || $field [ 'type' ] == 'htmlarea' ? ( string ) $contact [ $name ] :
2021-10-07 18:22:45 +02:00
Customfields :: format ( $field , ( string ) $contact [ $name ]);
2016-04-05 20:43:46 +02:00
}
2018-04-03 23:26:48 +02:00
if ( $content && strpos ( $content , '$$#' ) !== FALSE )
{
$this -> cf_link_to_expand ( $contact , $content , $replacements , 'addressbook' );
}
2016-04-05 20:43:46 +02:00
// Add in extra cat field
$cats = array ();
2021-10-07 18:22:45 +02:00
foreach ( is_array ( $contact [ 'cat_id' ]) ? $contact [ 'cat_id' ] : explode ( ',' , $contact [ 'cat_id' ]) as $cat_id )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if ( ! $cat_id )
{
continue ;
}
if ( $GLOBALS [ 'egw' ] -> categories -> id2name ( $cat_id , 'main' ) != $cat_id )
2016-04-05 20:43:46 +02:00
{
$path = explode ( ' / ' , $GLOBALS [ 'egw' ] -> categories -> id2name ( $cat_id , 'path' ));
unset ( $path [ 0 ]); // Drop main
2021-10-07 18:22:45 +02:00
$cats [ $GLOBALS [ 'egw' ] -> categories -> id2name ( $cat_id , 'main' )][] = implode ( ' / ' , $path );
}
elseif ( $cat_id )
{
2016-04-05 20:43:46 +02:00
$cats [ $cat_id ] = array ();
}
}
2021-10-07 18:22:45 +02:00
$replacements [ '$$' . ( $prefix ? $prefix . '/' : '' ) . 'categories$$' ] = '' ;
2021-10-05 14:11:11 +02:00
foreach ( $cats as $main => $cat )
{
2021-10-07 18:22:45 +02:00
$replacements [ '$$' . ( $prefix ? $prefix . '/' : '' ) . 'categories$$' ] .= $GLOBALS [ 'egw' ] -> categories -> id2name ( $main , 'name' )
2016-04-05 20:43:46 +02:00
. ( count ( $cat ) > 0 ? ': ' : '' ) . implode ( ', ' , $cats [ $main ]) . " \n " ;
}
return $replacements ;
}
/**
* Get links for the given record
*
* Uses egw_link system to get link titles
*
2021-10-12 22:18:18 +02:00
* @ param string app Name of current app
* @ param string id ID of current entry
* @ param string only_app Restrict links to only given application
* @ param string [] exclude Exclude links to these applications
* @ param string style One of :
2021-10-07 18:22:45 +02:00
* 'title' - plain text , just the title of the link
* 'link' - URL to the entry
* 'href' - HREF tag wrapped around the title
2016-04-05 20:43:46 +02:00
*/
2021-10-07 18:22:45 +02:00
protected function get_links ( $app , $id , $only_app = '' , $exclude = array (), $style = 'title' )
2016-04-05 20:43:46 +02:00
{
$links = Api\Link :: get_links ( $app , $id , $only_app );
$link_titles = array ();
foreach ( $links as $link_info )
{
// Using only_app only returns the ID
if ( ! is_array ( $link_info ) && $only_app && $only_app [ 0 ] !== '!' )
{
$link_info = array (
2021-10-07 18:22:45 +02:00
'app' => $only_app ,
'id' => $link_info
2016-04-05 20:43:46 +02:00
);
}
2021-10-07 18:22:45 +02:00
if ( $exclude && in_array ( $link_info [ 'id' ], $exclude ))
{
continue ;
}
2016-04-05 20:43:46 +02:00
$title = Api\Link :: title ( $link_info [ 'app' ], $link_info [ 'id' ]);
2021-10-07 18:22:45 +02:00
2016-04-05 20:43:46 +02:00
if ( $style == 'href' || $style == 'link' )
{
$link = Api\Link :: view ( $link_info [ 'app' ], $link_info [ 'id' ], $link_info );
if ( $link_info [ 'app' ] != Api\Link :: VFS_APPNAME )
{
// Set app to false so we always get an external link
2021-10-07 18:22:45 +02:00
$link = str_replace ( ',' , '%2C' , $GLOBALS [ 'egw' ] -> framework -> link ( '/index.php' , $link , false ));
2016-04-05 20:43:46 +02:00
}
else
{
2016-04-07 22:42:06 +02:00
$link = Api\Framework :: link ( $link , array ());
2016-04-05 20:43:46 +02:00
}
// Prepend site
2021-10-07 18:22:45 +02:00
if ( $link [ 0 ] == '/' )
{
$link = Api\Framework :: getUrl ( $link );
}
2018-03-21 12:40:59 +01:00
2016-04-05 20:43:46 +02:00
$title = $style == 'href' ? Api\Html :: a_href ( Api\Html :: htmlspecialchars ( $title ), $link ) : $link ;
}
$link_titles [] = $title ;
}
2021-10-07 18:22:45 +02:00
return implode ( " \n " , $link_titles );
2016-04-05 20:43:46 +02:00
}
/**
* Get all link placeholders
*
* Calls get_links () repeatedly to get all the combinations for the content .
*
* @ param $app String appname
* @ param $id String ID of record
* @ param $prefix
* @ param $content String document content
*/
protected function get_all_links ( $app , $id , $prefix , & $content )
{
$array = array ();
2018-03-23 16:46:51 +01:00
$pattern = '@\$\$(links_attachments|links|attachments|link)\/?(title|href|link)?\/?([a-z]*)\$\$@' ;
2021-10-07 18:22:45 +02:00
static $link_cache = null ;
2016-04-05 20:43:46 +02:00
$matches = null ;
if ( preg_match_all ( $pattern , $content , $matches ))
{
foreach ( $matches [ 0 ] as $i => $placeholder )
{
2018-03-23 16:46:51 +01:00
$placeholder = substr ( $placeholder , 2 , - 2 );
2016-04-05 20:43:46 +02:00
if ( $link_cache [ $id ][ $placeholder ])
{
$array [ $placeholder ] = $link_cache [ $id ][ $placeholder ];
continue ;
}
switch ( $matches [ 1 ][ $i ])
{
case 'link' :
// Link to current record
$title = Api\Link :: title ( $app , $id );
if ( class_exists ( 'EGroupware\Stylite\Vfs\Links\StreamWrapper' ) && $app != Api\Link :: VFS_APPNAME )
{
$title = Stylite\Vfs\Links\StreamWrapper :: entry2name ( $app , $id , $title );
}
$link = Api\Link :: view ( $app , $id );
if ( $app != Api\Link :: VFS_APPNAME )
{
// Set app to false so we always get an external link
2021-10-07 18:22:45 +02:00
$link = str_replace ( ',' , '%2C' , $GLOBALS [ 'egw' ] -> framework -> link ( '/index.php' , $link , false ));
2016-04-05 20:43:46 +02:00
}
else
{
2016-04-07 22:42:06 +02:00
$link = Api\Framework :: link ( $link , array ());
2016-04-05 20:43:46 +02:00
}
// Prepend site
2021-10-07 18:22:45 +02:00
if ( $link [ 0 ] == '/' )
{
$link = Api\Framework :: getUrl ( $link );
}
2018-03-21 12:40:59 +01:00
2020-10-02 20:37:20 +02:00
// Formatting
if ( $matches [ 2 ][ $i ] == 'title' )
{
$link = $title ;
}
2021-10-07 18:22:45 +02:00
else
2020-10-02 20:37:20 +02:00
{
2021-10-07 18:22:45 +02:00
if ( $matches [ 2 ][ $i ] == 'href' )
{
// Turn on HTML style parsing or the link will be escaped
$this -> parse_html_styles = true ;
$link = Api\Html :: a_href ( Api\Html :: htmlspecialchars ( $title ), $link );
}
2020-10-02 20:37:20 +02:00
}
2021-10-07 18:22:45 +02:00
$array [ '$$' . ( $prefix ? $prefix . '/' : '' ) . $placeholder . '$$' ] = $link ;
2016-04-05 20:43:46 +02:00
break ;
case 'links' :
2021-10-07 18:22:45 +02:00
$link_app = $matches [ 3 ][ $i ] ? $matches [ 3 ][ $i ] : '!' . Api\Link :: VFS_APPNAME ;
$array [ '$$' . ( $prefix ? $prefix . '/' : '' ) . $placeholder . '$$' ] = $this -> get_links ( $app , $id , $link_app , array (), $matches [ 2 ][ $i ]);
2016-04-05 20:43:46 +02:00
break ;
case 'attachments' :
2021-10-07 18:22:45 +02:00
$array [ '$$' . ( $prefix ? $prefix . '/' : '' ) . $placeholder . '$$' ] = $this -> get_links ( $app , $id , Api\Link :: VFS_APPNAME , array (), $matches [ 2 ][ $i ]);
2016-04-05 20:43:46 +02:00
break ;
default :
2021-10-07 18:22:45 +02:00
$array [ '$$' . ( $prefix ? $prefix . '/' : '' ) . $placeholder . '$$' ] = $this -> get_links ( $app , $id , $matches [ 3 ][ $i ], array (), $matches [ 2 ][ $i ]);
2016-04-05 20:43:46 +02:00
break ;
}
$link_cache [ $id ][ $placeholder ] = $array [ $placeholder ];
}
}
return $array ;
}
2018-10-11 18:09:16 +02:00
/**
* Get share placeholder
*
* If the placeholder is present in the content , the share will be automatically
* created .
*/
protected function share_placeholder ( $app , $id , $prefix , & $content )
{
$replacements = array ();
// Skip if no content or content has no share placeholder
if ( ! $content || strpos ( $content , '$$share' ) === FALSE )
{
return $replacements ;
}
if ( ! $GLOBALS [ 'egw_info' ][ 'user' ][ 'apps' ][ 'stylite' ])
{
2021-10-07 18:22:45 +02:00
$replacements [ '$$' . $prefix . 'share$$' ] = lang ( 'EPL Only' );
2018-10-11 18:09:16 +02:00
return $replacements ;
}
// Get or create the share
2019-04-04 18:28:20 +02:00
$share = $this -> create_share ( $app , $id , $content );
if ( $share )
{
2021-10-07 18:22:45 +02:00
$replacements [ '$$' . $prefix . 'share$$' ] = $link = Api\Sharing :: share2link ( $share );
2019-04-04 18:28:20 +02:00
}
return $replacements ;
}
/**
* Create a share for an entry
*
* @ param string $app
* @ param string $id
2019-04-05 16:58:21 +02:00
* @ param String $content
* @ return \EGroupware\Api\Sharing
2019-04-04 18:28:20 +02:00
*/
protected function create_share ( $app , $id , & $content )
{
2018-10-11 18:09:16 +02:00
// Check if some other process created the share (with custom options)
// and put it in the session cache for us
$path = " $app :: $id " ;
$session = \EGroupware\Api\Cache :: getSession ( Api\Sharing :: class , $path );
if ( $session && $session [ 'share_path' ] == $path )
{
2019-04-04 18:28:20 +02:00
return $session ;
2018-10-11 18:09:16 +02:00
}
2019-04-04 18:28:20 +02:00
// Need to create the share here.
// No way to know here if it should be writable, or who it's going to
2021-10-07 18:22:45 +02:00
$mode = /* ? ? Sharing::WRITABLE :*/
Api\Sharing :: READONLY ;
2019-04-04 18:28:20 +02:00
$recipients = array ();
$extra = array ();
2018-10-11 18:09:16 +02:00
2019-04-04 18:28:20 +02:00
//$extra['share_writable'] |= ($mode == Sharing::WRITABLE ? 1 : 0);
2018-10-11 18:09:16 +02:00
2020-03-25 03:34:04 +01:00
return \EGroupware\Stylite\Link\Sharing :: create ( '' , $path , $mode , NULL , $recipients , $extra );
2018-10-11 18:09:16 +02:00
}
2016-04-05 20:43:46 +02:00
/**
* Format a datetime
*
* @ param int | string | DateTime $time unix timestamp or Y - m - d H : i : s string ( in user time ! )
* @ param string $format = null format string , default $this -> datetime_format
* @ return string
2021-10-07 18:22:45 +02:00
* @ deprecated use Api\DateTime :: to ( $time = 'now' , $format = '' )
2016-04-05 20:43:46 +02:00
*/
2021-10-07 18:22:45 +02:00
protected function format_datetime ( $time , $format = null )
2016-04-05 20:43:46 +02:00
{
trigger_error ( __METHOD__ . ' is deprecated, use Api\DateTime::to($time, $format)' , E_USER_DEPRECATED );
2021-10-07 18:22:45 +02:00
if ( is_null ( $format ))
{
$format = $this -> datetime_format ;
}
2016-04-05 20:43:46 +02:00
2021-10-07 18:22:45 +02:00
return Api\DateTime :: to ( $time , $format );
2016-04-05 20:43:46 +02:00
}
/**
* Checks if current user is excepted from the export - limit :
* a ) access to admin application
* b ) he or one of his memberships is named in export_limit_excepted config var
*
* @ return boolean
*/
public static function is_export_limit_excepted ()
{
2021-10-07 18:22:45 +02:00
static $is_excepted = null ;
2016-04-05 20:43:46 +02:00
2021-10-07 18:22:45 +02:00
if ( is_null ( $is_excepted ))
2016-04-05 20:43:46 +02:00
{
$is_excepted = isset ( $GLOBALS [ 'egw_info' ][ 'user' ][ 'apps' ][ 'admin' ]);
// check export-limit and fail if user tries to export more entries then allowed
2021-10-07 18:22:45 +02:00
if ( ! $is_excepted && ( is_array ( $export_limit_excepted = $GLOBALS [ 'egw_info' ][ 'server' ][ 'export_limit_excepted' ]) ||
is_array ( $export_limit_excepted = unserialize ( $export_limit_excepted ))))
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$id_and_memberships = $GLOBALS [ 'egw' ] -> accounts -> memberships ( $GLOBALS [ 'egw_info' ][ 'user' ][ 'account_id' ], true );
2016-04-05 20:43:46 +02:00
$id_and_memberships [] = $GLOBALS [ 'egw_info' ][ 'user' ][ 'account_id' ];
2021-10-07 18:22:45 +02:00
$is_excepted = ( bool ) array_intersect ( $id_and_memberships , $export_limit_excepted );
2016-04-05 20:43:46 +02:00
}
}
return $is_excepted ;
}
/**
* Checks if there is an exportlimit set , and returns
*
* @ param string $app = 'common' checks and validates app_limit , if not set returns the global limit
* @ return mixed - no if no export is allowed , false if there is no restriction and int as there is a valid restriction
2021-10-07 18:22:45 +02:00
* you may have to cast the returned value to int , if you want to use it as number
2016-04-05 20:43:46 +02:00
*/
2021-10-07 18:22:45 +02:00
public static function getExportLimit ( $app = 'common' )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
static $exportLimitStore = array ();
if ( empty ( $app ))
{
$app = 'common' ;
}
2016-04-05 20:43:46 +02:00
//error_log(__METHOD__.__LINE__.' called with app:'.$app);
2021-10-07 18:22:45 +02:00
if ( ! array_key_exists ( $app , $exportLimitStore ))
2016-04-05 20:43:46 +02:00
{
//error_log(__METHOD__.__LINE__.' -> '.$app_limit.' '.function_backtrace());
2022-04-26 20:24:37 +02:00
$exportLimitStore [ $app ] = $GLOBALS [ 'egw_info' ][ 'server' ][ 'export_limit' ] ? ? null ;
2021-10-07 18:22:45 +02:00
if ( $app != 'common' )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$app_limit = Api\Hooks :: single ( 'export_limit' , $app );
if ( $app_limit )
{
$exportLimitStore [ $app ] = $app_limit ;
}
2016-04-05 20:43:46 +02:00
}
//error_log(__METHOD__.__LINE__.' building cache for app:'.$app.' -> '.$exportLimitStore[$app]);
2021-10-07 18:22:45 +02:00
if ( empty ( $exportLimitStore [ $app ]))
2016-04-05 20:43:46 +02:00
{
$exportLimitStore [ $app ] = false ;
return false ;
}
2021-10-07 18:22:45 +02:00
if ( is_numeric ( $exportLimitStore [ $app ]))
2016-04-05 20:43:46 +02:00
{
$exportLimitStore [ $app ] = ( int ) $exportLimitStore [ $app ];
}
else
{
$exportLimitStore [ $app ] = 'no' ;
}
//error_log(__METHOD__.__LINE__.' -> '.$exportLimit);
}
//error_log(__METHOD__.__LINE__.' app:'.$app.' -> '.$exportLimitStore[$app]);
return $exportLimitStore [ $app ];
}
/**
* hasExportLimit
* checks wether there is an exportlimit set , and returns true or false
* @ param mixed $app_limit app_limit , if not set checks the global limit
* @ param string $checkas [ AND | ISALLOWED ], AND default ; if set to ISALLOWED it is checked if Export is allowed
*
* @ return bool - true if no export is allowed or a limit is set , false if there is no restriction
*/
2021-10-07 18:22:45 +02:00
public static function hasExportLimit ( $app_limit , $checkas = 'AND' )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if ( strtoupper ( $checkas ) == 'ISALLOWED' )
{
return ( empty ( $app_limit ) || ( $app_limit != 'no' && $app_limit > 0 ));
}
if ( empty ( $app_limit ))
{
return false ;
}
if ( $app_limit == 'no' )
{
return true ;
}
if ( $app_limit > 0 )
{
return true ;
}
2016-04-05 20:43:46 +02:00
}
/**
* Merges a given document with contact data
*
* @ param string $document path / url of document
* @ param array $ids array with contact id ( s )
* @ param string & $err error - message on error
* @ param string $mimetype mimetype of complete document , eg . text /* , application / vnd . oasis . opendocument . text , application / rtf
* @ param array $fix = null regular expression => replacement pairs eg . to fix garbled placeholders
* @ return string | boolean merged document or false on error
*/
2021-10-07 18:22:45 +02:00
public function & merge ( $document , $ids , & $err , $mimetype , array $fix = null )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if ( ! ( $content = file_get_contents ( $document )))
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$err = lang ( " Document '%1' does not exist or is not readable for you! " , $document );
2021-03-31 17:49:43 +02:00
$ret = false ;
return $ret ;
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
if ( self :: hasExportLimit ( $this -> export_limit ) && ! self :: is_export_limit_excepted () && count ( $ids ) > ( int ) $this -> export_limit )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$err = lang ( 'No rights to export more than %1 entries!' , ( int ) $this -> export_limit );
2021-03-31 17:49:43 +02:00
$ret = false ;
return $ret ;
2016-04-05 20:43:46 +02:00
}
// fix application/msword mimetype for rtf files
2021-10-07 18:22:45 +02:00
if ( $mimetype == 'application/msword' && strtolower ( substr ( $document , - 4 )) == '.rtf' )
2016-04-05 20:43:46 +02:00
{
$mimetype = 'application/rtf' ;
}
2021-10-07 18:22:45 +02:00
try
{
$content = $this -> merge_string ( $content , $ids , $err , $mimetype , $fix );
}
catch ( \Exception $e )
{
2016-07-25 14:53:30 +02:00
_egw_log_exception ( $e );
2016-04-05 20:43:46 +02:00
$err = $e -> getMessage ();
2021-03-31 17:49:43 +02:00
$ret = false ;
return $ret ;
2016-04-05 20:43:46 +02:00
}
return $content ;
}
2021-10-07 18:22:45 +02:00
protected function apply_styles ( & $content , $mimetype , $mso_application_progid = null )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if ( ! isset ( $mso_application_progid ))
2016-04-05 20:43:46 +02:00
{
$matches = null ;
$mso_application_progid = $mimetype == 'application/xml' &&
2021-10-07 18:22:45 +02:00
preg_match ( '/' . preg_quote ( '<?mso-application progid="' , '/' ) . '([^"]+)' . preg_quote ( '"?>' , '/' ) . '/' , substr ( $content , 0 , 200 ), $matches ) ?
$matches [ 1 ] : '' ;
2016-04-05 20:43:46 +02:00
}
// Tags we can replace with the target document's version
$replace_tags = array ();
2021-10-07 18:22:45 +02:00
switch ( $mimetype . $mso_application_progid )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.text' : // oo text
case 'application/vnd.oasis.opendocument.spreadsheet' : // oo spreadsheet
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.presentation' :
case 'application/vnd.oasis.opendocument.text-template' :
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
case 'application/vnd.oasis.opendocument.presentation-template' :
2016-04-05 20:43:46 +02:00
$doc = new DOMDocument ();
$xslt = new XSLTProcessor ();
2021-10-07 18:22:45 +02:00
$doc -> load ( EGW_INCLUDE_ROOT . '/api/templates/default/Merge/openoffice.xslt' );
2016-04-05 20:43:46 +02:00
$xslt -> importStyleSheet ( $doc );
//echo $content;die();
break ;
2021-10-07 18:22:45 +02:00
case 'application/xmlWord.Document' : // Word 2003*/
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' : // ms office 2007
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-word.document.macroenabled.12' :
2016-04-05 20:43:46 +02:00
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-excel.sheet.macroenabled.12' :
2016-04-05 20:43:46 +02:00
// It seems easier to split the parent tags here
$replace_tags = array (
// Tables, lists don't go inside <w:p>
2021-10-07 18:22:45 +02:00
'/<(ol|ul|table)( [^>]*)?>/' => '</w:t></w:r></w:p><$1$2>' ,
'/<\/(ol|ul|table)>/' => '</$1><w:p><w:r><w:t>' ,
2016-04-05 20:43:46 +02:00
// Fix for things other than text (newlines) inside table row
'/<(td)( [^>]*)?>((?!<w:t>))(.*?)<\/td>[\s]*?/' => '<$1$2><w:t>$4</w:t></td>' ,
// Remove extra whitespace
2021-10-07 18:22:45 +02:00
'/<li([^>]*?)>[^:print:]*?(.*?)<\/li>/' => '<li$1>$2</li>' , // This doesn't get it all
'/<w:t>[\s]+(.*?)<\/w:t>/' => '<w:t>$1</w:t>' ,
2016-04-05 20:43:46 +02:00
// Remove spans with no attributes, linebreaks inside them cause problems
2021-10-07 18:22:45 +02:00
'/<span>(.*?)<\/span>/' => '$1'
2016-04-05 20:43:46 +02:00
);
2021-10-07 18:22:45 +02:00
$content = preg_replace ( array_keys ( $replace_tags ), array_values ( $replace_tags ), $content );
2016-04-05 20:43:46 +02:00
/*
In the case where you have something like < span >< span ></ w : t >< w : br />< w : t ></ span ></ span > ( invalid - mismatched tags ),
it takes multiple runs to get rid of both spans . So , loop .
OO . o files have not yet been shown to have this problem .
*/
$count = $i = 0 ;
do
{
2021-10-07 18:22:45 +02:00
$content = preg_replace ( '/<span>(.*?)<\/span>/' , '$1' , $content , - 1 , $count );
2016-04-05 20:43:46 +02:00
$i ++ ;
2021-10-07 18:22:45 +02:00
}
while ( $count > 0 && $i < 10 );
2016-04-05 20:43:46 +02:00
$doc = new DOMDocument ();
$xslt = new XSLTProcessor ();
$xslt_file = $mimetype == 'application/xml' ? 'wordml.xslt' : 'msoffice.xslt' ;
2021-10-07 18:22:45 +02:00
$doc -> load ( EGW_INCLUDE_ROOT . '/api/templates/default/Merge/' . $xslt_file );
2016-04-05 20:43:46 +02:00
$xslt -> importStyleSheet ( $doc );
break ;
}
// XSLT transform known tags
if ( $xslt )
{
// does NOT work with php 5.2.6: Catchable fatal error: argument 1 to transformToXml() must be of type DOMDocument
//$element = new SimpleXMLelement($content);
$element = new DOMDocument ( '1.0' , 'utf-8' );
$result = $element -> loadXML ( $content );
if ( ! $result )
{
throw new Api\Exception ( 'Unable to parse merged document for styles. Check warnings in log for details.' );
}
$content = $xslt -> transformToXml ( $element );
2018-09-13 00:46:11 +02:00
//echo $content;die();
2016-04-05 20:43:46 +02:00
// Word 2003 needs two declarations, add extra declaration back in
2021-10-07 18:22:45 +02:00
if ( $mimetype == 'application/xml' && $mso_application_progid == 'Word.Document' && strpos ( $content , '<?xml' ) !== 0 )
{
$content = '<?xml version="1.0" encoding="UTF-8" standalone="yes"?>' . $content ;
2016-04-05 20:43:46 +02:00
}
// Validate
/*
$doc = new DOMDocument ();
$doc -> loadXML ( $content );
$doc -> schemaValidate ( * Schema ( xsd ) file * );
*/
}
}
/**
* Merges a given document with contact data
*
* @ param string $_content
* @ param array $ids array with contact id ( s )
* @ param string & $err error - message on error
* @ param string $mimetype mimetype of complete document , eg . text /* , application / vnd . oasis . opendocument . text , application / rtf
* @ param array $fix = null regular expression => replacement pairs eg . to fix garbled placeholders
* @ param string $charset = null charset to override default set by mimetype or export charset
* @ return string | boolean merged document or false on error
*/
2021-10-07 18:22:45 +02:00
public function & merge_string ( $_content , $ids , & $err , $mimetype , array $fix = null , $charset = null )
2016-04-05 20:43:46 +02:00
{
2021-10-04 13:02:34 +02:00
$ids = empty ( $ids ) ? [] : ( array ) $ids ;
2016-04-05 20:43:46 +02:00
$matches = null ;
2021-10-07 18:22:45 +02:00
if ( $mimetype == 'application/xml' &&
preg_match ( '/' . preg_quote ( '<?mso-application progid="' , '/' ) . '([^"]+)' . preg_quote ( '"?>' , '/' ) . '/' , substr ( $_content , 0 , 200 ), $matches ))
2016-04-05 20:43:46 +02:00
{
$mso_application_progid = $matches [ 1 ];
}
else
{
$mso_application_progid = '' ;
}
// alternative syntax using double curly brackets (eg. {{cat_id}} instead $$cat_id$$),
// agressivly removing all xml-tags eg. Word adds within placeholders
2021-10-07 18:22:45 +02:00
$content = preg_replace_callback ( '/{{[^}]+}}/i' , function ( $matches )
2016-07-10 11:09:21 +02:00
{
2021-10-07 18:22:45 +02:00
return '$$' . strip_tags ( substr ( $matches [ 0 ], 2 , - 2 )) . '$$' ;
}, $_content );
2016-04-05 20:43:46 +02:00
// Handle escaped placeholder markers in RTF, they won't match when escaped
if ( $mimetype == 'application/rtf' )
{
2021-10-07 18:22:45 +02:00
$content = preg_replace ( '/\\\{\\\{([^\\}]+)\\\}\\\}/i' , '$$\1$$' , $content );
2016-04-05 20:43:46 +02:00
}
// make currently processed mimetype available to class methods;
$this -> mimetype = $mimetype ;
// fix garbled placeholders
2021-10-07 18:22:45 +02:00
if ( $fix && is_array ( $fix ))
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$content = preg_replace ( array_keys ( $fix ), array_values ( $fix ), $content );
2016-04-05 20:43:46 +02:00
//die("<pre>".htmlspecialchars($content)."</pre>\n");
}
2021-10-07 18:22:45 +02:00
list ( $contentstart , $contentrepeat , $contentend ) = preg_split ( '/\$\$pagerepeat\$\$/' , $content , - 1 , PREG_SPLIT_NO_EMPTY ) + [ null ,
null ,
null ]; //get differt parts of document, seperatet by Pagerepeat
if ( $mimetype == 'text/plain' && $ids && count ( $ids ) > 1 )
2016-04-05 20:43:46 +02:00
{
// textdocuments are simple, they do not hold start and end, but they may have content before and after the $$pagerepeat$$ tag
// header and footer should not hold any $$ tags; if we find $$ tags with the header, we assume it is the pagerepeatcontent
$nohead = false ;
2021-10-07 18:22:45 +02:00
if ( stripos ( $contentstart , '$$' ) !== false )
{
$nohead = true ;
}
if ( $nohead )
2016-04-05 20:43:46 +02:00
{
$contentend = $contentrepeat ;
$contentrepeat = $contentstart ;
$contentstart = '' ;
}
}
2021-10-07 18:22:45 +02:00
if ( in_array ( $mimetype , array ( 'application/vnd.oasis.opendocument.text' ,
'application/vnd.oasis.opendocument.text-template' )) && count ( $ids ) > 1 )
2016-04-05 20:43:46 +02:00
{
if ( strpos ( $content , '$$pagerepeat' ) === false )
{
//for odt files we have to split the content and add a style for page break to the style area
2021-10-07 18:22:45 +02:00
list ( $contentstart , $contentrepeat , $contentend ) = preg_split ( '/office:body>/' , $content , - 1 , PREG_SPLIT_NO_EMPTY ); //get differt parts of document, seperatet by Pagerepeat
$contentstart = substr ( $contentstart , 0 , strlen ( $contentstart ) - 1 ); //remove "<"
$contentrepeat = substr ( $contentrepeat , 0 , strlen ( $contentrepeat ) - 2 ); //remove "</";
2016-04-05 20:43:46 +02:00
// need to add page-break style to the style list
2021-10-07 18:22:45 +02:00
list ( $stylestart , $stylerepeat , $styleend ) = preg_split ( '/<\/office:automatic-styles>/' , $content , - 1 , PREG_SPLIT_NO_EMPTY ); //get differt parts of document style sheets
$contentstart = $stylestart . '<style:style style:name="P200" style:family="paragraph" style:parent-style-name="Standard"><style:paragraph-properties fo:break-before="page"/></style:style></office:automatic-styles>' ;
2016-04-05 20:43:46 +02:00
$contentstart .= '<office:body>' ;
$contentend = '</office:body></office:document-content>' ;
}
else
{
// Template specifies where to repeat
2021-10-07 18:22:45 +02:00
list ( $contentstart , $contentrepeat , $contentend ) = preg_split ( '/\$\$pagerepeat\$\$/' , $content , - 1 , PREG_SPLIT_NO_EMPTY ); //get different parts of document, seperated by pagerepeat
2016-04-05 20:43:46 +02:00
}
}
2021-10-07 18:22:45 +02:00
if ( in_array ( $mimetype , array ( 'application/vnd.ms-word.document.macroenabled.12' ,
'application/vnd.openxmlformats-officedocument.wordprocessingml.document' )) && count ( $ids ) > 1 )
2016-04-05 20:43:46 +02:00
{
//for Word 2007 XML files we have to split the content and add a style for page break to the style area
2021-10-07 18:22:45 +02:00
list ( $contentstart , $contentrepeat , $contentend ) = preg_split ( '/w:body>/' , $content , - 1 , PREG_SPLIT_NO_EMPTY ); //get differt parts of document, seperatet by Pagerepeat
$contentstart = substr ( $contentstart , 0 , strlen ( $contentstart ) - 1 ); //remove "</"
$contentrepeat = substr ( $contentrepeat , 0 , strlen ( $contentrepeat ) - 2 ); //remove "</";
2016-04-05 20:43:46 +02:00
$contentstart .= '<w:body>' ;
$contentend = '</w:body></w:document>' ;
}
2021-10-07 18:22:45 +02:00
list ( $Labelstart , $Labelrepeat , $Labeltend ) = preg_split ( '/\$\$label\$\$/' , $contentrepeat , - 1 , PREG_SPLIT_NO_EMPTY ) + [ null ,
null ,
null ]; //get the label content
preg_match_all ( '/\$\$labelplacement\$\$/' , $contentrepeat , $countlables , PREG_SPLIT_NO_EMPTY );
2016-04-05 20:43:46 +02:00
$countlables = count ( $countlables [ 0 ]);
2021-10-07 18:22:45 +02:00
preg_replace ( '/\$\$labelplacement\$\$/' , '' , $Labelrepeat , 1 );
2021-10-05 14:11:11 +02:00
$lableprint = $countlables > 1 ;
2021-10-07 18:22:45 +02:00
if ( count ( $ids ) > 1 && ! $contentrepeat )
2016-04-05 20:43:46 +02:00
{
$err = lang ( 'for more than one contact in a document use the tag pagerepeat!' );
2021-03-31 17:49:43 +02:00
$ret = false ;
return $ret ;
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
if ( $this -> report_memory_usage )
{
error_log ( __METHOD__ . " (count(ids)= " . count ( $ids ) . " ) strlen(contentrepeat)= " . strlen ( $contentrepeat ) . ', strlen(labelrepeat)=' . strlen ( $Labelrepeat ));
}
2016-04-05 20:43:46 +02:00
2021-10-07 18:22:45 +02:00
if ( $contentrepeat )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$content_stream = fopen ( 'php://temp' , 'r+' );
2016-04-05 20:43:46 +02:00
fwrite ( $content_stream , $contentstart );
$joiner = '' ;
switch ( $mimetype )
{
case 'application/rtf' :
case 'text/rtf' :
$joiner = '\\par \\page\\pard\\plain' ;
break ;
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.text' : // oo text
case 'application/vnd.oasis.opendocument.spreadsheet' : // oo spreadsheet
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.presentation' :
case 'application/vnd.oasis.opendocument.text-template' :
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
case 'application/vnd.oasis.opendocument.presentation-template' :
2016-04-05 20:43:46 +02:00
case 'application/xml' :
case 'text/html' :
2017-11-09 13:16:06 +01:00
case 'text/csv' :
2016-04-05 20:43:46 +02:00
$joiner = '' ;
break ;
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-word.document.macroenabled.12' :
2016-04-05 20:43:46 +02:00
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-excel.sheet.macroenabled.12' :
2016-04-05 20:43:46 +02:00
$joiner = '<w:br w:type="page" />' ;
break ;
case 'text/plain' :
$joiner = " \r \n " ;
break ;
default :
2021-10-07 18:22:45 +02:00
$err = lang ( '%1 not implemented for %2!' , '$$pagerepeat$$' , $mimetype );
2021-03-31 17:49:43 +02:00
$ret = false ;
return $ret ;
2016-04-05 20:43:46 +02:00
}
}
2021-10-07 18:22:45 +02:00
foreach (( array ) $ids as $n => $id )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if ( $contentrepeat )
{
$content = $contentrepeat ;
} //content to repeat
if ( $lableprint )
{
$content = $Labelrepeat ;
}
2016-04-05 20:43:46 +02:00
2021-10-04 13:02:34 +02:00
// generate replacements; if exception is thrown, catch it set error message and return false
2016-04-05 20:43:46 +02:00
try
{
2021-10-07 18:22:45 +02:00
if ( ! ( $replacements = $this -> get_replacements ( $id , $content )))
2016-04-05 20:43:46 +02:00
{
$err = lang ( 'Entry not found!' );
2021-03-31 17:49:43 +02:00
$ret = false ;
return $ret ;
2016-04-05 20:43:46 +02:00
}
}
catch ( Api\Exception\WrongUserinput $e )
{
// if this returns with an exeption, something failed big time
$err = $e -> getMessage ();
2021-03-31 17:49:43 +02:00
$ret = false ;
return $ret ;
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
if ( $this -> report_memory_usage )
{
error_log ( __METHOD__ . " () $n : $id " . Api\Vfs :: hsize ( memory_get_usage ( true )));
}
2016-04-05 20:43:46 +02:00
// some general replacements: current user, date and time
2021-10-06 00:09:39 +02:00
if ( strpos ( $content , '$$user/' ) !== false && ( $user = $GLOBALS [ 'egw' ] -> accounts -> id2name ( $GLOBALS [ 'egw_info' ][ 'user' ][ 'account_id' ], 'person_id' )))
2016-04-05 20:43:46 +02:00
{
2021-10-06 00:09:39 +02:00
$replacements += $this -> contact_replacements ( $user , 'user' , false , $content );
$replacements [ '$$user/primary_group$$' ] = $GLOBALS [ 'egw' ] -> accounts -> id2name ( $GLOBALS [ 'egw' ] -> accounts -> id2name ( $GLOBALS [ 'egw_info' ][ 'user' ][ 'account_id' ], 'account_primary_group' ));
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
$replacements [ '$$date$$' ] = Api\DateTime :: to ( 'now' , true );
2016-04-05 20:43:46 +02:00
$replacements [ '$$datetime$$' ] = Api\DateTime :: to ( 'now' );
2021-10-07 18:22:45 +02:00
$replacements [ '$$time$$' ] = Api\DateTime :: to ( 'now' , false );
2016-04-05 20:43:46 +02:00
2018-10-11 18:09:16 +02:00
$app = $this -> get_app ();
2021-03-31 17:49:43 +02:00
$replacements += $this -> share_placeholder ( $app , $id , '' , $content );
2018-10-11 18:09:16 +02:00
2016-04-05 20:43:46 +02:00
// does our extending class registered table-plugins AND document contains table tags
2021-10-07 18:22:45 +02:00
if ( $this -> table_plugins && preg_match_all ( '/\\$\\$table\\/([A-Za-z0-9_]+)\\$\\$(.*?)\\$\\$endtable\\$\\$/s' , $content , $matches , PREG_SET_ORDER ))
2016-04-05 20:43:46 +02:00
{
// process each table
foreach ( $matches as $match )
{
2021-10-07 18:22:45 +02:00
$plugin = $match [ 1 ]; // plugin name
2016-04-05 20:43:46 +02:00
$callback = $this -> table_plugins [ $plugin ];
2021-10-07 18:22:45 +02:00
$repeat = $match [ 2 ]; // line to repeat
2016-04-05 20:43:46 +02:00
$repeats = '' ;
2021-10-07 18:22:45 +02:00
if ( isset ( $callback ))
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
for ( $n = 0 ; ( $row_replacements = $this -> $callback ( $plugin , $id , $n , $repeat )); ++ $n )
2016-04-05 20:43:46 +02:00
{
$_repeat = $this -> process_commands ( $repeat , $row_replacements );
2021-10-07 18:22:45 +02:00
$repeats .= $this -> replace ( $_repeat , $row_replacements , $mimetype , $mso_application_progid );
2016-04-05 20:43:46 +02:00
}
}
2021-10-07 18:22:45 +02:00
$content = str_replace ( $match [ 0 ], $repeats , $content );
2016-04-05 20:43:46 +02:00
}
}
2021-10-07 18:22:45 +02:00
$content = $this -> process_commands ( $this -> replace ( $content , $replacements , $mimetype , $mso_application_progid , $charset ), $replacements );
2016-04-05 20:43:46 +02:00
// remove not existing replacements (eg. from calendar array)
2021-10-07 18:22:45 +02:00
if ( strpos ( $content , '$$' ) !== null )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$content = preg_replace ( '/\$\$[a-z0-9_\/]+\$\$/i' , '' , $content );
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
if ( $contentrepeat )
2016-04-05 20:43:46 +02:00
{
fwrite ( $content_stream , ( $n == 0 ? '' : $joiner ) . $content );
}
if ( $lableprint )
{
2021-10-07 18:22:45 +02:00
$contentrep [ is_array ( $id ) ? implode ( ':' , $id ) : $id ] = $content ;
2016-04-05 20:43:46 +02:00
}
}
2021-10-07 18:22:45 +02:00
if ( $Labelrepeat )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$countpage = 0 ;
$count = 0 ;
$contentrepeatpages [ $countpage ] = $Labelstart . $Labeltend ;
2016-04-05 20:43:46 +02:00
2021-10-07 18:22:45 +02:00
foreach ( $contentrep as $Label )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$contentrepeatpages [ $countpage ] = preg_replace ( '/\$\$labelplacement\$\$/' , $Label , $contentrepeatpages [ $countpage ], 1 );
$count = $count + 1 ;
if (( $count % $countlables ) == 0 && count ( $contentrep ) > $count ) //new page
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$countpage = $countpage + 1 ;
$contentrepeatpages [ $countpage ] = $Labelstart . $Labeltend ;
2016-04-05 20:43:46 +02:00
}
}
2021-10-07 18:22:45 +02:00
$contentrepeatpages [ $countpage ] = preg_replace ( '/\$\$labelplacement\$\$/' , '' , $contentrepeatpages [ $countpage ], - 1 ); //clean empty fields
2016-04-05 20:43:46 +02:00
switch ( $mimetype )
{
case 'application/rtf' :
case 'text/rtf' :
2021-10-07 18:22:45 +02:00
$ret = $contentstart . implode ( '\\par \\page\\pard\\plain' , $contentrepeatpages ) . $contentend ;
2021-03-31 17:49:43 +02:00
break ;
2016-04-05 20:43:46 +02:00
case 'application/vnd.oasis.opendocument.text' :
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.presentation' :
case 'application/vnd.oasis.opendocument.text-template' :
case 'application/vnd.oasis.opendocument.presentation-template' :
2021-10-07 18:22:45 +02:00
$ret = $contentstart . implode ( '<text:line-break />' , $contentrepeatpages ) . $contentend ;
2021-03-31 17:49:43 +02:00
break ;
2016-04-05 20:43:46 +02:00
case 'application/vnd.oasis.opendocument.spreadsheet' :
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
2021-10-07 18:22:45 +02:00
$ret = $contentstart . implode ( '</text:p><text:p>' , $contentrepeatpages ) . $contentend ;
2021-03-31 17:49:43 +02:00
break ;
2016-04-05 20:43:46 +02:00
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-word.document.macroenabled.12' :
2016-04-05 20:43:46 +02:00
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-excel.sheet.macroenabled.12' :
2021-10-07 18:22:45 +02:00
$ret = $contentstart . implode ( '<w:br w:type="page" />' , $contentrepeatpages ) . $contentend ;
2021-03-31 17:49:43 +02:00
break ;
2016-04-05 20:43:46 +02:00
case 'text/plain' :
2021-10-07 18:22:45 +02:00
$ret = $contentstart . implode ( " \r \n " , $contentrep ) . $contentend ;
2021-03-31 17:49:43 +02:00
break ;
default :
2021-10-07 18:22:45 +02:00
$err = lang ( '%1 not implemented for %2!' , '$$labelplacement$$' , $mimetype );
2021-03-31 17:49:43 +02:00
$ret = false ;
2016-04-05 20:43:46 +02:00
}
2021-03-31 17:49:43 +02:00
return $ret ;
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
if ( $contentrepeat )
2016-04-05 20:43:46 +02:00
{
fwrite ( $content_stream , $contentend );
rewind ( $content_stream );
2021-03-31 17:49:43 +02:00
$content = stream_get_contents ( $content_stream );
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
if ( $this -> report_memory_usage )
{
error_log ( __METHOD__ . " () returning " . Api\Vfs :: hsize ( memory_get_peak_usage ( true )));
}
2016-04-05 20:43:46 +02:00
return $content ;
}
/**
* Replace placeholders in $content of $mimetype with $replacements
*
* @ param string $content
* @ param array $replacements name => replacement pairs
* @ param string $mimetype mimetype of content
* @ param string $mso_application_progid = '' MS Office 2003 : 'Excel.Sheet' or 'Word.Document'
* @ param string $charset = null charset to override default set by mimetype or export charset
* @ return string
*/
2021-10-07 18:22:45 +02:00
protected function replace ( $content , array $replacements , $mimetype , $mso_application_progid = '' , $charset = null )
2016-04-05 20:43:46 +02:00
{
switch ( $mimetype )
{
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.text' : // open office
2016-04-05 20:43:46 +02:00
case 'application/vnd.oasis.opendocument.spreadsheet' :
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.presentation' :
case 'application/vnd.oasis.opendocument.text-template' :
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
case 'application/vnd.oasis.opendocument.presentation-template' :
2021-10-07 18:22:45 +02:00
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' : // ms office 2007
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-word.document.macroenabled.12' :
2016-04-05 20:43:46 +02:00
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-excel.sheet.macroenabled.12' :
2016-04-05 20:43:46 +02:00
case 'application/xml' :
case 'text/xml' :
$is_xml = true ;
2021-10-07 18:22:45 +02:00
$charset = 'utf-8' ; // xml files --> always use utf-8
2016-04-05 20:43:46 +02:00
break ;
2019-03-08 11:26:25 +01:00
case 'application/rtf' :
case 'text/rtf' :
2021-10-07 18:22:45 +02:00
$charset = 'iso-8859-1' ; // rtf seems to user iso-8859-1 or equivalent windows charset, not utf-8
2019-03-08 11:26:25 +01:00
break ;
2016-04-05 20:43:46 +02:00
case 'text/html' :
$is_xml = true ;
$matches = null ;
2021-10-07 18:22:45 +02:00
if ( preg_match ( '/<meta http-equiv="content-type".*charset=([^;"]+)/i' , $content , $matches ))
2016-04-05 20:43:46 +02:00
{
$charset = $matches [ 1 ];
}
2021-10-07 18:22:45 +02:00
elseif ( empty ( $charset ))
2016-04-05 20:43:46 +02:00
{
$charset = 'utf-8' ;
}
break ;
2021-10-07 18:22:45 +02:00
default : // div. text files --> use our export-charset, defined in addressbook prefs
if ( empty ( $charset ))
{
$charset = $this -> contacts -> prefs [ 'csv_charset' ];
}
2016-04-05 20:43:46 +02:00
break ;
}
//error_log(__METHOD__."('$document', ... ,$mimetype) --> $charset (egw=".Api\Translation::charset().', export='.$this->contacts->prefs['csv_charset'].')');
// do we need to convert charset
2021-10-07 18:22:45 +02:00
if ( $charset && $charset != Api\Translation :: charset ())
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$replacements = Api\Translation :: convert ( $replacements , Api\Translation :: charset (), $charset );
2016-04-05 20:43:46 +02:00
}
// Date only placeholders for timestamps
if ( is_array ( $this -> date_fields ))
{
foreach ( $this -> date_fields as $field )
{
2021-10-07 18:22:45 +02:00
if (( $value = $replacements [ '$$' . $field . '$$' ] ? ? null ))
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$time = Api\DateTime :: createFromFormat ( '+' . Api\DateTime :: $user_dateformat . ' ' . Api\DateTime :: $user_timeformat . '*' , $value );
$replacements [ '$$' . $field . '/date$$' ] = $time ? $time -> format ( Api\DateTime :: $user_dateformat ) : '' ;
2016-04-05 20:43:46 +02:00
}
}
}
2022-04-26 20:24:37 +02:00
if ( ! empty ( $is_xml )) // zip'ed xml document (eg. OO)
2016-04-05 20:43:46 +02:00
{
// Numeric fields
$names = array ();
// Tags we can replace with the target document's version
$replace_tags = array ();
// only keep tags, if we have xsl extension available
2021-10-07 18:22:45 +02:00
if ( class_exists ( 'XSLTProcessor' ) && class_exists ( 'DOMDocument' ) && $this -> parse_html_styles )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
switch ( $mimetype . $mso_application_progid )
2016-04-05 20:43:46 +02:00
{
case 'text/html' :
$replace_tags = array (
2021-10-07 18:22:45 +02:00
'<b>' , '<strong>' , '<i>' , '<em>' , '<u>' , '<span>' , '<ol>' , '<ul>' , '<li>' ,
'<table>' , '<tr>' , '<td>' , '<a>' , '<style>' , '<img>' ,
2016-04-05 20:43:46 +02:00
);
break ;
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.text' : // open office
2016-04-05 20:43:46 +02:00
case 'application/vnd.oasis.opendocument.spreadsheet' :
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.presentation' :
case 'application/vnd.oasis.opendocument.text-template' :
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
case 'application/vnd.oasis.opendocument.presentation-template' :
2016-04-05 20:43:46 +02:00
$replace_tags = array (
2021-10-07 18:22:45 +02:00
'<b>' , '<strong>' , '<i>' , '<em>' , '<u>' , '<span>' , '<ol>' , '<ul>' , '<li>' ,
'<table>' , '<tr>' , '<td>' , '<a>' ,
2016-04-05 20:43:46 +02:00
);
break ;
2021-10-07 18:22:45 +02:00
case 'application/xmlWord.Document' : // Word 2003*/
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' : // ms office 2007
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-word.document.macroenabled.12' :
2016-04-05 20:43:46 +02:00
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-excel.sheet.macroenabled.12' :
2016-04-05 20:43:46 +02:00
$replace_tags = array (
2021-10-07 18:22:45 +02:00
'<b>' , '<strong>' , '<i>' , '<em>' , '<u>' , '<span>' , '<ol>' , '<ul>' , '<li>' ,
'<table>' , '<tr>' , '<td>' ,
2016-04-05 20:43:46 +02:00
);
break ;
}
}
// clean replacements from array values and html or html-entities, which mess up xml
foreach ( $replacements as $name => & $value )
{
// set unresolved array values to empty string
if ( is_array ( $value ))
{
$value = '' ;
continue ;
}
// decode html entities back to utf-8
2021-10-07 18:22:45 +02:00
if ( is_string ( $value ) && ( strpos ( $value , '&' ) !== false ) && $this -> parse_html_styles )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$value = html_entity_decode ( $value , ENT_QUOTES , $charset );
2016-04-05 20:43:46 +02:00
// remove all non-decodable entities
2021-10-07 18:22:45 +02:00
if ( strpos ( $value , '&' ) !== false )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$value = preg_replace ( '/&[^; ]+;/' , '' , $value );
2016-04-05 20:43:46 +02:00
}
}
2016-07-28 22:14:20 +02:00
if ( ! $this -> parse_html_styles || (
2021-10-07 18:22:45 +02:00
strpos ( $value , " \n " ) !== FALSE &&
strpos ( $value , '<br' ) === FALSE && strpos ( $value , '<span' ) === FALSE && strpos ( $value , '<p' ) === FALSE && strpos ( $value , '<div' ) === FALSE
))
2016-04-05 20:43:46 +02:00
{
// Encode special chars so they don't break the file
2021-10-07 18:22:45 +02:00
$value = htmlspecialchars ( $value , ENT_NOQUOTES );
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
else
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if ( is_string ( $value ) && ( strpos ( $value , '<' ) !== false ))
{
// Clean HTML, if it's being kept
if ( $replace_tags && extension_loaded ( 'tidy' ))
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$tidy = new tidy ();
$cleaned = $tidy -> repairString ( $value , self :: $tidy_config , 'utf8' );
// Found errors. Strip it all so there's some output
if ( $tidy -> getStatus () == 2 )
{
error_log ( $tidy -> errorBuffer );
$value = strip_tags ( $value );
}
else
{
$value = $cleaned ;
}
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
// replace </p> and <br /> with CRLF (remove <p> and CRLF)
$value = strip_tags ( str_replace ( array ( " \r " , " \n " , '<p>' , '</p>' , '<div>' , '</div>' , '<br />' ),
array ( '' , '' , '' , " \r \n " , '' , " \r \n " , " \r \n " ), $value
),
implode ( '' , $replace_tags )
);
// Change <tag>...\r\n</tag> to <tag>...</tag>\r\n or simplistic line break below will mangle it
// Loop to catch things like <b><span>Break:\r\n</span></b>
if ( $mso_application_progid )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$count = $i = 0 ;
do
{
$value = preg_replace ( '/<(b|strong|i|em|u|span)\b([^>]*?)>(.*?)' . " \r \n " . '<\/\1>/u' , '<$1$2>$3</$1>' . " \r \n " , $value , - 1 , $count );
$i ++ ;
}
while ( $count > 0 && $i < 10 ); // Limit of 10 chosen arbitrarily just in case
2016-04-05 20:43:46 +02:00
}
}
}
// replace all control chars (C0+C1) but CR (\015), LF (\012) and TAB (\011) (eg. vertical tabulators) with space
// as they are not allowed in xml
2021-10-07 18:22:45 +02:00
$value = preg_replace ( '/[\000-\010\013\014\016-\037\177-\237\x{FFF0}-\x{FFFD}]/u' , ' ' , $value );
2016-04-05 20:43:46 +02:00
if ( is_numeric ( $value ) && $name != '$$user/account_id$$' ) // account_id causes problems with the preg_replace below
{
2021-10-07 18:22:45 +02:00
$names [] = preg_quote ( $name , '/' );
2016-04-05 20:43:46 +02:00
}
}
// Look for numbers, set their value if needed
2021-10-07 18:22:45 +02:00
if ( property_exists ( $this , 'numeric_fields' ) || count ( $names ))
2016-04-05 20:43:46 +02:00
{
2021-10-05 14:11:11 +02:00
foreach ( $this -> numeric_fields as $fieldname )
{
2021-10-07 18:22:45 +02:00
$names [] = preg_quote ( $fieldname , '/' );
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
$this -> format_spreadsheet_numbers ( $content , $names , $mimetype . $mso_application_progid );
2016-04-05 20:43:46 +02:00
}
// Look for dates, set their value if needed
if ( $this -> date_fields || count ( $names ))
{
$names = array ();
2021-10-07 18:22:45 +02:00
foreach (( array ) $this -> date_fields as $fieldname )
{
2016-04-05 20:43:46 +02:00
$names [] = $fieldname ;
}
2021-10-07 18:22:45 +02:00
$this -> format_spreadsheet_dates ( $content , $names , $replacements , $mimetype . $mso_application_progid );
2016-04-05 20:43:46 +02:00
}
// replace CRLF with linebreak tag of given type
2021-10-07 18:22:45 +02:00
switch ( $mimetype . $mso_application_progid )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.text' : // open office writer
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.text-template' :
case 'application/vnd.oasis.opendocument.presentation' :
case 'application/vnd.oasis.opendocument.presentation-template' :
2016-04-05 20:43:46 +02:00
$break = '<text:line-break/>' ;
break ;
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.spreadsheet' : // open office calc
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
2016-04-05 20:43:46 +02:00
$break = '</text:p><text:p>' ;
break ;
2021-10-07 18:22:45 +02:00
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' : // ms word 2007
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-word.document.macroenabled.12' :
2016-04-05 20:43:46 +02:00
$break = '</w:t><w:br/><w:t>' ;
break ;
2021-10-07 18:22:45 +02:00
case 'application/xmlExcel.Sheet' : // Excel 2003
2016-04-05 20:43:46 +02:00
$break = ' ' ;
break ;
2021-10-07 18:22:45 +02:00
case 'application/xmlWord.Document' : // Word 2003*/
2016-04-05 20:43:46 +02:00
$break = '</w:t><w:br/><w:t>' ;
break ;
case 'text/html' :
$break = '<br/>' ;
break ;
2021-10-07 18:22:45 +02:00
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' : // ms excel 2007
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-excel.sheet.macroenabled.12' :
2016-04-05 20:43:46 +02:00
default :
$break = " \r \n " ;
break ;
}
// now decode &, < and >, which need to be encoded as entities in xml
// Check for encoded >< getting double-encoded
if ( $this -> parse_html_styles )
{
2021-10-07 18:22:45 +02:00
$replacements = str_replace ( array ( '&' , " \r " , " \n " , '&lt;' , '&gt;' ), array ( '&' , '' , $break ,
'<' ,
'>' ), $replacements );
2016-04-05 20:43:46 +02:00
}
2016-04-11 17:21:16 +02:00
else
{
// Need to at least handle new lines, or it'll be run together on one line
2021-10-07 18:22:45 +02:00
$replacements = str_replace ( array ( " \r " , " \n " ), array ( '' , $break ), $replacements );
2016-04-11 17:21:16 +02:00
}
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
if ( $mimetype == 'application/x-yaml' )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$content = preg_replace_callback ( '/^( +)([^$\n]*)(\$\$.+?\$\$)/m' , function ( $matches ) use ( $replacements )
2016-04-05 20:43:46 +02:00
{
// allow with {{name/replace/with}} syntax to replace eg. commas with linebreaks: "{{name/, */\n}}"
$parts = null ;
2021-10-07 18:22:45 +02:00
if ( preg_match ( '|^\$\$([^/]+)/([^/]+)/([^$]*)\$\$$|' , $matches [ 3 ], $parts ) && isset ( $replacements [ '$$' . $parts [ 1 ] . '$$' ]))
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$replacement =& $replacements [ '$$' . $parts [ 1 ] . '$$' ];
$replacement = preg_replace ( '/' . $parts [ 2 ] . '/' , strtr ( $parts [ 3 ], array (
2016-04-05 20:43:46 +02:00
'\\n' => " \n " , '\\r' => " \r " , '\\t' => " \t " , '\\v' => " \ v " , '\\\\' => '\\' , '\\f' => " \ f " ,
2021-10-07 18:22:45 +02:00
)), $replacement
);
2016-04-05 20:43:46 +02:00
}
else
{
$replacement =& $replacements [ $matches [ 3 ]];
}
// replacement with multiple lines --> add same number of space as before placeholder
2021-10-07 18:22:45 +02:00
if ( isset ( $replacement ))
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
return $matches [ 1 ] . $matches [ 2 ] . implode ( " \n " . $matches [ 1 ], preg_split ( " / \r ? \n / " , $replacement ));
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
return $matches [ 0 ]; // regular replacement below
}, $content );
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
return str_replace ( array_keys ( $replacements ), array_values ( $replacements ), $content );
2016-04-05 20:43:46 +02:00
}
/**
* Convert numeric values in spreadsheets into actual numeric values
*/
protected function format_spreadsheet_numbers ( & $content , $names , $mimetype )
{
2021-10-05 14:11:11 +02:00
foreach ( $this -> numeric_fields as $fieldname )
{
2021-10-07 18:22:45 +02:00
$names [] = preg_quote ( $fieldname , '/' );
2016-04-05 20:43:46 +02:00
}
switch ( $mimetype )
{
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.spreadsheet' : // open office calc
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
2021-10-07 18:22:45 +02:00
$format = '/<table:table-cell([^>]+?)office:value-type="[^"]+"([^>]*?)(?:calcext:value-type="[^"]+")?>.?<([a-z].*?)[^>]*>(' . implode ( '|' , $names ) . ')<\/\3>.?<\/table:table-cell>/s' ;
2018-04-23 17:24:49 +02:00
$replacement = '<table:table-cell$1office:value-type="float" office:value="$4"$2><$3>$4</$3></table:table-cell>' ;
2016-04-05 20:43:46 +02:00
break ;
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.text' : // tables in open office writer
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.presentation' :
case 'application/vnd.oasis.opendocument.text-template' :
case 'application/vnd.oasis.opendocument.presentation-template' :
2021-10-07 18:22:45 +02:00
$format = '/<table:table-cell([^>]+?)office:value-type="[^"]+"([^>]*?)>.?<([a-z].*?)[^>]*>(' . implode ( '|' , $names ) . ')<\/\3>.?<\/table:table-cell>/s' ;
2016-04-05 20:43:46 +02:00
$replacement = '<table:table-cell$1office:value-type="float" office:value="$4"$2><text:p text:style-name="Standard">$4</text:p></table:table-cell>' ;
break ;
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.text' : // open office writer
case 'application/xmlExcel.Sheet' : // Excel 2003
$format = '/' . preg_quote ( '<Data ss:Type="String">' , '/' ) . '(' . implode ( '|' , $names ) . ')' . preg_quote ( '</Data>' , '/' ) . '/' ;
2016-04-05 20:43:46 +02:00
$replacement = '<Data ss:Type="Number">$1</Data>' ;
break ;
}
2021-10-07 18:22:45 +02:00
if ( ! empty ( $format ) && $names )
2016-04-05 20:43:46 +02:00
{
// Dealing with backtrack limit per AmigoJack 10-Jul-2010 comment on php.net preg-replace docs
2021-10-07 18:22:45 +02:00
do
{
2016-04-05 20:43:46 +02:00
$result = preg_replace ( $format , $replacement , $content , - 1 );
}
2021-10-07 18:22:45 +02:00
// try to increase/double pcre.backtrack_limit failure
2016-04-05 20:43:46 +02:00
while ( preg_last_error () == PREG_BACKTRACK_LIMIT_ERROR && self :: increase_backtrack_limit ());
2021-10-07 18:22:45 +02:00
if ( $result )
{
$content = $result ;
} // On failure $result would be NULL
2016-04-05 20:43:46 +02:00
}
}
/**
* Increase / double prce . backtrack_limit up to 1 / 4 of memory_limit
*
* @ return boolean true : backtrack_limit increased , may try again , false limit already to high
*/
protected static function increase_backtrack_limit ()
{
2021-10-07 18:22:45 +02:00
static $backtrack_limit = null , $memory_limit = null ;
if ( ! isset ( $backtrack_limit ))
2016-04-05 20:43:46 +02:00
{
$backtrack_limit = ini_get ( 'pcre.backtrack_limit' );
}
2021-10-07 18:22:45 +02:00
if ( ! isset ( $memory_limit ))
2016-04-05 20:43:46 +02:00
{
$memory_limit = ini_get ( 'memory_limit' );
switch ( strtoupper ( substr ( $memory_limit , - 1 )))
{
2021-10-07 18:22:45 +02:00
case 'G' :
$memory_limit *= 1024 ;
case 'M' :
$memory_limit *= 1024 ;
case 'K' :
$memory_limit *= 1024 ;
2016-04-05 20:43:46 +02:00
}
}
2021-10-07 18:22:45 +02:00
if ( $backtrack_limit < $memory_limit / 8 )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
ini_set ( 'pcre.backtrack_limit' , $backtrack_limit *= 2 );
2016-04-05 20:43:46 +02:00
return true ;
}
error_log ( " pcre.backtrack_limit exceeded @ $backtrack_limit , some cells left as text. " );
return false ;
}
/**
* Convert date / timestamp values in spreadsheets into actual date / timestamp values
*/
protected function format_spreadsheet_dates ( & $content , $names , & $values , $mimetype )
{
if ( ! in_array ( $mimetype , array (
2021-10-07 18:22:45 +02:00
'application/vnd.oasis.opendocument.spreadsheet' , // open office calc
'application/xmlExcel.Sheet' , // Excel 2003
2016-04-05 20:43:46 +02:00
//'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'//Excel WTF
2021-10-07 18:22:45 +02:00
)))
{
return ;
}
2016-04-05 20:43:46 +02:00
// Some different formats dates could be in, depending what they've been through
$formats = array (
2021-10-07 18:22:45 +02:00
'!' . Api\DateTime :: $user_dateformat . ' ' . Api\DateTime :: $user_timeformat . ':s' ,
'!' . Api\DateTime :: $user_dateformat . '*' . Api\DateTime :: $user_timeformat . ':s' ,
'!' . Api\DateTime :: $user_dateformat . '* ' . Api\DateTime :: $user_timeformat ,
'!' . Api\DateTime :: $user_dateformat . '*' ,
'!' . Api\DateTime :: $user_dateformat ,
2016-08-24 16:21:57 +02:00
'!Y-m-d\TH:i:s'
2016-04-05 20:43:46 +02:00
);
// Properly format values for spreadsheet
foreach ( $names as $idx => & $field )
{
2021-10-07 18:22:45 +02:00
$key = '$$' . $field . '$$' ;
2016-04-05 20:43:46 +02:00
$field = preg_quote ( $field , '/' );
2022-04-26 20:24:37 +02:00
if ( ! empty ( $values [ $key ]))
2016-04-05 20:43:46 +02:00
{
2018-02-02 19:37:02 +01:00
$date = Api\DateTime :: createFromUserFormat ( $values [ $key ]);
2017-03-07 20:08:01 +01:00
if ( $mimetype == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ||
$mimetype == 'application/vnd.ms-excel.sheet.macroenabled.12' ) //Excel WTF
2016-04-05 20:43:46 +02:00
{
$interval = $date -> diff ( new Api\DateTime ( '1900-01-00 0:00' ));
2021-10-07 18:22:45 +02:00
$values [ $key ] = $interval -> format ( '%a' ) + 1 ; // 1900-02-29 did not exist
2016-04-05 20:43:46 +02:00
// 1440 minutes in a day - fractional part
2021-10-07 18:22:45 +02:00
$values [ $key ] += ( $date -> format ( 'H' ) * 60 + $date -> format ( 'i' )) / 1440 ;
2016-04-05 20:43:46 +02:00
}
else
{
2021-10-07 18:22:45 +02:00
$values [ $key ] = date ( 'Y-m-d\TH:i:s' , Api\DateTime :: to ( $date , 'ts' ));
2016-04-05 20:43:46 +02:00
}
}
else
{
unset ( $names [ $idx ]);
}
}
switch ( $mimetype )
{
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.spreadsheet' : // open office calc
2016-04-05 20:43:46 +02:00
// Removing these forces calc to respect our set value-type
2021-10-07 18:22:45 +02:00
$content = str_ireplace ( 'calcext:value-type="string"' , '' , $content );
2016-04-05 20:43:46 +02:00
2021-10-07 18:22:45 +02:00
$format = '/<table:table-cell([^>]+?)office:value-type="[^"]+"([^>]*?)>.?<([a-z].*?)[^>]*>\$\$(' . implode ( '|' , $names ) . ')\$\$<\/\3>.?<\/table:table-cell>/s' ;
2016-04-05 20:43:46 +02:00
$replacement = '<table:table-cell$1office:value-type="date" office:date-value="\$\$$4\$\$"$2><$3>\$\$$4\$\$</$3></table:table-cell>' ;
break ;
2021-10-07 18:22:45 +02:00
case 'application/xmlExcel.Sheet' : // Excel 2003
$format = '/' . preg_quote ( '<Data ss:Type="String">' , '/' ) . '..(' . implode ( '|' , $names ) . ')..' . preg_quote ( '</Data>' , '/' ) . '/' ;
2016-04-05 20:43:46 +02:00
$replacement = '<Data ss:Type="DateTime">\$\$$1\$\$</Data>' ;
break ;
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-excel.sheet.macroenabled.12' :
2016-04-05 20:43:46 +02:00
break ;
}
if ( $format && $names )
{
// Dealing with backtrack limit per AmigoJack 10-Jul-2010 comment on php.net preg-replace docs
2021-10-07 18:22:45 +02:00
do
{
2016-04-05 20:43:46 +02:00
$result = preg_replace ( $format , $replacement , $content , - 1 );
}
2021-10-07 18:22:45 +02:00
// try to increase/double pcre.backtrack_limit failure
2016-04-05 20:43:46 +02:00
while ( preg_last_error () == PREG_BACKTRACK_LIMIT_ERROR && self :: increase_backtrack_limit ());
2021-10-07 18:22:45 +02:00
if ( $result )
{
$content = $result ;
} // On failure $result would be NULL
2016-04-05 20:43:46 +02:00
}
}
/**
* Expand link_to custom fields with the merge replacements from the app
* but only if the template uses them .
*/
public function cf_link_to_expand ( $values , $content , & $replacements , $app = null )
{
if ( $app == null )
{
2021-10-07 18:22:45 +02:00
$app = str_replace ( '_merge' , '' , get_class ( $this ));
2016-04-05 20:43:46 +02:00
}
$cfs = Api\Storage\Customfields :: get ( $app );
// Cache, in case more than one sub-placeholder is used
$app_replacements = array ();
// Custom field placeholders look like {{#name}}
// Placeholders that need expanded will look like {{#name/placeholder}}
$matches = null ;
preg_match_all ( '/\${2}(([^\/#]*?\/)?)#([^$\/]+)\/(.*?)[$}]{2}/' , $content , $matches );
list ( $placeholders , , , $cf , $sub ) = $matches ;
2017-01-19 18:51:57 +01:00
// Collect any used custom fields from entries so you can do
// {{#other_app/#other_app_cf/n_fn}}
$expand_sub_cfs = [];
foreach ( $sub as $index => $cf_sub )
{
2021-10-07 18:22:45 +02:00
if ( str_starts_with ( $cf_sub , '#' ))
2017-01-19 18:51:57 +01:00
{
2021-10-07 18:22:45 +02:00
$expand_sub_cfs [ $cf [ $index ]] .= '$$' . $cf_sub . '$$ ' ;
2017-01-19 18:51:57 +01:00
}
}
2016-04-05 20:43:46 +02:00
foreach ( $cf as $index => $field )
{
if ( $cfs [ $field ])
{
2021-10-07 18:22:45 +02:00
if ( in_array ( $cfs [ $field ][ 'type' ], array_keys ( $GLOBALS [ 'egw_info' ][ 'apps' ])))
2016-04-05 20:43:46 +02:00
{
$field_app = $cfs [ $field ][ 'type' ];
}
else
{
2021-10-07 18:22:45 +02:00
if ( $cfs [ $field ][ 'type' ] == 'api-accounts' || $cfs [ $field ][ 'type' ] == 'select-account' )
{
// Special case for api-accounts -> contact
$field_app = 'addressbook' ;
$account = $GLOBALS [ 'egw' ] -> accounts -> read ( $values [ '#' . $field ]);
$app_replacements [ $field ] = $this -> contact_replacements ( $account [ 'person_id' ]);
}
else
{
if (( $list = explode ( '-' , $cfs [ $field ][ 'type' ])) && in_array ( $list [ 0 ], array_keys ( $GLOBALS [ 'egw_info' ][ 'apps' ])))
{
// Sub-type - use app
$field_app = $list [ 0 ];
}
else
{
continue ;
}
}
2016-04-05 20:43:46 +02:00
}
// Get replacements for that application
if ( ! $app_replacements [ $field ])
{
2017-12-01 19:58:44 +01:00
// If we send the real content it can result in infinite loop of lookups
// so we send only the used fields
2021-10-20 22:06:28 +02:00
$content = $expand_sub_cfs [ $field ] ? ? $matches [ 0 ][ $index ];
2021-10-07 18:22:45 +02:00
$app_replacements [ $field ] = $this -> get_app_replacements ( $field_app , $values [ '#' . $field ], $content );
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
$replacements [ $placeholders [ $index ]] = $app_replacements [ $field ][ '$$' . $sub [ $index ] . '$$' ];
2016-04-05 20:43:46 +02:00
}
else
{
2021-10-07 18:22:45 +02:00
if ( $cfs [ $field ][ 'type' ] == 'date' || $cfs [ $field ][ 'type' ] == 'date-time' )
{
$this -> date_fields [] = '#' . $field ;
}
2016-04-05 20:43:46 +02:00
}
}
}
2018-10-11 18:09:16 +02:00
/**
* Figure out which app we ' re running as
*
* @ return string
*/
protected function get_app ()
{
2021-10-07 18:22:45 +02:00
switch ( get_class ( $this ))
2018-10-11 18:09:16 +02:00
{
case 'EGroupware\Api\Contacts\Merge' :
$app = 'addressbook' ;
break ;
default :
2021-10-07 18:22:45 +02:00
$app = str_replace ( '_merge' , '' , get_class ( $this ));
2021-11-13 17:39:33 +01:00
if ( ! in_array ( $app , array_keys ( $GLOBALS [ 'egw_info' ][ 'apps' ] ? ? [])))
2018-10-11 18:09:16 +02:00
{
$app = false ;
}
break ;
}
return $app ;
}
2021-09-20 22:58:02 +02:00
/**
* Get the correct class for the given app
*
* @ param $appname
*/
public static function get_app_class ( $appname )
{
2021-09-27 22:46:41 +02:00
$classname = " { $appname } _merge " ;
2021-10-07 17:31:43 +02:00
if ( class_exists ( $classname ) && is_subclass_of ( $classname , 'EGroupware\\Api\\Storage\\Merge' ))
2021-09-20 22:58:02 +02:00
{
$document_merge = new $classname ();
}
else
{
$document_merge = new Api\Contacts\Merge ();
}
return $document_merge ;
}
2017-11-15 23:41:12 +01:00
/**
* Get the replacements for any entry specified by app & id
*
2021-10-12 22:18:18 +02:00
* @ param string $app
2017-11-15 23:41:12 +01:00
* @ param string $id
* @ param string $content
* @ return array
*/
2021-09-20 22:58:02 +02:00
public function get_app_replacements ( $app , $id , $content , $prefix = '' )
2017-11-15 23:41:12 +01:00
{
$replacements = array ();
2021-10-19 17:17:22 +02:00
if ( ! $app || ! $id || ! $content )
2021-10-15 17:09:53 +02:00
{
return $replacements ;
}
2017-11-15 23:41:12 +01:00
if ( $app == 'addressbook' )
{
2018-04-03 23:26:48 +02:00
return $this -> contact_replacements ( $id , $prefix , false , $content );
2017-11-15 23:41:12 +01:00
}
try
{
2021-10-06 19:58:39 +02:00
$class = $this -> get_app_class ( $app );
$method = $app . '_replacements' ;
if ( method_exists ( $class , $method ))
2017-11-15 23:41:12 +01:00
{
$replacements = $class -> $method ( $id , $prefix , $content );
}
else
{
$replacements = $class -> get_replacements ( $id , $content );
}
}
catch ( \Exception $e )
{
// Don't break merge, just log it
error_log ( $e -> getMessage ());
}
2021-10-22 17:39:24 +02:00
return $replacements ? : [];
2017-11-15 23:41:12 +01:00
}
2021-09-27 18:52:39 +02:00
/**
* Prefix a placeholder , taking care of $ $ or {{}} markers
*
* @ param string $prefix Placeholder prefix
* @ param string $placeholder Placeholder , with or without {{ ... }} or $ $ ... $ $ markers
* @ param null | string $wrap " { " or " $ " to add markers , omit to exclude markers
* @ return string
*/
protected function prefix ( $prefix , $placeholder , $wrap = null )
{
$marker = [ '' , '' ];
if ( $placeholder [ 0 ] == '{' && is_null ( $wrap ) || $wrap [ 0 ] == '{' )
{
$marker = [ '{{' , '}}' ];
}
elseif ( $placeholder [ 0 ] == '$' && is_null ( $wrap ) || $wrap [ 0 ] == '$' )
{
$marker = [ '$$' , '$$' ];
}
$placeholder = str_replace ([ '{{' , '}}' , '$$' ], '' , $placeholder );
return $marker [ 0 ] . ( $prefix ? $prefix . '/' : '' ) . $placeholder . $marker [ 1 ];
}
2016-04-05 20:43:46 +02:00
/**
* Process special flags , such as IF or NELF
*
2021-10-12 22:18:18 +02:00
* @ param string content Text to be examined and changed
* @ param array replacements array of markers => replacement
2016-04-05 20:43:46 +02:00
*
2021-10-12 22:18:18 +02:00
* @ return string changed content
2016-04-05 20:43:46 +02:00
*/
private function process_commands ( $content , $replacements )
{
2021-10-07 18:22:45 +02:00
if ( strpos ( $content , '$$IF' ) !== false )
{ //Example use to use: $$IF n_prefix~Herr~Sehr geehrter~Sehr geehrte$$
2016-04-05 20:43:46 +02:00
$this -> replacements =& $replacements ;
2021-10-07 18:22:45 +02:00
$content = preg_replace_callback ( '/\$\$IF ([#0-9a-z_\/-]+)~(.*)~(.*)~(.*)\$\$/imU' , array ( $this ,
'replace_callback' ), $content );
2016-04-05 20:43:46 +02:00
unset ( $this -> replacements );
}
2021-10-07 18:22:45 +02:00
if ( strpos ( $content , '$$NELF' ) !== false )
{ //Example: $$NEPBR org_unit$$ sets a LF and value of org_unit, only if there is a value
2016-04-05 20:43:46 +02:00
$this -> replacements =& $replacements ;
2021-10-07 18:22:45 +02:00
$content = preg_replace_callback ( '/\$\$NELF ([#0-9a-z_\/-]+)\$\$/imU' , array ( $this ,
'replace_callback' ), $content );
2016-04-05 20:43:46 +02:00
unset ( $this -> replacements );
}
2021-10-07 18:22:45 +02:00
if ( strpos ( $content , '$$NENVLF' ) !== false )
{ //Example: $$NEPBRNV org_unit$$ sets only a LF if there is a value for org_units, but did not add any value
2016-04-05 20:43:46 +02:00
$this -> replacements =& $replacements ;
2021-10-07 18:22:45 +02:00
$content = preg_replace_callback ( '/\$\$NENVLF ([#0-9a-z_\/-]+)\$\$/imU' , array ( $this ,
'replace_callback' ), $content );
2016-04-05 20:43:46 +02:00
unset ( $this -> replacements );
}
2021-10-07 18:22:45 +02:00
if ( strpos ( $content , '$$LETTERPREFIX$$' ) !== false )
{ //Example use to use: $$LETTERPREFIX$$
2016-04-05 20:43:46 +02:00
$LETTERPREFIXCUSTOM = '$$LETTERPREFIXCUSTOM n_prefix title n_family$$' ;
2021-10-07 18:22:45 +02:00
$content = str_replace ( '$$LETTERPREFIX$$' , $LETTERPREFIXCUSTOM , $content );
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
if ( strpos ( $content , '$$LETTERPREFIXCUSTOM' ) !== false )
{ //Example use to use for a custom Letter Prefix: $$LETTERPREFIX n_prefix title n_family$$
2016-04-05 20:43:46 +02:00
$this -> replacements =& $replacements ;
2021-10-07 18:22:45 +02:00
$content = preg_replace_callback ( '/\$\$LETTERPREFIXCUSTOM ([#0-9a-z_-]+)(.*)\$\$/imU' , array ( $this ,
'replace_callback' ), $content );
2016-04-05 20:43:46 +02:00
unset ( $this -> replacements );
}
return $content ;
}
/**
* Callback for preg_replace to process $$IF
*
* @ param array $param
* @ return string
*/
private function replace_callback ( $param )
{
2022-04-26 20:24:37 +02:00
if ( ! empty ( $param [ 4 ]) && array_key_exists ( '$$' . $param [ 4 ] . '$$' , $this -> replacements ))
2021-10-07 18:22:45 +02:00
{
$param [ 4 ] = $this -> replacements [ '$$' . $param [ 4 ] . '$$' ];
}
2022-04-26 20:24:37 +02:00
if ( ! empty ( $param [ 3 ]) && array_key_exists ( '$$' . $param [ 3 ] . '$$' , $this -> replacements ))
2021-10-07 18:22:45 +02:00
{
$param [ 3 ] = $this -> replacements [ '$$' . $param [ 3 ] . '$$' ];
}
2016-04-05 20:43:46 +02:00
2022-04-26 20:24:37 +02:00
$pattern = '/' . preg_quote ( $param [ 2 ] ? ? '' , '/' ) . '/' ;
2021-10-07 18:22:45 +02:00
if ( strpos ( $param [ 0 ], '$$IF' ) === 0 && ( trim ( $param [ 2 ]) == " EMPTY " || $param [ 2 ] === '' ))
2016-04-05 20:43:46 +02:00
{
$pattern = '/^$/' ;
}
2022-04-26 20:24:37 +02:00
$replace = preg_match ( $pattern , $this -> replacements [ '$$' . $param [ 1 ] . '$$' ] ? ? '' ) ? ( $param [ 3 ] ? ? null ) : ( $param [ 4 ] ? ? null );
2016-04-05 20:43:46 +02:00
switch ( $this -> mimetype )
{
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.text' : // open office
2016-04-05 20:43:46 +02:00
case 'application/vnd.oasis.opendocument.spreadsheet' :
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.presentation' :
case 'application/vnd.oasis.opendocument.text-template' :
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
case 'application/vnd.oasis.opendocument.presentation-template' :
2021-10-07 18:22:45 +02:00
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' : // ms office 2007
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-word.document.macroenabled.12' :
2016-04-05 20:43:46 +02:00
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-excel.sheet.macroenabled.12' :
2016-04-05 20:43:46 +02:00
case 'application/xml' :
case 'text/xml' :
case 'text/html' :
$is_xml = true ;
break ;
}
switch ( $this -> mimetype )
2021-10-07 18:22:45 +02:00
{
case 'application/rtf' :
case 'text/rtf' :
$LF = '}\par \pard\plain{' ;
break ;
case 'application/vnd.oasis.opendocument.text' :
case 'application/vnd.oasis.opendocument.presentation' :
case 'application/vnd.oasis.opendocument.text-template' :
case 'application/vnd.oasis.opendocument.presentation-template' :
$LF = '<text:line-break/>' ;
break ;
case 'application/vnd.oasis.opendocument.spreadsheet' : // open office calc
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
$LF = '</text:p><text:p>' ;
break ;
case 'application/xmlExcel.Sheet' : // Excel 2003
$LF = ' ' ;
break ;
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' :
case 'application/vnd.ms-word.document.macroenabled.12' :
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' :
case 'application/vnd.ms-excel.sheet.macroenabled.12' :
$LF = '</w:t></w:r></w:p><w:p><w:r><w:t>' ;
break ;
case 'application/xml' ;
$LF = '</w:t></w:r><w:r><w:br w:type="text-wrapping" w:clear="all"/></w:r><w:r><w:t>' ;
break ;
case 'text/html' :
$LF = " <br/> " ;
break ;
default :
$LF = " \n " ;
}
if ( $is_xml )
{
$this -> replacements = str_replace ( array ( '&' , '&amp;' , '<' , '>' , " \r " , " \n " ), array ( '&' , '&' ,
'<' , '>' , '' ,
$LF ), $this -> replacements );
}
if ( strpos ( $param [ 0 ], '$$NELF' ) === 0 )
{ //sets a Pagebreak and value, only if the field has a value
2022-04-26 20:24:37 +02:00
if ( ! empty ( $this -> replacements [ '$$' . $param [ 1 ] . '$$' ]))
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$replace = $LF . $this -> replacements [ '$$' . $param [ 1 ] . '$$' ];
2016-04-05 20:43:46 +02:00
}
}
2021-10-07 18:22:45 +02:00
if ( strpos ( $param [ 0 ], '$$NENVLF' ) === 0 )
{ //sets a Pagebreak without any value, only if the field has a value
if ( $this -> replacements [ '$$' . $param [ 1 ] . '$$' ] != '' )
{
$replace = $LF ;
}
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
if ( strpos ( $param [ 0 ], '$$LETTERPREFIXCUSTOM' ) === 0 )
{ //sets a Letterprefix
2016-04-05 20:43:46 +02:00
$replaceprefixsort = array ();
2021-10-07 18:22:45 +02:00
$replaceprefix = explode ( ' ' , substr ( $param [ 0 ], 21 , - 2 ));
foreach ( $replaceprefix as $nameprefix )
2016-04-05 20:43:46 +02:00
{
2022-04-26 20:24:37 +02:00
if ( ! empty ( $this -> replacements [ '$$' . $nameprefix . '$$' ]))
2021-10-07 18:22:45 +02:00
{
$replaceprefixsort [] = $this -> replacements [ '$$' . $nameprefix . '$$' ];
}
2016-04-05 20:43:46 +02:00
}
2021-09-24 12:29:48 +02:00
$replace = implode ( ' ' , $replaceprefixsort );
2016-04-05 20:43:46 +02:00
}
return $replace ;
}
/**
* Download document merged with contact ( s )
*
2022-06-10 10:52:07 +02:00
* Uses the Collabora conversion API to convert the file to a different format
* @ see https :// sdk . collaboraonline . com / docs / conversion_api . html
2016-04-05 20:43:46 +02:00
* @ param string $document vfs - path of document
* @ param array $ids array with contact id ( s )
* @ param string $name = '' name to use for downloaded document
* @ param string $dirs comma or whitespace separated directories , used if $document is a relative path
2022-06-10 10:52:07 +02:00
* @ param string $convert_to = '' extension to convert to eg . 'pdf' or null to NOT convert
2016-04-05 20:43:46 +02:00
* @ return string with error - message on error , otherwise it does NOT return
*/
2022-06-10 10:52:07 +02:00
public function download ( $document , $ids , $name = '' , $dirs = '' , $convert_to = null )
2017-10-04 22:15:47 +02:00
{
$result = $this -> merge_file ( $document , $ids , $name , $dirs , $header );
2022-06-10 10:52:07 +02:00
if ( is_file ( $result ) && is_readable ( $result ))
2017-10-04 22:15:47 +02:00
{
2022-06-10 10:52:07 +02:00
if ( $convert_to && class_exists ( 'EGroupware\\Collabora\\Conversion' ))
{
$convert = new Conversion ();
if ( ! $convert -> convert ( $result , $converted , $convert_to , $error_msg , false ))
{
return $error_msg ;
}
$header = [
'name' => pathinfo ( $name , PATHINFO_FILENAME ) . '.' . $convert_to ,
'mime' => Api\MimeMagic :: ext2mime ( $convert_to ),
'filesize' => filesize ( $converted ),
];
$result = $converted ;
}
2021-10-07 18:22:45 +02:00
Api\Header\Content :: type ( $header [ 'name' ], $header [ 'mime' ], $header [ 'filesize' ]);
2022-06-10 10:52:07 +02:00
readfile ( $result );
2017-10-04 22:15:47 +02:00
exit ;
}
return $result ;
}
/**
* Merge the IDs into the document , puts the document into the output buffer
*
* @ param string $document vfs - path of document
* @ param array $ids array with contact id ( s )
* @ param string $name = '' name to use for downloaded document
* @ param string $dirs comma or whitespace separated directories , used if $document is a relative path
2021-10-12 22:18:18 +02:00
* @ param array $header File name , mime & filesize if you want to send a header
2017-10-04 22:15:47 +02:00
*
* @ return string with error - message on error
* @ throws Api\Exception
*/
2021-10-07 18:22:45 +02:00
public function merge_file ( $document , $ids , & $name = '' , $dirs = '' , & $header )
2016-04-05 20:43:46 +02:00
{
//error_log(__METHOD__."('$document', ".array2string($ids).", '$name', dirs='$dirs') ->".function_backtrace());
2021-10-07 18:22:45 +02:00
if (( $error = $this -> check_document ( $document , $dirs )))
2016-04-05 20:43:46 +02:00
{
return $error ;
}
2021-10-07 18:22:45 +02:00
$content_url = Api\Vfs :: PREFIX . $document ;
switch (( $mimetype = Api\Vfs :: mime_content_type ( $document )))
2016-04-05 20:43:46 +02:00
{
case 'message/rfc822' :
//error_log(__METHOD__."('$document', ".array2string($ids).", '$name', dirs='$dirs')=>$content_url ->".function_backtrace());
$mail_bo = Api\Mail :: getInstance ();
$mail_bo -> openConnection ();
try
{
2021-03-31 17:49:43 +02:00
$_folder = $this -> keep_emails ? '' : FALSE ;
$msgs = $mail_bo -> importMessageToMergeAndSend ( $this , $content_url , $ids , $_folder );
2016-04-05 20:43:46 +02:00
}
catch ( Api\Exception\WrongUserinput $e )
{
// if this returns with an exeption, something failed big time
return $e -> getMessage ();
}
//error_log(__METHOD__.__LINE__.' Message after importMessageToMergeAndSend:'.array2string($msgs));
$retString = '' ;
2021-10-07 18:22:45 +02:00
if ( count ( $msgs [ 'success' ]) > 0 )
{
$retString .= count ( $msgs [ 'success' ]) . ' ' . ( count ( $msgs [ 'success' ]) + count ( $msgs [ 'failed' ]) == 1 ? lang ( 'Message prepared for sending.' ) : lang ( 'Message(s) send ok.' ));
} //implode('<br />',$msgs['success']);
2016-04-05 20:43:46 +02:00
//if (strlen($retString)>0) $retString .= '<br />';
2021-10-07 18:22:45 +02:00
foreach ( $msgs [ 'failed' ] as $c => $e )
{
$errorString .= lang ( 'contact' ) . ' ' . lang ( 'id' ) . ':' . $c . '->' . $e . '.' ;
}
if ( count ( $msgs [ 'failed' ]) > 0 )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$retString .= count ( $msgs [ 'failed' ]) . ' ' . lang ( 'Message(s) send failed!' ) . '=>' . $errorString ;
2016-04-05 20:43:46 +02:00
}
return $retString ;
case 'application/vnd.oasis.opendocument.text' :
case 'application/vnd.oasis.opendocument.spreadsheet' :
2018-05-07 21:34:35 +02:00
case 'application/vnd.oasis.opendocument.presentation' :
case 'application/vnd.oasis.opendocument.text-template' :
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
case 'application/vnd.oasis.opendocument.presentation-template' :
switch ( $mimetype )
{
2021-10-07 18:22:45 +02:00
case 'application/vnd.oasis.opendocument.text' :
$ext = '.odt' ;
break ;
case 'application/vnd.oasis.opendocument.spreadsheet' :
$ext = '.ods' ;
break ;
case 'application/vnd.oasis.opendocument.presentation' :
$ext = '.odp' ;
break ;
case 'application/vnd.oasis.opendocument.text-template' :
$ext = '.ott' ;
break ;
case 'application/vnd.oasis.opendocument.spreadsheet-template' :
$ext = '.ots' ;
break ;
case 'application/vnd.oasis.opendocument.presentation-template' :
$ext = '.otp' ;
break ;
2018-05-07 21:34:35 +02:00
}
2021-10-07 18:22:45 +02:00
$archive = tempnam ( $GLOBALS [ 'egw_info' ][ 'server' ][ 'temp_dir' ], basename ( $document , $ext ) . '-' ) . $ext ;
copy ( $content_url , $archive );
$content_url = 'zip://' . $archive . '#' . ( $content_file = 'content.xml' );
2016-05-24 21:48:41 +02:00
$this -> parse_html_styles = true ;
2016-04-05 20:43:46 +02:00
break ;
2021-10-07 18:22:45 +02:00
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.d' : // mimetypes in vfs are limited to 64 chars
2016-04-05 20:43:46 +02:00
$mimetype = 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ;
case 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-word.document.macroenabled.12' :
2021-10-07 18:22:45 +02:00
$archive = tempnam ( $GLOBALS [ 'egw_info' ][ 'server' ][ 'temp_dir' ], basename ( $document , '.docx' ) . '-' ) . '.docx' ;
copy ( $content_url , $archive );
$content_url = 'zip://' . $archive . '#' . ( $content_file = 'word/document.xml' );
$fix = array ( // regular expression to fix garbled placeholders
'/' . preg_quote ( '$$</w:t></w:r><w:proofErr w:type="spellStart"/><w:r><w:t>' , '/' ) . '([a-z0-9_]+)' .
preg_quote ( '</w:t></w:r><w:proofErr w:type="spellEnd"/><w:r><w:t>' , '/' ) . '/i' => '$$\\1$$' ,
'/' . preg_quote ( '$$</w:t></w:r><w:proofErr w:type="spellStart"/><w:r><w:rPr><w:lang w:val="' , '/' ) .
'([a-z]{2}-[A-Z]{2})' . preg_quote ( '"/></w:rPr><w:t>' , '/' ) . '([a-z0-9_]+)' .
preg_quote ( '</w:t></w:r><w:proofErr w:type="spellEnd"/><w:r><w:rPr><w:lang w:val="' , '/' ) .
'([a-z]{2}-[A-Z]{2})' . preg_quote ( '"/></w:rPr><w:t>$$' , '/' ) . '/i' => '$$\\2$$' ,
'/' . preg_quote ( '$</w:t></w:r><w:proofErr w:type="spellStart"/><w:r><w:t>' , '/' ) . '([a-z0-9_]+)' .
preg_quote ( '</w:t></w:r><w:proofErr w:type="spellEnd"/><w:r><w:t>' , '/' ) . '/i' => '$\\1$' ,
'/' . preg_quote ( '$ $</w:t></w:r><w:proofErr w:type="spellStart"/><w:r><w:t>' , '/' ) . '([a-z0-9_]+)' .
preg_quote ( '</w:t></w:r><w:proofErr w:type="spellEnd"/><w:r><w:t>' , '/' ) . '/i' => '$ $\\1$ $' ,
2016-04-05 20:43:46 +02:00
);
break ;
case 'application/xml' :
2021-10-07 18:22:45 +02:00
$fix = array ( // hack to get Excel 2003 to display additional rows in tables
'/ss:ExpandedRowCount="\d+"/' => 'ss:ExpandedRowCount="9999"' ,
2016-04-05 20:43:46 +02:00
);
break ;
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.shee' :
$mimetype = 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' ;
case 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' :
2017-03-07 20:08:01 +01:00
case 'application/vnd.ms-excel.sheet.macroenabled.12' :
2021-10-07 18:22:45 +02:00
$fix = array ( // hack to get Excel 2007 to display additional rows in tables
'/ss:ExpandedRowCount="\d+"/' => 'ss:ExpandedRowCount="9999"' ,
2016-04-05 20:43:46 +02:00
);
2021-10-07 18:22:45 +02:00
$archive = tempnam ( $GLOBALS [ 'egw_info' ][ 'server' ][ 'temp_dir' ], basename ( $document , '.xlsx' ) . '-' ) . '.xlsx' ;
copy ( $content_url , $archive );
$content_url = 'zip://' . $archive . '#' . ( $content_file = 'xl/sharedStrings.xml' );
2016-04-05 20:43:46 +02:00
break ;
}
$err = null ;
2021-10-07 18:22:45 +02:00
if ( ! ( $merged =& $this -> merge ( $content_url , $ids , $err , $mimetype , $fix )))
2016-04-05 20:43:46 +02:00
{
//error_log(__METHOD__."() !this->merge() err=$err");
return $err ;
}
// Apply HTML formatting to target document, if possible
// check if we can use the XSL extension, to not give a fatal error and rendering whole merge-print non-functional
2021-10-07 18:22:45 +02:00
if ( class_exists ( 'XSLTProcessor' ) && class_exists ( 'DOMDocument' ) && $this -> parse_html_styles )
2016-04-05 20:43:46 +02:00
{
try
{
$this -> apply_styles ( $merged , $mimetype );
}
2016-06-06 11:03:22 +02:00
catch ( \Exception $e )
2016-04-05 20:43:46 +02:00
{
// Error converting HTML styles over
error_log ( $e -> getMessage ());
2021-10-07 18:22:45 +02:00
error_log ( " Target document: $content_url , IDs: " . array2string ( $ids ));
2016-04-05 20:43:46 +02:00
// Try again, but strip HTML so user gets something
$this -> parse_html_styles = false ;
2021-10-07 18:22:45 +02:00
if ( ! ( $merged =& $this -> merge ( $content_url , $ids , $err , $mimetype , $fix )))
2016-04-05 20:43:46 +02:00
{
return $err ;
}
}
2021-10-07 18:22:45 +02:00
if ( $this -> report_memory_usage )
{
error_log ( __METHOD__ . " () after HTML processing " . Api\Vfs :: hsize ( memory_get_peak_usage ( true )));
}
2016-04-05 20:43:46 +02:00
}
if ( ! empty ( $name ))
{
if ( empty ( $ext ))
{
2021-10-07 18:22:45 +02:00
$ext = '.' . pathinfo ( $document , PATHINFO_EXTENSION );
2016-04-05 20:43:46 +02:00
}
$name .= $ext ;
}
else
{
$name = basename ( $document );
}
2017-10-04 22:15:47 +02:00
$header = array ( 'name' => $name , 'mime' => $mimetype );
2021-10-07 18:22:45 +02:00
if ( isset ( $archive ))
2016-04-05 20:43:46 +02:00
{
$zip = new ZipArchive ;
2021-10-07 18:22:45 +02:00
if ( $zip -> open ( $archive , ZipArchive :: CHECKCONS ) !== true )
{
error_log ( __METHOD__ . __LINE__ . " !ZipArchive::open(' $archive ',ZIPARCHIVE " . " ::CHECKCONS) failed. Trying open without validating " );
if ( $zip -> open ( $archive ) !== true )
{
throw new Api\Exception ( " !ZipArchive::open(' $archive ',|ZIPARCHIVE::CHECKCONS) " );
}
}
if ( $zip -> addFromString ( $content_file , $merged ) !== true )
{
throw new Api\Exception ( " !ZipArchive::addFromString(' $content_file ', \$ merged) " );
}
if ( $zip -> close () !== true )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
throw new Api\Exception ( " !ZipArchive::close() " );
2016-04-05 20:43:46 +02:00
}
unset ( $zip );
unset ( $merged );
2021-10-07 18:22:45 +02:00
if ( $this -> report_memory_usage )
{
error_log ( __METHOD__ . " () after ZIP processing " . Api\Vfs :: hsize ( memory_get_peak_usage ( true )));
}
2017-10-04 22:15:47 +02:00
$header [ 'filesize' ] = filesize ( $archive );
2016-04-05 20:43:46 +02:00
}
else
{
2021-10-07 18:22:45 +02:00
$archive = tempnam ( $GLOBALS [ 'egw_info' ][ 'server' ][ 'temp_dir' ], basename ( $document , '.' . $ext ) . '-' ) . '.' . $ext ;
if ( $mimetype == 'application/xml' )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if ( strpos ( $merged , '<?mso-application progid="Word.Document"?>' ) !== false )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$header [ 'mimetype' ] = 'application/msword' ; // to open it automatically in word or oowriter
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
elseif ( strpos ( $merged , '<?mso-application progid="Excel.Sheet"?>' ) !== false )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$header [ 'mimetype' ] = 'application/vnd.ms-excel' ; // to open it automatically in excel or oocalc
2016-04-05 20:43:46 +02:00
}
}
2017-10-04 22:15:47 +02:00
$handle = fopen ( $archive , 'w' );
fwrite ( $handle , $merged );
fclose ( $handle );
2016-04-05 20:43:46 +02:00
}
2017-10-04 22:15:47 +02:00
return $archive ;
2016-04-05 20:43:46 +02:00
}
/**
* Download document merged with contact ( s )
* frontend for HTTP POST requests
* accepts POST vars and calls internal function download ()
* string data_document_name : the document name
* string data_document_dir : the document vfs directory
* string data_checked : contact id ( s ) to merge with ( can be comma separated )
*
* @ return string with error - message on error , otherwise it does NOT return
*/
public function download_by_request ()
{
2021-10-07 18:22:45 +02:00
if ( empty ( $_POST [ 'data_document_name' ]))
{
return false ;
}
if ( empty ( $_POST [ 'data_document_dir' ]))
{
return false ;
}
if ( empty ( $_POST [ 'data_checked' ]))
{
return false ;
}
2016-04-05 20:43:46 +02:00
return $this -> download (
$_POST [ 'data_document_name' ],
2021-10-07 18:22:45 +02:00
explode ( ',' , $_POST [ 'data_checked' ]),
2016-04-05 20:43:46 +02:00
'' ,
$_POST [ 'data_document_dir' ]
);
}
/**
* Get a list of document actions / files from the given directory
*
* @ param string $dirs Directory ( s comma or space separated ) to search
2021-10-07 18:22:45 +02:00
* @ param string $prefix = 'document_' prefix for array keys
* @ param array | string $mime_filter = null allowed mime type ( s ), default all , negative filter if $mime_filter [ 0 ] === '!'
2016-04-05 20:43:46 +02:00
* @ return array List of documents , suitable for a selectbox . The key is document_ < filename >.
*/
2021-10-07 18:22:45 +02:00
public static function get_documents ( $dirs , $prefix = 'document_' , $mime_filter = null , $app = '' )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$export_limit = self :: getExportLimit ( $app );
if ( ! $dirs || ( ! self :: hasExportLimit ( $export_limit , 'ISALLOWED' ) && ! self :: is_export_limit_excepted ()))
{
return array ();
}
2016-04-05 20:43:46 +02:00
// split multiple comma or whitespace separated directories
// to still allow space or comma in dirnames, we also use the trailing slash of all pathes to split
2021-10-07 18:22:45 +02:00
if ( count ( $dirs = preg_split ( '/[,\s]+\//' , $dirs )) > 1 )
2016-04-05 20:43:46 +02:00
{
foreach ( $dirs as $n => & $d )
{
2021-10-07 18:22:45 +02:00
if ( $n )
{
$d = '/' . $d ;
} // re-adding trailing slash removed by split
2016-04-05 20:43:46 +02:00
}
}
2021-10-07 18:22:45 +02:00
if ( $mime_filter && ( $negativ_filter = $mime_filter [ 0 ] === '!' ))
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if ( is_array ( $mime_filter ))
2016-04-05 20:43:46 +02:00
{
unset ( $mime_filter [ 0 ]);
}
else
{
$mime_filter = substr ( $mime_filter , 1 );
}
}
$list = array ();
foreach ( $dirs as $dir )
{
2021-10-07 18:22:45 +02:00
if (( $files = Api\Vfs :: find ( $dir , array ( 'need_mime' => true ), true )))
2016-04-05 20:43:46 +02:00
{
foreach ( $files as $file )
{
// return only the mime-types we support
2021-10-07 18:22:45 +02:00
$parts = explode ( '.' , $file [ 'name' ]);
if ( ! self :: is_implemented ( $file [ 'mime' ], '.' . array_pop ( $parts )))
{
continue ;
}
if ( $mime_filter && $negativ_filter === in_array ( $file [ 'mime' ], ( array ) $mime_filter ))
{
continue ;
}
$list [ $prefix . $file [ 'name' ]] = Api\Vfs :: decodePath ( $file [ 'name' ]);
2016-04-05 20:43:46 +02:00
}
}
}
return $list ;
}
/**
* From this number of documents , show them in submenus by mime type
*/
const SHOW_DOCS_BY_MIME_LIMIT = 10 ;
/**
* Get insert - in - document action with optional default document on top
*
* If more than SHOW_DOCS_BY_MIME_LIMIT = 10 documents found , they are displayed in submenus by mime type .
*
* @ param string $dirs Directory ( s comma or space separated ) to search
* @ param int $group see nextmatch_widget :: egw_actions
* @ param string $caption = 'Insert in document'
* @ param string $prefix = 'document_'
* @ param string $default_doc = '' full path to default document to show on top with action == 'document' !
* @ param int | string $export_limit = null export - limit , default $GLOBALS [ 'egw_info' ][ 'server' ][ 'export_limit' ]
* @ return array see nextmatch_widget :: egw_actions
*/
2021-10-07 18:22:45 +02:00
public static function document_action ( $dirs , $group = 0 , $caption = 'Insert in document' , $prefix = 'document_' , $default_doc = '' ,
$export_limit = null )
2016-04-05 20:43:46 +02:00
{
$documents = array ();
2021-10-07 18:22:45 +02:00
if ( $export_limit == null )
{
$export_limit = self :: getExportLimit ();
} // check if there is a globalsetting
2017-10-05 17:50:19 +02:00
2021-10-07 18:22:45 +02:00
try
{
if ( class_exists ( 'EGroupware\\collabora\\Bo' ) &&
$GLOBALS [ 'egw_info' ][ 'user' ][ 'apps' ][ 'collabora' ] &&
( $discovery = \EGroupware\collabora\Bo :: discover ()) &&
$GLOBALS [ 'egw_info' ][ 'user' ][ 'preferences' ][ 'filemanager' ][ 'merge_open_handler' ] != 'download'
2017-10-05 17:50:19 +02:00
)
2017-10-05 11:00:38 +02:00
{
$editable_mimes = $discovery ;
}
}
2017-10-05 17:50:19 +02:00
catch ( \Exception $e )
{
2017-10-05 11:00:38 +02:00
// ignore failed discovery
2017-10-05 17:50:19 +02:00
unset ( $e );
2017-10-04 22:15:47 +02:00
}
2021-10-07 18:22:45 +02:00
if ( $default_doc && ( $file = Api\Vfs :: stat ( $default_doc ))) // put default document on top
2016-04-05 20:43:46 +02:00
{
if ( ! $file [ 'mime' ])
{
$file [ 'mime' ] = Api\Vfs :: mime_content_type ( $default_doc );
$file [ 'path' ] = $default_doc ;
}
$documents [ 'document' ] = array (
2021-10-01 18:06:29 +02:00
'icon' => Api\Vfs :: mime_icon ( $file [ 'mime' ]),
2016-04-05 20:43:46 +02:00
'caption' => Api\Vfs :: decodePath ( Api\Vfs :: basename ( $default_doc )),
2021-10-01 18:06:29 +02:00
'group' => 1
2016-04-05 20:43:46 +02:00
);
2021-10-01 18:06:29 +02:00
self :: document_editable_action ( $documents [ 'document' ], $file );
2021-10-07 18:22:45 +02:00
if ( $file [ 'mime' ] == 'message/rfc822' )
2016-04-05 20:43:46 +02:00
{
self :: document_mail_action ( $documents [ 'document' ], $file );
}
}
$files = array ();
2021-10-07 18:22:45 +02:00
if ( $dirs )
2016-04-05 20:43:46 +02:00
{
// split multiple comma or whitespace separated directories
// to still allow space or comma in dirnames, we also use the trailing slash of all pathes to split
2021-10-07 18:22:45 +02:00
if ( count ( $dirs = preg_split ( '/[,\s]+\//' , $dirs )) > 1 )
2016-04-05 20:43:46 +02:00
{
foreach ( $dirs as $n => & $d )
{
2021-10-07 18:22:45 +02:00
if ( $n )
{
$d = '/' . $d ;
} // re-adding trailing slash removed by split
2016-04-05 20:43:46 +02:00
}
}
foreach ( $dirs as $dir )
{
2021-10-07 18:22:45 +02:00
$files += Api\Vfs :: find ( $dir , array (
2016-04-05 20:43:46 +02:00
'need_mime' => true ,
2021-10-07 18:22:45 +02:00
'order' => 'fs_name' ,
'sort' => 'ASC' ,
), true );
2016-04-05 20:43:46 +02:00
}
}
$dircount = array ();
foreach ( $files as $key => $file )
{
// use only the mime-types we support
2021-10-07 18:22:45 +02:00
$parts = explode ( '.' , $file [ 'name' ]);
if ( ! self :: is_implemented ( $file [ 'mime' ], '.' . array_pop ( $parts )) ||
! Api\Vfs :: check_access ( $file [ 'path' ], Api\Vfs :: READABLE , $file ) || // remove files not readable by user
$file [ 'path' ] === $default_doc ) // default doc already added
2016-04-05 20:43:46 +02:00
{
unset ( $files [ $key ]);
}
else
{
$dirname = Api\Vfs :: dirname ( $file [ 'path' ]);
if ( ! isset ( $dircount [ $dirname ]))
{
$dircount [ $dirname ] = 1 ;
}
else
{
2021-10-07 18:22:45 +02:00
$dircount [ $dirname ] ++ ;
2016-04-05 20:43:46 +02:00
}
}
}
foreach ( $files as $file )
{
2021-10-07 18:22:45 +02:00
if ( count ( $dircount ) > 1 )
2016-04-05 20:43:46 +02:00
{
$name_arr = explode ( '/' , $file [ 'name' ]);
$current_level = & $documents ;
for ( $count = 0 ; $count < count ( $name_arr ); $count ++ )
{
if ( $count == 0 )
{
$current_level = & $documents ;
}
else
{
2021-10-07 18:22:45 +02:00
$current_level = & $current_level [ $prefix . $name_arr [( $count - 1 )]][ 'children' ];
2016-04-05 20:43:46 +02:00
}
switch ( $count )
{
2021-09-29 01:00:55 +02:00
case ( count ( $name_arr ) - 1 ) :
2021-10-07 18:22:45 +02:00
if ( ! isset ( $current_level [ $prefix . $file [ 'name' ]]))
2021-10-07 12:17:33 +02:00
{
$current_level [ $prefix . $file [ 'name' ]] = [];
}
2021-09-29 01:00:55 +02:00
self :: document_editable_action ( $current_level [ $prefix . $file [ 'name' ]], $file );
2021-10-07 18:22:45 +02:00
if ( $file [ 'mime' ] === 'message/rfc822' )
2016-04-05 20:43:46 +02:00
{
2021-09-29 01:00:55 +02:00
self :: document_mail_action ( $current_level [ $prefix . $file [ 'name' ]], $file );
2016-04-05 20:43:46 +02:00
}
break ;
default :
2021-10-07 18:22:45 +02:00
if ( ! isset ( $current_level [ $prefix . $name_arr [ $count ]]))
2016-04-05 20:43:46 +02:00
{
// create parent folder
2021-09-29 01:00:55 +02:00
$current_level [ $prefix . $name_arr [ $count ]] = array (
'icon' => 'phpgwapi/foldertree_folder' ,
'caption' => Api\Vfs :: decodePath ( $name_arr [ $count ]),
'group' => 2 ,
'children' => array (),
2016-04-05 20:43:46 +02:00
);
}
break ;
}
}
}
2021-10-07 18:22:45 +02:00
else
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if ( count ( $files ) >= self :: SHOW_DOCS_BY_MIME_LIMIT )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if ( ! isset ( $documents [ $file [ 'mime' ]]))
{
$documents [ $file [ 'mime' ]] = array (
'icon' => Api\Vfs :: mime_icon ( $file [ 'mime' ]),
'caption' => Api\MimeMagic :: mime2label ( $file [ 'mime' ]),
'group' => 2 ,
'children' => array (),
);
}
$documents [ $file [ 'mime' ]][ 'children' ][ $prefix . $file [ 'name' ]] = array ();
self :: document_editable_action ( $documents [ $file [ 'mime' ]][ 'children' ][ $prefix . $file [ 'name' ]], $file );
if ( $file [ 'mime' ] == 'message/rfc822' )
{
self :: document_mail_action ( $documents [ $file [ 'mime' ]][ 'children' ][ $prefix . $file [ 'name' ]], $file );
}
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
else
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$documents [ $prefix . $file [ 'name' ]] = array ();
self :: document_editable_action ( $documents [ $prefix . $file [ 'name' ]], $file );
if ( $file [ 'mime' ] == 'message/rfc822' )
{
self :: document_mail_action ( $documents [ $prefix . $file [ 'name' ]], $file );
}
2016-04-05 20:43:46 +02:00
}
}
}
2021-09-29 01:00:55 +02:00
// Add PDF checkbox
$documents [ 'as_pdf' ] = array (
'caption' => 'As PDF' ,
'checkbox' => true ,
);
2016-04-05 20:43:46 +02:00
return array (
2021-09-29 01:00:55 +02:00
'icon' => 'etemplate/merge' ,
'caption' => $caption ,
'children' => $documents ,
2016-04-05 20:43:46 +02:00
// disable action if no document or export completly forbidden for non-admins
2021-09-29 01:00:55 +02:00
'enabled' => ( boolean ) $documents && ( self :: hasExportLimit ( $export_limit , 'ISALLOWED' ) || self :: is_export_limit_excepted ()),
'hideOnDisabled' => true ,
// do not show 'Insert in document', if no documents defined or no export allowed
'group' => $group ,
2016-04-05 20:43:46 +02:00
);
}
/**
* Set up a document action for an eml ( email ) document
*
* Email ( . eml ) documents get special action handling . They don ' t send a file
* back to the client like the other documents . Merging for a single selected
* contact opens a compose window , multiple contacts just sends .
*
2021-10-12 22:18:18 +02:00
* @ param array & $action Action to be modified for mail
* @ param array $file Array of information about the document from Api\Vfs :: find
2016-04-05 20:43:46 +02:00
* @ return void
*/
2021-10-07 18:22:45 +02:00
private static function document_mail_action ( array & $action , $file )
2016-04-05 20:43:46 +02:00
{
unset ( $action [ 'postSubmit' ]);
2021-10-01 18:06:29 +02:00
unset ( $action [ 'onExecute' ]);
2016-04-05 20:43:46 +02:00
// Lots takes a while, confirm
$action [ 'confirm_multiple' ] = lang ( 'Do you want to send the message to all selected entries, WITHOUT further editing?' );
// These parameters trigger compose + merge - only if 1 row
$extra = array (
'from=merge' ,
2021-10-07 18:22:45 +02:00
'document=' . $file [ 'path' ],
'merge=' . get_called_class ()
2016-04-05 20:43:46 +02:00
);
// egw.open() used if only 1 row selected
2021-10-07 18:22:45 +02:00
$action [ 'egw_open' ] = 'edit-mail--' . implode ( '&' , $extra );
$action [ 'target' ] = 'compose_' . $file [ 'path' ];
2016-04-05 20:43:46 +02:00
// long_task runs menuaction once for each selected row
$action [ 'nm_action' ] = 'long_task' ;
$action [ 'popup' ] = Api\Link :: get_registry ( 'mail' , 'edit_popup' );
2021-10-07 18:22:45 +02:00
$action [ 'message' ] = lang ( 'insert in %1' , Api\Vfs :: decodePath ( $file [ 'name' ]));
$action [ 'menuaction' ] = 'mail.mail_compose.ajax_merge&document=' . $file [ 'path' ] . '&merge=' . get_called_class ();
2016-04-05 20:43:46 +02:00
}
2017-10-04 22:15:47 +02:00
/**
* Set up a document action so the generated file is saved and opened in
* the collabora editor ( if collabora is available )
*
2021-10-12 22:18:18 +02:00
* @ param array & $action Action to be modified for editor
* @ param array $file Array of information about the document from Api\Vfs :: find
2017-10-04 22:15:47 +02:00
* @ return void
*/
2021-10-07 18:22:45 +02:00
private static function document_editable_action ( array & $action , $file )
2017-10-04 22:15:47 +02:00
{
2021-09-29 01:00:55 +02:00
static $action_base = array (
// The same for every file
'group' => 2 ,
// Overwritten for every file
'icon' => '' , //Api\Vfs::mime_icon($file['mime']),
'caption' => '' , //Api\Vfs::decodePath($name_arr[$count]),
);
2021-06-23 19:19:36 +02:00
$edit_attributes = array (
2021-09-29 01:00:55 +02:00
'menuaction' => $GLOBALS [ 'egw_info' ][ 'flags' ][ 'currentapp' ] . '.' . get_called_class () . '.merge_entries' ,
'document' => $file [ 'path' ],
'merge' => get_called_class (),
2021-06-23 19:19:36 +02:00
);
2021-10-01 18:06:29 +02:00
$action = array_merge (
$action_base ,
array (
'icon' => Api\Vfs :: mime_icon ( $file [ 'mime' ]),
2021-10-21 17:51:05 +02:00
'caption' => Api\Vfs :: decodePath ( Api\Vfs :: basename ( $file [ 'name' ])),
2021-10-01 18:06:29 +02:00
'onExecute' => 'javaScript:app.' . $GLOBALS [ 'egw_info' ][ 'flags' ][ 'currentapp' ] . '.merge' ,
'merge_data' => $edit_attributes
),
// Merge in provided action last, so we can customize if needed (eg: default document)
$action
);
2017-10-04 22:15:47 +02:00
}
2016-04-05 20:43:46 +02:00
/**
* Check if given document ( relative path from document_actions ()) exists in one of the given dirs
*
* @ param string & $document maybe relative path of document , on return true absolute path to existing document
* @ param string $dirs comma or whitespace separated directories
* @ return string | boolean false if document exists , otherwise string with error - message
*/
public static function check_document ( & $document , $dirs )
{
if ( $document [ 0 ] !== '/' )
{
// split multiple comma or whitespace separated directories
// to still allow space or comma in dirnames, we also use the trailing slash of all pathes to split
2021-10-07 18:22:45 +02:00
if ( $dirs && ( $dirs = preg_split ( '/[,\s]+\//' , $dirs )))
2016-04-05 20:43:46 +02:00
{
foreach ( $dirs as $n => $dir )
{
2021-10-07 18:22:45 +02:00
if ( $n )
{
$dir = '/' . $dir ;
} // re-adding trailing slash removed by split
if ( Api\Vfs :: stat ( $dir . '/' . $document ) && Api\Vfs :: is_readable ( $dir . '/' . $document ))
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
$document = $dir . '/' . $document ;
2016-04-05 20:43:46 +02:00
return false ;
}
}
}
}
2021-10-07 18:22:45 +02:00
elseif ( Api\Vfs :: stat ( $document ) && Api\Vfs :: is_readable ( $document ))
2016-04-05 20:43:46 +02:00
{
return false ;
}
//error_log(__METHOD__."('$document', dirs='$dirs') returning 'Document '$document' does not exist or is not readable for you!'");
2021-10-07 18:22:45 +02:00
return lang ( " Document '%1' does not exist or is not readable for you! " , $document );
2016-04-05 20:43:46 +02:00
}
/**
2021-06-23 19:19:36 +02:00
* Merge the selected IDs into the given document , save it to the VFS , then
* either open it in the editor or have the browser download the file .
2021-08-09 21:44:43 +02:00
*
2021-09-29 01:00:55 +02:00
* @ param string [] | null $ids Allows extending classes to process IDs in their own way . Leave null to pull from request .
2021-08-09 21:44:43 +02:00
* @ param Merge | null $document_merge Already instantiated Merge object to do the merge .
2021-09-29 01:00:55 +02:00
* @ param boolean | null $pdf Convert result to PDF
2021-08-09 21:44:43 +02:00
* @ throws Api\Exception
* @ throws Api\Exception\AssertionFailed
2021-06-23 19:19:36 +02:00
*/
2021-09-29 01:00:55 +02:00
public static function merge_entries ( array $ids = null , Merge & $document_merge = null , $pdf = null )
2021-06-23 19:19:36 +02:00
{
2021-09-29 01:00:55 +02:00
if ( is_null ( $document_merge ) && class_exists ( $_REQUEST [ 'merge' ]) && is_subclass_of ( $_REQUEST [ 'merge' ], 'EGroupware\\Api\\Storage\\Merge' ))
2021-06-23 19:19:36 +02:00
{
$document_merge = new $_REQUEST [ 'merge' ]();
}
2021-09-29 01:00:55 +02:00
elseif ( is_null ( $document_merge ))
2021-06-23 19:19:36 +02:00
{
$document_merge = new Api\Contacts\Merge ();
}
2021-10-07 18:22:45 +02:00
if (( $error = $document_merge -> check_document ( $_REQUEST [ 'document' ], '' )))
2021-06-23 19:19:36 +02:00
{
2021-09-29 19:01:07 +02:00
error_log ( __METHOD__ . " ( { $_REQUEST [ 'document' ] } ) $error " );
2021-06-23 19:19:36 +02:00
return ;
}
2021-08-09 21:44:43 +02:00
if ( is_null (( $ids )))
{
$ids = is_string ( $_REQUEST [ 'id' ]) && strpos ( $_REQUEST [ 'id' ], '[' ) === FALSE ? explode ( ',' , $_REQUEST [ 'id' ]) : json_decode ( $_REQUEST [ 'id' ], true );
}
2021-06-23 19:19:36 +02:00
if ( $_REQUEST [ 'select_all' ] === 'true' )
{
$ids = self :: get_all_ids ( $document_merge );
}
2021-09-29 01:00:55 +02:00
if ( is_null ( $pdf ))
{
$pdf = ( boolean ) $_REQUEST [ 'pdf' ];
}
2021-10-06 19:58:39 +02:00
$filename = $document_merge -> get_filename ( $_REQUEST [ 'document' ], $ids );
2021-06-23 19:19:36 +02:00
$result = $document_merge -> merge_file ( $_REQUEST [ 'document' ], $ids , $filename , '' , $header );
if ( ! is_file ( $result ) || ! is_readable ( $result ))
{
2021-09-29 01:00:55 +02:00
throw new Api\Exception\AssertionFailed ( " Unable to generate merge file \n " . $result );
2021-06-23 19:19:36 +02:00
}
2021-09-30 20:01:37 +02:00
// Put it into the vfs using user's preferred directory if writable,
2021-06-23 19:19:36 +02:00
// or expected home dir (/home/username) if not
2021-09-30 20:01:37 +02:00
$target = $document_merge -> get_save_path ( $filename );
// Make sure we won't overwrite something already there
2021-09-28 22:48:25 +02:00
$target = Vfs :: make_unique ( $target );
2021-09-30 20:01:37 +02:00
2021-09-28 22:48:25 +02:00
copy ( $result , Vfs :: PREFIX . $target );
2021-06-23 19:19:36 +02:00
unlink ( $result );
// Find out what to do with it
$editable_mimes = array ();
2021-09-30 20:01:37 +02:00
try
{
if ( class_exists ( 'EGroupware\\collabora\\Bo' ) &&
2021-06-23 19:19:36 +02:00
$GLOBALS [ 'egw_info' ][ 'user' ][ 'apps' ][ 'collabora' ] &&
( $discovery = \EGroupware\collabora\Bo :: discover ()) &&
$GLOBALS [ 'egw_info' ][ 'user' ][ 'preferences' ][ 'filemanager' ][ 'merge_open_handler' ] != 'download'
)
{
$editable_mimes = $discovery ;
}
}
catch ( \Exception $e )
{
// ignore failed discovery
unset ( $e );
}
2021-09-29 01:00:55 +02:00
// PDF conversion
if ( $editable_mimes [ Vfs :: mime_content_type ( $target )] && $pdf )
{
$error = '' ;
2021-09-29 19:01:07 +02:00
$converted_path = '' ;
2021-09-29 01:00:55 +02:00
$convert = new Conversion ();
2021-09-29 19:01:07 +02:00
$convert -> convert ( $target , $converted_path , 'pdf' , $error );
2021-09-30 20:01:37 +02:00
2021-09-29 19:01:07 +02:00
if ( $error )
{
error_log ( __METHOD__ . " ( { $_REQUEST [ 'document' ] } ) $target => $converted_path Error in PDF conversion: $error " );
}
else
{
// Remove original
Vfs :: unlink ( $target );
$target = $converted_path ;
}
2021-09-29 01:00:55 +02:00
}
if ( $editable_mimes [ Vfs :: mime_content_type ( $target )] &&
! in_array ( Vfs :: mime_content_type ( $target ), explode ( ',' , $GLOBALS [ 'egw_info' ][ 'user' ][ 'preferences' ][ 'filemanager' ][ 'collab_excluded_mimes' ])))
2021-06-23 19:19:36 +02:00
{
\Egroupware\Api\Egw :: redirect_link ( '/index.php' , array (
'menuaction' => 'collabora.EGroupware\\Collabora\\Ui.editor' ,
2021-09-29 01:00:55 +02:00
'path' => $target
2021-06-23 19:19:36 +02:00
));
}
else
{
2021-09-03 17:33:32 +02:00
\Egroupware\Api\Egw :: redirect_link ( Vfs :: download_url ( $target , true ));
2021-06-23 19:19:36 +02:00
}
}
2021-08-09 21:44:43 +02:00
/**
2021-09-30 20:01:37 +02:00
* Generate a filename for the merged file , without extension
2021-08-09 21:44:43 +02:00
*
2021-10-06 19:58:39 +02:00
* Default filename is just the name of the template .
* We use the placeholders from get_filename_placeholders () and the application ' s document filename preference
* to generate a custom filename .
*
* @ param string $document Template filename
* @ param string [] $ids List of IDs being merged
2021-08-09 21:44:43 +02:00
* @ return string
*/
2021-10-06 19:58:39 +02:00
protected function get_filename ( $document , $ids = []) : string
2021-08-09 21:44:43 +02:00
{
2021-10-06 19:58:39 +02:00
$name = '' ;
if ( isset ( $GLOBALS [ 'egw_info' ][ 'user' ][ 'preferences' ][ $this -> get_app ()][ static :: PREF_DOCUMENT_FILENAME ]))
{
$pref = $GLOBALS [ 'egw_info' ][ 'user' ][ 'preferences' ][ $this -> get_app ()][ static :: PREF_DOCUMENT_FILENAME ];
$placeholders = $this -> get_filename_placeholders ( $document , $ids );
// Make values safe for VFS
foreach ( $placeholders as & $value )
{
$value = Api\Mail :: clean_subject_for_filename ( $value );
}
// Do replacement
$name = str_replace (
array_keys ( $placeholders ),
array_values ( $placeholders ),
2021-10-07 18:22:45 +02:00
is_array ( $pref ) ? implode ( ' ' , $pref ) : str_replace ( ',' , ', ' , $pref )
2021-10-06 19:58:39 +02:00
);
}
return $name ;
}
protected function get_filename_placeholders ( $document , $ids )
{
$ext = '.' . pathinfo ( $document , PATHINFO_EXTENSION );
$link_title = count ( $ids ) == 1 ? Api\Link :: title ( $this -> get_app (), $ids [ 0 ]) : lang ( " multiple " );
$contact_title = count ( $ids ) == 1 ? Api\Link :: title ( $this -> get_app (), $ids [ 0 ]) : lang ( " multiple " );
$current_date = str_replace ( '/' , '-' , Api\DateTime :: to ( 'now' , Api\DateTime :: $user_dateformat ));
$values = [
'$$document$$' => basename ( $document , $ext ),
'$$link_title$$' => $link_title ,
'$$contact_title$$' => $contact_title ,
'$$current_date$$' => $current_date
];
return $values ;
2021-08-09 21:44:43 +02:00
}
2021-09-30 20:01:37 +02:00
/**
* Return a path where we can save the generated file
* Takes into account user preference .
*
* @ param string $filename The name of the generated file , including extension
* @ return string
*/
protected function get_save_path ( $filename ) : string
{
// Default is home directory
$target = ( Vfs :: is_writable ( Vfs :: get_home_dir ()) ?
Vfs :: get_home_dir () :
" /home/ { $GLOBALS [ 'egw_info' ][ 'user' ][ 'account_lid' ] } "
);
// Check for a configured preferred directory
2021-10-21 10:39:30 +02:00
if ( ! empty ( $pref = $GLOBALS [ 'egw_info' ][ 'user' ][ 'preferences' ][ $this -> get_app ()][ Merge :: PREF_STORE_LOCATION ]) && Vfs :: is_writable ( $pref ))
2021-09-30 20:01:37 +02:00
{
$target = $pref ;
}
return $target . " / $filename " ;
}
2021-06-23 19:19:36 +02:00
/**
* Get all ids for when they try to do 'Select All' , then merge into document
*
* @ param Api\Contacts\Merge $merge App - specific merge object
*/
2021-10-12 12:54:45 +02:00
protected static function get_all_ids ( Api\Storage\Merge $merge )
2021-06-23 19:19:36 +02:00
{
$ids = array ();
$locations = array ( 'index' , 'session_data' );
// Get app
2021-10-07 18:22:45 +02:00
list ( $appname , $_merge ) = explode ( '_' , get_class ( $merge ));
2021-06-23 19:19:36 +02:00
2021-10-07 18:22:45 +02:00
if ( $merge instanceof Api\Contacts\Merge )
2021-06-23 19:19:36 +02:00
{
$appname = 'addressbook' ;
}
switch ( get_class ( $merge ))
{
case \calendar_merge :: class :
$ui_class = 'calendar_uilist' ;
$locations = array ( 'calendar_list' );
break ;
case \projectmanager_merge :: class ;
$ui_class = 'projectmanager_ui' ;
$locations = array ( 'project_list' );
break ;
default :
$ui_class = $appname . '_ui' ;
break ;
}
// Ask app
if ( class_exists ( $ui_class ))
{
$ui = new $ui_class ();
2021-10-07 18:22:45 +02:00
if ( method_exists ( $ui_class , 'get_all_ids' ))
2021-06-23 19:19:36 +02:00
{
return $ui -> get_all_ids ();
}
2021-09-13 18:02:39 +02:00
// Try cache, preferring get_rrows over get_rows
2021-10-07 18:22:45 +02:00
if ( method_exists ( $ui_class , $get_rows = 'get_rrows' ) || method_exists ( $ui_class , $get_rows = 'get_rows' ))
2021-06-23 19:19:36 +02:00
{
foreach ( $locations as $location )
{
$session = Api\Cache :: getSession ( $appname , $location );
if ( $session && $session [ 'row_id' ])
{
break ;
}
}
$rows = $readonlys = array ();
2021-10-07 18:22:45 +02:00
@ set_time_limit ( 0 ); // switch off the execution time limit, as it's for big selections to small
$session [ 'num_rows' ] = - 1 ; // all
2021-09-13 18:02:39 +02:00
$ui -> $get_rows ( $session , $rows , $readonlys );
2021-06-23 19:19:36 +02:00
foreach ( $rows as $row_number => $row )
{
2021-10-07 18:22:45 +02:00
if ( ! is_numeric ( $row_number ))
{
continue ;
}
2021-06-23 19:19:36 +02:00
$row_id = $row [ $session [ 'row_id' ] ? $session [ 'row_id' ] : 'id' ];
2021-10-07 18:22:45 +02:00
switch ( get_class ( $merge ))
2021-06-23 19:19:36 +02:00
{
case \calendar_merge :: class :
2021-10-07 18:22:45 +02:00
$explody = explode ( ':' , $row_id );
2021-06-23 19:19:36 +02:00
$ids [] = array ( 'id' => $explody [ 0 ], 'recur_date' => $explody [ 1 ]);
break ;
case \timesheet_merge :: class :
// Skip the rows with totalss
2021-10-07 18:22:45 +02:00
if ( ! is_numeric ( $row_id ))
{
continue 2 ;
} // +1 for switch
2021-06-23 19:19:36 +02:00
// Fall through
default :
$ids [] = $row_id ;
}
}
}
}
return $ids ;
}
/**
2016-04-05 20:43:46 +02:00
* Get a list of supported extentions
*/
public static function get_file_extensions ()
{
return array ( 'txt' , 'rtf' , 'odt' , 'ods' , 'docx' , 'xml' , 'eml' );
}
/**
* Format a number according to user prefs with decimal and thousands separator
*
* Reimplemented from etemplate to NOT use user prefs for Excel 2003 , which gives an xml error
*
* @ param int | float | string $number
* @ param int $num_decimal_places = 2
* @ param string $_mimetype = ''
* @ return string
*/
2021-10-07 18:22:45 +02:00
static public function number_format ( $number , $num_decimal_places = 2 , $_mimetype = '' )
2016-04-05 20:43:46 +02:00
{
2021-10-07 18:22:45 +02:00
if (( string ) $number === '' )
{
return '' ;
}
2016-04-05 20:43:46 +02:00
//error_log(__METHOD__.$_mimetype);
switch ( $_mimetype )
{
2021-10-07 18:22:45 +02:00
case 'application/xml' : // Excel 2003
2016-04-05 20:43:46 +02:00
case 'application/vnd.oasis.opendocument.spreadsheet' : // OO.o spreadsheet
2021-10-07 18:22:45 +02:00
return number_format ( str_replace ( ' ' , '' , $number ), $num_decimal_places , '.' , '' );
2016-04-05 20:43:46 +02:00
}
2021-10-07 18:22:45 +02:00
return Api\Etemplate :: number_format ( $number , $num_decimal_places );
2016-04-05 20:43:46 +02:00
}
2020-10-06 18:56:08 +02:00
/**
* Get a list of common replacements available to all applications
*
* @ return array
*/
public function get_common_replacements ()
{
return array (
// Link to current entry
2022-04-12 17:04:18 +02:00
'link' => lang ( 'URL of current record' ),
'link/href' => lang ( 'HTML link to the current record' ),
'link/title' => lang ( 'Link title of current record' ),
2020-10-06 18:56:08 +02:00
// Link system - linked entries
2022-04-12 17:04:18 +02:00
'links' => lang ( 'Titles of any entries linked to the current record, excluding attached files' ),
'links/href' => lang ( 'HTML links to any entries linked to the current record, excluding attached files' ),
'links/url' => lang ( 'URLs of any entries linked to the current record, excluding attached files' ),
'attachments' => lang ( 'List of files linked to the current record' ),
'links_attachments' => lang ( 'Links and attached files' ),
'links/[appname]' => lang ( 'Links to specified application. Example: {{links/infolog}}' ),
2020-10-06 18:56:08 +02:00
// General information
2022-04-12 17:04:18 +02:00
'date' => lang ( 'Date' ),
'datetime' => lang ( 'Date + time' ),
'time' => lang ( 'Time' ),
'user/n_fn' => lang ( 'Name of current user, all other contact fields are valid too' ),
'user/account_lid' => lang ( 'Username' ),
2020-10-06 18:56:08 +02:00
// Merge control
2022-04-12 17:04:18 +02:00
'pagerepeat' => lang ( 'For serial letter use this tag. Put the content, you want to repeat between two Tags.' ),
'label' => lang ( 'Use this tag for addresslabels. Put the content, you want to repeat, between two tags.' ),
'labelplacement' => lang ( 'Tag to mark positions for address labels' ),
2020-10-06 18:56:08 +02:00
// Commands
2022-04-12 17:04:18 +02:00
'IF fieldname' => lang ( 'Example {{IF n_prefix~Mr~Hello Mr.~Hello Ms.}} - search the field "n_prefix", for "Mr", if found, write Hello Mr., else write Hello Ms.' ),
'IF fieldname~EMPTY~True~False' => lang ( 'Check for empty values in IF statements. Example {{IF url~EMPTY~~Website:}} - If url is not empty, writes "Website:"' ),
'NELF' => lang ( 'Example {{NELF role}} - if field role is not empty, you will get a new line with the value of field role' ),
'NENVLF' => lang ( 'Example {{NENVLF role}} - if field role is not empty, set a LF without any value of the field' ),
'LETTERPREFIX' => lang ( 'Example {{LETTERPREFIX}} - Gives a letter prefix without double spaces, if the title is emty for example' ),
'LETTERPREFIXCUSTOM' => lang ( 'Example {{LETTERPREFIXCUSTOM n_prefix title n_family}} - Example: Mr Dr. James Miller' ),
2020-10-06 18:56:08 +02:00
);
}
2021-09-22 19:15:49 +02:00
2021-09-27 19:09:38 +02:00
/**
* Get a list of common placeholders
*
* @ param string $prefix
*/
public function get_common_placeholder_list ( $prefix = '' )
{
$placeholders = [
'URLs' => [],
'Egroupware links' => [],
'General' => [],
'Repeat' => [],
'Commands' => []
];
// Iterate through the list & switch groups as we go
// Hopefully a little better than assigning each field to a group
$group = 'URLs' ;
foreach ( $this -> get_common_replacements () as $name => $label )
{
if ( in_array ( $name , array ( 'user/n_fn' , 'user/account_lid' )))
{
continue ;
} // don't show them, they're in 'User'
switch ( $name )
{
case 'links' :
$group = 'Egroupware links' ;
break ;
case 'date' :
$group = 'General' ;
break ;
case 'pagerepeat' :
$group = 'Repeat' ;
break ;
case 'IF fieldname' :
$group = 'Commands' ;
}
$marker = $this -> prefix ( $prefix , $name , '{' );
if ( ! array_filter ( $placeholders , function ( $a ) use ( $marker )
{
return array_key_exists ( $marker , $a );
}))
{
2021-10-04 22:45:57 +02:00
$placeholders [ $group ][] = [
'value' => $marker ,
'label' => $label
];
2021-09-27 19:09:38 +02:00
}
}
return $placeholders ;
}
2021-09-22 19:15:49 +02:00
/**
* Get a list of placeholders for the current user
*/
public function get_user_placeholder_list ( $prefix = '' )
{
$contacts = new Api\Contacts\Merge ();
2021-09-27 19:09:38 +02:00
$replacements = $contacts -> get_placeholder_list ( $this -> prefix ( $prefix , 'user' ));
unset ( $replacements [ 'details' ][ $this -> prefix ( $prefix , 'user/account_id' , '{' )]);
2021-09-22 19:15:49 +02:00
$replacements [ 'account' ] = [
2021-10-04 22:45:57 +02:00
[
'value' => $this -> prefix ( $prefix , 'user/account_id' , '{' ),
'label' => 'Account ID'
],
[
'value' => $this -> prefix ( $prefix , 'user/account_lid' , '{' ),
'label' => 'Login ID'
]
2021-09-22 19:15:49 +02:00
];
return $replacements ;
}
2021-09-27 22:46:41 +02:00
2021-10-04 22:45:57 +02:00
/**
* Get the list of placeholders for an application ' s customfields
* If the customfield is a link to another application , we expand and add those placeholders as well
*/
protected function add_customfield_placeholders ( & $placeholders , $prefix = '' )
{
foreach ( Customfields :: get ( $this -> get_app ()) as $name => $field )
{
2021-10-13 16:39:23 +02:00
// Avoid recursing between custom fields of different apps
if ( array_key_exists ( $field [ 'type' ], Api\Link :: app_list ()) && substr_count ( $prefix , '#' ) == 0 )
2021-10-04 22:45:57 +02:00
{
$app = self :: get_app_class ( $field [ 'type' ]);
if ( $app )
{
2021-10-07 22:51:16 +02:00
$this -> add_linked_placeholders ( $placeholders , $name , $app -> get_placeholder_list (( $prefix ? $prefix . '/' : '' ) . '#' . $name ));
2021-10-04 22:45:57 +02:00
}
}
else
{
$placeholders [ 'customfields' ][] = [
'value' => $this -> prefix ( $prefix , '#' . $name , '{' ),
'label' => $field [ 'label' ] . ( $field [ 'type' ] == 'select-account' ? '*' : '' )
];
}
}
}
2021-09-27 22:46:41 +02:00
/**
* Get a list of placeholders provided .
*
* Placeholders are grouped logically . Group key should have a user - friendly translation .
* Override this method and specify the placeholders , as well as groups or a specific order
*/
public function get_placeholder_list ( $prefix = '' )
{
$placeholders = [
];
2021-10-04 22:45:57 +02:00
$this -> add_customfield_placeholders ( $placeholders , $prefix );
2021-09-27 22:46:41 +02:00
return $placeholders ;
}
2021-10-04 22:45:57 +02:00
/**
* Add placeholders from another application into the given list of placeholders
*
* This is used for linked entries ( like info_contact ) and custom fields where the type is another application .
* Here we adjust the group name , and add the group to the end of the placeholder list
* @ param array $placeholder_list Our placeholder list
* @ param string $base_name Name of the entry ( eg : Contact , custom field name )
2021-10-06 00:09:39 +02:00
* @ param array $add_placeholder_groups Placeholder list from the other app . Placeholders should include any needed prefix
2021-10-04 22:45:57 +02:00
*/
protected function add_linked_placeholders ( & $placeholder_list , $base_name , $add_placeholder_groups ) : void
{
if ( ! $add_placeholder_groups )
{
// Skip empties
return ;
}
/*
foreach ( $add_placeholder_groups as $group => $add_placeholders )
{
$placeholder_list [ $base_name . ': ' . lang ( $group )] = $add_placeholders ;
}
*/
$placeholder_list [ $base_name ] = $add_placeholder_groups ;
}
2021-10-07 18:22:45 +02:00
/**
* Get preference settings
*
* Merge has some preferences that the same across apps , but can have different values for each app :
* - Default document
* - Document template directory
* - Filename customization
* - Generated document target directory
*/
public function merge_preferences ()
{
$settings = array ();
2021-10-14 17:05:12 +02:00
switch ( $this -> get_app ())
{
case 'addressbook' :
// lang() will mangle the %5C encoded \ in api.EGroupware\\Api\\Contacts\\Merge.show_replacements
$pref_list_link = Api\Html :: a_href ( '' , Api\Framework :: link ( '/index.php' , [
'menuaction' => 'addressbook.addressbook_merge.show_replacements'
], $this -> get_app ())
);
break ;
default :
$pref_list_link = Api\Html :: a_href ( '' , Api\Framework :: link ( '/index.php' , [
'menuaction' => $this -> get_app () . '.' . get_class ( $this ) . '.show_replacements'
], $this -> get_app ())
);
}
$pref_list_link = str_replace ( '</a>' , '' , $pref_list_link );
2021-10-07 18:22:45 +02:00
$settings [ self :: PREF_DEFAULT_TEMPLATE ] = array (
'type' => 'vfs_file' ,
'size' => 60 ,
'label' => 'Default document to insert entries' ,
'name' => self :: PREF_DEFAULT_TEMPLATE ,
'help' => lang ( 'If you specify a document (full vfs path) here, %1 displays an extra document icon for each entry. That icon allows to download the specified document with the data inserted.' , lang ( $this -> get_app ())) . ' ' .
2021-10-14 17:05:12 +02:00
lang ( 'the document can contain placeholder like {{%3}}, to be replaced with the data (%1full list of placeholder names%2).' , $pref_list_link , '</a>' , 'name' ) . ' <br/>' .
2021-10-07 18:22:45 +02:00
lang ( 'The following document-types are supported:' ) . implode ( ',' , self :: get_file_extensions ()),
'run_lang' => false ,
'xmlrpc' => True ,
'admin' => False ,
);
$settings [ self :: PREF_TEMPLATE_DIR ] = array (
'type' => 'vfs_dirs' ,
'size' => 60 ,
'label' => 'Directory with documents to insert entries' ,
'name' => self :: PREF_TEMPLATE_DIR ,
2021-10-14 17:05:12 +02:00
'help' => lang ( 'if you specify a directory (full vfs path) here, %1 displays an action for each document. that action allows to download the specified document with the data inserted.' , lang ( $this -> get_app ())) . ' ' .
lang ( 'the document can contain placeholder like {{%3}}, to be replaced with the data (%1full list of placeholder names%2).' , $pref_list_link , '</a>' , 'name' ) . ' <br/>' .
2021-10-07 18:22:45 +02:00
lang ( 'The following document-types are supported:' ) . implode ( ',' , self :: get_file_extensions ()),
'run_lang' => false ,
'xmlrpc' => True ,
'admin' => False ,
'default' => '/templates/' . $this -> get_app (),
);
$settings [ self :: PREF_STORE_LOCATION ] = array (
'type' => 'vfs_dir' ,
'size' => 60 ,
'label' => 'Directory for storing merged documents' ,
'name' => self :: PREF_STORE_LOCATION ,
'help' => lang ( 'When you merge entries into documents, they will be stored here. If no directory is provided, they will be stored in your home directory (%1)' , Vfs :: get_home_dir ())
);
$settings [ self :: PREF_DOCUMENT_FILENAME ] = array (
'type' => 'taglist' ,
'label' => 'Merged document filename' ,
'name' => self :: PREF_DOCUMENT_FILENAME ,
'values' => self :: DOCUMENT_FILENAME_OPTIONS ,
'help' => 'Choose the default filename for merged documents.' ,
'xmlrpc' => True ,
'admin' => False ,
2021-10-13 23:47:01 +02:00
'default' => '$$document$$' ,
2021-10-07 18:22:45 +02:00
);
return $settings ;
}
2021-10-12 22:18:18 +02:00
/**
* Show replacement placeholders for the app
*
* Generates a page that shows all the available placeholders for this appliction . By default ,
* we have all placeholders generated in get_placeholder_list () ( including any custom fields )
* as well as the common and current user placeholders .
*
* By overridding show_replacements_hook (), extending classes can override without having to
* re - implement everything .
*/
public function show_replacements ()
{
$template_name = 'api.show_replacements' ;
$content = $sel_options = $readonlys = $preserve = array ();
$content [ 'appname' ] = $this -> get_app ();
$content [ 'placeholders' ] = $this -> remap_replacement_list ( $this -> get_placeholder_list ());
$content [ 'extra' ] = array ();
$content [ 'common' ] = $this -> remap_replacement_list ( $this -> get_common_placeholder_list ());
$content [ 'user' ] = $this -> remap_replacement_list ( $this -> get_user_placeholder_list ());
$this -> show_replacements_hook ( $template_name , $content , $sel_options , $readonlys );
$etemplate = new Api\Etemplate ( $template_name );
$etemplate -> exec ( 'filemanager.filemanager_ui.file' , $content , $sel_options , $readonlys , $preserve , 2 );
}
/**
* Helper function for show_replacements () to change the output of get_placeholder_list () into somethig
* more suited for etemplate repeating rows .
*
* @ param $list
* @ return array
*/
protected function remap_replacement_list ( $list , $title_prefix = '' )
{
$new_list = [];
foreach ( $list as $group_title => $group_placeholders )
{
if ( is_array ( $group_placeholders ) && ! array_key_exists ( '0' , $group_placeholders ))
{
// Limit how far we go through linked entries
if ( $title_prefix )
{
continue ;
}
$new_list = array_merge ( $new_list , $this -> remap_replacement_list ( $group_placeholders , $group_title ));
}
else
{
$new_list [] = [
'title' => ( $title_prefix ? $title_prefix . ': ' : '' ) . $group_title ,
'placeholders' => $group_placeholders
];
}
}
return $new_list ;
}
/**
* Hook for extending apps to customise the replacements UI without having to override the whole method .
*
* This can include detailed descriptions or instructions , documentation of tables and custom stuff
* Set $content [ 'extra_template' ] to a template ID with extra descriptions or instructions and it will be
* added into the main template .
*
* @ param string $template_name
* @ param $content
* @ param $sel_options
* @ param $readonlys
*/
protected function show_replacements_hook ( & $template_name , & $content , & $sel_options , & $readonlys )
{
}
2022-04-26 20:24:37 +02:00
}