Code Monkey home page Code Monkey logo

tinybutstrong's People

Contributors

roxblnfk avatar simonschaufi avatar skrol29 avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar

tinybutstrong's Issues

Feature request: support multiple "when" conditions

Hello Skrol,

for conditional blocks often it would be handy to combine multiple conditions to create an "and" condition, like

[onload;file='cms.login.html';when [var..cst.EDITMODE]=0;when [var..cst.DEVELOPER]=1]

Currently this can be solved with either wrapping the whole block in another condition, defining another constant/variable or using regular expression matching. It would be much more intuitive and readable to combine the conditions, keeping the whole logic in the template itself.

Thank you for TBS every day.

p tag bug?(solved)

ErrorSample.zip
I found a strange thing about p tag on use [var.xxx;htmlconv=no].

after replace <p>[var.hello;htmlconv=no;noerr]</p>
p tag appear in error position
<p></p>
<li>hello</li>
<p></p>

if I remove htmlconv=no
it will be correct

if change <p>to <div> ,it will be correct,too.

Replace text in paragraph keeping the runs object and styles

Hi everyone, i want find a solution. I working on translate app too like smartcart.com extract text and translate to other language and create new doc file result and keep format style text. I have issue, i unzip docx and receipt a document.xml file contain:

<w:p w14:paraId="69C7E71C" w14:textId="423B6516" w:rsidRDefault="00426B63">
	<w:pPr>
		<w:ind w:left="720"/>
		<w:jc w:val="both"/>
	</w:pPr>
	<w:r>
		<w:rPr>
			<w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:cs="Times New Roman"/>
			<w:sz w:val="28"/>
		</w:rPr>
		<w:tab/>
		<w:t>•</w:t>
	</w:r>
	<w:r>
		<w:rPr>
			<w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:cs="Times New Roman"/>
			<w:sz w:val="28"/>
		</w:rPr>
		<w:tab/>
	</w:r>
	<w:hyperlink r:id="rId5" w:history="1">
		<w:r>
			<w:rPr>
				<w:rStyle w:val="Hyperlink"/>
				<w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:cs="Times New Roman"/>
				<w:sz w:val="28"/>
			</w:rPr>
			<w:t>Vietnam's National Assembly has passed a cybersecurity law requiring companies such as Alphabet Inc.'s Google and Facebook Inc. to store all data of Vietnam-based users in the country and open local offices. The measure</w:t>
		</w:r>
	</w:hyperlink>
	<w:r>
		<w:rPr>
			<w:rFonts w:ascii="Times New Roman" w:hAnsi="Times New Roman" w:cs="Times New Roman"/>
			<w:sz w:val="28"/>
		</w:rPr>
		<w:t xml:space="preserve"> has drawn rare dissent from some lawmakers and government leaders as well as local tech groups, who sent a petition to the legislature that warned it would hurt the economy. </w:t>
	</w:r>
</w:p>

i want extract text by newline break or ". " to 3 segment:
1 => •
2 => Vietnam's National Assembly has passed a cybersecurity law requiring companies such as Alphabet Inc.'s Google and Facebook Inc. to store all data of Vietnam-based users in the country and open local offices.
3 => The measure has drawn rare dissent from some lawmakers and government leaders as well as local tech groups, who sent a petition to the legislature that warned it would hurt the economy.
I see result json api of smartcart for segment 3 same:

{
  "id": 4079,
  "prevSegmentId": 4078,
  "nextSegmentId": 4080,
  "number": 7,
  "order": 7,
  "documentId": "b2fbca4ecc49c3883d7afa77",
  "subtitleId": [],
  "topicId": "23d961eb-4423-433e-82cc-5f23b8f9abff",
  "commentState": 0,
  "localizationContext": [],
  "wordsCount": 32,
  "isSplitting": false,
  "paragraphId": 6,
  "targetTextLengthLimit": null,
  "canModifyTextLengthLimit": true,
  "segmentRepetitionState": 0,
  "source": {
    "segmentId": 4079,
    "text": "The measure has drawn rare dissent from some lawmakers and government leaders as well as local tech groups, who sent a petition to the legislature that warned it would hurt the economy.",
    "languageId": 6153,
    "tags": [
      {
        "tagNumber": 1,
        "tagType": 0,
        "position": 0,
        "isSubtitleTag": false,
        "isVirtual": true,
        "formatting": null,
        "isRequired": true,
        "visualization": null
      },
      {
        "tagNumber": 1,
        "tagType": 1,
        "position": 11,
        "isSubtitleTag": false,
        "isVirtual": false,
        "formatting": null,
        "isRequired": true,
        "visualization": null
      }
    ],
    "placeholders": []
  },
  "targets": [
    {
      "segmentId": 4079,
      "languageId": 42,
      "documentId": "b2fbca4ecc49c3883d7afa77",
      "text": "",
      "lockType": 0,
      "tags": [],
      "placeholders": [],
      "revisions": [],
      "stageNumber": 1,
      "isConfirmed": false,
      "errors": [],
      "lockUserId": null,
      "workflowRollbackStep": null,
      "machineTranslations": [
        {
          "priority": 30,
          "id": "61c919bbf07d744bf8632fba",
          "segmentId": 4079,
          "languageId": 42,
          "resourceId": "engine:Yandex",
          "resourceType": 2,
          "resourceName": "Yandex Free",
          "sourceText": "The measure has drawn rare dissent from some lawmakers and government leaders as well as local tech groups, who sent a petition to the legislature that warned it would hurt the economy.",
          "targetText": "Các biện pháp đã rút ra hiếm bất đồng từ một nhà lập pháp và các lãnh đạo chính phủ cũng như công nghệ địa phương nhóm những người đã gửi đơn cơ quan lập pháp mà cảnh báo nó sẽ làm tổn thương các nền kinh tế.",
          "targetTextAfterAutoReplacement": null,
          "matchPercentage": 0,
          "createdDate": "2021-12-27T01:41:15.904Z",
          "lastUpdateDate": "2021-12-27T01:41:15.904Z",
          "tagsTransferData": [
            {
              "position": 13,
              "order": 0
            }
          ],
          "tagsTransferDataAfterAutoReplacement": null,
          "dialectSourceLanguageId": null,
          "dialectTargetLanguageId": null
        }
      ],
      "textForNonAlphabeticAutoFill": null,
      "termEntries": [],
      "insertResourceType": 0,
      "matchPercentage": 0
    }
  ],
  "images": [],
  "previewUrl": null,
  "defaultFormatting": {
    "hyperlink": null,
    "bold": false,
    "italic": false,
    "strike": false,
    "superscript": false,
    "subscript": false,
    "underline": false,
    "fontSize": 14,
    "fontFamily": "Times New Roman",
    "backgroundColor": "0, 0, 0, 0",
    "foregroundColor": "0, 0, 0, 0"
  },
  "lockType": 0
}

But word in xml paragraph
1 => •
2 => Vietnam's National Assembly has passed a cybersecurity law requiring companies such as Alphabet Inc.'s Google and Facebook Inc. to store all data of Vietnam-based users in the country and open local offices. The measure
3 => has drawn rare dissent from some lawmakers and government leaders as well as local tech groups, who sent a petition to the legislature that warned it would hurt the economy.
my solution translate:
extract text to 4 segments
1 => •
2 => Vietnam's National Assembly has passed a cybersecurity law requiring companies such as Alphabet Inc.'s Google and Facebook Inc. to store all data of Vietnam-based users in the country and open local offices. ==> and request google API translate and receipt result
3 => The measure ==> and request google API translate and receipt result
4 => has drawn rare dissent from some lawmakers and government leaders as well as local tech groups, who sent a petition to the legislature that warned it would hurt the economy. ==> and request google API translate and receipt result
I want concat segment 3 to 4 of my solution translate result for display
and when create new doc i want concat segment 3 to segment 2 because it in hyperlink, origin text:
"Vietnam's National Assembly has passed a cybersecurity law requiring companies such as Alphabet Inc.'s Google and Facebook Inc. to store all data of Vietnam-based users in the country and open local offices. (segment 2) The measure (segment 3)" because it match text in hyperlink, and i want result translate too. Please help me solution. Tks all

Add newline or <br />? if not empty

Forgive if this is dumb question - I couldn't find anything obvious in the manual...

Suppose I have several fields which form an Address. I would like to add a newline to each field, only if they are not empty.

i.e.

[onload.street1;ope=add:\n][onload.street2;ope=add:\n][onload.city;ope=add:\n][etc...

Is something like this possible?

using magnet to remove attribute resulting in bad render

I'm upgrading an app that uses an older version of tinybutstrong, to a more recent version to get it to run on php7 (and 8) as well as start using composer.

I run into a possible bug when an attribute is to be removed from the template using magnet config. It could also be I'm doing something wrong.

I can reproduce the problem with a small bit of code+template.
The following started failing in 3.10.0. Using version 3.9.0 works just fine.

<?php
require __DIR__ . '/../tbs_3100/tbs_class.php';

$tbs = new clsTinyButStrong();
$tbs->loadTemplate(__DIR__ . '/template.html');

$items = [
    ['url' => '/wherever', 'target' => '_blank', 'follow' => 'nofollow', 'name' => 'just a label' ],
    ['url' => '/wherever', 'target' => '',       'follow' => '',         'name' => 'just a label' ],
    ['url' => '/wherever', 'target' => '',       'follow' => '',         'name' => 'just a label' ],
    ['url' => '/wherever', 'target' => '_blank', 'follow' => 'nofollow', 'name' => 'just a label' ],
];

$tbs->MergeBlock('items', $items);

echo PHP_EOL . $tbs->Source . PHP_EOL;

template.html :

<ul>
  [items;block=begin;bmagnet=ul]
  <li>
    <a href="[items.url;magnet=li]" target="[items.target;magnet=#]" rel="[items.follow;magnet=#]">
      [items.name;ope=upper1]
    </a>
  </li>
  [items;block=end]
</ul>

This results in the following output:

<ul>
  <li>
    <a href="/wherever" target="_blank" rel="nofollow">
      Just a label
    </a>
  </li>
  <li>
    <a href="/wherever">
      Just a label
    </a>
  </li>
  <li>
    <a href="/wherever"items.target;magnet=#]"items.follow;magnet=#]">
      Just a label
    </a>
  </li>
  <li>
    <a href="/wherever" target="_blank" rel="nofollow">
      Just a label
    </a>
  </li>
</ul>

As you can see the first 2 items go fine, but whenever it needs to remove the same attribute for the next row again it fails for some reason.
Am I doing something wrong here? or was a bug introduced in version 3.10 ?

Thanks.

How to run the unit tests

I see that simple unit test framework is used and not phpunit. I have no idea how to run the tests on command line. please help!

Usage of global constants breaks apps using PHP 7.4s class preloading

Hi, I enabled PHP class preloading for my Symfony based app. But when it comes to creating files with TBS/OpenTBS, I get an error "Undefined constant 'TBS_INSTALL'". After digging in, I realized that preloading and global constants defined at runtime with define() won't work together: they are simply not defined when their class is preloaded.

Can anyone confirm that? Any ideas to solve that (besides refactoring the constants-system of TBS/OpenTBS creating a BC break)?

I tried to exclude the (service) class using the TBS_INSTALL constant from preloading, but that doesn't solve the problem (as it and the TBS classes are still preloaded as a dependency).

How to reproduce

Just try to use TBS/OpenTBS in an application with PHP preloading. In opcache_get_status()['preload_statistics']['classes'] you get a list of preloaded classes where clsTinyButStrong, clsTbsDataSource and clsTbsLocator are included, provoking the error.

Add composer.json

Hello!
Thank you for your awesome library!
Could you please add a composer.json files so that i can automatically include it in my project with composer?
If you are not familiar with composer, here is a pull request that already includes the file: bff0ef6
You then need to register your package on packagist.org as well.
If you need help, feel free to ask!

Formatting some timestamps results in wrong date

When a field with a date format is merged with a timestamp, the result is - sometimes - wrong, if the timestamp is passed in as a string and not a number.

Example:

$timestamp1 = 1523447097;   // 13:44:57
$timestamp2 = 1528648609;   // 18:36:49

$TBS = new clsTinyButStrong;
$TBS->Source = "[timestamp1;frm='hh:nn:ss'] [timestamp2;frm='hh:nn:ss']\n[timestamp1string;frm='hh:nn:ss'] [timestamp2string;frm='hh:nn:ss']";
$TBS->MergeField("timestamp1", $timestamp1);
$TBS->MergeField("timestamp2", $timestamp2);
$TBS->MergeField("timestamp1string", "$timestamp1");
$TBS->MergeField("timestamp2string", "$timestamp2");
$TBS->Show();

Output:

13:44:57 18:36:49
15:23:44 18:36:49

I found that out while trying to find a fix for kimai/kimai#1032

Version 3.10.0 for PHP 5

Parameter to detect if field exists?

I'm trying to apply a block with data that may or may not have a given field set. I can use a conditional to display things or not with when , but this causes an error (naturally) when it's evaluating the conditional.
I can apply noerr at the template level (I think?), but I'd rather it be done at the block level (or possibly field level).
Is this possible, or should I try making a empty_if_missing() function at the passed-in-class object thing?

Search&Replace with Regex

Hello,

can I search and replace inside the text content with regex?

I have a lot of batch regex to apply on my ODT documents.

Thanks

Juergen

TBS project development

Hi @Skrol29 i read your post that you often think about project development.
This is great, and I would like to speculate about how it looks to me. Perhaps you are interested in something from what is written below.

Let's start with what the first steps would be nice to take:

  • Create an organization tinybutstrong on github. It's free.

    • Move all TBS repositories there. (Repository Settings -> Options -> Transfer ownership)
    • Enable Discussions for repositories.
    • You can also add maintainers so that you don't have to pull the project alone. For example, i will gladly join and devote part of my free time.
  • Prepare codebase.

    • Create a project structure according to PSR-4 (move classes to tinybutstrong namespace).
    • For version 3.x, keep the classes in the same namespace, but mark them with @deprecated. They will inherit from classes from the tinybutstrong namespace. All deprecated will be removed or hidden in the next major release.
    • For version 3.x, create the tbs-3 branch. Development of version 4 will be in the master branch.
    • For TBS 4, you can immediately set the php version ^7.4|^8.0 and not look back.
  • Create roadmap.

    • First of all, you need to decide what things need to be thrown away. Removing them from the code immediately makes refactoring easier.
    • Determine what functions to save and what new features to add in the project. In part, this concerns not the code itself, but the syntax, workflow and api in general.
    • If you know active TBS users, then you can try to get feedback from the community.
    • There may come a time when it will be necessary to decide: rewrite everything from scratch or decompose and refactor what is.
      I have some suggestions (see below) that, in my opinion, are very cool, but for their implementation it is necessary to revise the entire code.

As a result of drawing up the Roadmap, i see the following options for developing new versions:

  • Conservative development v4: a gradual rewriting of the code with decomposition and refactoring. Without huge changes, but with major improvements. Implementation of advanced testing techniques and static analysis.
  • Innovative development v4: a complete redesign of the template engine. Implementation of killer features, processing of the gained experience into a new product.
  • Development of conservative version 4 and innovative version 5.

What suggestions for changes do i mean?

  • The hardest and most serious thing is streamed templating. The merge process will not be the same as before.
    TBS will not merge data immediately after calling the merge method.
    First, we prepare all data, and then we start the merge process. The search for markers and their replacement will occur on the fly.
    In this case, you will not need to store the generated part of the document in memory. What do we get from this?

    • Less memory consumption and more performance.
    • Generation of endless (very big) excel files without going out of memory (killer feature). Yes, in php create zip archives in a stream.
    • It will be possible to merge the same blocks several times.
  • Add more abstractions when working with data.
    I suggest using the DataReader/DataWriter interfaces from the Yii Framework and separate modifiers to offload the templating code.
    For example, the code for working with the database will disappear from TBS, but their support will remain. The template engine doesn't care where the data comes from.
    At the same time, this data can be easily sorted, limited and filtered if DataReader implements appropriate interface (SortableDataInterface, FilterableDataInterface...).

  • Add support for PSR logger. Errors should not be emitted into the output, they should be logged.

  • Add PSR-7 support to return the template file as a ResponseInterface object.

Here's some more food for thought:

  • You can create a fund on opencollective to raise funds for the development of the project, as many open source projects do.
  • In my TBS fork, i implemented sorting, filtering and grouping of block data.
    There is very bad documentation (this is my weak point), but everything is covered by tests and works very good.
    I use these functions to generate payment receipts and reports in one of the projects.
    If you are interested add this funcitons into v3, i can do a PR, but the documentation is still bad for me.

Apply enlarge to CSS-compatible comments

Something like this:

	if ( $ReadPrm && ( isset($Loc->PrmLst['enlargeCSS'])  ) ) {
		$Loc->PosBeg0 = $Loc->PosBeg;
		$Loc->PosEnd0 = $Loc->PosEnd;
		$enlarge = (isset($Loc->PrmLst['enlargeCSS'])) ? $Loc->PrmLst['enlargeCSS'] : false;
		if (($enlarge===true) || ($enlarge==='')) {
			$Loc->Enlarged = self::f_Loc_EnlargeToStr($Txt,$Loc,'/*' ,'*/');
		}
	}

TBS library not working with latest pptx versions

hi
We are using TBS library to create a new pptx file after find and replace tags from master pptx file.
It is working fine. But same code is not working with latest pptx files. Can you please help me to fix this issue.
I am using below set of code. Please review and please let me know if i am doing something wrong.Also sharing file.

require_once ("opentbs/tbs_class.php");
require_once ("opentbs/tbs_plugin_opentbs.php");
$pptx = new clsTinyButStrong (); // new instance of TBS
$pptx->Plugin ( TBS_INSTALL, OPENTBS_PLUGIN ); // load the OpenTBS plugin
$pptx->LoadTemplate($fileNameIn, OPENTBS_ALREADY_UTF8);
$pptx->PlugIn(OPENTBS_SELECT_SLIDE, 1);
$pptx->VarRef["Rep_Name"] = $templateDataArray["Rep_Name"];
$pptx->PlugIn(OPENTBS_SELECT_SLIDE, 1);
$pptx->VarRef["Rep_Title"] = $templateDataArray["Rep_Title"];
$pptx->PlugIn(OPENTBS_SELECT_SLIDE, 1);
$pptx->VarRef["Client"] = $templateDataArray["Client"];
$pptx->Show(OPENTBS_FILE, $pptxFileNameOut);

PPTX with merge tags_new_version.pptx

tbs_class.php line 3936

bug in
$this->meth_Misc_Alert("with parameter 'combo'", "Combo '". $a. "' is not yet set.");

?

Random XML rendering

Hello,

Thanks again for sharing your Library.
I'm embedding images on a Word (docx) document and I'm actually facing a strange issue. There are somes XML attributes that are html encoded and some not.

On a file with 23 embed attributes, 2 are wrong like this one

<a:blip r:embed=&quot;rId12" cstate="print">

Other are corrects like the Following :

<a:blip r:embed="rId12" cstate="print">

When I checked function that generate this line, the quote symbol is correct

// phpdocx/classes/CreateElement.php:180
protected function generateBLIP($cstate = 'print')
    {
        $xml = '<' . CreateImage::NAMESPACEWORD1 .
                ':blip r:embed="rId' . $this->getRId() .
                '" cstate="' . $cstate .
                '"></' . CreateImage::NAMESPACEWORD1 .
                ':blip>__GENERATEBLIPFILL__';

        $this->_xml = str_replace('__GENERATEBLIPFILL__', $xml, $this->_xml);
    }

Did I do something wrong?

Version used: 3.10.1
PHP: 5.5.9 & 7.2.7

PHP doc variable types

Hello, Would you be interested in a pull request that adds some phpdoc comments to help modern IDEs trace the variable types and function return types?

I saw a pull request with thousands of lines of code, and I realize that is hard to process. But would a smaller request just adding in PHPDoc structures be useful?

If it is welcome, I would put some time into it. But I don't want to waste time if its not desired.

Example in clsTbsDataSource:

`
/**

  • @var object|string|array|resource|iterator|ArrayObject|IteratorAggregate|MySQLi|PDO|Zend_Db_Adapter_Abstract|SQLite3|SQLite3Stmt|SQLite3Result
    /
    public $SrcId = false;
    /
    *
  • @var object|string|array|resource|iterator|ArrayObject|IteratorAggregate|MySQLi|PDO|Zend_Db_Adapter_Abstract|SQLite3|SQLite3Stmt|SQLite3Result
    */
    public $TBS = false;
    `

Thanks for the very useful library

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.