Scss List Font-Face Loop - list

I'm trying to use SCSS to render out the webfont font-face declaration in css. I defined variable names for the font-family and the file name in a list. Then I used the variable names as placeholders in the css.
I can't find the error in my code.
$fonts: (
"paradise thoughts": paradisethoughts-regular,
"masterblush": masterblush-regular,
"steadfast": steadfast-regular,
"beautiful bloom": beautiful-bloom-regular,
"rosefield": rosefield-regular,
"silverberry": silverberry-regular,
"little bestseller": little-bestseller-regular,
"the saturday": thesaturday-clean-regular,
"smaragdines script": smaragdines-script-regular,
"trendsetter": trendsetter-regular,
"imperfectly": imperfectly-regular,
"summer festival": summer-festival-regular,
"northern lights": northern-lights-regular,
"hello stockholm": hello-stockholm-regular,
"wilderness": wilderness-regular,
"riverside avenue": riverside-avenue-regular,
"perfect sunset": perfect-sunset-regular,
"sugarstyle millenial": sugarstyle-millenial-regular,
);
#each $family, $file in $fonts {
#font-face {
font-family: '#{$family}';
src: url('#{$file}.eot');
src: local('#{$family} regular'), local('#{$file}'),
url('#{$file}.eot?#iefix') format('embedded-opentype'),
url('#{$file}.woff2') format('woff2'),
url('#{$file}.woff') format('woff'),
url('#{$file}.ttf') format('truetype'),
url('#{$file}.svg##{$file}') format('svg');
font-weight: normal;
font-style: normal;
}
}
Thanks in advance!

Related

How to add buttons to a main window by programmatically in Qt and change styles them by use css file?

I will add two buttons to the a dialog and I want to change style sheets of them by use css file:
I also define the buttons as follows that didn't work:
sendButton = new QPushButton();
sendButton->setVisible(true);
sendButton->setText("sendButton");
sendButton->setStyleSheet("QPushButton#sendButton {\n"
"background-color: red;\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 10px;\n"
"border-color: beige;\n"
"font: bold 14px;\n"
"min-width: 10em;\n"
"padding: 6px;\n"
"}\n"
"QPushButton#reciveButton {\n"
"background-color: green;\n"
"border-style: outset;\n"
"border-width: 2px;\n"
"border-radius: 10px;\n"
"border-color: beige;\n"
"font: bold 14px;\n"
"min-width: 10em;\n"
"padding: 6px;\n"
"}\n");
ui->horizontalLayout->addWidget(sendButton);
If you are using the ID Selector QPushButton#objectName, be sure to also set the object name for your QPushButton, otherwise the selector will not work
sendButton = new QPushButton();
sendButton->setVisible(true);
sendButton->setText("sendButton");
sendButton->setObjectName("sendButton"); /* Set the object name */
sendButton->setStyleSheet(...);
Hope this helps =)
To add any widgets programmatically to a window (MainWindow, Dialog, ...) you have to do as follows:
Create an instance of your widgets
Create a layout (vertical, horizontal, or grid layout)
Add widgets to the layout
Set your window's layout
For example:
//Step 1: create widgets
QPushButton *sendbtn = new QPushButton("sendButton");
sendbtn->setObjectName("mySendButton");
QPushButton *receivebtn = new QPushButton("receiveButton");
receivebtn->setObjectName("myReceiveButton");
//Step 2: create a layout
QHBoxLayout *hlayout = new QHBoxLayout;
//Step 3: add widgets to the layout
hlayout->addWidget(sendbtn);
hlayout->addWidget(receivebtn);
QWidget *w = new QWidget;
w->setLayout(hlayout);
setCentralWidget(w);
setStyleSheet("QPushButton#mySendButton"
"{"
"background-color: red;"
"border-style: outset;"
"border-width: 2px;"
"border-radius: 10px;"
"border-color: beige;"
"font: bold 14px;"
"min-width: 10em;"
"padding: 6px;"
"}"
"QPushButton#myReceiveButton"
"{"
"background-color: green;"
"border-style: outset;"
"border-width: 2px;"
"border-radius: 10px;"
"border-color: beige;"
"font: bold 14px;"
"min-width: 10em;"
"padding: 6px;"
"}");
The output is as follows:

How to color table rows with 3 alternate color

I want a table to display with 3 alternate colors (1-black,2-red,3-white,4-black, 5-red,6-white ....) i tried with nth-child(even) and nth-child(odd)
but how to get alternate 3 row colors
Following to the w3c, you try this:
tr:nth-child(3n+1) {
background-color: black;
}
tr:nth-child(3n+2) {
background-color: red;
}
tr:nth-child(3n) {
background-color: white;
}

Swift - Add attributed string to items in parenthesis

I'm trying to display text to a view from a set of definitions and in cases where that text/string has parenthesis, I would like to display that parenthesis element in a different way - let's say bolded vs non bolded.
"This string a"
"This string b (has parenthesis)" - parenthesis show in lower
weight font
Now I'm aware that the solution is found by combining regular expressions - \(\w*\) - with attributed strings, but I haven't been able to combine it meaningfully.
This is my function that prints the words
func setWord(_ index:Int) {
if (index < 0) { return }
let word:[String:AnyObject] = self.definitions[index]
if let wordLabelText = word[self.store.sourceLanguage.lowercased()] as? String {
self.wordLabel.attributedText = NSMutableAttributedString(string: wordLabelText, attributes: [NSKernAttributeName: 1.0])
}
print(word)
self.definitionView.word = word
}
What I've done so far is added some more definitions for the attributed strings output, but then I'm not sure how to continue:
func setWord(_ index:Int) {
if (index < 0) { return }
let font = UIFont.preferredFont(forTextStyle: UIFontTextStyle.headline)
let fontSize = font.pointSize * 3
let plainFont = UIFont(name: "X-BoldItalic", size: fontSize)
let boldFont = UIFont(name: "X-Italic", size: fontSize)
let word:[String:AnyObject] = self.definitions[index]
if let wordLabelText = word[self.store.sourceLanguage.lowercased()] as? String {
self.wordLabel.attributedText = NSMutableAttributedString(string: wordLabelText, attributes: [NSKernAttributeName: 1.0, NSFontAttributeName: boldFont])
Here I'd need to loop through the words looking for the (elements), but I'm not sure how to do that and properly return the words. Am I on the right path? Thanks a bunch :)
A solution in Objective-C, with explained logic that should be easily translated in Swift.
NSDictionary *defaultAttributes = #{NSFontAttributeName: [UIFont boldSystemFontOfSize:15]};
NSDictionary *otherAttributes = #{NSFontAttributeName: [UIFont systemFontOfSize:12]};
NSRegularExpression *regex = [NSRegularExpression regularExpressionWithPattern:#"\\(.*?\\)" options:0 error:nil];
NSString *initialString = #"This string a (has parenthesis), This string b (has parenthesis too), This string C hasn't.";
NSMutableAttributedString *attr = [[NSMutableAttributedString alloc] initWithString:initialString attributes:defaultAttributes];
NSLog(#"Attr: %#", attr);
NSArray *allMatches = [regex matchesInString:[attr string] options:0 range:NSMakeRange(0, [attr length])];
for (NSTextCheckingResult *aResult in allMatches)
{
[attr addAttributes:otherAttributes range:[aResult range]];
}
NSLog(#"Attr: %#", attr);
Logs:
$> Attr: This string a (has parenthesis), This string b (has parenthesis too), This string C hasn't.{
NSFont = "<UICTFont: 0x14663df0> font-family: \".SFUIText-Semibold\"; font-weight: bold; font-style: normal; font-size: 15.00pt";
}
$> Attr: This string a {
NSFont = "<UICTFont: 0x14663df0> font-family: \".SFUIText-Semibold\"; font-weight: bold; font-style: normal; font-size: 15.00pt";
}(has parenthesis){
NSFont = "<UICTFont: 0x14666260> font-family: \".SFUIText\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
}, This string b {
NSFont = "<UICTFont: 0x14663df0> font-family: \".SFUIText-Semibold\"; font-weight: bold; font-style: normal; font-size: 15.00pt";
}(has parenthesis too){
NSFont = "<UICTFont: 0x14666260> font-family: \".SFUIText\"; font-weight: normal; font-style: normal; font-size: 12.00pt";
}, This string C hasn't.{
NSFont = "<UICTFont: 0x14663df0> font-family: \".SFUIText-Semibold\"; font-weight: bold; font-style: normal; font-size: 15.00pt";
}
What is the idea:
Create a NSMutableAttributedString with the "default" attributes (in our case bold font with "big size").
Then create a NSRegularExpression and find all occurrences.
You'll add the attributes (in our case small and normal font) at that occurrence range.
In our case, it works simply, because since you can only have one attribute per kind maximum at a specific range, the NSFontAttributeName attribute will be replaced for that range.
If you added more attributes, and want to remove them, you may need to not call addAttributes:range:, but replaceCharactersInRange:withAttributedString: instead:
NSAttributedString *replacement = [[NSAttributedString alloc] initWithString:[[attr string] substringWithRange:[aResult range]]
attributes:otherAttributes];
[attr replaceCharactersInRange:[aResult range] withAttributedString:replacement];
Edit: Swift 3 Version
Nota Bene: I'm clearly not a Swift Developer, this code seems to work, but clearly, I "write" Swift like I write Objective-C, and many things since I don't use them daily and didn't read the doc are wrongly done (like the conversion/cast/explicit type/class, the "as", the "!", the "?", etc.), but it could be a start for you.
If you are a Swift developer and spots issues, feel free to comment the post and suggest your modifications. If you're just here because you have the same issue, don't forget to read in the comment if there are more Swifty things to fix in my pseudo code.
let defaultAttributes:[String:Any] = [NSFontAttributeName:UIFont.boldSystemFont(ofSize:15)];
let otherAttributes:[String:Any] = [NSFontAttributeName:UIFont.systemFont(ofSize:12)];
do {
let regex = try NSRegularExpression.init(pattern: "\\(.*?\\)", options: [])
let initialString:String = "This string a (has parenthesis), This string b (has parenthesis too), This string C hasn't."
let attr = NSMutableAttributedString.init(string: initialString, attributes: defaultAttributes)
print("Attr\(attr)");
let allMatches:[NSTextCheckingResult] = regex.matches(in: attr.string, options:[], range: NSRange(location: 0, length: attr.string.characters.count))
for aResult in allMatches
{
let occurrence = (attr.string as NSString).substring(with: aResult.range)
let replacement = NSAttributedString.init(string: occurrence , attributes: otherAttributes)
attr.replaceCharacters(in: aResult.range, with: replacement)
//attr.addAttributes(otherAttributes, range: aResult.range)
}
print("Attr\(attr)");
} catch let regexError {
print(regexError)
}

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

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).

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>