Example #1
0
 public function testGetContent()
 {
     $this->source->expects($this->exactly(2))->method('getContent')->with($this->object)->will($this->returnValue('content'));
     $this->assertEquals('content', $this->object->getContent());
     $this->assertEquals('content', $this->object->getContent());
     // no in-memory caching for content
 }
Example #2
0
 /**
  * Converts the code to HTML
  *
  * @param File        $file File to render
  * @param Tool_Result $res  Tool result to integrate
  *
  * @return string HTML
  */
 public function toHtml(File $file, Tool_Result $res = null)
 {
     if (class_exists('\\Michelf\\Markdown', true)) {
         //composer-installed version 1.4+
         $markdown = \Michelf\Markdown::defaultTransform($file->getContent());
     } else {
         //PEAR-installed version 1.0.2 has a different API
         require_once 'markdown.php';
         $markdown = \markdown($file->getContent());
     }
     return '<div class="markdown">' . $markdown . '</div>';
 }
Example #3
0
 /**
  * Resize an SVG image
  */
 protected function executeResizeSvg()
 {
     $doc = new \DOMDocument();
     if ($this->fileObj->extension == 'svgz') {
         $doc->loadXML(gzdecode($this->fileObj->getContent()));
     } else {
         $doc->loadXML($this->fileObj->getContent());
     }
     $svgElement = $doc->documentElement;
     // Set the viewBox attribute from the original dimensions
     if (!$svgElement->hasAttribute('viewBox')) {
         $origWidth = $svgElement->getAttribute('width');
         $origHeight = $svgElement->getAttribute('height');
         $svgElement->setAttribute('viewBox', '0 0 ' . floatval($origWidth) . ' ' . floatval($origHeight));
     }
     $coordinates = $this->computeResize();
     $svgElement->setAttribute('x', $coordinates['target_x']);
     $svgElement->setAttribute('y', $coordinates['target_y']);
     $svgElement->setAttribute('width', $coordinates['target_width']);
     $svgElement->setAttribute('height', $coordinates['target_height']);
     $svgWrapElement = $doc->createElementNS('http://www.w3.org/2000/svg', 'svg');
     $svgWrapElement->setAttribute('version', '1.1');
     $svgWrapElement->setAttribute('width', $coordinates['width']);
     $svgWrapElement->setAttribute('height', $coordinates['height']);
     $svgWrapElement->appendChild($svgElement);
     $doc->appendChild($svgWrapElement);
     if ($this->fileObj->extension == 'svgz') {
         $xml = gzencode($doc->saveXML());
     } else {
         $xml = $doc->saveXML();
     }
     $objCacheFile = new \File($this->getCacheName());
     $objCacheFile->write($xml);
     $objCacheFile->close();
 }
Example #4
0
 /**
  * Create the folders and protect them.
  */
 protected function checkFolders()
 {
     // Get folders from config
     $strBackupDB = $this->standardizePath($GLOBALS['SYC_PATH']['db']);
     $strBackupFile = $this->standardizePath($GLOBALS['SYC_PATH']['file']);
     $strTemp = $this->standardizePath($GLOBALS['SYC_PATH']['tmp']);
     $objHt = new File('system/modules/syncCto/config/.htaccess');
     $strHT = $objHt->getContent();
     $objHt->close();
     // Check each one
     if (!file_exists(TL_ROOT . '/' . $strBackupDB)) {
         new Folder($strBackupDB);
         $objFile = new File($strBackupDB . '/' . '.htaccess');
         $objFile->write($strHT);
         $objFile->close();
     }
     if (!file_exists(TL_ROOT . '/' . $strBackupFile)) {
         new Folder($strBackupFile);
         $objFile = new File($strBackupFile . '/' . '.htaccess');
         $objFile->write($strHT);
         $objFile->close();
     }
     if (!file_exists(TL_ROOT . '/' . $strTemp)) {
         new Folder($strTemp);
     }
 }
 public function loadDebuggerstate($varValue, $dc)
 {
     $objFile = new File('system/config/initconfig.php');
     $strContent = $objFile->getContent();
     $objFile->close();
     return $varValue && strpos($strContent, self::DEBUGCONFIG_STRING);
 }
Example #6
0
function Poll($id, $question, $answer1 = 'Yes', $answer2 = 'No')
{
    // values
    $id = isset($id) ? $id : '';
    $question = isset($question) ? $question : '';
    $answer1 = isset($answer1) ? $answer1 : '';
    $answer2 = isset($answer2) ? $answer2 : '';
    // json dir
    $dir = PLUGINS_PATH . '/poll/db/db.json';
    // clear vars init
    $db = '';
    $data = '';
    // check if exists file if not make one
    if (File::exists($dir)) {
        $db = File::getContent($dir);
        $data = json_decode($db, true);
        if (!$data[$id]) {
            // array of data
            $data[$id] = array('question' => '', 'yes' => '', 'no' => '');
            File::setContent($dir, json_encode($data));
            // redirect
            Request::redirect(Url::getCurrent());
        }
    } else {
        File::setContent($dir, '[]');
    }
    // check session if exists show answer only
    if (Session::get('user_poll' . $id)) {
        $template = Template::factory(PLUGINS_PATH . '/poll/template/');
        return $template->fetch('answer.tpl', ['id' => trim($id), 'question' => trim($question), 'answer1' => trim($answer1), 'answer2' => trim($answer2), 'yes' => $data[$id]['yes'], 'no' => $data[$id]['no']]);
    } else {
        // form post
        if (Request::post('sendData_' . $id)) {
            // check token
            if (Request::post('token')) {
                if (Request::post('answer') == 1) {
                    $good = $data[$id]['yes'] + 1;
                    $bad = $data[$id]['no'];
                } elseif (Request::post('answer') == 0) {
                    $bad = $data[$id]['no'] + 1;
                    $good = $data[$id]['yes'];
                }
                // array of data
                $data[$id] = array('question' => $question, 'yes' => $good, 'no' => $bad);
                // set content
                File::setContent($dir, json_encode($data));
                // set session cookie
                Session::set('user_poll' . $id, uniqid($id));
                // redirect
                Request::redirect(Url::getCurrent());
            } else {
                die('crsf detect !');
            }
        }
        // show template form
        $template = Template::factory(PLUGINS_PATH . '/poll/template/');
        return $template->fetch('poll.tpl', ['id' => trim($id), 'question' => trim($question), 'answer1' => trim($answer1), 'answer2' => trim($answer2), 'yes' => $data[$id]['yes'], 'no' => $data[$id]['no']]);
    }
}
 /**
  * Decode file content.
  *
  * @param string $filePath
  * @return array
  * @throws \InvalidArgumentException
  */
 public function decodeFile($filePath)
 {
     $file = new File($filePath);
     $fileData = $file->getContent();
     $dataDecoder = new JsonDataDecoder();
     $result = $dataDecoder->decodeData($fileData);
     return $result;
 }
Example #8
0
 public function testGetContentThrowsAnExceptionIfTheFileDoesNotExistsInTheFilesystem()
 {
     $fs = $this->getFilesystemMock();
     $fs->expects($this->once())->method('has')->with($this->equalTo('myFile'))->will($this->returnValue(false));
     $file = new File('myFile', $fs);
     $this->setExpectedException('LogicException');
     $file->getContent();
 }
 protected function parseExtJs($objLayout, &$arrReplace)
 {
     $arrJs = array();
     $objJs = ExtJsModel::findMultipleByIds(deserialize($objLayout->extjs));
     if ($objJs === null) {
         return false;
     }
     $cache = !$GLOBALS['TL_CONFIG']['debugMode'];
     while ($objJs->next()) {
         $objFiles = ExtJsFileModel::findMultipleByPid($objJs->id);
         if ($objFiles === null) {
             continue;
         }
         $strChunk = '';
         $strFile = 'assets/js/' . $objJs->title . '.js';
         $strFileMinified = str_replace('.js', '.min.js', $strFile);
         $objGroup = new \File($strFile, file_exists(TL_ROOT . '/' . $strFile));
         $objGroupMinified = new \File($strFileMinified, file_exists(TL_ROOT . '/' . $strFile));
         $rewrite = $objJs->tstamp > $objGroup->mtime || $objGroup->size == 0 || $cache && $objGroupMinified->size == 0;
         while ($objFiles->next()) {
             $objFileModel = \FilesModel::findByPk($objFiles->src);
             if ($objFileModel === null || !file_exists(TL_ROOT . '/' . $objFileModel->path)) {
                 continue;
             }
             $objFile = new \File($objFileModel->path);
             $strChunk .= $objFile->getContent() . "\n";
             if ($objFile->mtime > $objGroup->mtime) {
                 $rewrite = true;
             }
         }
         // simple file caching
         if ($rewrite) {
             $objGroup->write($strChunk);
             $objGroup->close();
             // minify js
             if ($cache) {
                 $objGroup = new \File($strFileMinified);
                 $objMinify = new \MatthiasMullie\Minify\JS();
                 $objMinify->add($strChunk);
                 $objGroup->write(rtrim($objMinify->minify(), ";") . ";");
                 // append semicolon, otherwise "(intermediate value)(...) is not a function"
                 $objGroup->close();
             }
         }
         $arrJs[] = $cache ? "{$strFileMinified}|static" : "{$strFile}";
     }
     // HOOK: add custom css
     if (isset($GLOBALS['TL_HOOKS']['parseExtJs']) && is_array($GLOBALS['TL_HOOKS']['parseExtJs'])) {
         foreach ($GLOBALS['TL_HOOKS']['parseExtJs'] as $callback) {
             $arrJs = static::importStatic($callback[0])->{$callback}[1]($arrJs);
         }
     }
     if ($objJs->addBootstrap) {
         $this->addTwitterBootstrap();
     }
     // inject extjs before other plugins, otherwise bootstrap may not work
     $GLOBALS['TL_JAVASCRIPT'] = is_array($GLOBALS['TL_JAVASCRIPT']) ? array_merge($GLOBALS['TL_JAVASCRIPT'], $arrJs) : $arrJs;
 }
Example #10
0
 public function testXpath()
 {
     $f = new File("/" . FRAMEWORK_CORE_PATH . "tests/xml/xml_file.xml");
     $xml_doc = new SimpleXMLElement(str_replace("xmlns", "ns", $f->getContent()));
     $config_params = $xml_doc->xpath("/module-declaration/config-params");
     $this->assertTrue($config_params, "Impossibile leggere i parametri di configurazione!!");
     $install_data = $xml_doc->xpath('/module-declaration/action[@name="install"]');
     $this->assertTrue($install_data, "Impossibile leggere i dati per l'installazione!!");
 }
 function import_data_from_file($filename_or_file)
 {
     if ($filename_or_file instanceof File) {
         $f = $filename_or_file;
     } else {
         $f = new File($filename_or_file);
     }
     $this->import_data($f->getContent());
 }
 public function getResponsePart($strFilename, $intFilecount)
 {
     $strFilepath = "/system/tmp/" . $intFilecount . "_" . $strFilename;
     if (!file_exists(TL_ROOT . $strFilepath)) {
         throw new \RuntimeException("Missing partfile {$strFilepath}");
     }
     $objFile = new \File($strFilepath);
     $strReturn = $objFile->getContent();
     $objFile->close();
     return $strReturn;
 }
Example #13
0
 function testBlackHole()
 {
     $f = new File("/" . FRAMEWORK_CORE_PATH . "tests/io/black_hole_test.php");
     $this->assertTrue($f->exists(), "Il file del test non esiste!!");
     $content = $f->getContent();
     $f->delete();
     $this->assertFalse($f->exists(), "Il file del test black hole non e' stato eliminato!!");
     $f->touch();
     $f->setContent($content);
     $this->assertTrue($f->exists(), "Il file del test black hole non e' stato rigenerato!!");
 }
Example #14
0
 protected function loadTempList()
 {
     $objCompareList = new File($this->objSyncCtoHelper->standardizePath($GLOBALS['SYC_PATH']['tmp'], "synccomparelistTo-ID-" . $this->intClientID . ".txt"));
     $strContent = $objCompareList->getContent();
     if (strlen($strContent) == 0) {
         $this->arrListCompare = array();
     } else {
         $this->arrListCompare = unserialize($strContent);
     }
     $objCompareList->close();
 }
 /**
  * Add the result from json file object
  *
  * @param \File $file
  */
 public function addJsonFile(\File $file)
 {
     if (substr($file->name, -4, 4) != 'json') {
         return;
     }
     $data = array();
     $data = json_decode($file->getContent(), true);
     if ($data) {
         foreach ($data as $result) {
             $this->addResult($result);
         }
     }
 }
Example #16
0
 /**
  * Runs the test.
  */
 public function test()
 {
     $path = DIR_FILES . '/mail/logo.gif';
     $name = 'logo.gif';
     $mimeType = 'image/gif';
     $attachment = new File($path, $name, $mimeType);
     $this->assertEquals(file_get_contents($path), $attachment->getContent());
     $this->assertEquals($name, $attachment->getName());
     $this->assertEquals($mimeType, $attachment->getMimeType());
     $this->assertEquals(\Jyxo\Mail\Email\Attachment::DISPOSITION_ATTACHMENT, $attachment->getDisposition());
     $this->assertFalse($attachment->isInline());
     $this->assertEquals('', $attachment->getCid());
     $this->assertEquals('', $attachment->getEncoding());
 }
 /**
  * {@inheritdoc}
  */
 public function handle(\Input $input)
 {
     $configFile = new \File($this->configPathname);
     if ($input->post('save')) {
         $tempPathname = $this->configPathname . '~';
         $tempFile = new \File($tempPathname);
         $config = $input->postRaw('config');
         $config = html_entity_decode($config, ENT_QUOTES, 'UTF-8');
         $tempFile->write($config);
         $tempFile->close();
         $validator = new ConfigValidator($this->io);
         list($errors, $publishErrors, $warnings) = $validator->validate(TL_ROOT . '/' . $tempPathname);
         if (!$errors && !$publishErrors) {
             $_SESSION['TL_CONFIRM'][] = $GLOBALS['TL_LANG']['composer_client']['configValid'];
             $this->import('Files');
             $this->Files->rename($tempPathname, $this->configPathname);
         } else {
             $tempFile->delete();
             $_SESSION['COMPOSER_EDIT_CONFIG'] = $config;
             if ($errors) {
                 foreach ($errors as $message) {
                     $_SESSION['TL_ERROR'][] = 'Error: ' . $message;
                 }
             }
             if ($publishErrors) {
                 foreach ($publishErrors as $message) {
                     $_SESSION['TL_ERROR'][] = 'Publish error: ' . $message;
                 }
             }
         }
         if ($warnings) {
             foreach ($warnings as $message) {
                 $_SESSION['TL_ERROR'][] = 'Warning: ' . $message;
             }
         }
         $this->reload();
     }
     if (isset($_SESSION['COMPOSER_EDIT_CONFIG'])) {
         $config = $_SESSION['COMPOSER_EDIT_CONFIG'];
         unset($_SESSION['COMPOSER_EDIT_CONFIG']);
     } else {
         $config = $configFile->getContent();
     }
     $template = new \BackendTemplate('be_composer_client_editor');
     $template->composer = $this->composer;
     $template->config = $config;
     return $template->parse();
 }
Example #18
0
 function execute()
 {
     $nome_script = $this->nome_script;
     if (self::$dummy_mode) {
         echo "Execute sql if found : " . $this->module_dir->getPath() . "/sql/" . $nome_script . ".sql<br />";
         return;
     }
     $script_file = new File($this->module_dir->getPath() . "/sql/" . $nome_script . ".sql");
     if ($script_file->exists()) {
         $script_sql = $script_file->getContent();
         $direct_sql_query = DB::newDirectSql($script_sql);
         $direct_sql_query->exec();
         return true;
     } else {
         return false;
     }
 }
 /**
  * Import a rule set
  *
  * @param string
  * @param int
  */
 private function importRuleSet($file, $themeId)
 {
     $file = new \File($file, true);
     $doc = new \DOMDocument('1.1', 'UTF-8');
     $doc->loadXML($file->getContent());
     $rules = $doc->getElementsByTagName('rule');
     $sortIndex = 0;
     $lastRule = RuleModel::findBy('pid', $themeId, array('order' => 'sorting DESC', 'limit' => 1));
     if ($lastRule) {
         $sortIndex = $lastRule->sorting + 128;
     }
     foreach ($rules as $rule) {
         $set = array('pid' => $themeId, 'sorting' => $sortIndex, 'type' => $rule->getElementsByTagName('type')->item(0)->nodeValue, 'selector' => $rule->getElementsByTagName('selector')->item(0)->nodeValue, 'enable_replace' => $rule->getElementsByTagName('enable_replace')->item(0)->nodeValue === 'true' ? '1' : '', 'replace_directives' => $rule->getElementsByTagName('replace_directives')->item(0)->nodeValue, 'enable_add' => $rule->getElementsByTagName('enable_add')->item(0)->nodeValue === 'true' ? '1' : '', 'add_directives' => $rule->getElementsByTagName('add_directives')->item(0)->nodeValue, 'published' => $rule->getElementsByTagName('published')->item(0)->nodeValue === 'true' ? '1' : '');
         $sortIndex += 128;
         \Database::getInstance()->prepare('INSERT INTO tl_css_class_replacer %s')->set($set)->execute();
     }
 }
 /**
  * Chop up any local CSS files that are too big and add an IE conditional
  *
  * @param string $strBuffer
  * @param string $strTemplate
  *
  * @return string $strBuffer
  */
 public function run($strBuffer, $strTemplate)
 {
     $ua = \Environment::get('agent');
     if (stripos($strTemplate, 'fe_') !== false && $ua->browser == 'ie') {
         $objDOM = new \DOMDocument();
         $objDOM->loadHTML($strBuffer);
         $objCSSLinks = $objDOM->getElementsByTagName('link');
         foreach ($objCSSLinks as $link) {
             //Local files only
             if (strpos($link->getAttribute('href'), 'assets/css/') !== false) {
                 //Replace ASSETS_URL
                 $strFile = str_replace(TL_ASSETS_URL, '', $link->getAttribute('href'));
                 $objFile = new \File($strFile);
                 $strContent = $objFile->getContent();
                 //Split up into chunklets
                 $splitter = new Splitter();
                 $count = $splitter->countSelectors($strContent) - 4095;
                 if ($count > 0) {
                     $part = 2;
                     for ($i = $count; $i > 0; $i -= 4095) {
                         $strFilename = 'assets/css/' . $objFile->filename . '-ie9-' . $part . '.css';
                         if (!file_exists(TL_ROOT . '/' . $strFilename)) {
                             //Write content
                             $strChunkContent = $splitter->split($strContent, $part);
                             $objNewFile = new \File($strFilename);
                             $objNewFile->write($strChunkContent);
                             $objNewFile->close();
                         }
                         //Add IE Conditional
                         foreach ($objDOM->getElementsByTagName('head') as $head) {
                             $strComment = '[if lte IE 9]><link rel="stylesheet" href="';
                             $strComment .= TL_ASSETS_URL . $strFilename . '"><![endif]';
                             $objChildNode = new \DOMComment($strComment);
                             $head->appendChild($objChildNode);
                         }
                         $part++;
                     }
                 }
             }
         }
         $strBuffer = $objDOM->saveHTML();
     }
     return $strBuffer;
 }
Example #21
0
 /**
  * Execute the default Events (send mail / add/remove groups)
  * @param string $strEvent
  * @param object $objMember
  * @param object $objAbo
  * @param object $objAboOrder
  */
 public function defaultEvents($strEvent, $objMember, $objAbo, $objAboOrder)
 {
     $objEvents = \Database::getInstance()->prepare("\n\t\t\tSELECT\t* FROM tl_abo_events as e\n\t\t\t\tLEFT JOIN tl_abo as a\n\t\t\t\tON a.id = e.pid\n\t\t\tWHERE a.id = ?\n\t\t\t\tAND e.published = 1\n\t\t\t\tAND e.event = ?")->execute($objAbo->id, $strEvent);
     if (!$objEvents->numRows) {
         return;
     }
     $this->aboLog("Event: " . $strEvent . " ausgeführt", __METHOD__, 'INFO', $objMember->id);
     // Load Current Abo
     $this->setAbo($objAbo);
     $this->setMember($objMember);
     $this->setAboOrder($objAboOrder);
     while ($objEvents->next()) {
         // send mail ?
         if ($objEvents->use_email) {
             $objMail = new \Email();
             $objMail->subject = $this->replaceInsertTagsAbo($objEvents->email_subject, $objMember);
             $objMail->text = $this->replaceInsertTagsAbo($objEvents->email_text, $objMember);
             if ($objEvents->email_template) {
                 $strTemplatePath = $objEvents->email_template;
                 if (VERSION >= 3) {
                     $objFile = \FilesModel::findByPk($strTemplatePath);
                     $strTemplatePath = $objFile->path;
                 }
                 $objMailTemplate = new File($strTemplatePath);
                 $objMail->html = $this->replaceInsertTagsAbo($objMailTemplate->getContent(), $objMember);
             }
             $objMail->from = $objEvents->email_from;
             $objMail->fromName = $objEvents->email_fromname;
             if ($objEvents->email_bcc) {
                 $objMail->sendBcc($objEvents->email_bcc);
             }
             $objMail->sendTo($objMember->email);
             $this->aboLog("E-Mail an " . $objMember->email . ' versendet.', __METHOD__, 'INFO', $objMember->id);
         }
         // set groups ?
         if ($objEvents->use_groups) {
             $arrMergedGroups = $this->groupManager($objMember, $objEvents->addGroups, $objEvents->removeGroups);
             Database::getInstance()->prepare("UPDATE tl_member SET groups = ? WHERE id = ?")->execute(serialize($arrMergedGroups), $objMember->id);
             $this->aboLog("Mitgliedergruppen: Aktiviert (" . implode(',', deserialize($objEvents->addGroups, true)) . ') / Deaktiviert: (' . implode(',', deserialize($objEvents->removeGroups, true)) . ')', __METHOD__, 'INFO', $objMember->id);
         }
     }
 }
Example #22
0
 /**
  * Converts the code to HTML
  *
  * @param File        $file File to render
  * @param Tool_Result $res  Tool result to integrate
  *
  * @return string HTML
  */
 public function toHtml(File $file, Tool_Result $res = null)
 {
     /**
      * Yes, geshi needs to be in your include path
      * We use the geshi pear package.
      */
     if (!class_exists('\\geshi', true)) {
         require_once $GLOBALS['phorkie']['cfg']['geshi'];
     }
     $geshi = new \geshi($file->getContent(), $this->getType($file));
     $geshi->enable_line_numbers(GESHI_NORMAL_LINE_NUMBERS);
     $geshi->set_header_type(GESHI_HEADER_PRE_TABLE);
     $geshi->enable_classes();
     $geshi->set_line_style('color: #DDD;');
     if ($res !== null) {
         $geshi->highlight_lines_extra(array_keys($res->annotations));
         $geshi->set_highlight_lines_extra_style('background-color: #F2DEDE');
     }
     return '<style type="text/css">' . $geshi->get_stylesheet() . '</style>' . '<div class="code">' . str_replace('&nbsp;', '&#160;', $geshi->parse_code()) . '</div>';
 }
Example #23
0
 /**
  * Converts the rST to HTML
  *
  * @param File $file File to render
  *
  * @return string HTML
  */
 public function toHtml(File $file)
 {
     $descriptorspec = array(0 => array('pipe', 'r'), 1 => array('pipe', 'w'), 2 => array('pipe', 'w'));
     $process = proc_open('rst2html', $descriptorspec, $pipes);
     if (!is_resource($process)) {
         return '<div class="alert alert-error">' . 'Cannot open process to execute rst2html' . '</div>';
     }
     fwrite($pipes[0], $file->getContent());
     fclose($pipes[0]);
     $html = stream_get_contents($pipes[1]);
     fclose($pipes[1]);
     $errors = stream_get_contents($pipes[2]);
     fclose($pipes[2]);
     $retval = proc_close($process);
     //cheap extraction of the rst html body
     $html = substr($html, strpos($html, '<body>') + 6);
     $html = substr($html, 0, strpos($html, '</body>'));
     if ($retval != 0) {
         $html = '<div class="alert">' . 'rst2html encountered some error; return value ' . $retval . '<br/>' . 'Error message: ' . $errors . '</div>' . $html;
     }
     return $html;
 }
 /**
  * {@inheritdoc}
  */
 public function handle(\Input $input)
 {
     $outFile = new \File(self::OUT_FILE_PATHNAME);
     $pidFile = new \File(self::PID_FILE_PATHNAME);
     $output = $outFile->getContent();
     $pid = $pidFile->getContent();
     // We send special signal 0 to test for existance of the process which is much more bullet proof than
     // using anything like shell_exec() wrapped ps/pgrep magic (which is not available on all systems).
     $isRunning = (bool) posix_kill($pid, 0);
     $startTime = new \DateTime();
     $startTime->setTimestamp(filectime(TL_ROOT . '/' . self::PID_FILE_PATHNAME));
     $endTime = new \DateTime();
     $endTime->setTimestamp($isRunning ? time() : filemtime(TL_ROOT . '/' . self::OUT_FILE_PATHNAME));
     $uptime = $endTime->diff($startTime);
     $uptime = $uptime->format('%h h %I m %S s');
     if (!$isRunning && \Input::getInstance()->post('close')) {
         $outFile->renameTo(UpdatePackagesController::OUTPUT_FILE_PATHNAME);
         $pidFile->delete();
         $this->redirect('contao/main.php?do=composer&amp;update=database');
     } else {
         if ($isRunning && \Input::getInstance()->post('terminate')) {
             posix_kill($pid, SIGTERM);
             $this->reload();
         }
     }
     $converter = new ConsoleColorConverter();
     $output = $converter->parse($output);
     if (\Environment::getInstance()->isAjaxRequest) {
         header('Content-Type: application/json; charset=utf-8');
         echo json_encode(array('output' => $output, 'isRunning' => $isRunning, 'uptime' => $uptime));
         exit;
     } else {
         $template = new \BackendTemplate('be_composer_client_detached');
         $template->output = $output;
         $template->isRunning = $isRunning;
         $template->uptime = $uptime;
         return $template->parse();
     }
 }
 /**
  * Do the import.
  *
  * @param DataContainer $dc
  */
 public function onsubmit_callback(DataContainer $dc)
 {
     $source = $dc->getData('source');
     $upload = $dc->getData('upload');
     $emails = $dc->getData('emails');
     $totalCount = 0;
     if (is_array($source)) {
         foreach ($source as $csvFile) {
             $file = new File($csvFile);
             $this->removeRecipients($file->getContent(), $totalCount);
         }
     }
     if ($upload) {
         $this->removeRecipients(file_get_contents($upload['tmp_name']), $totalCount);
     }
     if ($emails) {
         $this->removeRecipients($emails, $totalCount);
     }
     $_SESSION['TL_CONFIRM'][] = sprintf($GLOBALS['TL_LANG']['orm_avisota_recipient_remove']['confirm'], $totalCount);
     setcookie('BE_PAGE_OFFSET', 0, 0, '/');
     $this->reload();
 }
Example #26
0
 static function validate_module($nome_categoria, $nome_modulo)
 {
     $module_file = new File(AvailableModules::get_available_module_path($nome_categoria, $nome_modulo) . AvailableModules::MODULE_DEFINITION_FILE);
     $schema_url = "http://www.mbcraft.it/schemas/2011/module.rnc";
     $validator_url = "http://validator.nu?level=error&out=xml&schema=" . urlencode($schema_url);
     $ch = curl_init($validator_url);
     $headers = array("Content-Type: application/xml", "Referer: MBCRAFT - Italy - info@mbcraft.it");
     curl_setopt($ch, CURLOPT_HEADER, 0);
     curl_setopt($ch, CURLOPT_VERBOSE, 0);
     curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
     curl_setopt($ch, CURLOPT_POST, true);
     curl_setopt($ch, CURLOPT_POSTFIELDS, $module_file->getContent());
     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
     $result = curl_exec($ch);
     $xml_result = new SimpleXMLElement($result);
     foreach ($xml_result->error as $error) {
         //$attribs = $error->attributes();
         var_dump($error);
         //echo $attribs->line_number." : ".$error->message."<br />";
     }
     return count($xml_result->children()) == 0;
 }
 /**
  * Main Emails admin function
  */
 public static function main()
 {
     // Init vars
     $email_templates_path = STORAGE . DS . 'emails' . DS;
     $email_templates_list = array();
     // Check for get actions
     // -------------------------------------
     if (Request::get('action')) {
         // Switch actions
         // -------------------------------------
         switch (Request::get('action')) {
             // Plugin action
             // -------------------------------------
             case "edit_email_template":
                 if (Request::post('edit_email_template') || Request::post('edit_email_template_and_exit')) {
                     if (Security::check(Request::post('csrf'))) {
                         // Save Email Template
                         File::setContent(STORAGE . DS . 'emails' . DS . Request::post('email_template_name') . '.email.php', Request::post('content'));
                         Notification::set('success', __('Your changes to the email template <i>:name</i> have been saved.', 'emails', array(':name' => Request::post('email_template_name'))));
                         if (Request::post('edit_email_template_and_exit')) {
                             Request::redirect('index.php?id=emails');
                         } else {
                             Request::redirect('index.php?id=emails&action=edit_email_template&filename=' . Request::post('email_template_name'));
                         }
                     }
                 }
                 $content = File::getContent($email_templates_path . Request::get('filename') . '.email.php');
                 // Display view
                 View::factory('box/emails/views/backend/edit')->assign('content', $content)->display();
                 break;
         }
     } else {
         // Get email templates
         $email_templates_list = File::scan($email_templates_path, '.email.php');
         // Display view
         View::factory('box/emails/views/backend/index')->assign('email_templates_list', $email_templates_list)->display();
     }
 }
 /**
  * Generate the content element
  */
 protected function compile()
 {
     try {
         $file = new \File($this->sourcefile, true);
         if (!$file->exists()) {
             throw new \Exception(sprintf('Datei \'%s\' exitiert nicht!', $this->sourcefile));
         }
         $filecontent = $file->getContent();
         $data = trimsplit("\n", $filecontent);
         // Kopfzeile
         $header_columns = str_getcsv(array_shift($data), ';');
         // ';' mit $this->inputFieldSeparator konfigurierbar machen
         $this->Template->header_columns = $header_columns;
         // Daten
         $row_data = array();
         foreach ($data as $row) {
             $row_data[] = str_getcsv($row, ';');
         }
         $this->Template->row_data = $row_data;
     } catch (\Exception $e) {
         // Eintrag in Contao Log ?
     }
 }
 /**
  * {@inheritdoc}
  */
 public function handle(\Input $input)
 {
     $outFile = new \File(self::OUT_FILE_PATHNAME);
     $pidFile = new \File(self::PID_FILE_PATHNAME);
     $output = $outFile->getContent();
     $pid = $pidFile->getContent();
     $isRunning = $this->isPidStillRunning($pid);
     $startTime = new \DateTime();
     $startTime->setTimestamp(filectime(TL_ROOT . '/' . self::PID_FILE_PATHNAME));
     $endTime = new \DateTime();
     $endTime->setTimestamp($isRunning ? time() : filemtime(TL_ROOT . '/' . self::OUT_FILE_PATHNAME));
     $uptime = $endTime->diff($startTime);
     $uptime = $uptime->format('%h h %I m %S s');
     if (!$isRunning && \Input::getInstance()->post('close')) {
         $outFile->renameTo(UpdatePackagesController::OUTPUT_FILE_PATHNAME);
         $pidFile->delete();
         $this->redirect('contao/main.php?do=composer&amp;update=database');
     } else {
         if ($isRunning && \Input::getInstance()->post('terminate')) {
             $this->killPid($pid);
             $this->reload();
         }
     }
     $converter = new ConsoleColorConverter();
     $output = $converter->parse($output);
     if (\Environment::getInstance()->isAjaxRequest) {
         header('Content-Type: application/json; charset=utf-8');
         echo json_encode(array('output' => $output, 'isRunning' => $isRunning, 'uptime' => $uptime));
         exit;
     } else {
         $template = new \BackendTemplate('be_composer_client_detached');
         $template->output = $output;
         $template->isRunning = $isRunning;
         $template->uptime = $uptime;
         return $template->parse();
     }
 }
Example #30
0
    /**
     * Return a form to choose an existing style sheet and import it
     * @return string
     */
    public function importStyleSheet()
    {
        if ($this->Input->get('key') != 'import') {
            return '';
        }
        // Import CSS
        if ($this->Input->post('FORM_SUBMIT') == 'tl_style_sheet_import') {
            if (!$this->Input->post('source') || !is_array($this->Input->post('source'))) {
                $this->addErrorMessage($GLOBALS['TL_LANG']['ERR']['all_fields']);
                $this->reload();
            }
            foreach ($this->Input->post('source') as $strCssFile) {
                // Folders cannot be imported
                if (is_dir(TL_ROOT . '/' . $strCssFile)) {
                    $this->addErrorMessage(sprintf($GLOBALS['TL_LANG']['ERR']['importFolder'], basename($strCssFile)));
                    continue;
                }
                $objFile = new File($strCssFile);
                // Check the file extension
                if ($objFile->extension != 'css') {
                    $this->addErrorMessage(sprintf($GLOBALS['TL_LANG']['ERR']['filetype'], $objFile->extension));
                    continue;
                }
                $strFile = $objFile->getContent();
                $strFile = str_replace("\r", '', $strFile);
                $strName = preg_replace('/\\.css$/i', '', basename($strCssFile));
                $strName = $this->checkStyleSheetName($strName);
                // Create the new style sheet
                $objStyleSheet = $this->Database->prepare("INSERT INTO tl_style_sheet (pid, tstamp, name, media) VALUES (?, ?, ?, ?)")->execute($this->Input->get('id'), time(), $strName, array('all'));
                $insertId = $objStyleSheet->insertId;
                $intSorting = 0;
                $strComment = '';
                $strCategory = '';
                $arrChunks = array();
                if (!is_numeric($insertId) || $insertId < 0) {
                    throw new Exception('Invalid insert ID');
                }
                $strFile = str_replace('/**/', '[__]', $strFile);
                $strFile = preg_replace(array('/\\/\\*\\*\\n( *\\*.*\\n){2,} *\\*\\//', '/\\/\\*[^\\*]+\\{[^\\}]+\\}[^\\*]+\\*\\//'), '', $strFile);
                $arrChunks = preg_split('/\\{([^\\}]*)\\}|\\*\\//U', $strFile, -1, PREG_SPLIT_DELIM_CAPTURE);
                for ($i = 0; $i < count($arrChunks); $i++) {
                    $strChunk = trim($arrChunks[$i]);
                    if ($strChunk == '') {
                        continue;
                    }
                    $strChunk = preg_replace('/[\\n\\r\\t]+/', ' ', $strChunk);
                    // Category
                    if (strncmp($strChunk, '/**', 3) === 0) {
                        $strCategory = str_replace(array('/*', '*/', '*', '[__]'), '', $strChunk);
                        $strCategory = trim(preg_replace('/\\s+/', ' ', $strCategory));
                    } elseif (strncmp($strChunk, '/*', 2) === 0) {
                        $strComment = str_replace(array('/*', '*/', '*', '[__]'), '', $strChunk);
                        $strComment = trim(preg_replace('/\\s+/', ' ', $strComment));
                    } else {
                        $strNext = trim($arrChunks[$i + 1]);
                        $strNext = preg_replace('/[\\n\\r\\t]+/', ' ', $strNext);
                        $arrDefinition = array('pid' => $insertId, 'category' => $strCategory, 'comment' => $strComment, 'sorting' => $intSorting += 128, 'selector' => $strChunk, 'attributes' => $strNext);
                        $this->createDefinition($arrDefinition);
                        ++$i;
                        $strComment = '';
                    }
                }
                // Write the style sheet
                $this->updateStyleSheet($insertId);
                // Notify the user
                if ($strName . '.css' != basename($strCssFile)) {
                    $this->addInfoMessage(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_renamed'], basename($strCssFile), $strName . '.css'));
                } else {
                    $this->addConfirmationMessage(sprintf($GLOBALS['TL_LANG']['tl_style_sheet']['css_imported'], $strName . '.css'));
                }
            }
            // Redirect
            setcookie('BE_PAGE_OFFSET', 0, 0, '/');
            $this->redirect(str_replace('&key=import', '', $this->Environment->request));
        }
        $objTree = new FileTree($this->prepareForWidget($GLOBALS['TL_DCA']['tl_style_sheet']['fields']['source'], 'source', null, 'source', 'tl_style_sheet'));
        // Return form
        return '
<div id="tl_buttons">
<a href="' . ampersand(str_replace('&key=import', '', $this->Environment->request)) . '" class="header_back" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['backBT']) . '" accesskey="b">' . $GLOBALS['TL_LANG']['MSC']['backBT'] . '</a>
</div>

<h2 class="sub_headline">' . $GLOBALS['TL_LANG']['tl_style_sheet']['import'][1] . '</h2>
' . $this->getMessages() . '
<form action="' . ampersand($this->Environment->request, true) . '" id="tl_style_sheet_import" class="tl_form" method="post">
<div class="tl_formbody_edit">
<input type="hidden" name="FORM_SUBMIT" value="tl_style_sheet_import">
<input type="hidden" name="REQUEST_TOKEN" value="' . REQUEST_TOKEN . '">

<div class="tl_tbox">
  <h3><label for="source">' . $GLOBALS['TL_LANG']['tl_style_sheet']['source'][0] . '</label> <a href="contao/files.php" title="' . specialchars($GLOBALS['TL_LANG']['MSC']['fileManager']) . '" data-lightbox="files 765 80%">' . $this->generateImage('filemanager.gif', $GLOBALS['TL_LANG']['MSC']['fileManager'], 'style="vertical-align:text-bottom"') . '</a></h3>' . $objTree->generate() . (strlen($GLOBALS['TL_LANG']['tl_style_sheet']['source'][1]) ? '
  <p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_style_sheet']['source'][1] . '</p>' : '') . '
</div>

</div>

<div class="tl_formbody_submit">

<div class="tl_submit_container">
  <input type="submit" name="save" id="save" class="tl_submit" accesskey="s" value="' . specialchars($GLOBALS['TL_LANG']['tl_style_sheet']['import'][0]) . '">
</div>

</div>
</form>';
    }