Extension:Wiki2LaTeX/Development/w2lCore.php
From MediaWiki.org
<?php
/*
* File: w2lCore.php
* Created: 2007-09-01
* Version: 0.7
*
* Purpose:
* Contains the main class, which provides the export-functionality to Mediawiki
*
* License:
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*/
if ( !defined('MEDIAWIKI') ) {
$msg = 'To install Wiki2LaTeX, put the following line in LocalSettings.php:<br/>';
$msg .= '<tt>require_once( $IP."/extensions/path_to_Wiki2LaTeX_files/wiki2latex.php" );</tt>';
echo $msg;
exit( 1 );
}
class Wiki2LaTeX {
var $actions_converter = array('w2llatexform', 'w2ltexfiles', 'w2lpdf', 'w2ltextarea', 'w2lcleartempfolder', 'w2lsyntax');
var $actions_archive = array('w2lpdfarchive', 'w2lpdfsave', 'w2larchivedelete');
var $actions = array();
var $options = array();
var $messagesLoaded = false;
var $version = '0.7';
var $required_mw = '1.11';
function Wiki2LaTeX() {
$this->__construct();
}
function __construct() {
global $w2lConfig;
$this->config =& $w2lConfig;
$this->actions = array_merge($this->actions_converter, $this->actions_archive);
}
// Mediawiki Functions
public function Setup() {
global $wgExtensionCredits;
// A current MW-Version is required so check for it...
wfUseMW($this->required_mw);
if ($this->messagesLoaded == false ) {
$this->onLoadAllMessages();
}
$wgExtensionCredits['other'][] = array(
'name' => wfMsg('wiki2latex'),
'author' => 'Hans-Georg Kluge',
'description' => wfMsg('w2l_description'),
'url' => 'http://www.mediawiki.org/wiki/Extension:Wiki2LaTeX'
);
}
function onBeforePageDisplay(&$out) {
$script = <<<EOF
<style type="text/css">/*<![CDATA[*/
li#ca-latex {margin-left:1.6em;}
li#ca-pdfarchive {margin-right:1.6em;}
/*]]>*/</style>
EOF;
$out->addScript($script."\n");
return true;
}
public function onSkinTemplateContentActions(&$content_actions) {
// Here comes the small Wiki2LaTeX-Tab
global $wgUser;
global $wgTitle;
if ($this->messagesLoaded == false ) {
$this->onLoadAllMessages();
}
$values = new webRequest();
$action = $values->getVal('action');
$cur_ns = $wgTitle->getNamespace();
$d_a = array('edit', 'submit'); // disallowed actions
if (($wgUser->getID() == 0) AND ($this->config['allow_anonymous'] == false) ) {
return true;
}
if ( ( in_array($cur_ns, $this->config['allowed_ns']) ) and !in_array($action, $d_a)) {
$content_actions['latex'] = array(
'class' => ( in_array($action, $this->actions_converter ) ) ? 'selected' : false,
'style' => 'margin-left:10px;',
'text' => wfMsg('w2l_tab'),
'href' => $wgTitle->getLocalUrl( 'action=w2llatexform' )
);
if ($this->config['enable_archive'] ) {
$content_actions['pdfarchive'] = array(
'class' => ( in_array($action, $this->actions_archive ) ) ? 'selected' : false,
'text' => wfMsg('w2l_tab_pdfarchive'),
'href' => $wgTitle->getLocalUrl( 'action=w2lpdfarchive' )
);
}
}
return true;
}
public function onLoadAllMessages() {
global $wgMessageCache;
if ( $this->messagesLoaded ) return true;
$this->messagesLoaded = true;
$wgMessageCache->clear();
require( dirname( __FILE__ ) . '/w2lMessages.php' );
foreach ( $w2lMessages as $lang => $langMessages ) {
$wgMessageCache->addMessages( $langMessages, $lang );
}
return true;
}
public function onUnknownAction($action, &$article) {
// Here comes all the stuff to show the form and parse it...
global $wgTitle, $wgOut, $wgUser;
// Check the requested action
// return if not for w2l
$action = strtolower($action);
if (!in_array($action, $this->actions)) {
// Not our action, so return!
return true;
}
// Check, if anonymous usage is allowed...
if (($wgUser->getID() == 0) AND ($this->config['allow_anonymous'] == false) ) {
return true;
}
// we are on our own now!
$action = str_replace('w2l', '', $action);
$action = 'on'.ucfirst(strtolower($action));
// Call appropriate method
if ( method_exists( $this, $action ) ) {
// Mediawiki objects
$this->mArticle =& $article;
$this->mTitle =& $wgTitle;
$this->mUser =& $wgUser;
$this->mValues = new webRequest();
// Wiki2LaTeX objects
$this->Parser = new Wiki2LaTeXParser;
$this->Parser->initParsing();
$options = $this->getParserConfig();
$this->Parser->setConfig($options);
$this->mwVars = $this->prepareVariables();
$this->Parser->setMwVariables($this->mwVars);
$this->prepareTempFolder();
$success = $this->$action();
return false;
}
}
// Our Methods to do the work we have to do
private function onLatexform($msg_add = '') {
global $wgOut, $wgScriptPath, $wgExtraNamespaces;
$title = $this->mTitle->getEscapedText();
$url_title = $this->mTitle->getPrefixedDBkey();
$namespace = $this->mTitle->getNamespace();
$select['action'] = $this->config['default_action'];
$select['template'] = $this->config['default_template'];
if ( isset($this->config['defaults']) ) {
foreach ($this->config['defaults'] as $def_line) {
if ( preg_match('/'.preg_quote($def_line['search']).'/', $title) ) {
$select['action'] = $def_line['action'];
$select['template'] = $def_line['template'];
}
}
}
$events = $this->Parser->getEventHandlers();
$output = '';
// Show a message, if form os called by a redirect from deleting all temp-files
if ( $msg_add != '' ) {
$output .= $msg_add;
}
$output .= '<form method="post" action="'.$wgScriptPath.'/index.php">'."\n";
$output .= '<input type="hidden" name="title" value="'.$url_title.'" />'."\n";
$output .= '<input type="hidden" name="started" value="1" />'."\n";
// Exportoptionen
$output .= '<fieldset>'."\n";
$output .= '<legend>'.wfMsg('w2l_options').'</legend>'."\n";
$output .= '<label><input type="radio" name="documentclass" id="documentclass" value="book"/> ';
$output .= wfMsg('w2l_select_docclass_book').'</label><br/>'."\n";
$output .= '<label><input type="radio" name="documentclass" id="documentclass" value="report" /> ';
$output .= wfMsg('w2l_select_docclass_report').'</label><br />'."\n";
$output .= '<label><input type="radio" name="documentclass" id="documentclass" value="article" checked="checked" /> ';
$output .= wfMsg('w2l_select_docclass_article').'</label><br />'."\n";
$output .= '<label><input type="checkbox" name="use_paralist" value="1" /> ';
$output .= wfMsg('w2l_select_paralist').'</label><br />'."\n";
$output .= '<label><input type="checkbox" name="typographic_quotes_detect" value="1" /> ';
$output .= wfMsg('w2l_select_quotedetection').'</label><br />'."\n";
$output .= '<label><input type="checkbox" name="leave_noinclude" value="1" checked="checked" /> ';
$output .= wfMsg('w2l_select_leavenoinclude').'</label><br />'."\n";
$output .= '<label><input type="checkbox" name="insert_includeonly" value="1" /> ';
$output .= wfMsg('w2l_select_insertincludeonly').'</label><br />'."\n";
$output .= '<label><input type="radio" name="process_curly_braces" value="0" /> ';
$output .= wfMsg('w2l_select_removetemplates').'</label><br />'."\n";
$output .= '<label><input type="radio" name="process_curly_braces" value="1" /> ';
$output .= wfMsg('w2l_select_donotprocesstemplates').'</label><br />'."\n";
$output .= '<label><input type="radio" name="process_curly_braces" checked="checked" value="2" /> ';
$output .= wfMsg('w2l_select_processtemplates').'</label><br />'."\n";
$output .= '</fieldset> '."\n";
// Auswahl für Events...
if ( count($events) > 0 ) {
$output .= '<fieldset>'."\n";
$output .= '<legend>';
$output .= wfMsg('w2l_select_events_heading');
$output .='</legend>'."\n";
foreach ($events as $event) {
$output .= '<label><input type="checkbox" name="'.$event.'" value="exec" checked="checked" /> ';
$output .= wfMsg('w2l_select_event', $event);
$output .= '</label><br />'."\n";
}
$output .= '</fieldset>'."\n";
}
$output .= '<fieldset><legend>';
$output .= wfMsg('w2l_select_templates_heading');
$output .= '</legend>';
$output .= '<label>';
$output .= wfMsg('w2l_select_template');
$output .= ' <select name="template">'."\n";
$output .= '<option value="auto">(auto)</option>';
// Auswahl des Templates...
if ( !is_array($wgExtraNamespaces) ) {
$LaTeX_namespace = false;
} else {
$LaTeX_namespace = array_search('LaTeX', $wgExtraNamespaces);
}
if ($LaTeX_namespace !== false ) {
$tables = 'page';
$vars = array('page_title', 'page_id');
$conds = array("page_namespace = ".$LaTeX_namespace, "page_title Like 'W2L_%'");
$db = wfGetDB(DB_SLAVE);
$result = $db->select($tables, $vars, $conds);
while ($line = $db->fetchRow( $result )) {
$tmpl_name = str_replace("W2L_", "", $line['page_title']);
$tmpl_name = str_replace("_", " ", $tmpl_name);
$select_it = 0;
if ($tmpl_name == $select['template']) {
$output .= '<option value="'.$line['page_id'].'" selected="selected">'.$tmpl_name.'</option>'."\n";
} else {
$output .= '<option value="'.$line['page_id'].'">'.$tmpl_name.'</option>'."\n";
}
}
$db->freeResult($result);
}
$output .= "</select></label>\n</fieldset>";
// Auswahl der Art des Exports...
$sel_textarea = ($select['action'] == 'w2ltextarea') ? ' checked="checked"': '' ;
$sel_syntax = ($select['action'] == 'w2lsyntax') ? ' checked="checked"': '' ;
$sel_tex = ($select['action'] == 'w2ltexfiles') ? ' checked="checked"': '' ;
$sel_pdf = ($select['action'] == 'w2lpdf') ? ' checked="checked"': '' ;
$output .= '<fieldset>'."\n";
$output .= '<legend>';
$output .= wfMsg('w2l_select_output');
$output .= '</legend>'."\n";
$output .= '<label><input type="radio" name="action" value="w2ltextarea"'.$sel_textarea.' /> ';
$output .= wfMsg('w2l_select_textarea');
$output .= '</label><br />'."\n";
if ($this->config['enable_geshi'] == true) {
$output .= '<label><input type="radio" name="action" value="w2lsyntax"'.$sel_syntax.' /> ';
$output .= wfMsg('w2l_select_geshi');
$output .='</label><br />'."\n";
}
$output .= '<label><input type="radio" name="action" value="w2ltexfiles"'.$sel_tex.' /> ';
$output .= wfMsg('w2l_select_texfiles');
$output .= '</label><br />'."\n";
if (true == $this->config['pdfexport']) {
$output .= '<label><input type="radio" name="action" value="w2lpdf"'.$sel_pdf.' /> ';
$output .= wfMsg('w2l_select_pdf',$this->config['output_format']);
$output .= '</label><br /> '."\n";
}
$output .= '</fieldset>'."\n";
$output .= '<button>';
$output .= wfMsg('w2l_start_export');
$output .= '</button>';
$output .= $this->getFolderLinks();
$output .= '</form>'."\n";
$wgOut->addHTML($output);
$wgOut->setPagetitle( wfMsg('w2l_export_title', $title) );
$wgOut->setSubtitle( wfMsg('w2l_export_subtitle', $title) );
return true;
}
private function onSyntax() {
$this->onTextarea(true);
return true;
}
private function onTexfiles() {
$this->onPdf(false);
return true;
}
private function onTextarea($use_geshi = false) {
global $wgOut;
$title = $this->mTitle->getEscapedText();
$events = $this->Parser->getEventHandlers();
foreach ($events as $event) {
if ($this->mValues->getVal($event) != 'exec' ) {
$this->Parser->deactivateEventHandler($event);
}
}
$to_parse = $this->mArticle->getContent();
$parsed = $this->Parser->parse($to_parse, $this->mTitle, W2L_STRING);
if ($use_geshi == false ) {
$output = '<textarea style="height:200px;">'.$parsed.'</textarea>';
$output .= $this->Parser->getErrorMessages();
} else {
$geshi = new GeSHi($parsed, 'latex');
$geshi->set_encoding('UTF-8');
$geshi->set_header_type(GESHI_HEADER_DIV);
$geshi->enable_line_numbers(GESHI_FANCY_LINE_NUMBERS);
$geshi->set_line_style('margin:0; padding:0;', 'margin:0; padding:0;', true);
$output = $this->Parser->getErrorMessages();
$output .= $geshi->parse_code();
}
if ($this->config['debug'] == true) {
$output .= wfMsg('w2l_debug_info', round($this->Parser->getParseTime(), 3), $this->Parser->curlyBraceDebugCounter, $this->Parser->curlyBraceLength);
}
$wgOut->addHTML($output);
$wgOut->setPagetitle( wfMsg('w2l_result_title', $title) );
$wgOut->setSubtitle( wfMsg('w2l_result_subtitle', $title) );
return true;
}
private function onPdf($compile = true) {
global $wgOut, $wgLang, $IP;
$output = '';
$title = $this->mTitle->getEscapedText();
if ( ($this->config['pdfexport'] == false) AND ($compile == true) ) {
// pdf export is not allowed, so don't export
$wgOut->addHTML(wfMsg('w2l_pdfexport_disabled'));
return false;
}
$events = $this->Parser->getEventHandlers();
foreach ($events as $event) {
if ($this->mValues->getVal($event) != 'exec' ) {
$this->Parser->deactivateEventHandler($event);
}
}
$to_parse = $this->mArticle->getContent();
// Get Template-Vars...
$template_vars = $this->mwVars;
$template_vars = $this->getTemplateVars($to_parse);
//If title was not set by a <templatevar> tag, use page title
// Put some special variables in the template vars
$rev = Revision::newFromTitle($this->mTitle);
if (!is_null($rev)) {
$date = $wgLang->timeanddate( wfTimestamp(TS_MW, $rev->getTimestamp()), true );
if(!in_array("Title", $template_vars)) {
$template_vars['Title'] = $title;
}
$template_vars['revision timestamp'] = $date;
$template_vars['revision user'] = $rev->getUserText();
$template_vars['revision id'] = $rev->getId();
$template_vars['page id'] = $this->mTitle->getArticleID();
}
// we need that template-file...
$temp_id = $this->mValues->getVal("template");
if ( $temp_id == 'false' ) {
// now this is bad!
$wgOut->addHTML( wfMsg('w2l_error_no_template') );
} else {
//echo $temp_id;
$parsed = $this->Parser->parse($to_parse, $this->mTitle);
if ( $temp_id == 'auto' ) {
// create a template automagically,
// future, nothing here yet...
$template = $this->createMagicTemplate();
} else {
$template = $this->getTemplate($temp_id);
}
$files = $this->createTemplateFiles($template);
// Adding some Template-Variables...
$template_vars['W2L_CONTENT'] = $parsed; //new templates should use this one!
$template_vars['W2L_VERSION'] = $this->version;
// For compatibility-reasons:
$template_vars['WikiContent'] = $parsed; // Old, for compatibility
// Now the template vars need to be put into ((var))
$tpl_vars = array();
foreach($template_vars as $tplv_key => $tplv_value) {
$tpl_vars['(('.$tplv_key.'))'] = $tplv_value;
}
// define the path for the files...
// Create temp-folder
$mytemp = $this->getTempF('local-abs');
$this->path = $mytemp;
mkdir($mytemp);
chmod($mytemp, 0777);
//$mytemp .= $this->tempFolder['piece'];
$cur_dir = getcwd();
chdir($mytemp);
$work_folder = getcwd();
$msg = '';
$msg .= 'Temporary directory: '.$mytemp."\n";
$msg .= 'Current directory: '.$work_folder."\n";
foreach( $files as $file_name => $file_content) {
$file_content = str_replace(array_keys($tpl_vars), array_values($tpl_vars), $file_content);
$failure = file_put_contents($file_name, $file_content);
if (failure !== false ) {
$msg .= 'Creating file '.$file_name.' with '.$failure.' Bytes'."\n";
} else {
$msg .= 'Error creating file '.$file_name."\n";
}
chmod($file_name, 0666);
}
if ($compile == true ) {
$latex_command = $this->config['command'];
switch ( $this->config['plattform'] ) {
case 'win':
$latex_command = str_replace("/",'\\', $latex_command);
break;
case 'linux':
break;
default:
// leave everything as is...
break;
}
$msg .= wfMsg('w2l_compile_command', $latex_command)."\n";
$msg .= wfMsg('w2l_temppath', getcwd())."\n";
for ($i = 1; $i <= $this->config['repeat']; $i++) {
$msg .= "\n".wfMsg('w2l_compile_run', $i)."\n";
$msg .= shell_exec($latex_command);
}
$this->chmodFolder($mytemp, 0666);
if ( $this->config['enable_archive'] ) {
// Show a form to save the current pdf to the pdf-folder...
$form = '<form method="post" action="'.$wgScriptPath.'/index.php">'."\n";
$form .= '<input type="hidden" name="title" value="'.$this->mTitle->getPrefixedDBkey().'" />'."\n";
$form .= '<input type="hidden" name="action" value="w2lpdfsave" />'."\n";
$form .= '<input type="hidden" name="w2l-tempdir" value="'.$this->tempFolder['piece'].'" />'."\n";
$form .= '<input type="hidden" name="w2l-v-articleid" value="'.$this->mTitle->getArticleID().'" />'."\n";
$form .= '<input type="hidden" name="w2l-v-revid" value="'.$this->mTitle->getLatestRevId().'" />'."\n";
// title should be:
// (PAGENAME)_(rev_id)_(TIMESTAMP).(OUTPUTFORMAT)
$save_title = $this->mwVars['FULLPAGENAMEE'].'_'.$this->mwVars['REVISIONID'].'_'.$this->mwVars['LOCALTIMESTAMP'];
$save_title .= '.'.$this->config['output_format'];
$save_title = str_replace('/', '_', $save_title);
$form .= '<fieldset>';
$form .= '<legend>'.wfMsg('w2l_save_legend').'</legend>';
//$form .=
$form .= '<label>'.wfMsg('w2l_save_filename').' <input type="text" name="w2l-filename" value="'.$save_title.'" style="width:300px;" /></label><br/>'."\n";
//$form .= wfMsg('w2l_save_comment').' <input type="text" id="w2l-comment" name="w2l-comment" style="width:400px;" /><br />';
$form .= '<button>';
$form .= wfMsg('w2l_save_file');
$form .='</button>';
$form .= '</form>';
} else {
$form = '';
}
}
chdir($cur_dir);
if ($this->config['debug'] == true) {
$output .= wfMsg('w2l_debug_info', $this->Parser->getParseTime(), $this->Parser->curlyBraceDebugCounter, $this->Parser->curlyBraceLength);
}
$output .= $this->getFolderLinks();
$wgOut->setPagetitle( wfMsg('w2l_result_title', $title) );
$wgOut->setSubtitle( wfMsg('w2l_result_subtitle', $title) );
$wgOut->addHTML( wfMsg('w2l_export_mode', $this->config['output_format']) );
$wgOut->addHTML( wfMsg('w2l_result_folder', $this->getTmpF('url-rel'), $this->config['output_format'], strtoupper($this->config['output_format'])) );
$wgOut->addHTML( wfMsg('w2l_result_heading') );
$wgOut->addHTML($this->Parser->getErrorMessages());
$wgOut->addHTML('<textarea style="height:200px;">'.$msg.'</textarea>');
if ($form) {
$wgOut->addHTML($form);
}
$wgOut->addHTML($output);
}
}
function onPdfarchive($msg_add = '') {
global $wgOut, $IP, $wgContLang;
// Checl if it is enabled...
$title = $this->mTitle->getEscapedText();
$page_id = $this->mTitle->getArticleID();
if ( $this->config['enable_archive'] != true ) {
$wgOut->addHTML( wfMsg('w2l_archive_disabled') );
$wgOut->setPagetitle( wfMsg('w2l_archive_title', $title) );
$wgOut->setSubtitle( wfMsg('w2l_archive_subtitle', $title) );
return false;
}
if ( $msg_add != '' ) {
$wgOut->addHTML($msg_add);
}
$local_folder = $this->getF('archive', 'local-abs').$page_id;
$url = $this->getF('archive', 'url-rel').$page_id;
if ( is_dir($local_folder) ) {
$files = scandir($local_folder);
} else {
$files = false;
}
if ( is_array($files) ) {
$wgOut->addHTML('<table border="1" style="width:100%;">');
$wgOut->addHTML('<tr>');
$wgOut->addHTML('<th>'.wfMsg('w2l_archive_filename').'</th>');
$wgOut->addHTML('<th>'.wfMsg('w2l_archive_filetime').'</th>');
$wgOut->addHTML('<th>'.wfMsg('w2l_archive_filesize').'</th>');
//$wgOut->addHTML('<th>'.wfMsg('w2l_archive_comment').'</th>');
$wgOut->addHTML('<th>'.wfMsg('w2l_archive_actions').'</th>');
$wgOut->addHTML('</tr>');
$file_holder = array();
foreach ($files as $file) {
if ( !is_file($local_folder.'/'.$file) ) {
continue;
}
$filename = $local_folder.'/'.$file;
$filetimestamp = filemtime($filename);
$file_date = $wgContLang->timeanddate($filetimestamp);
$file_size = filesize($filename);
$file_size = $file_size/1024;
$comment = '---';
$file_holder[$filetimestamp] = '<tr>';
$file_holder[$filetimestamp] .= '<td><a href="'.$url.'/'.wfUrlEncode($file).'">'.$file.'</a></td>';
$file_holder[$filetimestamp] .= '<td>'.$file_date.'</td>';
$file_holder[$filetimestamp] .= '<td>'.round($file_size,2).'kb</td>';
//$file_holder[$filetimestamp] .= '<td>'.$comment.'</td>';
$file_holder[$filetimestamp] .= '<td>(<a href="'. $this->mTitle->getLocalUrl( 'action=w2larchivedelete&w2lfile='.$page_id.'/'.wfUrlEncode($file) ).'" onclick="return confirm(\''.wfMsg('w2l_delete_file_confirmation', $file).'\');">'.wfMsg('w2l_archive_delete').'</a>)</td>';
$file_holder[$filetimestamp] .= '</tr>';
}
krsort($file_holder, SORT_NUMERIC);
foreach($file_holder as $line) {
$wgOut->addHTML($line);
}
$wgOut->addHTML('</table>');
} else {
$wgOut->addHTML( wfMsg('w2l_archive_no_folder') );
}
// get the folder...
$wgOut->setPagetitle( wfMsg('w2l_archive_title', $title) );
$wgOut->setSubtitle( wfMsg('w2l_archive_subtitle', $title) );
}
function onPdfsave() {
// Save the pdf to the folder, show result, show link to pdfarchive!
global $wgOut, $IP;
if ( $this->config['enable_archive'] ) {
$destination = $this->getF('archive', 'local-abs');
//$filename = str_replace('/', '_', );
$page_id = $this->mTitle->getArticleID();
//var_dump($this->mTitle);
$folder = $destination.$page_id.'/';
$filename = $folder.$this->mValues->getVal('w2l-filename');
if ( !is_dir($folder) ) {
mkdir($folder);
chmod($folder, 0777);
}
$source = $this->getF('tmp', 'local-abs').$this->mValues->getVal('w2l-tempdir').'/Main.'.$this->config['output_format'];
$state = copy($source, $filename);
chmod ($filename, 0666);
if ( true == $state ) {
$text = wfMsg('w2l_archive_save_success', $this->getF('archive', 'url-rel').$page_id.'/'.$this->mValues->getVal('w2l-filename') );
$msg = $this->getStatusMessage($text, true);
} else {
$text = wfMsg('w2l_archive_save_error' );
$msg = $this->getStatusMessage($text, false);
}
} else {
$text = wfMsg('w2l_archive_disabled');
$msg = $this->getStatusMessage($text, true);
}
$this->onPdfarchive($msg);
}
function onArchivedelete() {
global $wgOut, $IP;
if ( $this->config['enable_archive'] ) {
$destination = $this->getF('archive', 'local-abs');
//$filename = str_replace('/', '_', );
$file = $destination.$this->mValues->getVal('w2lfile');
$folder = dirname($file);
if (is_file($file)) {
$state = unlink($file);
}
// check if the folder is empty...
// remove it if neccessary
$d = dir($folder);
$remove = true;
while (false !== ($entry = $d->read())) {
if (is_file($d->path.'/'.$entry) ) {
$remove = false;
}
}
if ($remove) {
rmdir($folder);
}
$d->close();
if ( true == $state ) {
$text = wfMsg('w2l_archive_delete_success' );
$msg = $this->getStatusMessage($text, true);
} else {
$text = wfMsg('w2l_archive_delete_error' );
$msg = $this->getStatusMessage($text, false);
}
} else {
$text = wfMsg('w2l_archive_disabled' );
$msg = $this->getStatusMessage($text, false);
}
$this->onPdfarchive($msg);
}
function onCleartempfolder() {
global $IP, $wgOut;
$dir = $this->getF('tmp', 'local-abs');
$state = $this->full_rmdir($dir, false);
if ($state) {
//$wgOut->redirect($this->mTitle->getLocalUrl( 'action=w2llatexform&deletesuccess=true' ));
$text = wfMsg('w2l_delete_success');
$msg = $this->getStatusMessage($text, true);
} else {
//$wgOut->redirect($this->mTitle->getLocalUrl( 'action=w2llatexform&deletesuccess=false' ));
$text = wfMsg('w2l_delete_error');
$msg = $this->getStatusMessage($text, false);
}
$this->onLatexform($msg);
}
// Our helperfunctions
function full_rmdir( $dir, $del_dir = true ) {
// Code from:
// http://de.php.net/manual/en/function.rmdir.php
// By:
// swizec at swizec dot com (31-Jul-2007 03:53)
if ( !is_writable( $dir ) ) {
if ( !@chmod( $dir, 0777 ) ) {
return false;
}
}
$d = dir( $dir );
while ( false !== ( $entry = $d->read() ) ) {
if ( $entry == '.' || $entry == '..' ) {
continue;
}
$entry = $dir . '/' . $entry;
if ( is_dir( $entry ) ) {
if ( !$this->full_rmdir( $entry ) ) {
return false;
}
continue;
}
if ( !@unlink( $entry ) ) {
$d->close();
return false;
}
}
$d->close();
if ($del_dir) {
rmdir( $dir );
}
return true;
}
function createMagicTemplate() {
$packages = $this->Parser->getUsePackageBlock();
$code = $this->Parser->getLatexHeadCode();
$tmpl = <<<EOF
==LaTeX-Template==
<latexfile name="Main">
\documentclass[12pt,a4paper]{scrartcl}
\usepackage[utf8x]{inputenc} % This is very important!
\usepackage[T1]{fontenc}
((W2L_REQUIRED_PACKAGES))
((W2L_HEAD))
\begin{document}
((W2L_CONTENT))
\end{document}
</latexfile>
EOF;
$tmpl = str_replace('((W2L_REQUIRED_PACKAGES))', $packages, $tmpl);
$tmpl = str_replace('((W2L_HEAD))', $code, $tmpl);
return $tmpl;
}
public function getTemplateVars( $text ) {
$vars = array();
$parts = explode('<templatevar vname="', " ".$text);
array_shift($parts);
foreach ($parts as $part) {
$var = explode('">', $part);
$var_name = $var[0];
$tmp = explode("</templatevar>", $var[1], 2);
$var_content = $tmp[0];
$vars[$var_name] = $var_content;
}
return $vars;
}
public function prepareVariables() {
global $wgContLang, $wgSitename, $wgServer, $wgServerName, $wgScriptPath;
global $wgContLanguageCode;
global $wgTitle;
$this->mRevisionId = $this->mTitle->getLatestRevID();
$ts = time();
# Use the time zone
global $wgLocaltimezone;
if ( isset( $wgLocaltimezone ) ) {
$oldtz = getenv( 'TZ' );
putenv( 'TZ='.$wgLocaltimezone );
}
wfSuppressWarnings(); // E_STRICT system time bitching
$localTimestamp = date( 'YmdHis', $ts );
$localMonth = date( 'm', $ts );
$localMonthName = date( 'n', $ts );
$localDay = date( 'j', $ts );
$localDay2 = date( 'd', $ts );
$localDayOfWeek = date( 'w', $ts );
$localWeek = date( 'W', $ts );
$localYear = date( 'Y', $ts );
$localHour = date( 'H', $ts );
if ( isset( $wgLocaltimezone ) ) {
putenv( 'TZ='.$oldtz );
}
wfRestoreWarnings();
// some simpler ones...
$w2lVars = array(
'currentmonth' => $wgContLang->formatNum( gmdate( 'm', $ts ) ),
'currentmonthname' => $wgContLang->getMonthName( gmdate( 'n', $ts ) ),
'currentmonthnamegen'=> $wgContLang->getMonthNameGen( gmdate( 'n', $ts ) ),
'currentmonthabbrev'=> $wgContLang->getMonthAbbreviation( gmdate( 'n', $ts ) ),
'currentday'=> $wgContLang->formatNum( gmdate( 'j', $ts ) ),
'currentday2'=> $wgContLang->formatNum( gmdate( 'd', $ts ) ),
'localmonth'=>$wgContLang->formatNum( $localMonth ),
'localmonthname' => $wgContLang->getMonthName( $localMonthName ),
'localmonthnamegen'=> $wgContLang->getMonthNameGen( $localMonthName ),
'localmonthabbrev'=> $wgContLang->getMonthAbbreviation( $localMonthName ),
'localday'=> $wgContLang->formatNum( $localDay ),
'localday2' => $wgContLang->formatNum( $localDay2 ),
'pagename' => wfEscapeWikiText( $this->mTitle->getText() ),
'pagenamee'=>$this->mTitle->getPartialURL(),
'fullpagename' =>wfEscapeWikiText( $this->mTitle->getPrefixedText() ),
'fullpagenamee' => $this->mTitle->getPrefixedURL(),
'subpagename' => wfEscapeWikiText( $this->mTitle->getSubpageText() ),
'subpagenamee' => $this->mTitle->getSubpageUrlForm(),
'basepagename' => wfEscapeWikiText( $this->mTitle->getBaseText() ),
'basepagenamee' => wfUrlEncode( str_replace( ' ', '_', $this->mTitle->getBaseText() ) ),
'revisionid' => $this->mRevisionId,
'revisionday' => intval( substr( $this->getRevisionTimestamp(), 6, 2 ) ),
'revisionday2' => substr( $this->getRevisionTimestamp(), 6, 2 ),
'revisionmonth' => intval( substr( $this->getRevisionTimestamp(), 4, 2 ) ),
'revisionyear' => substr( $this->getRevisionTimestamp(), 0, 4 ),
'revisiontimestamp' => $this->getRevisionTimestamp(),
'namespace' => str_replace('_',' ',$wgContLang->getNsText( $this->mTitle->getNamespace() ) ),
'namespacee' => wfUrlencode( $wgContLang->getNsText( $this->mTitle->getNamespace() ) ),
'talkspace' => $this->mTitle->canTalk() ? str_replace('_',' ',$this->mTitle->getTalkNsText()) : '',
'talkspacee' => $this->mTitle->canTalk() ? wfUrlencode( $this->mTitle->getTalkNsText() ) : '',
'subjectspace' => $this->mTitle->getSubjectNsText(),
'subjectspacee' =>wfUrlencode( $this->mTitle->getSubjectNsText() ),
'currentdayname' => $wgContLang->getWeekdayName( gmdate( 'w', $ts ) + 1 ),
'currentyear' => $wgContLang->formatNum( gmdate( 'Y', $ts ), true ),
'currenttime' => $wgContLang->time( wfTimestamp( TS_MW, $ts ), false, false ),
'currenthour' => $wgContLang->formatNum( gmdate( 'H', $ts ), true ),
'currentweek'=> $wgContLang->formatNum( (int)gmdate( 'W', $ts ) ),
'currentdow'=>$wgContLang->formatNum( gmdate( 'w', $ts ) ),
'localdayname'=> $wgContLang->getWeekdayName( $localDayOfWeek + 1 ),
'localyear' => $wgContLang->formatNum( $localYear, true ),
'localtime' => $wgContLang->time( $localTimestamp, false, false ),
'localhour' => $wgContLang->formatNum( $localHour, true ),
'localweek' => $wgContLang->formatNum( (int)$localWeek ),
'localdow' =>$wgContLang->formatNum( $localDayOfWeek ),
'numberofarticles' => $wgContLang->formatNum( SiteStats::articles() ),
'numberoffiles' =>$wgContLang->formatNum( SiteStats::images() ),
'numberofusers' => $wgContLang->formatNum( SiteStats::users() ),
'numberofpages' => $wgContLang->formatNum( SiteStats::pages() ),
'numberofadmins' => $wgContLang->formatNum( SiteStats::admins() ),
'numberofedits' =>$wgContLang->formatNum( SiteStats::edits() ),
'currenttimestamp' => wfTimestampNow(),
'localtimestamp' => $localTimestamp,
'currentversion' => SpecialVersion::getVersion(),
'sitename' =>$wgSitename,
'server' => $wgServer,
'servername' => $wgServerName,
'scriptpath' =>$wgScriptPath,
'directionmark' => $wgContLang->getDirMark(),
'contentlanguage' => $wgContLanguageCode
);
// These are a bit more complicated...
//case 'talkpagename':
if( $this->mTitle->canTalk() ) {
$talkPage = $this->mTitle->getTalkPage();
$talkpagename = wfEscapeWikiText( $talkPage->getPrefixedText() );
} else {
$talkpagename = '';
}
$w2lVars['talkpagename'] = $talkpagename;
//case 'talkpagenamee':
if( $this->mTitle->canTalk() ) {
$talkPage = $this->mTitle->getTalkPage();
$talkpagenamee = $talkPage->getPrefixedUrl();
} else {
$talkpagenamee = '';
}
$w2lVars['talkpagenamee'] = $talkpagenamee;
//case 'subjectpagename':
$subjPage = $this->mTitle->getSubjectPage();
$w2lVars['subjectpagename'] = wfEscapeWikiText( $subjPage->getPrefixedText() );
$w2lVars['subjectpagenamee'] = $subjPage->getPrefixedUrl();
return array_change_key_case($w2lVars, CASE_UPPER);
}
function getRevisionTimestamp() {
// At this point, we're dealing only with current articles.
// Needs to be changed, if oldid support is integrated!!!
// Required for prepareVariables
return $this->mArticle->getTimestamp();
}
public function createTemplateFiles($template) {
// extract all the files, which are in it
// AND: All the files, that need to be stripped out of other pages...
// required latexfiles:
$other_files = $this->getTagContents($template, 'latexpage');
$template = ' '.$template;
$template_sec = explode('<latexfile name="', $template);
array_shift($template_sec);
$files = array();
// die anderen Dateien
foreach ($other_files as $file) {
$file_content = $this->getWiki($file);
$tmp_content = $this->getTagContents($file_content, "latex");
$file_name = str_replace("LaTeX:", "", $file);
$file_name .= ".tex";
$files[$file_name] = trim($tmp_content[0]);
}
// Die Dateien aus dem Template
foreach ($template_sec as $file_info) {
$file = explode('">', $file_info,2);
$file_name = $file[0].".tex";
$file_content = explode('</latexfile>', $file[1],2);
$files[$file_name] = trim($file_content[0]);
}
return $files;
}
public function getParserConfig() {
$config = array();
$keys = array(
'use_paralist',
'typographic_quotes_detect',
'leave_noinclude',
'insert_includeonly',
'process_curly_braces',
'documentclass'
);
foreach($keys as $key) {
$config[$key] = $this->mValues->getVal($key);
}
return $config;
}
public function getTagContents($string, $tag) {
$string = " ".$string;
$open_tag = "<".$tag.">";
$close_tag = "</".$tag.">";
$contents = explode($open_tag, $string);
$tags = array();
array_shift($contents);
foreach ($contents as $tag_content) {
$tag_content2 = explode($close_tag, $tag_content,2);
$tags[] = $tag_content2[0];
}
return $tags;
}
private function getStatusMessage($msg, $success = true) {
// Show a message, if form os called by a redirect from deleting all temp-files
$output = '';
if ( $success == true ) {
$output = "\n".'<div onclick="this.style.display=\'none\'" style="text-align:center;border:1px solid black; background-color:#3c6; padding:5px; margin:5px;">';
$output .= $msg;
$output .= '</div>';
} elseif ( $success == false ) {
$output = '<div onclick="this.style.display=\'none\'" style="text-align:center;border:1px solid black; background-color:#c33; padding:5px; margin:5px;">';
$output .= $msg ;
$output .= '</div>';
} else {
$output = '<div onclick="this.style.display=\'none\'" style="text-align:center;border:1px solid black; background-color:'.$success.'; padding:5px; margin:5px;">';
$output .= $msg;
$output .= '</div>';
}
return $output;
}
public function getTemplate($id) {
$title = Title::newFromID( $id );
$rev = new Article( &$title, 0 );
$text = $rev->getContent();
return $text;
}
public function getWiki($title_str) {
$title = Title::newFromText( $title_str );
$rev = new Article( &$title, 0 );
$text = $rev->getContent();
return $text;
}
public function getFolderLinks() {
$output = '<div style="text-align:right;">';
if ( $this->config['enable_archive']) {
$output .= '<a href="'.$this->getF('archive', 'url-rel').'">(PDF-Archive)</a> ';
}
$output .= '<a href="'.$this->getF('tmp', 'url-rel').'">(temporary files)</a> ';
$output .= '<a href="'.$this->mTitle->getLocalUrl( 'action=w2lcleartempfolder' ).'" onclick="return confirm(\''.wfMsg('w2l_delete_confirmation').'\');">('.wfMsg('w2l_form_delete_link').')</a>';
$output .= '</div>';
return $output;
}
public function chmodFolder($folder, $mod = 0777) {
// latex might leave some files, which have to be chmodded...
if ( is_dir($folder) ) {
$directory = dir($folder);
while (false !== ($file = $directory->read())) {
if ( is_file($file) )
chmod($file, $mod);
}
$directory->close();
return true;
} else {
return false;
}
}
public function prepareTempFolder() {
global $IP;
// get the name of the temporary folder
$piece = "tmp-".time()."-".rand();
$this->tempFolder['piece'] = $piece;
$this->tempFolder['local'] = $this->getTempF("local-abs");
$this->tempFolder['url'] = $this->getTempF("url-rel");
return true;
}
private function getTempF($absrel, $with_piece = true) {
return $this->getTmpF($absrel, $with_piece);
}
private function getTmpF($absrel, $with_piece = true) {
$ret = $this->getF('tmp', $absrel);
if ($with_piece == true) {
$ret .= $this->tempFolder['piece'].'/';
}
return $ret;
}
private function getF($type, $absrel) {
// returns folder information
// path-tmp, path-archive
global $IP, $wgScriptPath;
//echo
switch($absrel) {
case 'local-rel':
// TODO: implement local-rel
return '';
case 'local-abs':
return $IP.$this->config['path-'.$type];
case 'url-rel':
return $wgScriptPath.$this->config['path-'.$type];
case 'url-abs':
// TODO: implement url-abs
return '';
}
}
}
