/** * @param string $dest * @param string[] $files * @return bool true, falls min ein Quelldokument verwendbar war */ public static function merge($dest, $files) { Logging::info('Erzeuge ' . $dest); //$dest = Files::validateFilename($dest); $pdf = new \mPDF('de-DE', 'A4'); $pdf->SetImportUse(); $page = 0; foreach ($files as $curFile) { Logging::info('Eingangsdatei ' . $curFile); if ($curFile == '') { continue; } $pagecount = $pdf->SetSourceFile($curFile); if ($page != 0) { $pdf->AddPage(); } for ($i = 1; $i <= $pagecount; $i++) { $import_page = $pdf->ImportPage($i); $pdf->UseTemplate($import_page); if ($i < $pagecount) { $pdf->AddPage(); } } $page++; } $pdf->Output($dest, 'F'); return $page > 0; }
/** * Gibt den Text mit den ersetzten Links zurück * @return string */ public function getText() { $this->text = html_entity_decode($this->text); $matches = []; // Suchen nach allem, dass in [[ ]] eingeschlossen ist preg_match_all('/\\[\\[([\\w\\.\\säöüÄÖÜß]+)\\]\\]/', $this->text, $matches); Logging::debug(print_r($matches, true)); foreach ($matches[1] as $match) { $artikel = CmsArtikel::loadByBezeichnung($match, $this->kategorieId); if ($artikel == null) { Logging::info('Lege Artikel neu an: ' . $match); $artikel = new CmsArtikel(); $artikel->ca_kategorie = $this->kategorieId; $artikel->ca_bezeichnung = $match; $artikel->ca_aktiv = 1; $artikel->ca_autor = Security::getUserId(); $artikel->save(); $titel = Text::get($artikel->getElementId() . '.titel'); $titel->te_text = $match; $titel->save(); } $link = EntityLinks::show($artikel); $tag = "<a href=\"{$link}\">{$match}</a>"; $this->text = str_replace('[[' . $match . ']]', $tag, $this->text); } return $this->text; }
/** * @covers \NewFrontiers\Framework\Output\Css::registerLibrary * @covers \NewFrontiers\Framework\Output\Css::requireLibrary * @covers \NewFrontiers\Framework\Output\Css::getLinkTags * @covers \NewFrontiers\Framework\Output\Css::includeLibraries */ public function testIncludeLibraries() { static::assertEquals('', Css::getLinkTags()); Css::registerLibrary('test1', ['test1.css', 'test2.css']); Css::registerLibrary('test2', 'test3.css'); $soll = "\n<link href=\"test1.css\" rel=\"stylesheet\" type=\"text/css\" />" . "\n<link href=\"test2.css\" rel=\"stylesheet\" type=\"text/css\" />" . "\n<link href=\"test3.css\" rel=\"stylesheet\" type=\"text/css\" />"; Css::requireLibrary('test1'); Css::requireLibrary('test2'); Css::requireLibrary('test3'); //this will create en error log static::assertEquals($soll, Css::getLinkTags()); //error log asserted here $items = Logging::getLogItems(); $msg = end($items)["msg"]; static::assertStringStartsWith("CSS-Bibliothek nicht gefunden: test3", $msg); //Logging actually puts \r\n at the end of the message //the following code depends on the previous code, that' s why it isn't a single test Css::registerLibrary(0, '" /><link href="test'); Css::registerLibrary('test1', ''); $soll = "\n<link href=\"\" rel=\"stylesheet\" type=\"text/css\" />" . "\n<link href=\"test3.css\" rel=\"stylesheet\" type=\"text/css\" />" . "\n<link href=\"\" /><link href=\"test\" rel=\"stylesheet\" type=\"text/css\" />" . "\n<link href=\"test3.css\" rel=\"stylesheet\" type=\"text/css\" />"; Css::requireLibrary(0); Css::requireLibrary('test2'); //this will create a second entry for text3.css, what is correct html static::assertEquals($soll, Css::getLinkTags()); Css::includeLibraries(); $this->expectOutputString(Css::getLinkTags()); }
/** * @inheritdoc */ public function init() { Javascript::requireLibrary('froala'); $this->options = new FroalaOptions(); Logging::info('Requiring...'); $this->options->requirePlugins(); }
/** * Diese Methode erzeugt aus den übergebenen Parameteren ein Request-Objekt * Könnte man vielleicht noch aufhübschen * * @return Request * */ public function route() { Profiler::startSection('Routing.route'); // TODO: Bei Get und im Pathinfo können wir sehr viel // schärfere Sicherheitsrichtlinien durchsetzen. Da kann // und darf nie HTML kommen (XSS) $request = new Request(); if (array_key_exists('REQUEST_METHOD', $_SERVER)) { $request->methode = $_SERVER['REQUEST_METHOD']; } else { $request->method = 'get'; } $request->admin = isset($_GET['admin']); Logging::info('Methode ' . $request->method); // Falls es ein Pathinfo gibt, dieses aufbereiten $pathInfo = getenv('PATH_INFO'); if (array_key_exists('pathinfo', $_GET) && isset($_GET['pathinfo'])) { $pathInfo = '/' . $_GET['pathinfo']; } Logging::info('Pathinfo is: ' . $pathInfo); $request->pathinfo = $pathInfo; if (isset($pathInfo)) { // Der Pathinfo fängt mit einem Slash an! (z.B. /cms/showKategorie) $pathInfo = substr($pathInfo, 1); $this->fillRequestByPathinfo($request, $pathInfo); } foreach ($_REQUEST as $key => $value) { $request->{$key} = $value; } $request->sanitize(); Profiler::endSection('Routing.route'); $this->postRoute($request); return $request; }
protected function createControls() { $artikelliste = $this->controller->kategorie->getArtikel(); Logging::info('Kategorie enthält ' . count($artikelliste) . ' Artikel'); $i = 1; foreach ($artikelliste as $artikel) { $text = Text::get($artikel->getElementId() . '.intro', $_SESSION['sp_id'])->te_text; $anchor = new HtmlControl($this); $anchor->setInnerHtml('<a name="' . $artikel->id . '"></a>'); $artikelPanel = new CaptionedPanelControl($this, 'artikel_' . $artikel->id); $artikelPanel->setCaption($artikel->titel); $blogInfos = new HtmlControl($artikelPanel); $blogInfos->setInnerHtml(' <div class="blog-post-tags"> <ul class="list-unstyled list-inline blog-info"> <li><i class="fa fa-calendar"></i> ' . $artikel->ca_geschrieben_am . '</li> <li><i class="fa fa-pencil"></i> ' . $artikel->autor . '</li> </ul> </div> '); $artikelText = new HtmlControl($artikelPanel, 'text_' . $artikel->id); $artikelText->setInnerHtml(' <img src="' . $artikel->ca_hauptbild . '" class="blogimage" /> ' . $text); $i++; } }
/** * Schaltet den Cache ab * @return mixed */ public function disable() { Logging::warning('Cache deaktivert!'); $this->enabled = false; $this->clear(); return $this; }
/** * Stoppt das Debugging. Die Fehlerausgabe wird unterdr�ckt */ public function stop() { Logging::info('Debug: OFF'); $this->active = false; $_SESSION['DEBUG'] = false; ini_set('display_errors', 0); Profiler::setActive(false); }
public function get($key, $default = '') { if (!isset($this->cache[$key])) { Logging::debug("{$key} nicht gefunden"); Logging::info(print_r(array_keys($this->cache), true)); return $default; } else { return $this->cache[$key]; } }
public function getConnection($host, $database, $user, $password) { $connString = static::getConnectionString($host, $database); Logging::debug("Datenbankverbindung aufbauen {$connString}"); // Persistente Verbindung erzeugen try { $result = new PDO($connString, $user, $password); $result->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); } catch (Exception $e) { throw new \RuntimeException("Fehler beim Verbinden mit der Datenbank " . $e->getMessage()); } return $result; }
/** * */ public function install() { Logging::info('Installiere Modul ' . $this->getModulename()); $module = Modules::getModule($this->getModulename()); $this->migrateDatabase(); Logging::info('Vergebe Berechtigungen'); foreach ($module->actions as $action) { /**@var Action $action */ if ($action->securityLevel === Action::LEVEL_CONFIG) { Security::berechtigungSchreiben($action->getSecurityToken(), self::ID_ADMIN_ROLLE, 1); } } }
public function getConnection($host, $database, $user, $password) { $connString = $this->getConnectionString($host, $database); Logging::debug("Datenbankverbindung aufbauen {$connString}"); // Persistente Verbindung erzeugen try { $result = new PDO($connString, $user, $password, [PDO::ATTR_PERSISTENT => true]); $statement = $result->prepare('set names utf8;'); $statement->execute(); $statement->closeCursor(); } catch (Exception $e) { throw new Exception("Fehler beim Verbinden mit der Datenbank " . $e->getMessage()); } return $result; }
/** * Erzeugt die <link> Tags für die benötigten CSS Bibliotheken * * @return string */ public static function getLinkTags() { Logging::debug('Binde CSS-Bibliotheken ein: ' . count(static::$requiredLibraries) . ' / ' . count(static::$registeredLibraries)); $result = ''; foreach (static::$requiredLibraries as $lib) { if (array_key_exists($lib, static::$registeredLibraries)) { $filesToInclude = static::$registeredLibraries[$lib]; foreach ($filesToInclude as $file) { $result .= "\n<link href=\"{$file}\" rel=\"stylesheet\" type=\"text/css\" />"; } } else { Logging::error('CSS-Bibliothek nicht gefunden: ' . $lib); } } return $result; }
public function getConnection($host, $database, $user, $password) { if (FirebirdDatabaseProvider::$instance === null) { FirebirdDatabaseProvider::$instance = new FirebirdDatabaseProvider(); } $connString = FirebirdDatabaseProvider::getConnectionString($host, $database); Logging::debug("Datenbankverbindung aufbauen {$connString}"); // Persistente Verbindung erzeugen try { $result = new PDO($connString, $user, $password, array()); $result->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Names um den CharacterSet zu setzen.. } catch (Exception $e) { throw new \RuntimeException("Fehler beim Verbinden mit der Datenbank {$connString} " . $e->getMessage()); } return $result; }
/** * @covers \NewFrontiers\Framework\Output\Mailer::sendMail */ public function testSendMailFails() { //Create a new Mailer, because other tests use the mailer instance for mocking $mailer = new Mailer(); //reset config (from other tests) $config = Configuration::getInstance(); $reflection = new ReflectionClass($config); $reflection_property = $reflection->getProperty('configuration'); $reflection_property->setAccessible(true); $reflection_property->setValue($config, new SimpleXMLElement('<configuration></configuration>')); //No configuration is loaded, that means the sender is not set and sendMail() will return false. $this->assertFalse($mailer->sendMail(self::$workingMailAdress, "Test-E-Mail von nostromo-framework", "Bitte E-Mail-Adresse in MailerTest.php ändern.")); $items = Logging::getLogItems(); $this->assertContains("Kein Absender in der Konfiguration", end($items)["msg"]); Configuration::getInstance()->readConfig(); //empty Empfänger $this->assertFalse($mailer->sendMail("", "test", "testnachricht")); $items = Logging::getLogItems(); $this->assertContains("Keine E-Mail Adresse", end($items)["msg"]); }
/** * Diese Methode erzeugt das PDO Statement und bindet die * Parameter gegen deren Werte. Es erfolgt tatsächlich eine Wert- * Bindung und keine Referenz-Bindungen! Nachträgliche Änderungen * der Parametervariablen haben also keinen Einfluss auf die * Ausführung des Statements. * * @param $sql * @param array $params */ protected function prepareQueryAndBindParameter($sql, $params) { // Statement preparen try { $this->statement = $this->pdo->prepare($sql); } catch (Exception $e) { die('Query konnte nicht prepared werden ' . $e->getMessage() . "| {$sql}"); } if ($this->statement === false) { Logging::error('Query konnte nicht prepared werden ' . print_r($this->pdo->errorInfo(), true)); die('Query konnte nicht prepared werden ' . print_r($this->pdo->errorInfo(), true)); } // Paramter binden if ($params !== null) { foreach ($params as $name => $value) { // Der Parameter-Name muss eigentlich mit : angegeben werden // Ist allerdings nervig, so dass wir das an dieser Stelle // abstrahieren. if ($name[0] !== ':') { $name = ':' . $name; } $this->statement->bindValue($name, $value); } } }
/** * Gibt das HTML Markup aus. Die Funktion hinter dem Wrapper wird jetzt erst aufgerufen! * @return string * @throws Exception */ public function toHtml() { // Erzeugen des neuen Requests $request = Application::getCurrentRequest()->createSubRequest(); $request->module = $this->module; $request->action = $this->action; $request->embedded = true; $request->setViaArray($this->param); $module = Modules::getModule($this->module); if ($module == null) { throw new Exception("[Wrapper] Modul {$this->module} konnte nicht geladen werden"); } $controller = $module->createController($request); if ($controller->hatBerechtigung()) { $response = $controller->execute($request); Logging::warning((string) $response->getContent()); if ($response->getContent() instanceof View) { $result = '<div id="' . $this->id . '" class="wrapper">' . $response->getContent()->render() . '</div>'; } else { $result = 'NO VIEW'; } } else { $result = '<div class="alert alert-danger">Für diese Funktion haben Sie keine ausreichende Berechtigung</div>'; } // Ergebnis in einem Panel verpacken if ($this->showInPanel) { $panel = new CaptionedPanelControl(null, 'panel-' . $this->id); $panel->setCaption($this->panelCaption); $panel->setCollapsed($this->panelCollapsed); $html = new HtmlControl($panel); $html->setInnerHtml($result); $result = $panel->toHtml(); } return $result; }
/** * Speichert den Datensatz ab, wenn sich der Wert des Felds geändert hat. * * @param $feld string Name des Felds, das geprüft werden soll * @param $wert mixed Neuer Wert * @return bool true, falls sich der Wert geändert hat */ public function saveIfUpdated($feld, $wert) { // TODO: An der Stelle ist nicht klar, ob $wert den rohen // Wert oder die String-Repräsentation beinhaltet if (!$this->hasField($feld)) { Logging::error('Feld nicht gefunden ' . $feld); return false; } else { if ($wert != $this->felder[$feld]->getValue()) { $this->felder[$feld]->setValue($wert); $this->save(); return true; } return false; } }
use NewFrontiers\Framework\Core\Application; use NewFrontiers\Framework\Events\FrameworkEvents; use Nostromo\Contracts\Facades\Events; use Nostromo\Contracts\Facades\Logging; use Nostromo\Contracts\Facades\Profiler; use Nostromo\Contracts\Facades\Security; use Symfony\Component\EventDispatcher\Event; Profiler::startSection('initApplication'); // Listener, der als Login-Gate fungiert // TODO: In eigene Klasse Events::addListener(FrameworkEvents::REQUEST_BEFORE, function (\NewFrontiers\Framework\Events\RequestEvent $event) { $request = $event->getRequest(); // Nur Admin schützen if (!$request->admin) { return; } // API ausnhemen (pauschal) if ($request->module == 'api' || $request->module == 'Api') { return; } $allowedActions = array('showLogin', 'login', 'loginFailure', 'logout', 'password', 'doPassword', 'reset', 'doReset'); if (!Security::isAuthenticated() && !in_array($request->action, $allowedActions)) { $request->followUpModule = $request->module; $request->followUpAction = $request->action; $request->module = 'defaultMod'; $request->action = 'showLogin'; Logging::warning('Action not allowed. User was sent to Login-Screen'); } else { } }); Profiler::endSection('initApplication');
/** * Gibt ein Entity aus dem Datenmodell zurück. Shortcut-Methode * @param $name string * @return null */ public function getEntity($name) { if ($this->model !== null) { return $this->model->getEntity($name); } else { Logging::warning("Modul {$this->name} besitzt kein eigenes Datenmodell"); return null; } }
/** * Sendet eine Mail über den in der Konfiguration hinterlegten SMTP Account. * @param string $empfaenger Empfängeradresse / Wird automatisch von UTF-8 nach ANSI gewandelt * @param string $betreff Empfängeradresse / Wird automatisch von UTF-8 nach ANSI gewandelt * @param string $nachricht Nachricht als Plaintext * @param string $html Nachricht als HTML * @param string $attachment Pfad und Dateiname eines Anhangs * @return boolean */ public function sendMail($empfaenger, $betreff, $nachricht, $html = null, $attachment = null) { if (Configuration::get('mail.from') === '') { Logging::warning('Kein Absender in der Konfiguration eingetragen. E-Mail wird nicht versendet'); return false; } if ($empfaenger === '') { Logging::warning('Keine E-Mail Adresse übergeben'); return false; } $empfaenger = trim($empfaenger); Profiler::startSection('Mailer::sendMail'); try { $message = Swift_Message::newInstance(); $message->setSubject($betreff); $message->setFrom(array(Configuration::get('mail.from'))); $message->setTo(array(utf8_decode($empfaenger))); $message->setBody(strip_tags($nachricht)); if ($html !== null) { $templatePath = Environment::get()->srcDir . '/site/mails/template.html'; if (file_exists($templatePath)) { $html = str_replace('{mail}', $html, file_get_contents($templatePath)); } $message->addPart($html, 'text/html'); } if ($attachment !== null) { $message->attach(Swift_Attachment::fromPath($attachment)); } if ($this->transport === null) { $this->transport = Swift_SmtpTransport::newInstance(Configuration::get('mail.smtp_host'), Configuration::get('mail.smtp_port'))->setUsername(Configuration::get('mail.smtp_user'))->setPassword(Configuration::get('mail.smtp_pass')); $this->mailer = Swift_Mailer::newInstance($this->transport); } Logging::debug('Versende Mail per SMTP an ' . $empfaenger . ' über ' . Configuration::get('mail.smtp_host') . ':' . Configuration::get('mail.smtp_port') . ' / ' . Configuration::get('mail.smtp_user') . ' / ' . Configuration::get('mail.smtp_pass')); $result = $this->mailer->send($message); Logging::debug('Result des Mails ' . print_r($result, true)); Profiler::endSection('Mailer::sendMail'); return $result; } catch (Exception $ex) { Logging::error('Exception beim Senden einer Mail ' . $ex->getMessage()); Profiler::endSection('Mailer::sendMail'); return false; } }
/** * Wird angezeigt wenn versucht wird ohne entsprechende Berechtigung * auf eine Funktion zuzugreifen */ protected function showNoAccess() { Logging::warning('Zugriff wurde verweigert'); $request = new Request(); $request->module = 'DefaultMod'; $request->action = 'noaccess'; $this->handleRequest($request); }
/** * @param $importId * @param $meldung */ public static function error($importId, $meldung) { Logging::error($meldung); self::neuerEintrag($importId, self::LEVEL_ERROR, $meldung); }
/** * Bearbeitet einen Request. Ist diese Instanz zuständig, so wir der Request * ausgeführt. Wenn nicht, dann wird false zuurückgegen. * * @param Request $request * @param Response $response * @return bool */ public function handleResourceRequest(Request $request, Response $response) { if ($this->isResourceRequest($request->action)) { // TODO: Für die Berechtigungsprüfung braucht man die Action noch. // TODO: Ggf. als Resource erfassen um das loszuwerden? Logging::debug('Handling Request via ' . (string) $this); if ($request->present('id')) { $this->resource = $this->loadOrCreateResource($request->id); } else { $this->resource = $this->loadOrCreateResource(); } $callable = $this->possibleActions[$request->action]; $callable($request, $response); if ($response->getContent() instanceof View) { $response->getContent()->setResource($this->resource); } return true; } return false; }
/** * Gibt einen ListView mit den aufgelaufenen Log-Meldungen zurück * @return ListGroupControl * @throws \Exception */ public function showLog() { $listGroup = new ListGroupControl(null, 'debugEntries'); $listGroup->addItems(Logging::getLogItems()); return $listGroup; }
/** * Erstellt die Unterobjekte für die einzelnen Menüs */ protected function loadSubItems() { try { $pages = $this->page->loadChildrenForCurrentUser(); } catch (\Exception $e) { Logging::error('Fehler beim Laden der Children für die Page des MenuItemControls ' . $e->getMessage()); $pages = []; } foreach ($pages as $page) { $itemControl = new MenuItemControl($this, 'page' . $page->id); $itemControl->setPage($page); $itemControl->setRenderChildren($this->renderChildren); } }
/** * Führt einen Request per Reflection auf dem Controller aus * * @param ReflectionMethod $method * @return mixed */ private function executeViaReflection(ReflectionMethod $method) { Logging::debug('Ausführen via Reflection ' . (string) $method); $parameters = $method->getParameters(); if (count($parameters) === 0) { $result = $method->invoke($this); } elseif (count($parameters) === 1) { $resource = $parameters[0]->getClass()->newInstance($this->request->id); $result = $method->invoke($this, $resource); } else { throw new \RuntimeException('Mehr als ein Argument wird aktuell nicht unterstützt'); } return $result; }
/** * Erzeugt einen neuen Benutzernamen * @return string */ protected function generateUsername() { // TODO: ACHTUNG! Diese Methode funktioniert nicht!!! Logging::error('generate Username liefert u.U. falsche -> doppelte Namen!!!'); $sql = 'select count(*) anzahl from user where substr(us_vorname,1,1) = substr(:vorname,1,1) and us_nachname = :nachname'; $this->db->query($sql, array('vorname' => $this->us_vorname, 'nachname' => $this->us_nachname)); $row = $this->db->fetch(); $anzahl = $row['anzahl']; // Falls ID > 0, dann ist der aktuelle Datensatz dabei // sonst dazuzählen if ($this->id <= 0) { $anzahl++; } // Benutzername $username = substr($this->us_vorname, 0, 1) . $this->us_nachname; if ($anzahl > 1) { $username .= $anzahl; } return $username; }
/** * @inheritdoc */ public function add(HtmlOutputInterface $child, $collectionName = '') { // Das Standard-Control hat nur eine Collection. Der Parameter CollectionName // wird daher komplett ignoriert if ($child !== null) { $existierenderKnoten = $this->get($child->getId()); if ($existierenderKnoten !== null) { if ($existierenderKnoten === $child) { return $this; } else { Logging::error("Doppelte-ID! ID: {$child->getId()} Container: {$this->getId()}"); return $this; } } if ($child->getId() !== '') { $this->children[$child->getId()] = $child; } else { $this->children[] = $child; } } return $this; }
/** * statische Methode, die in einem Template Variablen der Form {Var} ersetzt. * * @param BaseEntity $entity * @param Control $controlContainer * @param object[] $vars Ein Array aus Objekten. Die Objekte müssen einem Schlüssel zugeordnet sein, wie * z.B. ["schlüssel" => new Musterobjekt]. Über ein Match "{schlüssel.eigenschaft}" * kann auf das Feld 'eigenschaft' des Objekts zugegriffen werden, wenn es public ist. * @param string $template Wird template nicht angegeben (null) wird das zu letzt verwendete genommen * @param null|array $matches * @return string Template mit ersetzten Weren */ public static function parse($entity, $controlContainer, $vars, $template, &$matches = null) { // Wenn das gleiche Template (z.B. ListView oder Grid) mehrfach ausgeführt brauchen wir // ja nicht den regulären Ausdruck dauernd drüber laufen lassen if ($matches === null && $template !== self::getInstance()->lastTemplate) { preg_match_all('/{([\\w\\.]*)}/', $template, $matches); self::getInstance()->lastTemplate = $template; self::getInstance()->lastMatches = $matches; } elseif ($matches === null) { $template = self::getInstance()->lastTemplate; $matches = self::getInstance()->lastMatches; } //in $matches[1] liegen die Group-Matches ohne geschweifte Klammern foreach ($matches[1] as $match) { $origMatch = $match; $useControl = false; if (strpos($match, '.') !== false) { $match = explode('.', $match); } else { if (substr($match, 0, 8) === 'control_') { $useControl = true; $match = substr($match, 8); } } $replaceWith = self::getInstance()->getReplacement($match, $entity, $controlContainer, $vars, $useControl); $template = str_replace("{" . $origMatch . "}", $replaceWith, $template); } // foreach // Ggf. enthaltenen PHP Code ausführen try { if (strpos($template, '?php') !== false) { ob_start(); eval('?>' . $template); $template = ob_get_contents(); ob_end_clean(); } } catch (FatalErrorException $e) { Logging::error($e->getMessage() . ' / ' . substr($template, 0, 100)); } return $template; }