QTextEdit inserting inconsistent HTML (when performing the same operation repeatedly / consistently) - c++

I am using QTextEdit widget to display a nicely formatted chat-window to a user. To keep it basic for testing I use the following format for my html:
QString style = is_message_sent_by_myself ?
"background-color:rgb(255,255,255);font-size:14px;color:rgb(10,10,10);" :
"background-color:rgb(249,86,79);font-size:14px;color:rgb(255,255,255);";
QString format("<div style='%1'> %2 </div> <div style='font-size:3px;'> ‌ </div>");
QString text_to_append = format.arg(style).arg(message.toHtmlEscaped());
QTextEdit->append(text_to_append)
This works nice when creating the html myself but when generating it with QT 5.6 by using QTextEdit->append(text_to_be_append) I get a different (and even inconsistent) result.
For a start, when running the above snippet once, the following html is generated (got it with QTextEdit->toHtml()):
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
<meta name="qrichtext" content="1" />
<style type="text/css">
p, li { white-space: pre-wrap; }
</style>
</head>
<body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#ffffff;"><span style=" font-size:14px; color:#0a0a0a; background-color:#ffffff;">Some message </span></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:3px;">‌ </span></p>
</body>
</html>
(which looks perfect for the first message)
But after executing the code again, an inconsistency occurs:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html>
<head>
<meta name="qrichtext" content="1" />
<style type="text/css">
p, li { white-space: pre-wrap; }
</style>
</head>
<body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt; font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#ffffff;"><span style=" font-size:14px; color:#0a0a0a; background-color:#ffffff;">Some message </span></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:3px;">‌ </span></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:14px; color:#ffffff; background-color:#f9564f;">Some message </span></p>
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><span style=" font-size:3px;">‌ </span></p>
</body>
</html>
(which looks like this, but should look like this)
As you can see, the background color attribute is missing in the third <p> tag. Where as the background-color attribute is present in the first <p> tag. The same code is repeated over and over and subsequent calls keep generating <p> tags without a background-color attribute.
Why is this happening and how could I work around this issue?
I'm using QT 5.6 with the Visual Studio 2015 Add-on (unofficial one) on Windows 10 x64.
This is how I am creating the QTextEdit box (including all other components for a tabPage):
PAChatClientUI::PAChatClientUI(QTabWidget* tabs_container, QObject *parent)
: QObject(parent), tabs_container_(tabs_container)
{
QString suffix = QString::number((size_t)this, 16);
tab_ = new QWidget();
tab_->setObjectName("tab_" + suffix);
tab_grid_layout_ = new QGridLayout(tab_);
tab_grid_layout_->setSpacing(6);
tab_grid_layout_->setContentsMargins(11, 11, 11, 11);
tab_grid_layout_->setObjectName("tab_grid_layout_" + suffix);
chat_container_grid_ = new QGridLayout();
chat_container_grid_->setSpacing(6);
chat_container_grid_->setObjectName("chat_container_grid_" + suffix);
chat_container_button_grid_ = new QHBoxLayout();
chat_container_button_grid_->setSpacing(6);
chat_container_button_grid_->setObjectName("chat_container_button_grid_" + suffix);
chat_manager_bot_remove_ = new QPushButton(tab_);
chat_manager_bot_remove_->setObjectName("chat_manager_bot_remove_" + suffix);
chat_manager_bot_remove_->setMinimumSize(QSize(119, 23));
chat_container_button_grid_->addWidget(chat_manager_bot_remove_);
chat_manager_keep_chat_ = new QPushButton(tab_);
chat_manager_keep_chat_->setObjectName("chat_manager_keep_chat_" + suffix);
chat_manager_keep_chat_->setMinimumSize(QSize(119, 23));
chat_container_button_grid_->addWidget(chat_manager_keep_chat_);
chat_manager_end_chat_ = new QPushButton(tab_);
chat_manager_end_chat_->setObjectName("chat_manager_end_chat_" + suffix);
chat_manager_end_chat_->setMinimumSize(QSize(118, 23));
chat_container_button_grid_->addWidget(chat_manager_end_chat_);
chat_manager_send_ = new QPushButton(tab_);
chat_manager_send_->setObjectName("chat_manager_send_" + suffix);
chat_manager_send_->setMinimumSize(QSize(119, 23));
chat_container_button_grid_->addWidget(chat_manager_send_);
chat_container_grid_->addLayout(chat_container_button_grid_, 3, 0, 1, 1);
chat_box_text_messages_ =
//new QPlainTextEdit(tab_);
new QTextEdit(tab_);
chat_box_text_messages_->setObjectName("chat_box_text_messages_" + suffix);
chat_box_text_messages_->setMinimumSize(QSize(495, 178));
chat_container_grid_->addWidget(chat_box_text_messages_, 1, 0, 1, 1);
chat_box_text_input_message_ = new QLineEdit(tab_);
chat_box_text_input_message_->setObjectName("chat_box_text_input_message_" + suffix);
chat_box_text_input_message_->setMinimumSize(QSize(495, 20));
chat_box_text_input_message_->setMaximumSize(QSize(16777215, 16777215));
chat_container_grid_->addWidget(chat_box_text_input_message_, 2, 0, 1, 1);
tab_grid_layout_->addLayout(chat_container_grid_, 0, 0, 1, 1);
chat_manager_bot_remove_->setText("Remove Bot");
chat_manager_keep_chat_->setText("Keep Chat");
chat_manager_end_chat_->setText("End Chat");
chat_manager_send_->setText("Send");
QPalette p = chat_box_text_messages_->palette();
p.setColor(QPalette::Active, QPalette::Base, Qt::black);
p.setColor(QPalette::Inactive, QPalette::Base, Qt::black);
chat_box_text_messages_->setPalette(p);
chat_box_text_messages_->setWordWrapMode(QTextOption::WordWrap);
chat_box_text_messages_->setReadOnly(true);
//Add nice html messages:
AddMessage(true, "Some message");
AddMessage(false, "Some message");
AddMessage(true, "Some message");
AddMessage(false, "Some message");
tabs_container_->addTab(tab_, " 6");
}
void PAChatClientUI::AddMessage(bool me, const QString& message)
{
QString style = me ?
"background-color:rgb(255,255,255);font-size:14px;color:rgb(10,10,10);" :
"background-color:rgb(249,86,79);font-size:14px;color:rgb(255,255,255);";
QString format("<div style='%1'> %2 </div> <div style='font-size:3px;'> ‌ </div>");
QString safe_msg = format.arg(style).arg(message.toHtmlEscaped());
qDebug() << "Writing: " << safe_msg;
chat_box_text_messages_->append(safe_msg);
qDebug() << "HTML: " << chat_box_text_messages_->toHtml();
}
Edit:
I have tried to edit the code according to the answers and also to one of my thoughts, yielding the following two results for the code:
void PAChatClientUI::AddMessage(bool me, const QString& message)
{
QString style = me ?
"background-color:rgb(255,255,255);font-size:14px;color:rgb(10,10,10);" :
"background-color:rgb(249,86,79);font-size:14px;color:rgb(255,255,255);";
QString format("<div style='%1'> %2 </div> <div style='font-size:3px;'> ‌ </div>");
QString safe_msg = format.arg(style).arg(message.toHtmlEscaped());
qDebug() << "Writing: " << safe_msg;
QTextCursor cursor = chat_box_text_messages_->textCursor();
if (!cursor.atStart())
cursor.insertBlock();
cursor.insertHtml(safe_msg);
qDebug() << "HTML: " << chat_box_text_messages_->toHtml();
}
This produced exactly the same effect, so to avoid QT "converting" the HTML, I tought I can just write what QT writes, but exactly the same issue happens:
void PAChatClientUI::AddMessage(bool me, const QString& message)
{
QString bgColor = me ? "ffffff" : "f9564f";
QString txtColor = me ? "0a0a0a" : "ffffff";
QString to_append("\
<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px; background-color:#" + bgColor + ";\"><span style=\" font-size:14px; color:#" + txtColor + "; background-color:#" + bgColor + ";\">" + message.toHtmlEscaped() + " </span></p>\
<p style=\" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;\"><span style=\" font-size:3px;\">‌ </span></p>\
");
chat_box_text_messages_->append(to_append);
}

Edit: This suggestion doesn't solve the issue; it's left here for completeness.
QTextEdit does some RichText magic to the underlying QTextDocument when appending text blocks. Try explicitely creating a block and use QTextCursor::insertHtml() instead of QTextEdit::append():
QTextCursor cursor = m_ui.entryText->textCursor();
if(!cursor.atStart())
cursor.insertBlock();
cursor.insertHtml(htmlText);
This should also improve performance for large amounts of text.

I was able to reproduce this behaviour when packing two <div> into a common call to append(); splitting them into two calls results in the expected appearance (using Qt 4.7 here).

Related

Dynamic options not showing up after adding Chosen

Initially I had everything working with Chosen plugin when the options were directly passed from python to the html template.
I then tried to make the options filled dynamically depending on one of the buttons clicked, the options were not rendered so nothing showed up (but if I inspect the Elements, each optgroup was filled correctly with options).
And if I remove $(".chosen-select").chosen() , then the options are rendered.
Here's my code:
<!-- language: html -->
<div class="container" style="margin:auto; padding-top: 2%; text-align: center;">
<b>Choose the Program:</b>
<ul id="programs" class="no-bullets" data-tag="programList">
<li onclick="selectProgram(this)">Type1</li>
<li onclick="selectProgram(this)">Type2</li>
<li onclick="selectProgram(this)">Type3</li>
</ul>
<b>Choose the Documents:</b>
<select id="documentOptions" name="documents" data-placeholder="Your Documents" class="chosen-select" multiple>
<optgroup label="Group1" id="Group1"></optgroup>
<optgroup label="Group2" id="Group2"></optgroup>
<optgroup label="Group3" id="Group3"></optgroup>
</select>
</div>
<!-- language: lang-js -->
<script>
$(".chosen-select").chosen()
function selectProgram(el){
Array.prototype.slice.call(document.querySelectorAll('ul[data-tag="programList"] li')).forEach(function(element){
element.classList.remove('selected');
});
el.classList.add('selected');
programSelected = el.innerText;
//console.log(programSelected);
fetch(`/api/data/get_program/${programSelected}`)
.then(function(response){
return response.json();
}).then(function(documentList){
documentListJSON = {"documents":documentList};
//console.log(documentListJSON);
$.ajax({
type: 'POST',
url: '/api/data/programDocuments',
contentType: 'application/json',
data: JSON.stringify(documentListJSON),
success: function( allDocuments ){
console.log(allDocuments);
const Type1_Options = document.getElementById("Group1");
const Type2_Options = document.getElementById("Group2");
const Type3_Options = document.getElementById("Group3");
Type1_Options.innerHTML = "";
Type2_Options.innerHTML = "";
Type3_Options.innerHTML = "";
let docs_type1 = allDocuments['type1'];
let docs_type2 = allDocuments['type2'];
let docs_type3 = allDocuments['type3'];
// create list of options
var options = "";
for(var i = 0; i<docs_type1.length;i++){
options += "<option value='" + docs_type1[i] +"'>" + docs_type1[i] + "</option>";
}
Type1_Options.innerHTML += options;
$(Type1_Options).appendTo('#Group1');
var options = "";
for(var i = 0; i<docs_type2.length;i++){
options += "<option value='" + docs_type2[i] +"'>" + docs_type2[i] + "</option>";
}
Type2_Options.innerHTML += options;
$(Type2_Options).appendTo('#Group2');
var options = "";
for(var i = 0; i<docs_type3.length;i++){
options += "<option value='" + docs_type3[i] +"'>" + docs_type3[i] + "</option>";
}
Type3_Options.innerHTML += options;
$(Type3_Options).appendTo('#Group3');
}
})
})
}
</script>
I'm quite new to JavaScript and Jquery..Could someone please help explain why this happens?
Any help is very much appreciated. Thank you!

How to use if statments to run second function Google script

I am trying to speed up my script, right now I currently have it set up so that on a button click a custom dialog (HTML) appears asking some questions. On submit, it calls out a gs function to pull the info back as variables. Depending on the first answer I have a series of If statments that trigger. Each of them pull up a different template, make a copy, populate some cells, emails it to you, and then dumps the data into a tracker. Each of them are different so the script is rather long - is there a way to have each if statment its own function? Would this even help the speed? I am new to scripting so any feedback is appreciated. Below is the Code and HTML
function onOpen() //adds option to top row in case buttons are not working.
{
var ui = SpreadsheetApp.getUi();
ui.createMenu('Create Doc.')
.addItem('Create Tracked Document', 'addItem')
.addToUi();
}
function addItem()//starts the initiation process
{
var html = HtmlService.createTemplateFromFile('form')
.evaluate()
.setWidth(300)
.setHeight(550);
SpreadsheetApp.getUi()
.showModalDialog(html, 'Create New Document');
}
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
var Newform2= templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform2);
var dropSheet = qs.getSheetByName("blank");
var URL3 = Newform2.getUrl();
dropSheet.getRange("i8").setValue(title);
dropSheet.getRange("bc5").setValue(now);
dropSheet.getRange("b5").setValue(platform);
dropSheet.getRange("p5").setValue(area);
dropSheet.getRange("x5").setValue(rota);
dropSheet.getRange("al5").setValue(works);
dropSheet.getRange("at6").setValue(name);
NewOPLPOA.setSharing(DriveApp.Access.DOMAIN,DriveApp.Permission.COMMENT);
NewOPLPOA.setOwner("ME");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
}
else if (form_data.Document_Type == "Text1"){
var dumpfolder = DriveApp.getFolderById("abcd")
var templateSheet = DriveApp.getFileById("bgtrd");
var Newform1 = templateSheet.makeCopy(title+ " "+now,dumpfolder);
var qs = SpreadsheetApp.open(Newform1);
var dropSheet = qs.getSheetByName("DOC1");
var URL4 = Newform1.getUrl();
dropSheet.getRange("aa3").setValue(platform);
dropSheet.getRange("ah3").setValue(area);
dropSheet.getRange("ao3").setValue(works);
NewSEWO.setSharing(DriveApp.Access.DOMAIN, DriveApp.Permission.COMMENT);
NewSEWO.setOwner("Me");
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL4]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL4);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL4, ui.ButtonSet.OK);
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
}
--HTML--
<html>
<head>
<base target="_top">
<link rel="stylesheet" href="https://ssl.gstatic.com/docs/script/css/add-ons1.css">
</head>
<body>
<form id="myform">
<div class="form-group">
<label for="Document_Type">Document Type</label>
<select class="form-control" id="Document_Type" name = "Document_Type" required="required">
<?
var SS = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Set Up");
var Avals = SS.getRange("A2:A").getValues();
var numberOfValues = Avals.filter(String).length;
var RangeVals = SS.getRange(2,1,numberOfValues).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeVals.length; ++i) { ?>
<option><?!= RangeVals[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for ="Name">Your Name</label>
<select class="form-control" name='Name' id="Name" required="required">
<?
var AvalN = SS.getRange("E2:E").getValues();
var numberOfValuesN = AvalN.filter(String).length;
var RangeValsN = SS.getRange(2,5,numberOfValuesN).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsN.length; ++i) { ?>
<option><?!= RangeValsN[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Platform">Platform</label>
<select class="form-control" id="Platform" name = "Platform" required="required">
<?
var AvalP = SS.getRange("C2:C").getValues();
var numberOfValuesP = AvalP.filter(String).length;
var RangeValsP = SS.getRange(2,3,numberOfValuesP).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsP.length; ++i) { ?>
<option><?!= RangeValsP[i] ?></option>
<? } ?>
</select>
</div>
<div class="form-group">
<label for="Area">Area</label>
<select class="form-control" id="Area" name = "Area" required="required">
<?
var AvalA = SS.getRange("D2:D").getValues();
var numberOfValuesA = AvalA.filter(String).length;
var RangeValsA = SS.getRange(2,4,numberOfValuesA).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsA.length; ++i) { ?>
<option><?!= RangeValsA[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="Rotation">Rotation</label>
<select class="form-control" name='Rotation' id="Rotation">
<?
var AvalR = SS.getRange("F2:F").getValues();
var numberOfValuesR = AvalR.filter(String).length;
var RangeValsR = SS.getRange(2,6,numberOfValuesR).getValues();
?>
<option disabled selected value> -- select an option -- </option>
<? for (var i = 0; i < RangeValsR.length; ++i) { ?>
<option><?!= RangeValsR[i] ?></option>
<? } ?>
</select>
</div>
<div class="block form-group">
<label for="WorkSt">Work Station</label>
<input type='text' name='WorkSt' id="WorkSt" />
</div>
<div class="block form-group">
<label for="Title">Title</label>
<input type='text' name='Title' id="Title" required="required"/>
</div>
<div class="block">
<button type="submit" class="action">Submit</button>
</div>
</form>
<script>
document.querySelector("#myform").addEventListener("submit",
function(e)
{
e.preventDefault(); //stop form from submitting
google.script.run.addNewItem(this);
google.script.host.close();//close this dialogbox
}
);
</script>
</body>
</html>
is there a way to have each if statement its own function?
For visibility purposes, you certainly can modify your code as
function addNewItem(form_data)//pulls data from form
{
var ui = SpreadsheetApp.getUi();
var sheet = SpreadsheetApp.getActive().getSheetByName('Sheet1');
var n = new Date();
var now = ((n.getMonth()+1) + "/" + n.getDate() + "/" + n.getFullYear());
var doctyp = form_data.Document_Type;
var name = form_data.Name;
var title = form_data.Title;
var platform = form_data.Platform;
var area = form_data.Area;
var rota = form_data.Rotation;
var works = form_data.WorkSt;
var recipient = Session.getEffectiveUser().getEmail();
if (form_data.Document_Type == "Text2"){
function1();
}
else if (form_data.Document_Type == "Text1"){
function2();
}
else{
ui.alert("Error, Please try again, make sure you are listing all required information.");
}
function function1(){
var dumpfolder = DriveApp.getFolderById("12345")
var templateSheet = DriveApp.getFileById("67890");
...
}
function function2(){
var dumpfolder = DriveApp.getFolderById("abcd")
...
}
Would this even help the speed?
Not really. To help up speed, you should rather try to implement Best Practices.
In particular: Reduce repeated calls to external services, including SpreadsheetApp.
For example, try to position the cells to which you want to assign values into an adjacent range, so you can use the method setValues() instead of multiple setValue() and thus make your code more efficient.
Sample:
var range = dropSheet.getRange("I8:N8");
var values = [];
values[0] = [];
values[0].push(title, now, platform, area, rota, works, name);
range.setValues(values);
Also, try to avoid repeating the same request for each if condition and rather make a single request after exiting the if statement, e.g. for:
sheet.appendRow([now,doctyp,name,title,platform,area,rota,works,URL3]);
GmailApp.sendEmail(recipient, title+ " has been created.", "Your document has been created." +'\n'+ "Here is the link to your copy! Link: " + URL3);
ui.alert("Email Sent", "An email has been sent with your documents link. You can also use the below link to view the document now, click ctrl C to copy. \
" + URL3, ui.ButtonSet.OK);
I hope this helps!

How to select only inline style in html file using regex?

I tried to select the inline styles in p tag and div tag only. But no need to select td, inline styles
regex style=[\"\w\d\.\:\-\'\s\#\;]+
Input:
<p class="Test"><span style="font-family:Verdana">?</span><span style="font:7.0pt 'Times New Roman'">  </span><span>AAA</span></p>
<table cellspacing="0" cellpadding="0" style="border-collapse:collapse; margin-left:0pt">
<tr>
<td style="border-bottom-color:#808080; border-bottom-style:solid; border-bottom-width:0.5pt; border-top-color:#808080; border-top-style:solid; border-top-width:0.5pt; padding-bottom:2.85pt; padding-top:2.85pt; vertical-align:top; width:81pt">
<p class="Tabelle" style="margin-top:3pt; margin-bottom:3pt"><span style="font-family:Tahoma; font-size:9pt">Detail</span></p>
</td>
output:
style="margin-top:3pt; margin-bottom:3pt in p tag
Note:
I need to select only p tag, div tag tags inline styles.
You can try this:
Find by:
(<(?:p|div)[^<]*)(style="[^"]*")([^>]*>)
replace by:
$1$3
C# Code Sample:
using System;
using System.Text.RegularExpressions;
public class Test
{
public static void Main()
{
string pattern = #"(<(?:p|div)[^<]*)(style=""[^""]*"")([^>]*>)";
string substitution = #"$1$3";
string input = #"<p class=""Test""><span style=""font-family:Verdana"">?</span><span style=""font:7.0pt 'Times New Roman'"">  </span><span>AAA</span></p>
<table cellspacing=""0"" cellpadding=""0"" style=""border-collapse:collapse; margin-left:0pt"">
<tr>
<td style=""border-bottom-color:#808080; border-bottom-style:solid; border-bottom-width:0.5pt; border-top-color:#808080; border-top-style:solid; border-top-width:0.5pt; padding-bottom:2.85pt; padding-top:2.85pt; vertical-align:top; width:81pt"">
<p class=""Tabelle"" style=""margin-top:3pt; margin-bottom:3pt""><span style=""font-family:Tahoma; font-size:9pt"">Detail</span></p>
</td>
";
RegexOptions options = RegexOptions.Multiline;
Regex regex = new Regex(pattern, options);
string result = regex.Replace(input, substitution);
System.Console.WriteLine(result);
}
}
Explanation
You get yoru data in group 1

TYPO3 : subparts not found?

I'm trying to modify a template in TYPO3 and I can modify some parts of the page, but not some other parts that are 1 level deeper. For example :
HTML
<body>
...
<div class="wrapper">
...
<div id="content-right">
<div id="colRight">
<div id="metaNav"></div>
</div>
</div>
...
</div>
...
</body>
Typoscript
page.10.subparts {
colRight = HMENU
colRight.wrap = <ul>|</ul>
colRight.special.value = 6, 7, 8, 9
colRight.1 = TMENU
colRight.1 {
noBlur = 1
NO = 1
NO {
allWrap = <li>|</li>
}
}
}
But if I change colRight with metaNav (because this is where we want the links so we can place other contents in colRight), nothing happens; no content is displayed. Why?
While you have it mapped to #colRight and have problem with mapping it to its child div you can just add a HTML markup to element's wrap:
page.10.subparts {
colRight = HMENU
colRight.wrap = <div id="metaNav"><ul>|</ul></div>
// etc...
}
With rule #1: In TS every way is the best solution to get immediate results :)
edit
if you need to render many different elements under one HTML tag, you can also use COA element to span them:
page.10.subparts {
colRight = COA
colRight {
10 = HMENU
10 {
wrap = <div id="metaNav"><ul>|</ul></div>
// etc...
}
20 = TEXT
20 {
value = my text in #colRight right after #metaNav
wrap = <div class="containerAfterMetsNav">|</div>
}
}
}

File Upload Regularexpression

If someone knows please help me to build a regular expression that will valid
- no special characters allow in the file name
- only MS Word file can be uploaded (.docx,.doc, excel, ppt, etc)
- file name can not be more than 80 characters
Thanks
What language? Try this:
/^[A-Za-Z][A-Za-z0-9_ ]\.(docx|doc|xls|ppt|etc)$/
and then check length separately. You'll need to extend/edit the suffix list (etc is obviously not a legit suffix. :)
[a-z0-9A-Z-\s*]{1,80}\.(docx|doc|excel|ppt)
Add whatever file extensions you need seperated by |
All credits go to finalwesites.com, I've tweaked their demo file to fit your needs.
Live demo (without the tweak) at http://www.finalwebsites.com/demos/php_file_upload.php
<?php
require dirname(__FILE__).'/upload_class.php'; // Download it # http://pastebin.com/zAsn8V6R
$folder = dirname(__FILE__)."/upload/"; // "upload" is the folder for the uploaded files (you have to create this folder)
function select_files($dir) {
// removed in ver 1.01 the globals
$teller = 0;
if ($handle = opendir($dir)) {
$mydir = "<p>These are the files in the directory:</p>\n";
$mydir .= "<form name=\"form1\" method=\"post\" action=\"".$_SERVER['PHP_SELF']."\">\n";
$mydir .= " <select name=\"file_in_folder\">\n";
$mydir .= " <option value=\"\" selected>...\n";
while (false !== ($file = readdir($handle))) {
$files[] = $file;
}
closedir($handle);
sort($files);
foreach ($files as $val) {
if (is_file($dir.$val)) { // show only real files (ver. 1.01)
$mydir .= " <option value=\"".$val."\">";
$mydir .= (strlen($val) > 30) ? substr($val, 0, 30)."...\n" : $val."\n";
$teller++;
}
}
$mydir .= " </select>";
$mydir .= "<input type=\"submit\" name=\"download\" value=\"Download\">";
$mydir .= "</form>\n";
}
if ($teller == 0) {
echo "No files!";
} else {
echo $mydir;
}
}
if (isset($_POST['download'])) {
$fullPath = $folder.$_POST['file_in_folder'];
if ($fd = fopen ($fullPath, "rb")) {
$fsize = filesize($fullPath);
$path_parts = pathinfo($fullPath);
$ext = strtolower($path_parts["extension"]);
switch ($ext) {
case "pdf":
header("Content-type: application/pdf");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
case "docx":
header("Content-type: application/docx");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
case "doc":
header("Content-type: application/doc");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
case "xls":
header("Content-type: application/xls");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
case "ppt":
header("Content-type: application/ppt");
header("Content-Disposition: attachment; filename=\"".$path_parts["basename"]."\"");
break;
case "txt":
header("Content-type: application/txt");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
case "odt":
header("Content-type: application/odt");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
break;
default;
header("Content-type: application/octet-stream");
header("Content-Disposition: filename=\"".$path_parts["basename"]."\"");
}
header("Content-length: $fsize");
header("Cache-control: private");
while(!feof($fd)) {
$buffer = fread($fd, 2048);
echo $buffer;
}
}
fclose ($fd);
exit;
}
function del_file($file) {
$delete = #unlink($file);
clearstatcache();
if (#file_exists($file)) {
$filesys = eregi_replace("/","\\",$file);
$delete = #system("del $filesys");
clearstatcache();
if (#file_exists($file)) {
$delete = #chmod ($file, 0775);
$delete = #unlink($file);
$delete = #system("del $filesys");
}
}
}
function get_oldest_file($directory) {
if ($handle = opendir($directory)) {
while (false !== ($file = readdir($handle))) {
if (is_file($directory.$file)) { // add only files to the array (ver. 1.01)
$files[] = $file;
}
}
if (count($files) <= 12) {
return;
} else {
foreach ($files as $val) {
if (is_file($directory.$val)) {
$file_date[$val] = filemtime($directory.$val);
}
}
}
}
closedir($handle);
asort($file_date, SORT_NUMERIC);
reset($file_date);
$oldest = key($file_date);
return $oldest;
}
$max_size = 1024*2000; // the max. size for uploading = 2000 KB, change this to fit your needs
$my_upload = new file_upload;
$my_upload->upload_dir = $folder;
$my_upload->extensions = array(".docx", ".ppt", ".doc", ".pdf", ".xls", ".odt", ".txt"); // specify the allowed extensions here
if(isset($_POST['Submit'])) {
$my_upload->the_temp_file = $_FILES['upload']['tmp_name'];
$my_upload->the_file = $_FILES['upload']['name'];
$my_upload->http_error = $_FILES['upload']['error'];
$my_upload->replace = (isset($_POST['replace'])) ? $_POST['replace'] : "n";
$my_upload->do_filename_check = (isset($_POST['check'])) ? $_POST['check'] : "n";
if ($my_upload->upload()) {
$latest = get_oldest_file($folder);
del_file($folder.$latest);
}
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Demo: File upload/download and open directory</title>
<style type="text/css">
<!--
body {
font-family: Arial, Helvetica, sans-serif;
text-align:center;
}
p {
font-size: 14px;
line-height: 20px;
}
label {
font: 14px/20px Arial, Helvetica, sans-serif;
margin-top: 5px 0 0;
float:left;
display:block;
width:120px;
}
#main {
width:350px;
margin:0 auto;
padding:10px;
text-align:left;
border: 1px solid #000000;
}
input {
margin-left:5px;
}
-->
</style>
</head>
<body>
<div id="main">
<h2 style="text-align:center;margin-top:10px;">Demo page:</h2>
<p align="center">(File upload/download and open directory)</p>
<p>Max. filesize: <b><?php echo $max_size/1024; ?> KB</b><br>
<?php
$ext = "Allowed extensions are: <b>";
foreach ($my_upload->extensions as $val) {
$ext .= ltrim($val, ".").", ";
}
echo rtrim($ext, ", ")."</b>";
?>
</p>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data" name="form1">
<input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_size; ?>">
<center><input type="file" name="upload" id="upload" size="25"></center>
<label for="replace">Replace?</label>
<input type="checkbox" name="replace" id="replace" value="y"><br clear="all">
<label for="check">Validate filename ?</label>
<input name="check" type="checkbox" id="check" value="y" checked>
<br clear="all">
<center><input type="submit" name="Submit" id="Submit" value="Submit"></center>
</form>
<p style="margin-top:20px;color:#FF0000;"><?php echo $my_upload->show_error_string(); ?></p>
<?php echo select_files($folder); ?>
</div>
</body>
</html>