/**
  * {@inheritdoc}
  */
 public function bindTextDomain($textDomain, $codeSet = null)
 {
     $this->bendTextDomains[$textDomain] = array();
     $textDomainDir = bindtextdomain($textDomain, $this->directory);
     $translationFileDir = $textDomainDir . DIRECTORY_SEPARATOR . StringUtils::beforeFirst(setlocale(LC_MESSAGES, '0'), '.') . DIRECTORY_SEPARATOR . 'LC_MESSAGES';
     $moFilePath = $translationFileDir . DIRECTORY_SEPARATOR . $textDomain . '.mo';
     $poFilePath = $translationFileDir . DIRECTORY_SEPARATOR . $textDomain . '.po';
     if (file_exists($moFilePath) === true) {
         $this->bendTextDomains[$textDomain]['file_path'] = $moFilePath;
         $this->bendTextDomains[$textDomain]['type'] = 'mo';
     } elseif (file_exists($poFilePath) === true && $this->poParserInterface instanceof PoParserInterface === true) {
         $this->bendTextDomains[$textDomain]['file_path'] = $poFilePath;
         $this->bendTextDomains[$textDomain]['type'] = 'po';
         $this->bendTextDomains[$textDomain]['plural_expr'] = false;
         $this->bendTextDomains[$textDomain]['entries'] = $this->poParserInterface->extract($poFilePath);
         $this->bendTextDomains[$textDomain]['plural_expr'] = '$' . $this->defaultPluralRule . ';';
         // Default plural rule
         $this->bendTextDomains[$textDomain]['plurals'] = 2;
         if (isset($this->bendTextDomains[$textDomain]['entries']['']) === true) {
             foreach ($this->bendTextDomains[$textDomain]['entries']['']['msgstr'] as $meta) {
                 if (preg_match('/Plural-Forms:\\s+nplurals=(\\d+);\\s+(plural=[^;]+)/', $meta, $matches) === 0) {
                     continue;
                 }
                 $this->bendTextDomains[$textDomain]['plurals'] = (int) $matches[1];
                 $this->bendTextDomains[$textDomain]['plural_expr'] = '$' . $matches[2] . ';';
             }
         }
     } else {
         return;
     }
     $textDomainCodeSet = $codeSet !== null ? $codeSet : $this->defaultCodeSet;
     if (bind_textdomain_codeset($textDomain, $textDomainCodeSet) === $textDomainCodeSet) {
         $this->bendTextDomains[$textDomain]['code_set'] = $textDomainCodeSet;
     }
 }
 public function testIsFloat()
 {
     $this->assertEquals(false, StringUtils::isFloat('foo'), 'Not a float but a string');
     $this->assertEquals(false, StringUtils::isFloat('42'), 'Not a float but an int');
     $this->assertEquals(true, StringUtils::isFloat('42.3'), 'A float');
 }
示例#3
0
 /**
  * Creates a new HttpRequest object based on the given data
  * @param array $requestData Data of the HTTP request
  * @return HttpRequest
  */
 public static function create(array $requestData = array())
 {
     $defaultValues = array('REQUEST_TIME' => time(), 'SERVER_PORT' => null, 'SERVER_NAME' => null, 'QUERY_STRING' => null, 'REMOTE_ADDR' => null, 'HTTP_USER_AGENT' => null, 'HTTPS' => null, 'REQUEST_URI' => null, 'HTTP_ACCEPT_LANGUAGE' => null, 'HTTP_ACCEPT_ENCODING' => null, 'REQUEST_METHOD' => null);
     $requestData = array_merge($defaultValues, $requestData);
     $httpRequest = new HttpRequest();
     $protocol = null;
     if ($requestData['HTTPS'] !== null) {
         $protocol = $requestData['HTTPS'] === 'on' ? HttpRequest::PROTOCOL_HTTPS : HttpRequest::PROTOCOL_HTTP;
     }
     $uri = StringUtils::startsWith($requestData['REQUEST_URI'], self::$basePath) ? StringUtils::afterFirst($requestData['REQUEST_URI'], self::$basePath) : $requestData['REQUEST_URI'];
     $path = StringUtils::beforeLast($uri, '?');
     $languages = array();
     $langRates = array_filter(explode(',', $requestData['HTTP_ACCEPT_LANGUAGE']));
     foreach ($langRates as $lr) {
         list($langCode, $importance) = array_pad(preg_split('/;(?:q=)?/', $lr), 2, 1.0);
         $languages[$langCode] = (double) $importance;
     }
     $acceptedEncoding = array_filter(array_map('trim', explode(',', $requestData['HTTP_ACCEPT_ENCODING'])));
     $requestTime = new \DateTime();
     $requestTime->setTimestamp($requestData['REQUEST_TIME']);
     $httpRequest->setHost($requestData['SERVER_NAME']);
     $httpRequest->setPath($path);
     $httpRequest->setPort($requestData['SERVER_PORT']);
     $httpRequest->setProtocol($protocol);
     $httpRequest->setQuery($requestData['QUERY_STRING']);
     $httpRequest->setURI($uri);
     $httpRequest->setRequestTime($requestTime);
     $httpRequest->setAcceptedEncodings($acceptedEncoding);
     $httpRequest->setRequestMethod($requestData['REQUEST_METHOD']);
     $httpRequest->setUserAgent($requestData['HTTP_USER_AGENT']);
     $httpRequest->setAcceptedLanguages($languages);
     $httpRequest->setRemoteAddress($requestData['REMOTE_ADDR']);
     $headers = array();
     foreach ($_SERVER as $name => $value) {
         if (StringUtils::startsWith($name, 'HTTP_') === true) {
             $name = str_replace(' ', '-', ucwords(strtolower(str_replace('_', ' ', substr($name, 5)))));
             $headers[$name] = $value;
         } elseif ($name == 'CONTENT_TYPE') {
             $headers['Content-Type'] = $value;
         } elseif ($name == 'CONTENT_LENGTH') {
             $headers['Content-Length'] = $value;
         }
     }
     $httpRequest->setHeaders($headers);
     return $httpRequest;
 }
示例#4
0
 public function replaceNode(TemplateEngine $tplEngine, ElementNode $tagNode)
 {
     $compareAttr = $tagNode->getAttribute('compare')->value;
     $operatorAttr = $tagNode->getAttribute('operator')->value;
     $againstAttr = $tagNode->getAttribute('against')->value;
     $condAttr = $tagNode->getAttribute('cond')->value;
     if ($condAttr === null) {
         // Check required attrs
         $tplEngine->checkRequiredAttrs($tagNode, array('compare', 'operator', 'against'));
         if (strlen($againstAttr) === 0) {
             $againstAttr = "''";
         } elseif (is_int($againstAttr) === true) {
             $againstAttr = intval($againstAttr);
         } elseif (is_float($againstAttr) === true) {
             $againstAttr = floatval($againstAttr);
         } elseif (is_string($againstAttr) === true) {
             if (strtolower($againstAttr) === 'null') {
                 //$againstAttr = 'null';
             } elseif (strtolower($againstAttr) === 'true' || strtolower($againstAttr) === 'false') {
                 //$againstAttr = ($againstAttr === 'true')?true:false;
             } elseif (StringUtils::startsWith($againstAttr, '{') && StringUtils::endsWith($againstAttr, '}')) {
                 $arr = substr(explode(',', $againstAttr), 1, -1);
                 $againstAttr = array();
                 foreach ($arr as $a) {
                     $againstAttr[] = trim($a);
                 }
             } else {
                 $againstAttr = "'" . $againstAttr . "'";
             }
         }
         $operatorStr = '==';
         switch (strtolower($operatorAttr)) {
             case 'gt':
                 $operatorStr = '>';
                 break;
             case 'ge':
                 $operatorStr = '>=';
                 break;
             case 'lt':
                 $operatorStr = '<';
                 break;
             case 'le':
                 $operatorStr = '<=';
                 break;
             case 'eq':
                 $operatorStr = '==';
                 break;
             case 'ne':
                 $operatorStr = '!=';
                 break;
         }
         $phpCode = '<?php ';
         $phpCode .= 'if($this->getDataFromSelector(\'' . $compareAttr . '\') ' . $operatorStr . ' ' . $againstAttr . '): ?>';
         $phpCode .= $tagNode->getInnerHtml();
         if ($tplEngine->isFollowedBy($tagNode, array('else', 'elseif')) === false) {
             $phpCode .= '<?php endif; ?>';
         }
         $textNode = new TextNode($tplEngine->getDomReader());
         $textNode->content = $phpCode;
         $tagNode->parentNode->replaceNode($tagNode, $textNode);
         $tagNode->parentNode->removeNode($tagNode);
     } else {
         $phpCode = '<?php ';
         $phpCode .= 'if(' . preg_replace_callback('/\\${(.*?)}/i', function ($m) {
             if (strlen($m[1]) === 0) {
                 throw new TemplateEngineException('Empty template data reference');
             }
             return '$this->getDataFromSelector(\'' . $m[1] . '\')';
         }, $condAttr) . '): ?>';
         $phpCode .= $tagNode->getInnerHtml();
         if ($tplEngine->isFollowedBy($tagNode, array('else', 'elseif')) === false) {
             $phpCode .= '<?php endif; ?>';
         }
         $textNode = new TextNode($tplEngine->getDomReader());
         $textNode->content = $phpCode;
         $tagNode->parentNode->replaceNode($tagNode, $textNode);
         $tagNode->parentNode->removeNode($tagNode);
     }
 }
示例#5
0
 /**
  * @return HttpResponse
  * @throws CMSException
  * @throws HttpException
  * @throws \Exception
  */
 public function restoreElementAjax()
 {
     list($elementType, $elementID, $elementPageID) = explode('-', $this->httpRequest->getVar('module', 'strip_tags'));
     $revisionFile = $this->httpRequest->getVar('revision', 'strip_tags');
     $cmsPage = $this->pageModel->getPageByID($elementPageID);
     $moduleModel = new ModuleModel($this->db);
     $modInstance = $moduleModel->getElementInstanceByID($elementID, $cmsPage);
     try {
         $this->db->setListenersMute(true);
         $this->db->beginTransaction();
         $revisionControl = new RevisionControl($this->db);
         $revisionControl->restoreFromFile($revisionFile);
         $fileNameParts = explode('.', StringUtils::afterLast($revisionFile, '/'));
         $this->updateElementRevision($modInstance, $fileNameParts[2]);
         $this->db->commit();
         $this->db->setListenersMute(false);
     } catch (\Exception $e) {
         $this->db->setListenersMute(false);
         $this->db->rollBack();
         $this->logger->error('Could not restore element ' . $e->getMessage());
         return new HttpResponse(500, 'Could not restore element: ' . $e->getMessage());
     }
     // RENDER ELEMENT AGAIN, SEND BACK
     if ($modInstance instanceof CmsElementSettingsLoadable) {
         /** @var CmsElement $modInstance */
         $moduleModel->reloadSettings($modInstance, $cmsPage);
     }
     $referrerPath = StringUtils::beforeFirst($this->httpRequest->getVar('referrer', 'strip_tags'), '?');
     $httpRequestFrontend = clone $this->httpRequest;
     $httpRequestFrontend->setPath($referrerPath);
     $httpRequestFrontend->setRequestMethod('GET');
     $frontendController = new FrontendController($this->core, $httpRequestFrontend, $this->route);
     $frontendController->deliverCMSPage();
     // @TODO render and replace parent module of this one
     $newModuleHtml = $modInstance->render($frontendController, $this->moduleView);
     return new HttpResponse(200, $newModuleHtml);
 }
 /**
  * @param string $selectorStr
  * @param bool $returnNull
  *
  * @return mixed
  *
  * @throws TemplateEngineException
  */
 protected function getSelectorValue($selectorStr, $returnNull = false)
 {
     $selParts = explode('.', $selectorStr);
     $firstPart = array_shift($selParts);
     $currentSel = $firstPart;
     if ($this->dataPool->offsetExists($firstPart) === false) {
         if ($returnNull === false) {
             throw new TemplateEngineException('The data with offset "' . $currentSel . '" does not exist for template file ' . $this->currentTemplateFile);
         }
         return null;
     }
     $varData = $this->dataPool->offsetGet($firstPart);
     foreach ($selParts as $part) {
         $nextSel = $currentSel . '.' . $part;
         // Try to find value in hashmap, thats faster then parse again
         /*if($this->dataTable->offsetExists($nextSel)) {
         				$varData = $this->dataTable->offsetGet($nextSel);
         
         				continue;
         			}*/
         if ($varData instanceof \ArrayObject === true) {
             /** @var \ArrayObject $varData */
             if ($varData->offsetExists($part) === false) {
                 throw new TemplateEngineException('Array key "' . $part . '" does not exist in ArrayObject "' . $currentSel . '"');
             }
             $varData = $varData->offsetGet($part);
         } elseif (is_object($varData) === true) {
             $args = array();
             if (($argPos = strpos($part, '(')) !== false) {
                 $argStr = substr($part, $argPos + 1, -1);
                 $part = substr($part, 0, $argPos);
                 foreach (preg_split('/,/x', $argStr) as $no => $arg) {
                     if (StringUtils::startsWith($argStr, '\'') === false || StringUtils::endsWith($argStr, '\'') === false) {
                         $args[$no] = $this->getSelectorValue($argStr, $returnNull);
                     } else {
                         $args[$no] = substr($arg, 1, -1);
                     }
                 }
             }
             if (property_exists($varData, $part) === true) {
                 $getProperty = new \ReflectionProperty($varData, $part);
                 if ($getProperty->isPublic() === true) {
                     $varData = $varData->{$part};
                 } else {
                     $getterMethodName = null;
                     foreach ($this->getterMethodPrefixes as $mp) {
                         $getterMethodName = $mp . ucfirst($part);
                         if (method_exists($varData, $getterMethodName) === true) {
                             break;
                         }
                         $getterMethodName = null;
                     }
                     if ($getterMethodName === null) {
                         throw new TemplateEngineException('Could not access protected/private property "' . $part . '". Please provide a getter method');
                     }
                     $varData = call_user_func(array($varData, $getterMethodName));
                 }
             } elseif (method_exists($varData, $part) === true) {
                 $varData = call_user_func_array(array($varData, $part), $args);
             } else {
                 throw new TemplateEngineException('Don\'t know how to handle selector part "' . $part . '"');
             }
         } elseif (is_array($varData) === true) {
             if (array_key_exists($part, $varData) === false) {
                 throw new TemplateEngineException('Array key "' . $part . '" does not exist in array "' . $currentSel . '"');
             }
             $varData = $varData[$part];
         } else {
             throw new TemplateEngineException('The data with offset "' . $currentSel . '" is not an object nor an array.');
         }
         $currentSel = $nextSel;
         $this->dataTable->offsetSet($currentSel, $varData);
     }
     return $varData;
 }
示例#7
0
 public function processRouteEdit()
 {
     $this->abortIfUserHasNotRights('CMS_ROUTES_EDIT');
     //$coreModel = new CoreModel($this->db);
     $pageModel = new PageModel($this->db);
     $routeModel = new RouteModel($this->db);
     $moduleModel = new ModuleModel($this->db);
     $pageOptions = array();
     foreach ($pageModel->getAllPages() as $p) {
         $pageOptions[$p->ID] = $p->language_codeFK . ', ' . $p->title;
     }
     $routeOptions = array();
     foreach ($routeModel->getAllRoutes() as $r) {
         if ($r->ID == $this->route->getParam(0)) {
             continue;
         }
         $routeOptions[$r->ID] = $r->pattern;
     }
     $moduleOptions = array();
     foreach ($moduleModel->getModulesWithFrontendController() as $m) {
         $routeOptions[$m->ID] = $m->ID;
     }
     $this->formHelper = new FormHelper(FormHelper::METHOD_POST);
     $this->formHelper->addField('pattern', null, FormHelper::TYPE_STRING, true, array('missingError' => 'Please insert a pattern for this route'));
     $this->formHelper->addField('page', null, FormHelper::TYPE_OPTION, false, array('invalidError' => 'Please select a valid page', 'options' => $pageOptions));
     $this->formHelper->addField('robots', null, FormHelper::TYPE_STRING, false);
     $this->formHelper->addField('regexp', null, FormHelper::TYPE_CHECKBOX);
     $this->formHelper->addField('route_typ', null, FormHelper::TYPE_OPTION);
     $this->formHelper->addField('redirect', null, FormHelper::TYPE_OPTION, false, array('invalidError' => 'Please select a valid page', 'options' => $pageOptions));
     $this->formHelper->addField('module', null, FormHelper::TYPE_OPTION, false, array('invalidError' => 'Please select a valid module', 'options' => $moduleOptions));
     if (!$this->formHelper->sent() || !$this->formHelper->validate()) {
         return $this->getRouteEdit();
     }
     $patternStr = $this->formHelper->getFieldValue('pattern');
     if (StringUtils::startsWith($patternStr, '/')) {
         $this->formHelper->addError(null, 'The route can not start with a slash (/)');
         return $this->getRouteEdit();
     }
     if (preg_match('@^[A-Za-z0-9\\-\\._/?#\\@&+=]+$@', $patternStr) === 0) {
         $this->formHelper->addError(null, 'The route should only have alphanumeric characters and -._/?#@&+= in it');
         return $this->getRouteEdit();
     }
     if ($patternStr === 'backend' || StringUtils::startsWith($patternStr, 'backend/') === true) {
         $this->formHelper->addError(null, 'The route should not start with "backend/". This URI node is reserved by the CMS');
         return $this->getRouteEdit();
     }
     // save settings
     $routeTyp = $this->formHelper->getFieldValue('route_typ');
     $stmntUpdate = $this->db->prepare("\n\t\t\tINSERT INTO route\n\t\t\t\tSET ID = ?, pattern = ?, regex = ?, page_IDFK = ?, mod_IDFK = ?, robots = ?, redirect_route_IDFK = ?\n\t\t\tON DUPLICATE KEY UPDATE\n\t\t\t\tpattern = ?, regex = ?, page_IDFK = ?, mod_IDFK = ?, robots = ?, redirect_route_IDFK = ?\n\n\t\t");
     $resUpdate = $this->db->update($stmntUpdate, array($this->route->getParam(0), '/' . $patternStr, $this->formHelper->getFieldValue('regexp'), $routeTyp == 1 ? $this->formHelper->getFieldValue('page') : null, $this->formHelper->getFieldValue('module') == 0 ? null : $this->formHelper->getFieldValue('module'), $this->formHelper->getFieldValue('robots'), $routeTyp == 2 ? $this->formHelper->getFieldValue('redirect') : null, '/' . $patternStr, $this->formHelper->getFieldValue('regexp'), $routeTyp == 1 ? $this->formHelper->getFieldValue('page') : null, $this->formHelper->getFieldValue('module') == 0 ? null : $this->formHelper->getFieldValue('module'), $this->formHelper->getFieldValue('robots'), $routeTyp == 2 ? $this->formHelper->getFieldValue('redirect') : null));
     RequestHandler::redirect('/backend/routes');
 }
示例#8
0
 /**
  * @param array $sqlParams The params for the SQL query of the renderer
  *
  * @return string The rendered HTML table
  *
  * @throws \Exception
  */
 public function display(array $sqlParams = array())
 {
     $this->appendTableActions();
     $textSearch = array();
     $filterForm = false;
     foreach ($this->columns as $c) {
         /** @var Column $c */
         if (!$c->isFilterable()) {
             continue;
         }
         $filterForm = true;
         if ($this->filtersApplied === false) {
             break;
         }
         if ($c->getFilterable()->type === 'text') {
             $keywordGroupQueryStr = null;
             foreach ($this->keywords as $k) {
                 $compareWord = 'LIKE';
                 $prefix = ' OR ';
                 if (StringUtils::startsWith($k, '+')) {
                     $k = substr($k, 1);
                     $compareWord = 'LIKE';
                     $prefix = ' AND ';
                 } elseif (StringUtils::startsWith($k, '-')) {
                     $k = substr($k, 1);
                     $compareWord = 'NOT LIKE';
                     $prefix = ' AND ';
                 }
                 $keywordGroupQueryStr .= ($keywordGroupQueryStr !== null ? $prefix : null) . ($c->getSortSelector() === null ? $c->getSQLColumn() : $c->getSortSelector()) . " " . $compareWord . " ?";
                 $sqlParams[] = '%' . $k . '%';
             }
             if ($keywordGroupQueryStr === null) {
                 continue;
             }
             $textSearch[] = '(' . $keywordGroupQueryStr . ')';
         }
     }
     $hasColumnFilter = false;
     $columnFilterHtml = '<tr class="column-filters">';
     $columnFilterSql = array();
     foreach ($this->columns as $c) {
         if ($c->getColumnFilter() === null) {
             $columnFilterHtml .= '<th class="no-filter">&nbsp;</th>';
             continue;
         }
         $selection = isset($_SESSION['table'][$this->tableName]['filter'][$c->getColumnFilter()->getFilterName()]) ? $_SESSION['table'][$this->tableName]['filter'][$c->getColumnFilter()->getFilterName()] : null;
         $hasColumnFilter = true;
         $columnFilterHtml .= '<th>' . $c->getColumnFilter()->renderHtml($selection) . '</th>';
         if (($filterSql = $c->getColumnFilter()->renderSql($c->getSortSelector() !== null ? $c->getSortSelector() : $c->getSQLColumn(), $selection)) !== null) {
             $columnFilterSql[] = $filterSql;
             $sqlParams = array_merge($sqlParams, (array) $selection);
         }
     }
     if ($this->options !== null) {
         $columnFilterHtml .= "\t\t<th class=\"no-filter\">&nbsp;</th>\n";
     }
     $columnFilterHtml .= '</tr>';
     $searchHtml = null;
     $filterInfo = null;
     if ($filterForm === true) {
         $searchHtml = '<div class="table-data-search"><input type="hidden" name="table" value="' . $this->tableName . '"><input type="text" name="filter[keywords]" value="' . str_replace('"', '&quot;', $this->keywordStr) . '" placeholder="' . $this->getText('Keywords') . '"><button type="submit">' . $this->getText('Go') . '</button></div>';
     }
     $whereConds = array();
     if (count($textSearch) > 0) {
         $whereConds[] = '(' . implode(' OR ', $textSearch) . ')';
         $keywordsHtml = array();
         foreach ($this->keywords as $k) {
             $keywordsHtml[] = '<span class="' . $this->cssClass . '-keyword">' . $k . '</span>';
         }
         $filterInfo = ' (' . $this->getText('Result is filtered by keywords') . ': ' . implode(null, $keywordsHtml) . ')';
     }
     if ($this->filtersApplied) {
         $filterInfo .= ' (<a href="?table=' . $this->tableName . '&amp;resetfilters" class="table-reset-filters">' . $this->getText('reset filters') . '</a>)';
     }
     // filter
     foreach ($columnFilterSql as $filterSql) {
         $whereConds[] = '(' . $filterSql . ')';
     }
     if (count($whereConds) > 0) {
         $this->sqlQuery .= ' WHERE ' . implode(' AND ', $whereConds);
     }
     if ($this->sortable !== null) {
         $this->sqlQuery .= ' ORDER BY ' . $this->sortable['sort'];
     } elseif ($this->orderBy !== null && isset($this->columns[$this->orderBy['column']]) === true) {
         $this->sqlQuery .= ' ORDER BY ' . $this->columns[$this->orderBy['column']]->getSortSelector() . ' ' . $this->orderBy['sort'];
     }
     if (preg_match('/[\\s\\)]+FROM(?![^\\(]*\\)).*/ims', $this->sqlQuery, $fromMatches) === 0) {
         throw new TableRendererException('No FROM found in query: ' . $this->sqlQuery);
     }
     $this->stmnt = $this->db->prepare("SELECT COUNT(*) total_records " . $fromMatches[0]);
     $this->stmntLimited = $this->db->prepare($this->sqlQuery . " LIMIT ?,?");
     $res = $this->db->select($this->stmnt, $sqlParams);
     $entriesCount = $res[0]->total_records;
     $resStart = ($this->currentPage - 1) * $this->pageLimit;
     if ($resStart > $entriesCount) {
         $resStart = 0;
     }
     $sqlParams[] = $resStart;
     $sqlParams[] = $this->pageLimit;
     $resLimited = $this->db->select($this->stmntLimited, $sqlParams);
     $dataUriAttr = $this->ajaxUri !== null ? ' class="table-renderer-ajax" data-uri="' . $this->ajaxUri . '"' : null;
     $tableHtml = '<div id="' . $this->tableName . '" ' . $dataUriAttr . '><form method="post" action="?table=' . $this->tableName . '#' . $this->tableName . '" class="' . $this->cssClass . '-filters">';
     /*if($entriesCount <= 0)
     		return $tableHtml . $searchHtml . '<p class="' . $this->cssClass . '-info">' . $this->getText('No entries found.') . $filterInfo . '</p>';*/
     if ($this->columns === null) {
         $this->columns = $this->getColumnsByQuery($res);
     }
     $tableHtml .= $searchHtml;
     // PAGINATION
     $numPages = ceil($entriesCount / $this->pageLimit);
     $tableHtml .= '<div class="table-pagination-wrapper">';
     if ($numPages > 1) {
         $tableHtml .= '<ul class="' . $this->cssClass . '-pagination">';
         for ($i = 1; $i <= $numPages; ++$i) {
             $active = $i == $this->currentPage ? ' class="active"' : null;
             $tableHtml .= '<li><a href="?table=' . $this->tableName . '&amp;page=' . $i . '#' . $this->tableName . '"' . $active . '>' . $i . '</a></li>';
         }
         $tableHtml .= '</ul>';
     }
     $tableHtml .= '</div>';
     if ($this->displayInfo === true) {
         $tableHtml .= "<p class=\"" . $this->cssClass . "-info\">" . sprintf($this->getText('There is <b>%d</b> entry.', 'There are <b>%d</b> entries.', $entriesCount), $entriesCount) . $filterInfo . "</p>\n";
     }
     $tableHtml .= "<table class=\"" . $this->cssClass . "\">\n\t<thead>\n\t<tr>\n";
     if ($this->selectable === true) {
         $tableHtml .= "\t\t<th class=\"header-selectable\">&nbsp;</th>\n";
     }
     if ($this->reorder === true) {
         $tableHtml .= "\t\t<th class=\"header-reorder\">&nbsp;</th>\n";
     }
     foreach ($this->columns as $col) {
         /** @var Column $col */
         if ($col->isHidden() === true) {
             continue;
         }
         if ($this->sortable === null && $col->isSortable()) {
             $sortStr = $this->orderBy !== null && $this->orderBy['column'] == $col->getSQLColumn() && $this->orderBy['sort'] == 'ASC' ? 'DESC' : 'ASC';
             $sortClass = null;
             $sortFontIcon = '<i class="fa fa-sort"></i>';
             if ($this->orderBy !== null && $this->orderBy['column'] == $col->getSQLColumn()) {
                 $sortFontIcon = '<i class="fa ' . ($this->orderBy['sort'] === 'ASC' ? 'fa-caret-up' : 'fa-caret-down') . '"></i>';
                 $sortClass = ' class="active-' . strtolower($this->orderBy['sort']) . '"';
             }
             $label = '<a href="?table=' . $this->tableName . '&amp;sort=' . $col->getSQLColumn() . '-' . $sortStr . '#' . $this->tableName . '"' . $sortClass . '>' . $col->getLabel() . $sortFontIcon . '</a>';
         } else {
             $label = $col->getLabel();
         }
         $tableHtml .= "\t\t<th>" . $label . "</th>\n";
     }
     if ($this->options !== null) {
         $tableHtml .= "\t\t<th>&nbsp;</th>\n";
     }
     $tableHtml .= '</tr>';
     if ($hasColumnFilter) {
         $tableHtml .= $columnFilterHtml;
     }
     $sortableClass = $this->sortable !== null ? ' class="sortable-table"' : null;
     $tableHtml .= "\t</thead>\n\t<tbody" . $sortableClass . ">\n";
     $optsHtml = $this->getOptsAsHtml();
     $i = 0;
     foreach ($resLimited as $r) {
         $class = $i % 2 == 0 ? 'odd' : 'even';
         $entryID = null;
         if ($this->sortable !== null) {
             $kcArr = array();
             foreach ($this->sortable['key'] as $kc) {
                 $kcArr[] = $r->{$kc};
             }
             $entryID = 'id="sort-' . implode('-', $kcArr) . '" ';
         }
         $tableHtml .= "\t<tr " . $entryID . "class=\"" . $class . "\">\n";
         if ($this->selectable === true) {
             $tableHtml .= '<td class="selectable" style="vertical-align: middle;"><input type="checkbox" value="" name="' . $this->tableName . '[]"></td>';
         }
         if ($this->reorder === true) {
             $tableHtml .= '<td class="reorder"><span>' . $this->getText('move') . '</span></td>';
         }
         foreach ($this->columns as $col) {
             /** @var Column $col */
             if ($col->isHidden() === true) {
                 continue;
             }
             // @TODO Generate sql query don't give it as param in constructor so we can move this code to trash
             $sqlColumnIdentifier = StringUtils::afterFirst($col->getSQLColumn(), '.');
             if ($sqlColumnIdentifier === '') {
                 $sqlColumnIdentifier = $col->getSQLColumn();
             }
             $value = $col->getSQLColumn() !== null ? $r->{$sqlColumnIdentifier} : null;
             foreach ($col->getDecorators() as $d) {
                 /** @var  ColumnDecorator $d */
                 $value = $d->modify($value, $r, $col->getSQLColumn(), $this);
             }
             if ($col->isFilterable() && $this->filtersApplied) {
                 foreach ($this->keywords as $k) {
                     if (StringUtils::startsWith($k, '+') || StringUtils::startsWith($k, '-')) {
                         $k = substr($k, 1);
                     }
                     $k = str_replace(array('/', '(', ')'), array('\\/', '\\(', '\\)'), $k);
                     // regex look behind if we're not in a html tag
                     $value = preg_replace('/(?![^<]*>)(' . $k . ')/ims', '<span class="' . $this->cssClass . '-highlighted">$1</span>', $value);
                 }
             }
             $cssClassesAttr = count($col->getCssClasses()) > 0 ? ' class="' . implode(' ', $col->getCssClasses()) . '"' : null;
             $tableHtml .= "\t\t<td" . $cssClassesAttr . ">" . $value . "</td>\n";
         }
         $tableHtml .= $this->prepareOptLink($optsHtml, $r);
         $tableHtml .= "\t</tr>\n";
         ++$i;
     }
     $tableHtml .= '</tbody></table>';
     if ($this->selectable === true) {
         $tableHtml .= '<p><a href="">delete</a> or <a href="">edit</a> choosen ones </p>';
     }
     return $tableHtml . '</form></div>';
 }
 /**
  * @param string $selector
  * @param BackendController $backendController
  *
  * @return mixed
  */
 protected function getValues($selector, BackendController $backendController)
 {
     if (is_string($selector) === true) {
         return StringUtils::endsWith($selector, '()') ? call_user_func(array($this, StringUtils::beforeLast($selector, '()')), $backendController) : $this->{$selector};
     }
     return $selector;
 }
 public function reorderElements(DB $db, CmsElement $movedCmsElement, $dropZoneID, array $elementOrder)
 {
     // Remove all from column
     $colNo = (int) StringUtils::afterFirst($dropZoneID, 'column-') + 1;
     $this->logger->debug('-- Reorder module in column: ' . $colNo);
     $stmntRemove = $db->prepare("\n\t\t\tDELETE FROM element_column_layout_module WHERE col = ? AND page_IDFK = ? AND element_column_layout_IDFK = ?\n\t\t");
     $deletedElements = $db->delete($stmntRemove, array($colNo, $this->pageID, $this->ID));
     $this->logger->debug('Deleted ' . $deletedElements . ' elements');
     // Remove the element itself (cause of PK crashes)
     $stmntRemoveOriginal = $db->prepare("\n\t\t\tDELETE FROM element_column_layout_module WHERE element_column_layout_IDFK = ? AND page_IDFK = ? AND element_instance_IDFK = ?\n\t\t");
     $deletedOriginal = $db->delete($stmntRemoveOriginal, array($this->ID, $movedCmsElement->getPageID(), $movedCmsElement->getID()));
     $this->logger->debug('Deleted ' . $deletedOriginal . ' original element');
     // Add the new order
     $stmntInsert = $db->prepare("\n\t\t\tINSERT IGNORE INTO element_column_layout_module\n\t\t\t\tSET element_column_layout_IDFK = ?, page_IDFK = ?, col = ?, element_instance_IDFK = ?, sort = ?\n\t\t");
     $stmntUpdate = $db->prepare("UPDATE cms_element_instance SET parent_mod_IDFK = ? WHERE ID = ?");
     $this->logger->debug('Add those modules', array($elementOrder));
     foreach ($elementOrder as $k => $e) {
         $this->logger->debug('Added module: ' . $e);
         $eParts = explode('-', $e);
         if (isset($eParts[0]) === false) {
             continue;
         }
         $db->update($stmntUpdate, array($this->ID, $eParts[0]));
         $db->insert($stmntInsert, array($this->ID, $this->pageID, $colNo, $eParts[0], $k + 1));
     }
 }
 public function postPageEdit($params)
 {
     $this->cmsController->abortIfUserHasNotRights('MOD_PAGES_EDIT');
     $pageID = null;
     $routeID = null;
     if (isset($params[0]) === true) {
         $pageID = (int) $params[0];
         $routes = $this->routeModel->getRoutesByPageID($pageID);
         if (count($routes) > 0) {
             $routeData = array_shift($routes);
             $routeID = $routeData->ID;
         }
     }
     $coreModel = new CoreModel($this->cmsController->getDB());
     $basePagesOpts = array(0 => '- no base page -');
     foreach ($this->pageModel->getBasePagesForPage($pageID) as $p) {
         $basePagesOpts[$p->ID] = $p->language_codeFK . ', ' . $p->title;
     }
     $this->formHelper = new FormHelper(FormHelper::METHOD_POST);
     $this->formHelper->addField('title', null, FormHelper::TYPE_STRING, true, array('missingError' => 'Please insert a title for this page'));
     $this->formHelper->addField('language', null, FormHelper::TYPE_OPTION, true, array('missingError' => 'Please select a language this page', 'invalidError' => 'Please select a valid language for this page', 'options' => $coreModel->getLanguages()));
     $this->formHelper->addField('role', null, FormHelper::TYPE_OPTION, true, array('missingError' => 'Please select a role for this page', 'invalidError' => 'Please select a valid role for this page', 'options' => $this->getRoleOptions()));
     $this->formHelper->addField('base_page', null, FormHelper::TYPE_OPTION, false, array('invalidError' => 'Please select a valid base page for this page', 'options' => $basePagesOpts));
     $this->formHelper->addField('description', null, FormHelper::TYPE_STRING, false);
     $this->formHelper->addField('inherit_rights', null, FormHelper::TYPE_CHECKBOX);
     if (!$this->formHelper->sent() || !$this->formHelper->validate()) {
         return $this->getPageEdit($params);
     }
     $pageRole = $this->formHelper->getFieldValue('role');
     // Role specific form checks
     if ($pageRole === 'error') {
         $this->formHelper->addField('error_code', null, FormHelper::TYPE_OPTION, true, array('missingError' => 'Please select an error code for this page', 'invalidError' => 'Please select a valid error code for this page', 'options' => $this->getErrorCodeOptions()));
     }
     if (in_array($pageRole, array('page', 'module')) === true) {
         // Route
         $this->formHelper->addField('route', null, FormHelper::TYPE_STRING, true, array('missingError' => 'Please insert a title for this page'));
         $this->formHelper->addField('ssl', null, FormHelper::TYPE_OPTION, true, array('missingError' => 'Please choose an SSL option', 'invalidError' => 'Please choose a valid SSL option', 'options' => $this->getSSLOptions()));
     }
     if ($pageRole === 'module') {
         $this->formHelper->addField('module', null, FormHelper::TYPE_OPTION, true, array('missingError' => 'Please choose a module', 'invalidError' => 'Please choose a valid module', 'options' => $this->getModuleOptions()));
     }
     if (!$this->formHelper->validate()) {
         return $this->getPageEdit($params);
     }
     $stmntCheckErrorCode = $this->cmsController->getDB()->prepare("\n\t\t\tSELECT ID FROM page WHERE error_code = ?\n\t\t");
     $errorCode = $this->formHelper->getFieldValue('error_code');
     $resCheckErrorCode = $this->cmsController->getDB()->select($stmntCheckErrorCode, array($errorCode));
     if (count($resCheckErrorCode) > 0 && $resCheckErrorCode[0]->ID != $pageID) {
         $this->formHelper->addError('error_code', 'There is already an error page (#' . $resCheckErrorCode[0]->ID . ') for error case ' . $errorCode);
     }
     if ($this->formHelper->hasErrors()) {
         return $this->getPageEdit($params);
     }
     // save settings
     $layoutIDFK = null;
     if ($this->formHelper->getFieldValue('base_page') !== null) {
         $stmntLayout = $this->cmsController->getDB()->prepare("SELECT layout_IDFK FROM page WHERE ID = ?");
         $resLayout = $this->cmsController->getDB()->select($stmntLayout, array($this->formHelper->getFieldValue('base_page')));
         if (count($resLayout) > 0) {
             $layoutIDFK = $resLayout[0]->layout_IDFK;
         }
     }
     try {
         $stmntUpdate = $this->cmsController->getDB()->prepare("\n\t\t\t\tINSERT INTO page SET\n\t\t\t\t\tID = ?, title = ?, language_codeFK = ?, description = ?, base_page_IDFK = ?, layout_IDFK = ?, inhert_rights = ?, creator_IDFK = ?, created = NOW(), role = ?, error_code = ?, uniqid = ?\n\t\t\t\tON DUPLICATE KEY UPDATE\n\t\t\t\t\ttitle = ?, language_codeFK = ?, description = ?, base_page_IDFK = ?, layout_IDFK = ?, inhert_rights = ?, modifier_IDFK = ?, role = ?, error_code = ?, last_modified = NOW()\n\t\t\t");
         $basePageParam = $this->formHelper->getFieldValue('base_page') != 0 ? $this->formHelper->getFieldValue('base_page') : null;
         $msgKey = 'updated';
         $this->cmsController->getDB()->update($stmntUpdate, array($pageID, $this->formHelper->getFieldValue('title'), $this->formHelper->getFieldValue('language'), $this->formHelper->getFieldValue('description'), $basePageParam, $layoutIDFK, $this->formHelper->getFieldValue('inherit_rights'), $this->cmsController->getAuth()->getUserID(), $this->formHelper->getFieldValue('role'), $this->formHelper->getFieldValue('error_code'), uniqid(), $this->formHelper->getFieldValue('title'), $this->formHelper->getFieldValue('language'), $this->formHelper->getFieldValue('description'), $basePageParam, $layoutIDFK, $this->formHelper->getFieldValue('inherit_rights'), $this->cmsController->getAuth()->getUserID(), $this->formHelper->getFieldValue('role'), $this->formHelper->getFieldValue('error_code')));
         if ($pageID === null) {
             $pageID = $this->cmsController->getDB()->lastInsertId();
             $msgKey = 'created';
         }
         // Route things
         $ssl = $this->formHelper->getFieldValue('ssl');
         $sslRequired = 0;
         $sslForbidden = 0;
         if ($ssl === 'required') {
             $sslRequired = 1;
         } elseif ($ssl === 'forbidden') {
             $sslForbidden = 1;
         }
         $modID = null;
         if ($pageRole === CmsPage::ROLE_MODULE) {
             $modID = $this->formHelper->getFieldValue('module');
         }
         if (in_array($pageRole, array(CmsPage::ROLE_STANDARD, CmsPage::ROLE_MODULE)) === true) {
             $formPattern = $this->formHelper->getFieldValue('route');
             if (StringUtils::startsWith($formPattern, '/') === false) {
                 $formPattern = '/' . $formPattern;
             }
             $stmntRouteUpdate = $this->cmsController->getDB()->prepare("\n\t\t\t\t\tINSERT INTO route SET\n\t\t\t\t\t\tID = ?, pattern = ?, page_IDFK = ?, ssl_required = ?, ssl_forbidden = ?, mod_IDFK = ?, regex = 0\n\t\t\t\t\tON DUPLICATE KEY UPDATE\n\t\t\t\t\t\tpattern = ?, page_IDFK = ?, ssl_required = ?, ssl_forbidden = ?, mod_IDFK = ?\n\t\t\t\t");
             $this->cmsController->getDB()->update($stmntRouteUpdate, array($routeID, $formPattern, $pageID, $sslRequired, $sslForbidden, $modID, $formPattern, $pageID, $sslRequired, $sslForbidden, $modID));
         }
     } catch (\Exception $e) {
         $this->formHelper->addError(null, $e->getMessage());
         return $this->getPageEdit($params);
     }
     $this->setMessageKeyForNextPage($msgKey);
     RequestHandler::redirect($this->baseLink . '/page/' . $pageID);
 }
 public function afterMutation(DB $db, PDOStatement $stmnt, array $params, $queryType)
 {
     $cond = null;
     if (preg_match('/^\\s*(SELECT|UPDATE|DELETE\\s+FROM|INSERT\\s+INTO|INSERT\\s+IGNORE|REPLACE\\s+INTO)\\s+(.+?)\\s+(?:SET\\s+(.+))?(?:ON DUPLICATE KEY UPDATE|WHERE\\s+(.+))?$/ims', $stmnt->queryString, $mT) === false) {
         throw new CMSException('Revision control could not parse sql statement: ' . $stmnt->queryString);
     }
     $sqlFunction = $mT[1];
     $sqlTable = trim($mT[2]);
     $sqlColumns = isset($mT[3]) ? $mT[3] : null;
     $sqlCond = isset($mT[4]) ? $mT[4] : null;
     if (in_array($sqlFunction, array('REPLACE INTO', 'INSERT INTO', 'UPDATE', 'INSERT IGNORE'))) {
         $resPK = $this->getPKColumnsForTable($db, $sqlTable);
         $pkArray = array();
         foreach ($resPK as $pk) {
             $pkArray[] = $pk . ' = ?';
         }
         // params
         $cols = explode(',', $sqlColumns);
         $colsArr = array();
         $pkArr = array();
         $i = 0;
         foreach ($cols as $c) {
             $colClean = trim(preg_replace('/=\\s*\\?/', null, $c)) . ' = ?';
             $colsArr[] = $colClean;
             if (in_array($colClean, $pkArray)) {
                 $pkArr[] = $params[$i];
             }
             ++$i;
         }
         $joinedArr = array_intersect($colsArr, $pkArray);
         if (count($joinedArr) <= 0) {
             return;
         }
         $cond = implode(' AND ', $joinedArr);
     } elseif (in_array($sqlFunction, array('SELECT'))) {
         // ignore
         return;
     } else {
         //var_dump($mT); exit;
         $offsetParams = substr_count(StringUtils::beforeLast($stmnt->queryString, 'WHERE'), '?');
         $anzParams = substr_count($sqlCond, '?');
         $pkArr = array_slice($params, $offsetParams, $anzParams);
         $cond = trim($sqlCond);
     }
     $revSql = "SELECT * FROM " . $sqlTable . " WHERE " . $cond;
     try {
         $stmntRev = $db->prepare($revSql);
         $resRev = $db->select($stmntRev, $pkArr);
         if (count($resRev) <= 0) {
             return;
         }
         $xmlStr = "\t" . '<table name="' . $sqlTable . '" exectime="' . date('Y-m-d H:i:s') . '">' . "\n";
         $xmlStr .= "\t\t" . '<records>' . "\n";
         foreach ($resRev as $r) {
             $xmlStr .= "\t\t\t" . '<record>' . "\n";
             $xmlStr .= "\t\t\t\t" . '<fields>' . "\n";
             foreach ($r as $col => $val) {
                 $xmlStr .= "\t\t\t\t\t" . '<field name="' . $col . '"><![CDATA[' . $val . ']]></field>' . "\n";
             }
             $xmlStr .= "\t\t\t\t" . '</fields>' . "\n";
             $xmlStr .= "\t\t\t" . '</record>' . "\n";
         }
         $xmlStr .= "\t\t" . '</records>' . "\n";
         $xmlStr .= "\t" . '</table>' . "\n";
         if ($db->inTransaction() === true) {
             $this->cachedXML .= $xmlStr;
             return;
         }
         $this->saveOldRevision($xmlStr, $sqlTable . '.' . implode('-', $pkArr));
     } catch (DBException $e) {
         $this->logger->error('Problem with generated statement: ' . $e->getQueryString(), $e);
         throw $e;
     }
 }