code
stringlengths 52
7.75k
| docs
stringlengths 1
5.85k
|
---|---|
public function getStartCategoryOptions(\DataContainer $dc)
{
$dmsLoader = \DmsLoader::getInstance();
$params = new \DmsLoaderParams();
$params->rootCategoryId = 0;
$arrCategories = $dmsLoader->loadCategories($params);
$arrCategories = \DmsLoader::flattenCategories($arrCategories);
$arrOptions = array();
foreach ($arrCategories as $category)
{
$indent = "";
for ($i = 0; $i < $category->getLevel(); $i++)
{
$indent .= " ";
}
$arrOptions[$category->id] = $indent . $category->name;
}
return $arrOptions;
}
|
Get all articles and return them as array
@param DataContainer
@return array
|
public function getStartCategoryPath(\DataContainer $dc)
{
$dmsLoader = \DmsLoader::getInstance();
$params = new \DmsLoaderParams();
$params->loadRootCategory = true;
$category = $dmsLoader->loadCategory($dc->activeRecord->dmsStartCategory, $params);
$path = '';
if ($category != null)
{
$path .= implode($GLOBALS['TL_LANG']['DMS']['management_path_separator'], $category->getPathNames(false));
}
return '<div class="w50 widget">
<h3><label for="ctrl_dmsStartCategory">' . $GLOBALS['TL_LANG']['tl_module']['dmsStartCategoryPath'][0] . '</label></h3>
<input type="text" class="tl_text" value="' . $path . '" disabled="">
<p class="tl_help tl_tip">' . $GLOBALS['TL_LANG']['tl_module']['dmsStartCategoryPath'][1] . '</p>
</div>';
}
|
Return all dms templates as array
@param DataContainer
@param string the label
@return string
|
public function parse(HtmlNode $element, Inky $inkyInstance)
{
$table = $this->table($element->getAttributes());
$this->addCssClass('menu', $table);
$tr = $this->tr();
$td = $this->td();
$childTable = $this->table();
$childTr = $this->tr();
$this->copyChildren($element, $childTr);
$childTable->addChild($childTr);
$td->addChild($childTable);
$tr->addChild($td);
$table->addChild($tr);
return $table;
}
|
<menu>{inner}</menu>
----------------------------
<table class="menu">
<tr>
<td>
<table>
<tr>
{inner}
</tr>
</table>
</td>
</tr>
</table>
@param HtmlNode $element
@param Inky $inkyInstance
@return HtmlNode
|
public function parse(HtmlNode $element, Inky $inkyInstance)
{
$isParsed = true;
foreach($element->getChildren() as $childElement) {
if($childElement instanceof HtmlNode) {
if($childElement->getAttribute('align') !== 'center'
|| !$this->elementHasCssClass($childElement, 'float-center')) {
$isParsed = false;
}
}
}
if($isParsed) {
return $element;
}
$center = $this->node('center', $element->getAttributes());
foreach($element->getChildren() as $childElement) {
if($childElement instanceof HtmlNode) {
$childElement->setAttribute('align', 'center');
$this->addCssClass('float-center', $childElement);
}
$center->addChild($childElement);
}
$result = $center->find('.menu-item');
foreach($result as $node) {
if($node instanceof HtmlNode) {
$this->addCssClass('float-center', $node);
}
}
return $center;
}
|
@param HtmlNode $element
@param Inky $inkyInstance
@return HtmlNode
|
protected function encodeTime(AbstractTimeType $type, string $format)
{
$this->validateTimeType($type);
return parent::encodeTime($type, $format);
}
|
{@inheritdoc}
@throws EncoderException
|
protected function validateDateFormat(array $matches, array $matchMap)
{
if (isset($matchMap['fractions']) && isset($matches[$matchMap['fractions']]) && $matches[$matchMap['fractions']] !== '') {
if ($matches[$matchMap['fractions']][-1] === '0') {
throw new EncoderException('Trailing zeros must be omitted from Generalized Time types, but it is not.');
}
}
}
|
{@inheritdoc}
@throws EncoderException
|
public function parse(HtmlNode $element, Inky $inkyInstance)
{
$upAttribute = (string) $element->getAttribute('up');
$table = $this->table(array('class' => trim(sprintf(
'block-grid up-%s %s',
$upAttribute,
(string) $element->getAttribute('class')
))));
$tr = $this->tr();
$this->copyChildren($element, $tr);
$table->addChild($tr);
return $table;
}
|
<block-grid up="{up}">{inner}</block-grid>
------------------------------------------
<table class="block-grid up-{up}">
<tr>{inner}</tr>
</table>
@param HtmlNode $element
@param Inky $inkyInstance
@return HtmlNode
|
protected function decodeBytes(bool $isRoot = false, $tagType = null, $length = null, $isConstructed = null, $class = null): AbstractType
{
$type = parent::decodeBytes($isRoot, $tagType, $length, $isConstructed, $class);
$this->validate($type);
return $type;
}
|
{@inheritdoc}
|
protected function decodeLongDefiniteLength(int $length) : int
{
$length = parent::decodeLongDefiniteLength($length);
if ($length < 127) {
throw new EncoderException('DER must be encoded using the shortest possible length form, but it is not.');
}
return $length;
}
|
{@inheritdoc}
|
public function parse(HtmlNode $element, Inky $inkyInstance)
{
$attributes = $element->getAttributes();
if(isset($attributes['href'])) {
$href = $attributes['href'];
unset($attributes['href']);
} else {
$href = null;
}
if(isset($attributes['target'])) {
$target = $attributes['target'];
unset($attributes['target']);
} else {
$target = null;
}
$th = $this->th($attributes);
$this->addCssClass('menu-item', $th);
$a = $this->node('a');
if($href !== null) {
$a->setAttribute('href', $href);
if($target !== null) {
$a->setAttribute('target', (string) $target);
}
}
$this->copyChildren($element, $a);
$th->addChild($a);
return $th;
}
|
<item href="{href}">{inner}</item>
------------------------------
<th class="menu-item">
<a href="{href}">{inner}</a>
</th>
@param HtmlNode $element
@param Inky $inkyInstance
@return HtmlNode
|
public function addAlias($alias, $tagName)
{
if($this->getComponentFactory($tagName)) {
$this->alias[(string) $alias] = (string) $tagName;
}
return $this;
}
|
Adds an alisa for a component
@param $alias
@param $tagName
@return $this
|
public function getComponentFactory($tagName)
{
//check for alias first
if(isset($this->alias[$tagName])) {
$tagName = $this->alias[$tagName];
}
if(
isset($this->componentFactory[$tagName])
&& $this->componentFactory[$tagName] instanceof ComponentFactoryInterface
) {
return $this->componentFactory[$tagName];
}
return null;
}
|
returns a Component Factory for a given tag or alias
@param $tagName
@return null|ComponentFactoryInterface
|
public function toggleVisibility($intId, $blnVisible)
{
// Check permissions
if (!$this->User->isAdmin && !$this->User->hasAccess('tl_dms_access_rights::published', 'alexf'))
{
$this->log('Not enough permissions to activate/deactivate dms access right ID "'.$intId.'"', 'tl_dms_access_rights toggleVisibility', TL_ERROR);
$this->redirect('contao/main.php?act=error');
}
$this->createInitialVersion('tl_dms_access_rights', $intId);
// Trigger the save_callback
if (is_array($GLOBALS['TL_DCA']['tl_dms_access_rights']['fields']['published']['save_callback']))
{
foreach ($GLOBALS['TL_DCA']['tl_dms_access_rights']['fields']['published']['save_callback'] as $callback)
{
$this->import($callback[0]);
$blnVisible = $this->{$callback[0]}->{$callback[1]}($blnVisible, $this);
}
}
// Update the database
$this->Database->prepare("UPDATE tl_dms_access_rights SET tstamp=". time() .", published='" . ($blnVisible ? 1 : '') . "' WHERE id=?")
->execute($intId);
$this->createNewVersion('tl_dms_access_rights', $intId);
}
|
Activate/deactivate an access right
@param integer
@param boolean
|
protected function canonicalize(AbstractType ...$set) : array
{
$children = [
AbstractType::TAG_CLASS_UNIVERSAL => [],
AbstractType::TAG_CLASS_APPLICATION => [],
AbstractType::TAG_CLASS_CONTEXT_SPECIFIC => [],
AbstractType::TAG_CLASS_PRIVATE => [],
];
# Group them by their respective class type.
foreach ($set as $child) {
$children[$child->getTagClass()][] = $child;
}
# Sort the classes by tag number.
foreach ($children as $class => $type) {
\usort($children[$class], function ($a, $b) {
/* @var AbstractType $a
* @var AbstractType $b */
return ($a->getTagNumber() < $b->getTagNumber()) ? -1 : 1;
});
}
return \array_merge(
$children[AbstractType::TAG_CLASS_UNIVERSAL],
$children[AbstractType::TAG_CLASS_APPLICATION],
$children[AbstractType::TAG_CLASS_CONTEXT_SPECIFIC],
$children[AbstractType::TAG_CLASS_PRIVATE]
);
}
|
X.680 Sec 8.4. A set is canonical when:
- Universal classes first.
- Application classes second.
- Context specific classes third.
- Private classes last.
- Within each group of classes above, tag numbers should be ordered in ascending order.
@param AbstractType ...$set
@return AbstractType[]
|
private function uploadSelectFile(&$params, &$dmsLoader, &$uploadCategory, &$arrMessages, &$blnShowStart)
{
$params->loadRootCategory = true; // get complete path to root, for checking inherited access rights
$params->loadAccessRights = true;
$params->loadDocuments = false;
$category = $dmsLoader->loadCategory($uploadCategory, $params);
if ($category->isUploadableForCurrentMember())
{
$this->Template = new \FrontendTemplate("mod_dms_mgmt_upload_select_file");
$this->Template->setData($this->arrData);
$this->Template->category = $category;
$this->Template->maxUploadFileSizeByte = \DmsConfig::getMaxUploadFileSize(\Document::FILE_SIZE_UNIT_BYTE, false);
$this->Template->maxUploadFileSizeByteFormatted = \DmsConfig::getMaxUploadFileSize(\Document::FILE_SIZE_UNIT_BYTE, true);
$this->Template->maxUploadFileSizeKbFormatted = \DmsConfig::getMaxUploadFileSize(\Document::FILE_SIZE_UNIT_KB, true);
$this->Template->maxUploadFileSizeMbFormatted = \DmsConfig::getMaxUploadFileSize(\Document::FILE_SIZE_UNIT_MB, true);
$this->Template->maxUploadFileSizeGbFormatted = \DmsConfig::getMaxUploadFileSize(\Document::FILE_SIZE_UNIT_GB, true);
$blnShowStart = false;
}
else
{
$arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['upload_document_not_allowed'];
$blnShowStart = true;
}
}
|
Display the file select screen for upload
|
private function manageSelectDocument(&$params, &$dmsLoader, &$manageCategory, &$arrMessages, &$blnShowStart)
{
$params->loadRootCategory = true; // get complete path to root, for checking inherited access rights
$params->loadAccessRights = true;
$params->loadDocuments = true;
$category = $dmsLoader->loadCategory($manageCategory, $params);
if (!$category->isManageableForCurrentMember())
{
$arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_allowed'];
$blnShowStart = true;
}
else if (!$category->hasDocuments())
{
$arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_category_empty'];
$blnShowStart = true;
}
else
{
$this->Template = new \FrontendTemplate("mod_dms_mgmt_manage_document_select");
$this->Template->setData($this->arrData);
$this->Template->category = $category;
$blnShowStart = false;
}
}
|
Display the document select screen for managing
|
private function managePublishDocument(&$params, &$dmsLoader, &$manageCategory, &$arrMessages, &$blnShowStart, $documentId)
{
$params->loadRootCategory = true; // get complete path to root, for checking inherited access rights
$params->loadAccessRights = true;
$params->loadDocuments = false;
$category = $dmsLoader->loadCategory($manageCategory, $params);
if (!$category->isPublishableForCurrentMember())
{
$arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_allowed'];
$blnShowStart = true;
}
else
{
$document = $dmsLoader->loadDocument($documentId, $params);
if ($document != null)
{
if (!$document->isPublished())
{
$document->lasteditMemberId = $this->Member->id;
$document->lasteditDate = time();
$document->published = true;
$dmsWriter = \DmsWriter::getInstance();
$document = $dmsWriter->updateDocument($document);
$arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_successfully_published'];
}
else
{
$arrMessages['infos'][] = $GLOBALS['TL_LANG']['DMS']['INFO']['document_already_published'];
}
}
else
{
$arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_found'];
}
$this->manageSelectDocument($params, $dmsLoader, $manageCategory, $arrMessages, $blnShowStart);
}
}
|
Execute publishing documents
|
private function manageDeleteDocument(&$params, &$dmsLoader, &$manageCategory, &$arrMessages, &$blnShowStart, $documentId)
{
$params->loadRootCategory = true; // get complete path to root, for checking inherited access rights
$params->loadAccessRights = true;
$params->loadDocuments = false;
$category = $dmsLoader->loadCategory($manageCategory, $params);
if (!$category->isDeletableForCurrentMember())
{
$arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_allowed'];
$blnShowStart = true;
}
else
{
$document = $dmsLoader->loadDocument($documentId, $params);
if ($document != null)
{
// delete the document in the database
$dmsWriter = \DmsWriter::getInstance();
if ($dmsWriter->deleteDocument($document))
{
$arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_successfully_deleted'];
// delete the file
$filePath = \DmsConfig::getDocumentFilePath($document->getFileNameVersioned());
if (file_exists(TL_ROOT . '/' . $filePath))
{
unlink($filePath);
\Dbafs::deleteResource($filePath);
$arrMessages['successes'][] = $GLOBALS['TL_LANG']['DMS']['SUCCESS']['document_file_successfully_deleted'];
}
else
{
$arrMessages['infos'][] = $GLOBALS['TL_LANG']['DMS']['INFO']['document_delete_file_not_exists'];
}
}
else
{
$arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['delete_document_failed'];
}
}
else
{
$arrMessages['errors'][] = $GLOBALS['TL_LANG']['DMS']['ERR']['manage_document_not_found'];
}
$this->manageSelectDocument($params, $dmsLoader, $manageCategory, $arrMessages, $blnShowStart);
}
}
|
Execute unpublishing documents
|
private function applyAccessPermissionsToCategories(Array $arrCategories)
{
$arrSecureCategories = $arrCategories;
foreach ($arrSecureCategories as $category)
{
if (!$category->isPublished() || ($this->dmsHideLockedCategories && (!$category->isUploadableForCurrentMember() && !$category->isManageableForCurrentMember())))
{
unset($arrSecureCategories[$category->id]);
}
else if ($category->hasSubCategories())
{
$arrSecureSubCategories = $this->applyAccessPermissionsToCategories($category->subCategories);
$category->subCategories = $arrSecureSubCategories;
}
}
return $arrSecureCategories;
}
|
Apply the access permissions to the categories.
@param arr $arrCategories The structured array of categories.
@return array Returns a reduced array of categories (depends on the access permissions).
|
public function checkPermission()
{
// Check current action
switch ($this->Input->get('act'))
{
case 'delete':
if (!$this->isCategoryDeletable($this->Input->get('id')))
{
$this->log('Deleting the non empty category with ID "'.$this->Input->get('id').'" is not allowed.', 'tl_dms_categories checkPermission', TL_ERROR);
$this->redirect('contao/main.php?act=error');
}
break;
}
}
|
Check permissions to avoid not allowd deleting
|
public function getDeleteButton($row, $href, $label, $title, $icon, $attributes)
{
if (!$this->isCategoryDeletable($row['id']))
{
return $this->generateImage('delete_.gif', $GLOBALS['TL_LANG']['tl_dms_categories']['delete_'][0], 'title="' . sprintf($GLOBALS['TL_LANG']['tl_dms_categories']['delete_'][1], $row['id']) . '"') . " ";
}
return '<a href="'.$this->addToUrl($href.'&id='.$row['id']).'" title="'.specialchars($title).'"'.$attributes.'>'.$this->generateImage($icon, $label).'</a> ';
}
|
Return the "delete" button
@param array
@param string
@param string
@param string
@param string
@param string
@return string
|
private function getCategoryForId($intId, $blnLoadRootCategory, $blnLoadDocuments)
{
$params = new \DmsLoaderParams();
$params->loadRootCategory = $blnLoadRootCategory;
$params->loadDocuments = $blnLoadDocuments;
$dmsLoader = \DmsLoader::getInstance();
return $dmsLoader->loadCategory($intId, $params);
}
|
Get a category via DmsLoader.
|
private function isCategoryDeletable($intId)
{
$params = new \DmsLoaderParams();
$params->rootCategoryId = $intId;
$params->includeRootCategory = true;
$params->loadRootCategory = true;
$params->loadAccessRights = true;
$params->loadDocuments = true;
$dmsLoader = \DmsLoader::getInstance();
$arrCategories = $dmsLoader->loadCategories($params);
if (count($arrCategories) == 1)
{
$category = $arrCategories[0];
if ($category != null && ($category->hasDocuments() || $category->hasDocumentsInSubCategories()))
{
return false;
}
}
return true;
}
|
Get a category via DmsLoader.
|
public function saveFileTypes($varValue, DataContainer $dc)
{
if (strlen($varValue) > 0)
{
$arrFileTypes = \DmsUtils::getUniqueFileTypes($varValue);
$varValue = implode(",", $arrFileTypes);
}
return $varValue;
}
|
Cleanup the files types before saving
|
public function validateMaxUploadFileSize($varValue, DataContainer $dc)
{
$arrValue = deserialize($varValue);
$dmsUnit = $arrValue['unit'];
$dmsVal = \Document::convertFileSize((double) $arrValue['value'], $dmsUnit, \Document::FILE_SIZE_UNIT_BYTE);
$phpVal = $this->getPhpUploadMaxFilesize();
if ($dmsVal > $phpVal)
{
throw new \Exception(sprintf($GLOBALS['TL_LANG']['ERR']['dmsMaxUploadFileSize'], \Document::formatFileSize(\Document::convertFileSize($phpVal, \Document::FILE_SIZE_UNIT_BYTE, $dmsUnit), $dmsUnit)));
}
return $varValue;
}
|
Return the reduced file name
@param mixed
@param DataContainer
@return string
|
private function getPhpUploadMaxFilesize()
{
$param = trim(ini_get('upload_max_filesize'));
$unit = strtolower(substr($param, -1));
$val = (double) $param;
switch($unit)
{
case 'k':
$val = \Document::convertFileSize((double) substr($param, 0, - 1), \Document::FILE_SIZE_UNIT_KB, \Document::FILE_SIZE_UNIT_BYTE);
break;
case 'm':
$val = \Document::convertFileSize((double) substr($param, 0, - 1), \Document::FILE_SIZE_UNIT_MB, \Document::FILE_SIZE_UNIT_BYTE);
break;
case 'g':
$val = \Document::convertFileSize((double) substr($param, 0, - 1), \Document::FILE_SIZE_UNIT_GB, \Document::FILE_SIZE_UNIT_BYTE);
break;
}
if (!is_double($val))
{
throw new \Exception('PHP value for upload_max_filesize could not be determined.');
}
return $val;
}
|
Get the value of the upload_max_filesize set in PHP.
@return int The int value of the upload_max_filesize set in PHP in byte.
|
public function add($item)
{
if (is_array($item)) {
return array_map([$this, 'add'], $item);
}
if (! $item | strlen(trim($item)) === 0) {
return false;
}
$this->collection[] = trim(strip_tags($item));
}
|
Add an item to the collection.
@param $item
@return mixed
|
public function get($direction = 'regular')
{
if ($this->count() == 0) {
return $this->default;
}
if ($direction === 'downward') {
$this->collection = array_reverse($this->collection);
}
$this->addPageName();
if ($direction === 'reverse') {
$this->collection = array_reverse($this->collection);
}
return implode($this->getDelimeter(), $this->collection);
}
|
Get the page title.
@param bool|string $direction
@return string
|
protected function addPageName()
{
if (! empty($this->getPageName()) && ! in_array($this->getPageName(), $this->collection)) {
$this->add($this->getPageName());
}
}
|
Add the page name to the collection.
|
public function isActive()
{
$time = time();
$active = ($this->active && ($this->activationStart == '' || $this->activationStart < $time) && ($this->activationStop == '' || $this->activationStop > $time));
return $active;
}
|
Return if this access right is active.
@return bool True if this access right is active.
|
public function register()
{
$this->app->singleton('PageTitle', function () {
$delimeter = config('pagetitle.delimiter');
$page_name = config('pagetitle.page_name');
$default = config('pagetitle.default_title_when_empty');
return new PageTitle($delimeter, $page_name, $default);
});
}
|
Register the service provider.
|
public static function addUserId($tag)
{
if ($user = User::where('username', 'like', $tag->getAttribute('username'))->first()) {
$tag->setAttribute('id', $user->id);
$tag->setAttribute('displayname', $user->display_name);
return true;
}
}
|
@param $tag
@return bool
|
public function toBinary()
{
$bytes = '';
foreach (str_split($this->value, 8) as $piece) {
$bytes .= chr(bindec($piece));
}
return $bytes;
}
|
Get the packed binary representation.
@return string
|
public static function fromBinary($bytes, ?int $minLength = null)
{
$bitstring = '';
$length = strlen($bytes);
for ($i = 0; $i < $length; $i++) {
$bitstring .= sprintf('%08d', decbin(ord($bytes[$i])));
}
if ($minLength && strlen($bitstring) < $minLength) {
$bitstring = str_pad($bitstring, $minLength, '0');
}
return new self($bitstring);
}
|
Construct the bit string from a binary string value.
@param $bytes
@param int|null $minLength
@return BitStringType
|
public static function fromInteger(int $int, ?int $minLength = null)
{
$pieces = str_split(decbin($int), 8);
$num = count($pieces);
if ($num === 1 && strlen($pieces[0]) !== 8) {
$pieces[0] = str_pad($pieces[0], 8, '0', STR_PAD_LEFT);
} elseif ($num > 0 && strlen($pieces[$num - 1]) !== 8) {
$pieces[$num - 1] = str_pad($pieces[$num - 1], 8, '0', STR_PAD_RIGHT);
}
$bitstring = implode('', $pieces);
if ($minLength && strlen($bitstring) < $minLength) {
$bitstring = str_pad($bitstring, $minLength, '0');
}
return new self($bitstring);
}
|
Construct the bit string from an integer.
@param int $int
@param int|null $minLength
@return BitStringType
|
public function parse(HtmlNode $element, Inky $inkyInstance)
{
$tr = $this->tr();
$td = $this->td();
$img = $this->img(array('src' => $this->inkySrc));
$td->addChild($img);
$tr->addChild($td);
return $tr;
}
|
<inky />
----------------------------
<tr>
<td>
<img src="{inkySrc}" />
</td>
</tr>
@param HtmlNode $element
@param Inky $inkyInstance
@return HtmlNode
|
public function parse(HtmlNode $element, Inky $inkyInstance)
{
$table = $this->table($this->getUsableAttributes($element, 'class'));
$this->addCssClass('callout', $table);
$tr = $this->tr();
$th = $this->th($element->getAttributes());
$this->addCssClass('callout-inner', $th);
$this->copyChildren($element, $th);
$tr->addChild($th);
$expander = $this->th(['class' => 'expander']);
$tr->addChild($expander);
$table->addChild($tr);
return $table;
}
|
<callout>{inner}</callout>
----------------------------------
<table class="callout">
<tr>
<th class="callout-inner">Callout</th>
<th class="expander"></th>
</tr>
</table>
@param HtmlNode $element
@param Inky $inkyInstance
@return HtmlNode
|
public function parse(HtmlNode $element, Inky $inkyInstance)
{
// This is a hack for no-expander because PhpDomParser doesn't seem to support value-less attributes.
$outerHtml = $element->outerHtml();
if(!$element->getAttribute('no-expander') && stristr($outerHtml, 'no-expander'))
{
$element->setAttribute('no-expander', 'true');
}
$this->setGridColumns($inkyInstance->getGridColumns());
$th = $this->th($this->getUsableAttributes($element));
$th->setAttribute('class', $this->prepareCssClass($element));
$table = $this->table();
$tr = $this->tr();
$childTh = $this->th();
$isExpanding = (bool) (is_null($element->getAttribute('no-expander')) || $element->getAttribute('no-expander') == 'false');
$hasRowChildren = $this->hasRowChild($element, $inkyInstance); // must be called before children are moved
$this->copyChildren($element, $childTh);
$tr->addChild($childTh);
//if element contains as <row />
if($hasRowChildren && $isExpanding) {
$expander = $this->th(array('class' => 'expander'));
$tr->addChild($expander);
}
$table->addChild($tr);
$th->addChild($table);
return $th;
}
|
<columns small="{small}" large="{large}">{inner}</columns>
--------------------------------------------------------
<th class="small-{small} large-{large} columns">
<table>
<tr>
<th>
{inner}
</th>
<th class="expander"></th>
</tr>
</table>
</th>
@param HtmlNode $element
@param Inky $inkyInstance
@return HtmlNode
|
public function parse(HtmlNode $element, Inky $inkyInstance)
{
$table = $this->table($element->getAttributes());
$this->addCssClass('row', $table);
$body = $this->tbody();
$tr = $this->tr();
$body->addChild($tr);
$table->addChild($body);
$this->copyChildren($element, $tr);
return $table;
}
|
<row>{inner}</row>
---------------------------
<table class="row {class}">
<tbody>
<tr>{inner}</tr>
</tbody>
</table>
@param HtmlNode $element
@param Inky $inkyInstance
@return HtmlNode
|
public function storeDocument(\Document $document)
{
$arrSet = $this->buildDocumentDataArray($document, false);
$objDocument = $this->Database->prepare("INSERT INTO tl_dms_documents %s")->set($arrSet)->execute();
$document->id = $objDocument->insertId;
return $document;
}
|
Store the new document in the given category.
@param Document $document The document to store.
@return document Returns the document.
|
public function updateDocument(\Document $document)
{
$arrSet = $this->buildDocumentDataArray($document, false);
$this->Database->prepare("UPDATE tl_dms_documents %s WHERE id=?")->set($arrSet)->execute($document->id);
return $document;
}
|
Update the document.
@param Document $document The document to update.
@return document Returns the document.
|
public function deleteDocument(\Document $document)
{
$objStmt = $this->Database->prepare("DELETE FROM tl_dms_documents WHERE id=?")->execute($document->id);
return ($objStmt->affectedRows > 0);
}
|
Delete a document.
@param Document $document The document to delete.
@return bool Returns true, if the document was successfully deleted.
|
public function getBundles(ParserInterface $parser)
{
return [
BundleConfig::create(WebpackEncoreBundle::class),
BundleConfig::create(HeimrichHannotContaoEncoreBundle::class)->setLoadAfter([ContaoCoreBundle::class]),
];
}
|
{@inheritdoc}
|
public function addEncore(PageModel $page, LayoutModel $layout, PageRegular $pageRegular)
{
$this->doAddEncore($page, $layout, $pageRegular);
}
|
Modify the page object.
@param PageModel $page
@param LayoutModel $layout
@param PageRegular $pageRegular
|
public function isEntryActive(string $entry, string $encoreField = 'encoreEntries'): bool
{
global $objPage;
$parentPages = $this->modelUtil->findParentsRecursively('pid', 'tl_page', $objPage);
$result = false;
foreach (array_merge(is_array($parentPages) ? $parentPages : [], [$objPage]) as $i => $page) {
$isActive = $this->isEntryActiveForPage($entry, $page, $encoreField);
if (0 == $i || $isActive !== null) {
$result = $isActive;
}
}
return $result ? true : false;
}
|
@param string $entry
@return bool
|
public function isEntryActiveForPage(string $entry, Model $page, string $encoreField = 'encoreEntries')
{
$entries = \Contao\StringUtil::deserialize($page->{$encoreField}, true);
foreach ($entries as $row) {
if ($row['entry'] === $entry) {
return $row['active'] ? true : false;
}
}
return null;
}
|
@param string $entry
@param Model $page
@return null|bool Returns null, if no information about the entry is specified in the page; else bool
|
public function addIcon($row, $label, \DataContainer $dc=null, $imageAttribute='', $blnReturnImage=false)
{
$arrMimeInfo = \DmsUtils::getMimeInfo($row['data_file_type']);
$imgName = $arrMimeInfo['icon'];
if (!$row['published'])
{
$imgName .= '_';
}
return $this->generateImage('system/modules/DocumentManagementSystem/assets/mime/' . $imgName . '.png', $arrMimeInfo['type']) . $label;
}
|
Add an image to each record
@param array
@param string
@return string
|
public static function getValidFileTypesForCategory()
{
$db = \Database::getInstance();
$input = \Input::getInstance();
if($db->tableExists('tl_dms_categories') && $db->tableExists('tl_dms_documents'))
{
$objCategory = $db->prepare('SELECT cat.* FROM tl_dms_categories cat JOIN tl_dms_documents doc ON doc.pid = cat.id WHERE doc.id = ?')->execute($input->get('id'));
if ($objCategory->numRows)
{
return $objCategory->file_types;
}
}
return "";
}
|
Determine the valid file types for the current category
|
public function resortDocuments(\DataContainer $dc)
{
if (!$this->Input->get('act'))
{
$db = \Database::getInstance();
$stmt = "UPDATE tl_dms_documents doc, "
. " (SELECT @rownum := @rownum + 1 ROWNUM, t.id ID "
. " FROM "
. " (SELECT @rownum := 0) r, "
. " (SELECT * FROM tl_dms_documents ORDER BY pid, name, version_major, version_minor, version_patch) t) tsub "
. "SET doc.sorting = (tsub.ROWNUM *64) "
. "WHERE doc.id = tsub.ID";
$db->prepare($stmt)->execute();
}
}
|
Resort the document sorting value
@param DataContainer
|
public function getOriginalFileNameWidget(\DataContainer $dc)
{
$doc = $dc->activeRecord;
return '
<div class="w50 widget">
<h3><label for="ctrl_purge">'.$GLOBALS['TL_LANG']['tl_dms_documents']['data_file_name_org'][0].'</label></h3>
<input type="text" class="tl_text" value="' . $doc->data_file_name . '" disabled="">
<p class="tl_help tl_tip">'.$GLOBALS['TL_LANG']['tl_dms_documents']['data_file_name_org'][1].'</p>
</div>';
}
|
Return the complete file path
@param DataContainer
@return string
|
public function getFileTypeWidget(\DataContainer $dc)
{
$doc = $dc->activeRecord;
return '
<div class="w50 widget">
<h3><label for="ctrl_purge">'.$GLOBALS['TL_LANG']['tl_dms_documents']['data_file_type'][0].'</label></h3>
<input type="text" class="tl_text" value="' . $doc->data_file_type . '" disabled="">
<p class="tl_help tl_tip">'.$GLOBALS['TL_LANG']['tl_dms_documents']['data_file_type'][1].'</p>
</div>';
}
|
Return the complete file path
@param DataContainer
@return string
|
public function getFileSizeWidget(\DataContainer $dc)
{
$doc = $dc->activeRecord;
return '
<div class="w50 widget">
<h3><label for="ctrl_purge">'.$GLOBALS['TL_LANG']['tl_dms_documents']['data_file_size'][0].'</label></h3>
<input type="text" class="tl_text" value="' . $doc->data_file_size . '" disabled="">
<p class="tl_help tl_tip">'.$GLOBALS['TL_LANG']['tl_dms_documents']['data_file_size'][1].'</p>
</div>';
}
|
Return the complete file path
@param DataContainer
@return string
|
public function getFullFilePath($varValue, \DataContainer $dc)
{
$doc = $dc->activeRecord;
$strFile = \DmsConfig::getDocumentFilePath
(
\Document::buildFileNameVersioned
(
$varValue,
\Document::buildVersionForFileName($doc->version_major, $doc->version_minor, $doc->version_patch),
$doc->data_file_type
)
);
return \FilesModel::findByPath($strFile)->uuid;
}
|
Return the complete file path
@param mixed
@param DataContainer
@return string
|
public function reduceFilePath($varValue, \DataContainer $dc)
{
$doc = $dc->activeRecord;
$path = \FilesModel::findByUuid($varValue)->path;
$arrFileNameParts = \Document::splitFileName(substr($path, strlen(\DmsConfig::getBaseDirectory(true))));
// TODO (#33): reset the new fileType
// TODO (#33): reset the new fileSize
// TODO (#33): get version parts from POST ... maybe changed ... or reduce fileName via finding and counting underscores and removing them
return $arrFileNameParts['fileName'];
}
|
Return the reduced file name
@param mixed
@param DataContainer
@return string
|
public function deleteFile(\DataContainer $dc)
{
$filePath = TL_ROOT . '/' . $this->getFullFilePath($dc->activeRecord->data_file_name, $dc);
if (file_exists($filePath))
{
unlink($filePath);
}
}
|
Delete the file, if the document will be deleted.
@param DataContainer
|
public function loadCategories(\DmsLoaderParams $params)
{
$rootCategory = null;
// if another root category is selected
if ($params->loadRootCategory && $params->rootCategoryId > 0)
{
$rootCategory = $this->loadCategory($params->rootCategoryId, $params);
$arrCategories = $this->getCategoryLevel($params->rootCategoryId, $rootCategory, $params);
if ($params->includeRootCategory)
{
$rootCategory->subCategories = $arrCategories;
$arrCategories = array();
$arrCategories[] = $rootCategory;
}
return $arrCategories;
}
return $this->getCategoryLevel($params->rootCategoryId, null, $params);
}
|
Load the categories structure without consideration of access rights.
@param DmsLoaderParams $params The configured params to use while loading.
@return array Returns the category structure.
|
public static function flattenCategories(Array $arrCategories)
{
$arrFlattend = array();
foreach ($arrCategories as $category)
{
$arrFlattend[] = $category;
if ($category->hasSubCategories())
{
$arrFlattend = array_merge($arrFlattend, \DmsLoader::flattenCategories($category->subCategories));
}
}
return $arrFlattend;
}
|
Flatten a categories structure.
@param arr $arrCategories The structured array of categories.
@return array Returns the flattened array of categories.
|
public function loadCategory($categoryId, \DmsLoaderParams $params)
{
$objCategory = $this->Database->prepare("SELECT * FROM tl_dms_categories WHERE id = ?")
->limit(1)
->execute($categoryId);
$category = null;
if ($objCategory->numRows)
{
$category = $this->buildCategory($objCategory);
if ($params->loadAccessRights)
{
$category->accessRights = $this->getAccessRights($category, $params);
}
if ($params->loadDocuments)
{
$category->documents = $this->getDocuments($category, $params);
}
if ($params->loadRootCategory)
{
$category->parentCategory = $this->loadCategory($category->parentCategoryId, $params);
}
}
return $category;
}
|
Load the category with the given id.
@param int $categoryId The id of the category to load.
@param DmsLoaderParams $params The configured params to use while loading.
@return category Returns the category.
|
public function loadDocument($documentId, \DmsLoaderParams $params)
{
$objDocument = $this->Database->prepare("SELECT d.*, CONCAT(m1.firstname, ' ', m1.lastname) AS upload_member_name, CONCAT(m2.firstname, ' ', m2.lastname) AS lastedit_member_name "
. "FROM tl_dms_documents d "
. "LEFT JOIN tl_member m1 ON m1.id = d.upload_member "
. "LEFT JOIN tl_member m2 ON m2.id = d.lastedit_member "
. "WHERE d.id = ?")
->limit(1)
->execute($documentId);
$document = null;
if ($objDocument->numRows)
{
$document = $this->buildDocument($objDocument);
if ($params->loadCategory)
{
$document->category = $this->loadCategory($document->categoryId, $params);
}
}
return $document;
}
|
Load the document with the given id.
@param int $documentId The id of the document to load.
@param DmsLoaderParams $params The configured params to use while loading.
@return document Returns the document.
|
public function loadDocuments($strFileName, $strFileType, \DmsLoaderParams $params)
{
$arrDocuments = array();
$objDocument = $this->Database->prepare("SELECT d.*, CONCAT(m1.firstname, ' ', m1.lastname) AS upload_member_name, CONCAT(m2.firstname, ' ', m2.lastname) AS lastedit_member_name "
. "FROM tl_dms_documents d "
. "LEFT JOIN tl_member m1 ON m1.id = d.upload_member "
. "LEFT JOIN tl_member m2 ON m2.id = d.lastedit_member "
. "WHERE d.data_file_name = ? AND d.data_file_type = ? "
. "ORDER BY d.version_major, d.version_minor, d.version_patch")
->execute(array($strFileName, $strFileType));
$document = null;
while ($objDocument->next())
{
$document = $this->buildDocument($objDocument);
if ($params->loadCategory)
{
$document->category = $this->loadCategory($document->categoryId, $params);
}
$arrDocuments[] = $document;
}
return $arrDocuments;
}
|
Load the documents for the given file name and type.
@param string $strFileName The common file name for the documents to load.
@param string $strFileType The common file type for the documents to load.
@param DmsLoaderParams $params The configured params to use while loading.
@return array Returns an array of matching the documents.
|
protected function getCategoryLevel($parentCategoryId, \Category $parentCategory=null, \DmsLoaderParams $params)
{
$arrCategories = array();
$objCategory = $this->Database->prepare("SELECT * FROM tl_dms_categories WHERE pid = ? ORDER BY sorting")
->execute($parentCategoryId);
$category = null;
while ($objCategory->next())
{
$category = $this->buildCategory($objCategory);
$category->parentCategory = $parentCategory;
$category->subCategories = $this->getCategoryLevel($category->id, $category, $params);
if ($params->loadAccessRights)
{
$category->accessRights = $this->getAccessRights($category, $params);
}
if ($params->loadDocuments)
{
$category->documents = $this->getDocuments($category, $params);
}
$arrCategories[$category->id] = $category;
}
return $arrCategories;
}
|
Recursively reading the categories
|
private function getAccessRights(\Category $category, \DmsLoaderParams $params)
{
$objAccessRight = $this->Database->prepare("SELECT * FROM tl_dms_access_rights WHERE pid = ?")
->execute($category->id);
$arrAccessRights = array();
while ($objAccessRight->next())
{
$accessRight = $this->buildAccessRight($objAccessRight);
$accessRight->category = $category;
$arrAccessRights[$accessRight->id] = $accessRight;
}
return $arrAccessRights;
}
|
Get all access rights for the given category.
@param category $category The category to get the access rights for.
@param DmsLoaderParams $params The configured params to use while loading.
@return arr Returns array of access rights.
|
private function getDocuments(\Category $category, \DmsLoaderParams $params)
{
$whereClause = "WHERE d.pid = ? ";
$whereParams = array();
$whereParams[] = $category->id;
if ($params->hasDocumentSearchText())
{
if ($params->documentSearchType == \DmsLoaderParams::DOCUMENT_SEARCH_LIKE)
{
$whereClause .= "AND (UPPER(d.name) LIKE ? OR UPPER(d.description) LIKE ? OR UPPER(d.keywords) LIKE ?) ";
$seachText = "%" . $params->documentSearchText . "%";
}
else
{
$whereClause .= "AND (d.name = ? OR d.description = ? OR d.keywords = ?) ";
$seachText = $params->documentSearchText;
}
// add the search text 3 times
for ($i = 0; $i < 3; $i++)
{
$whereParams[] = $seachText;
}
}
$objDocument = $this->Database->prepare("SELECT d.*, CONCAT(m1.firstname, ' ', m1.lastname) AS upload_member_name, CONCAT(m2.firstname, ' ', m2.lastname) AS lastedit_member_name "
. "FROM tl_dms_documents d "
. "LEFT JOIN tl_member m1 ON m1.id = d.upload_member "
. "LEFT JOIN tl_member m2 ON m2.id = d.lastedit_member "
. $whereClause
. "ORDER BY d.name, d.version_major, d.version_minor, d.version_patch")
->execute($whereParams);
$arrDocuments = array();
while ($objDocument->next())
{
$document = $this->buildDocument($objDocument);
$document->category = $category;
$arrDocuments[$document->id] = $document;
}
return $arrDocuments;
}
|
Get all documents for the given category.
@param category $category The category to get the access rights for.
@param DmsLoaderParams $params The configured params to use while loading.
@return arr Returns array of documents.
|
private function buildCategory($objCategory)
{
$category = new \Category($objCategory->id, $objCategory->name);
$category->parentCategoryId = $objCategory->pid;
$category->description = $objCategory->description;
$category->fileTypes = $objCategory->file_types;
$category->fileTypesInherit = $objCategory->file_types_inherit;
$category->publishDocumentsPerDefault = $objCategory->publish_documents_per_default;
$category->generalReadPermission = $objCategory->general_read_permission;
$category->generalManagePermission = $objCategory->general_manage_permission;
$category->cssId = $objCategory->cssID;
$category->published = $objCategory->published;
$category->publicationStart = $objCategory->start;
$category->publicationStop = $objCategory->stop;
// HOOK: modify the category
if (isset($GLOBALS['TL_HOOKS']['dmsModifyLoadedCategory']) && is_array($GLOBALS['TL_HOOKS']['dmsModifyLoadedCategory']))
{
foreach ($GLOBALS['TL_HOOKS']['dmsModifyLoadedCategory'] as $callback)
{
$this->import($callback[0]);
$category = $this->{$callback[0]}->{$callback[1]}($category, $objCategory);
}
}
return $category;
}
|
Builds a category from a database result.
@param DatabaseResult $objCategory The database result.
@return category The created category.
|
private function buildAccessRight($objAccessRight)
{
$accessRight = new \AccessRight($objAccessRight->id, $objAccessRight->member_group);
$accessRight->categoryId = $objAccessRight->pid;
$strRight = \AccessRight::READ;
$accessRight->$strRight = $objAccessRight->right_read;
$strRight = \AccessRight::UPLOAD;
$accessRight->$strRight = $objAccessRight->right_upload;
$strRight = \AccessRight::DELETE;
$accessRight->$strRight = $objAccessRight->right_delete;
$strRight = \AccessRight::EDIT;
$accessRight->$strRight = $objAccessRight->right_edit;
$strRight = \AccessRight::PUBLISH;
$accessRight->$strRight = $objAccessRight->right_publish;
$accessRight->active = $objAccessRight->published;
$accessRight->activationStart = $objAccessRight->start;
$accessRight->activationStop = $objAccessRight->stop;
// HOOK: modify the access right
if (isset($GLOBALS['TL_HOOKS']['dmsModifyLoadedAccessRight']) && is_array($GLOBALS['TL_HOOKS']['dmsModifyLoadedAccessRight']))
{
foreach ($GLOBALS['TL_HOOKS']['dmsModifyLoadedAccessRight'] as $callback)
{
$this->import($callback[0]);
$accessRight = $this->{$callback[0]}->{$callback[1]}($accessRight, $objAccessRight);
}
}
return $accessRight;
}
|
Builds an access right from a database result.
@param DatabaseResult $objAccessRight The database result.
@return accessRight The created access right.
|
private function buildDocument($objDocument)
{
$document = new \Document($objDocument->id, $objDocument->name);
$document->categoryId = $objDocument->pid;
$document->description = $objDocument->description;
$document->keywords = $objDocument->keywords;
$document->fileName = $objDocument->data_file_name;
$document->fileType = $objDocument->data_file_type;
$document->fileSize = $objDocument->data_file_size;
$document->filePreview = $objDocument->data_file_preview;
$document->versionMajor = $objDocument->version_major;
$document->versionMinor = $objDocument->version_minor;
$document->versionPatch = $objDocument->version_patch;
$document->uploadMemberId = $objDocument->upload_member;
$document->uploadMemberName = $objDocument->upload_member_name;
$document->uploadDate = $objDocument->upload_date;
$document->lasteditMemberId = $objDocument->lastedit_member;
$document->lasteditMemberName = $objDocument->lastedit_member_name;
$document->lasteditDate = $objDocument->lastedit_date;
$document->published = $objDocument->published;
// HOOK: modify the document
if (isset($GLOBALS['TL_HOOKS']['dmsModifyLoadedDocument']) && is_array($GLOBALS['TL_HOOKS']['dmsModifyLoadedDocument']))
{
foreach ($GLOBALS['TL_HOOKS']['dmsModifyLoadedDocument'] as $callback)
{
$this->import($callback[0]);
$document = $this->{$callback[0]}->{$callback[1]}($document, $objDocument);
}
}
return $document;
}
|
Builds a document from a database result.
@param DatabaseResult $objDocument The database result.
@return document The created document.
|
public function parse(HtmlNode $element, Inky $inkyInstance)
{
if($element->getAttribute('size-sm') || $element->getAttribute('size-lg'))
{
return $this->parseResponsive($element, $inkyInstance);
}
return $this->parseNormal($element, $inkyInstance);
}
|
<spacer size="{size}" />
---------------------------
<table class="spacer">
<tbody>
<tr>
<td height="{size}px" style="font-size:{size}px;line-height:{size}px;"> </td>
</tr>
</tbody>
</table>
@param HtmlNode $element
@param Inky $inkyInstance
@return HtmlNode
|
protected function parseNormal(HtmlNode $element, Inky $inkyInstance)
{
$size = $element->getAttribute('size') ? (int) $element->getAttribute('size') : 16;
$table = $this->table($this->getUsableAttributes($element));
$this->addCssClass('spacer', $table);
$body = $this->tbody();
$tr = $this->tr();
$td = $this->td();
$td->setAttribute('height', sprintf('%dpx', $size));
$td->setAttribute('style', sprintf('font-size:%dpx;line-height:%dpx;', $size, $size));
$td->addChild(new TextNode(' '));
$tr->addChild($td);
$body->addChild($tr);
$table->addChild($body);
return $table;
}
|
<spacer size="{size}" />
---------------------------
<table class="spacer">
<tbody>
<tr>
<td height="{size}px" style="font-size:{size}px;line-height:{size}px;"> </td>
</tr>
</tbody>
</table>
@param HtmlNode $element
@param Inky $inkyInstance
@return HtmlNode
|
protected function parseResponsive(HtmlNode $element, Inky $inkyInstance)
{
$sizes = [];
if($element->getAttribute('size-sm'))
{
$sizes[] = 'size-sm';
}
if($element->getAttribute('size-lg'))
{
$sizes[] = 'size-lg';
}
$tables = new Collection();
foreach($sizes as $spacer)
{
$size = (int) $element->getAttribute($spacer);
$table = $this->table($this->getUsableAttributes($element));
$responsiveClass = $spacer == 'size-sm' ? 'hide-for-large' : 'show-for-large';
$this->addCssClass('spacer '.$responsiveClass, $table);
$body = $this->tbody();
$tr = $this->tr();
$td = $this->td();
$td->setAttribute('height', sprintf('%dpx', $size));
$td->setAttribute('style', sprintf('font-size:%dpx;line-height:%dpx;', $size, $size));
$td->addChild(new TextNode(' '));
$tr->addChild($td);
$body->addChild($tr);
$table->addChild($body);
$tables[] = $table;
}
return $tables;
}
|
<spacer size-sm="{size-sm}" size-lg="{size-lg}" />
---------------------------
<table class="spacer hide-for-large">
<tbody>
<tr>
<td height="{size-sm}px" style="font-size:{size-sm}px;line-height:{size-sm}px;"> </td>
</tr>
</tbody>
</table>
<table class="spacer show-for-large">
<tbody>
<tr>
<td height="{size-lg}px" style="font-size:{size-lg}px;line-height:{size-lg}px;"> </td>
</tr>
</tbody>
</table>
@param HtmlNode $element
@param Inky $inkyInstance
@return HtmlNode
|
public static function fromLine($line, array $lineOptions)
{
$line = \json_decode($line, true);
$method = Inflector::camelize($line['type']) . 'FromLine';
if (\method_exists(\get_class(new static()), $method) && $method !== 'FromLine') {
return static::$method($line, $lineOptions);
}
throw new \Exception('Unknown message type: ' . $line['type']);
}
|
@param string $line
@throws \Exception
@return mixed
|
public static function getBaseDirectory($blnAppendTrailingSlash)
{
$path = \FilesModel::findByUuid($GLOBALS['TL_CONFIG']['dmsBaseDirectory'])->path;
if ($blnAppendTrailingSlash)
{
$path .= "/";
}
return $path;
}
|
Return base directory for the DMS documents, defined in system settings.
@param bool $blnAppendTrailingSlash True if a trailing slash should be appended.
@return string The path to the base directory.
|
public static function getPreviewDirectory($blnAppendTrailingSlash)
{
$path = self::getBaseDirectory(true) . self::DIRECTORY_NAME_PREVIEW;
if ($blnAppendTrailingSlash)
{
$path .= "/";
}
return $path;
}
|
Return preview directory for the DMS document preview images.
@param bool $blnAppendTrailingSlash True if a trailing slash should be appended.
@return string The path to the preview directory.
|
public static function getTempDirectory($blnAppendTrailingSlash)
{
$path = self::getBaseDirectory(true) . self::DIRECTORY_NAME_TEMP;
if ($blnAppendTrailingSlash)
{
$path .= "/";
}
return $path;
}
|
Return temp directory for the DMS documents.
@param bool $blnAppendTrailingSlash True if a trailing slash should be appended.
@return string The path to the temp directory.
|
public static function getMaxUploadFileSize($strUnit, $blnFormatted)
{
$arrValue = deserialize($GLOBALS['TL_CONFIG']['dmsMaxUploadFileSize']);
$dmsUnit = $arrValue['unit'];
$dmsVal = \Document::convertFileSize((double) $arrValue['value'], $dmsUnit, $strUnit);
if ($blnFormatted)
{
return \Document::formatFileSize($dmsVal, $strUnit);
}
return $dmsVal;
}
|
Return the maximum allowed upload file size, defined in system settings.
@param string $strUnit The file size unit.
@param bool $blnFormatted True if the file size should be returned as formatted string (with unit).
@return mixed The file size for the given unit (as int or formatted as string).
|
private function initDirectoryStructure()
{
if (!file_exists(TL_ROOT . '/' . $this->getDmsBaseDirectory()))
{
mkdir(TL_ROOT . '/' . $this->getDmsBaseDirectory(), 0775, true);
$objDir = \Dbafs::addResource($this->getDmsBaseDirectory());
$objFolder = new \Folder($this->getDmsBaseDirectory());
$objFolder->unprotect();
mkdir(TL_ROOT . '/' . $this->getDmsBaseDirectory() . "/temp", 0775, true);
$objDir = \Dbafs::addResource($this->getDmsBaseDirectory() . "/temp");
}
}
|
Init the directory structure
Create structure if not exists
|
private function initSystemSettings()
{
if (\Config::get(self::DMS_BASE_DIRECTORY_KEY) && \Config::get(self::DMS_MAX_UPLOAD_FILE_SIZE_KEY))
{
return;
}
\System::log('Running init script for setting default DMS settings, if missing.', __METHOD__, TL_CONFIGURATION);
if (!\Config::get(self::DMS_BASE_DIRECTORY_KEY))
{
\System::log('Setting default DMS base directory to "' . $this->getDmsBaseDirectory() . '".', __METHOD__, TL_CONFIGURATION);
$uuid = null;
$objDatabase = \Database::getInstance();
$objDir = $objDatabase->prepare("SELECT * FROM tl_files WHERE path=?")
->limit(1)
->execute($this->getDmsBaseDirectory());
if ($objDir->next())
{
$uuid = \StringUtil::binToUuid($objDir->uuid);
}
if ($uuid == null)
{
if (file_exists(TL_ROOT . '/' . $this->getDmsBaseDirectory()))
{
$objDir = \Dbafs::addResource($this->getDmsBaseDirectory());
$uuid = \StringUtil::binToUuid($objDir->uuid);
}
else
{
\System::log('Initialization of system setting for DMS failed, because default base directory does not exists.', __METHOD__, TL_ERROR);
return;
}
}
if ($uuid != null)
{
\Config::persist(self::DMS_BASE_DIRECTORY_KEY, $uuid);
}
}
if (!\Config::get(self::DMS_MAX_UPLOAD_FILE_SIZE_KEY))
{
\System::log('Setting default DMS max. upload file size to "5 MB".', __METHOD__, TL_CONFIGURATION);
\Config::persist(self::DMS_MAX_UPLOAD_FILE_SIZE_KEY, serialize(self::DMS_MAX_UPLOAD_FILE_SIZE_VALUE));
}
}
|
Init the system setting
Set base directoy, if not set
|
public function decode($binary, array $tagMap = []) : AbstractType
{
$this->startEncoding($binary, $tagMap);
if ($this->maxLen === 0) {
throw new InvalidArgumentException('The data to decode cannot be empty.');
} elseif ($this->maxLen === 1) {
throw new PartialPduException('Received only 1 byte of data.');
}
$type = $this->decodeBytes(true);
$this->stopEncoding();
return $type;
}
|
{@inheritdoc}
|
public function complete(IncompleteType $type, int $tagType, array $tagMap = []) : AbstractType
{
$lastPos = $this->lastPos;
$this->startEncoding($type->getValue(), $tagMap);
$newType = $this->decodeBytes(false, $tagType, $this->maxLen, $type->getIsConstructed(), AbstractType::TAG_CLASS_UNIVERSAL);
$this->stopEncoding();
$newType->setTagNumber($type->getTagNumber())
->setTagClass($type->getTagClass());
$this->lastPos = $lastPos;
return $newType;
}
|
{@inheritdoc}
|
public function setTagMap(int $class, array $map)
{
if (isset($this->tagMap[$class])) {
$this->tagMap[$class] = $map;
}
return $this;
}
|
Map universal types to specific tag class values when decoding.
@param int $class
@param array $map
@return $this
|
public function setOptions(array $options)
{
if (isset($options['bitstring_padding']) && \is_string($options['bitstring_padding'])) {
$this->options['bitstring_padding'] = $options['bitstring_padding'];
}
return $this;
}
|
Set the options for the encoder.
@param array $options
@return $this
|
protected function getVlqBytesToInt()
{
$value = 0;
$isBigInt = false;
for ($this->pos; $this->pos < $this->maxLen; $this->pos++) {
if (!$isBigInt) {
$lshift = $value << 7;
# An overflow bitshift will result in a negative number. This will check if GMP is available and flip it
# to a bigint safe method in one shot.
if ($lshift < 0) {
$isBigInt = true;
$this->throwIfBigIntGmpNeeded(true);
$value = \gmp_init($value);
}
}
if ($isBigInt) {
$lshift = \gmp_mul($value, \gmp_pow('2', 7));
}
$orVal = (\ord($this->binary[$this->pos]) & 0x7f);
if ($isBigInt) {
$value = \gmp_or($lshift, \gmp_init($orVal));
} else {
$value = $lshift | $orVal;
}
# We have reached the last byte if the MSB is not set.
if ((\ord($this->binary[$this->pos]) & 0x80) === 0) {
$this->pos++;
return $isBigInt ? \gmp_strval($value) : $value;
}
}
throw new EncoderException('Expected an ending byte to decode a VLQ, but none was found.');
}
|
Given what should be VLQ bytes represent an int, get the int and the length of bytes.
@return string|int
@throws EncoderException
|
protected function intToVlqBytes($int)
{
$bigint = \is_float($int + 0);
$this->throwIfBigIntGmpNeeded($bigint);
if ($bigint) {
$int = \gmp_init($int);
$bytes = \chr(\gmp_intval(\gmp_and(\gmp_init(0x7f), $int)));
$int = \gmp_div($int, \gmp_pow(2, 7));
$intVal = \gmp_intval($int);
} else {
$bytes = \chr(0x7f & $int);
$int >>= 7;
$intVal = $int;
}
while ($intVal > 0) {
if ($bigint) {
$bytes = \chr(\gmp_intval(\gmp_or(\gmp_and(\gmp_init(0x7f), $int), \gmp_init(0x80)))).$bytes;
$int = \gmp_div($int, \gmp_pow('2', 7));
$intVal = \gmp_intval($int);
} else {
$bytes = \chr((0x7f & $int) | 0x80).$bytes;
$int >>= 7;
$intVal = $int;
}
}
return $bytes;
}
|
Get the bytes that represent variable length quantity.
@param string|int $int
@return string
@throws EncoderException
|
protected function executeLocked(InputInterface $input, OutputInterface $output)
{
$this->io = new SymfonyStyle($input, $output);
$this->rootDir = $this->getContainer()->getParameter('kernel.project_dir');
$twig = $this->getContainer()->get('twig');
$resultFile = $this->rootDir . DIRECTORY_SEPARATOR . 'encore.bundles.js';
echo PHP_EOL;
@unlink($resultFile);
$config = $this->getContainer()->getParameter('huh.encore');
// js
if (isset($config['encore']['entries']) && is_array($config['encore']['entries'])) {
// entries
$entries = [];
foreach ($config['encore']['entries'] as $entry) {
$preparedEntry = [
'name' => $entry['name']
];
$preparedEntry['file'] = './' . preg_replace('@^\.?\/@i', '', $entry['file']);
$entries[] = $preparedEntry;
}
$content = $twig->render('@HeimrichHannotContaoEncore/encore_bundles.js.twig', [
'entries' => $entries
]);
file_put_contents($resultFile, $content);
$this->io->success('Created encore.bundles.js in your project root. You can now require it in your webpack.config.js!');
} else {
$this->io->warning('No entries found in yml config huh.encore.entries -> No encore.bundles.js is created.');
// echo 'Warning: No encore.bundles.js is created.' . PHP_EOL . PHP_EOL;
}
return 0;
}
|
{@inheritdoc}
|
public function beforeSuite(SuiteEvent $event)
{
if (!$this->enabled) {
return;
}
$filter = $this->coverage->filter();
array_map(
[$filter, 'addDirectoryToWhitelist'],
$this->options['whitelist']
);
array_map(
[$filter, 'removeDirectoryFromWhitelist'],
$this->options['blacklist']
);
array_map(
[$filter, 'addFileToWhitelist'],
$this->options['whitelist_files']
);
array_map(
[$filter, 'removeFileFromWhitelist'],
$this->options['blacklist_files']
);
}
|
Note: We use array_map() instead of array_walk() because the latter expects
the callback to take the value as the first and the index as the seconds parameter.
|
public function up(): void
{
Schema::create(config('cortex.bookings.tables.services'), function (Blueprint $table) {
// Columns
$table->increments('id');
$table->string('slug');
$table->{$this->jsonable()}('name');
$table->{$this->jsonable()}('description')->nullable();
$table->boolean('is_active')->default(true);
$table->decimal('base_cost')->default('0.00');
$table->decimal('unit_cost')->default('0.00');
$table->string('currency', 3);
$table->string('unit')->default('hour');
$table->smallInteger('maximum_units')->unsigned()->nullable();
$table->smallInteger('minimum_units')->unsigned()->nullable();
$table->tinyInteger('is_cancelable')->unsigned()->default(0);
$table->tinyInteger('is_recurring')->unsigned()->default(0);
$table->mediumInteger('sort_order')->unsigned()->default(0);
$table->mediumInteger('capacity')->unsigned()->nullable();
$table->string('style')->nullable();
$table->auditableAndTimestamps();
$table->softDeletes();
});
}
|
Run the migrations.
@return void
|
public function findMatchingRoute( ProvidesDestinationInfo $destinationInfo ) : RoutesToReadHandler
{
$requiredHandlerType = HandlerMethodInterfaceMap::HTTP_METHODS[ $destinationInfo->getRequestMethod() ];
$uri = $destinationInfo->getUri();
foreach ( $this->getRoutes() as $route )
{
if ( !($route instanceof RoutesToReadHandler) )
{
continue;
}
if ( $route->matches( $uri ) && $route->getRequestHandler() instanceof $requiredHandlerType )
{
return $route;
}
}
throw (new UnresolvedRequest())->withDestinationInfo( $destinationInfo );
}
|
@param ProvidesDestinationInfo $destinationInfo
@throws UnresolvedRequest
@return RoutesToReadHandler
|
public function import(Event $event, ImportRecordsDataTable $importRecordsDataTable)
{
return $importRecordsDataTable->with([
'resource' => $event,
'tabs' => 'adminarea.events.tabs',
'url' => route('adminarea.events.stash'),
'id' => "adminarea-events-{$event->getRouteKey()}-import-table",
])->render('cortex/foundation::adminarea.pages.datatable-dropzone');
}
|
Import events.
@param \Cortex\Bookings\Models\Event $event
@param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable
@return \Illuminate\View\View
|
protected function form(Event $event)
{
$tags = app('rinvex.tags.tag')->pluck('name', 'id');
$event->duration = (optional($event->starts_at)->format(config('app.date_format')) ?? date(config('app.date_format'))).' - '.(optional($event->ends_at)->format(config('app.date_format')) ?? date(config('app.date_format')));
return view('cortex/bookings::adminarea.pages.event', compact('event', 'tags'));
}
|
Show event create/edit form.
@param \Cortex\Bookings\Models\Event $event
@return \Illuminate\View\View
|
public function destroy(Event $event)
{
$event->delete();
return intend([
'url' => route('adminarea.events.index'),
'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/bookings::common.event'), 'identifier' => $event->name])],
]);
}
|
Destroy given event.
@param \Cortex\Bookings\Models\Event $event
@throws \Exception
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
|
public function findMatchingRoutes( string $uri ) : array
{
$matchedRoutes = [];
foreach ( $this->getRoutes() as $route )
{
if ( $route->matches( $uri ) )
{
$matchedRoutes[] = $route;
}
}
return $matchedRoutes;
}
|
@param string $uri
@return RoutesToHandler[]
|
public function query()
{
$query = app($this->model)->query()->with(['ticketable']);
return $this->applyScopes($query);
}
|
Get the query object to be processed by dataTables.
@return \Illuminate\Database\Eloquent\Builder|\Illuminate\Database\Query\Builder|\Illuminate\Support\Collection
|
public function import(Service $service, ImportRecordsDataTable $importRecordsDataTable)
{
return $importRecordsDataTable->with([
'resource' => $service,
'tabs' => 'adminarea.services.tabs',
'url' => route('adminarea.services.stash'),
'id' => "adminarea-services-{$service->getRouteKey()}-import-table",
])->render('cortex/foundation::adminarea.pages.datatable-dropzone');
}
|
Import services.
@param \Cortex\Bookings\Models\Service $service
@param \Cortex\Foundation\DataTables\ImportRecordsDataTable $importRecordsDataTable
@return \Illuminate\View\View
|
public function hoard(ImportFormRequest $request)
{
foreach ((array) $request->get('selected_ids') as $recordId) {
$record = app('cortex.foundation.import_record')->find($recordId);
try {
$fillable = collect($record['data'])->intersectByKeys(array_flip(app('rinvex.bookings.service')->getFillable()))->toArray();
tap(app('rinvex.bookings.service')->firstOrNew($fillable), function ($instance) use ($record) {
$instance->save() && $record->delete();
});
} catch (Exception $exception) {
$record->notes = $exception->getMessage().(method_exists($exception, 'getMessageBag') ? "\n".json_encode($exception->getMessageBag())."\n\n" : '');
$record->status = 'fail';
$record->save();
}
}
return intend([
'back' => true,
'with' => ['success' => trans('cortex/foundation::messages.import_complete')],
]);
}
|
Hoard services.
@param \Cortex\Foundation\Http\Requests\ImportFormRequest $request
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
|
public function update(BookingFormRequest $request, ServiceBooking $serviceBooking): int
{
return $this->process($request, $serviceBooking);
}
|
Update given booking.
@param \Cortex\Bookings\Http\Requests\Adminarea\BookingFormRequest $request
@param \Cortex\Bookings\Models\ServiceBooking $serviceBooking
@return int
|
protected function process(FormRequest $request, ServiceBooking $serviceBooking): int
{
// Prepare required input fields
$data = $request->validated();
// Save booking
$serviceBooking->fill($data)->save();
return $serviceBooking->getKey();
}
|
Process stored/updated booking.
@param \Illuminate\Foundation\Http\FormRequest $request
@param \Cortex\Bookings\Models\ServiceBooking $serviceBooking
@return int
|
public function destroy(Service $service, ServiceBooking $serviceBooking)
{
$service->bookings()->where($serviceBooking->getKeyName(), $serviceBooking->getKey())->first()->delete();
return intend([
'url' => route('adminarea.services.bookings.index'),
'with' => [
'warning' => trans('cortex/foundation::messages.resource_deleted', [
'resource' => trans('cortex/bookings::common.service_booking'),
'identifier' => $service->name.':'.$serviceBooking->id,
]),
],
]);
return $serviceBooking->getKey();
}
|
Destroy given booking.
@param \Cortex\Bookings\Models\Service $service
@param \Cortex\Bookings\Models\ServiceBooking $serviceBooking
@throws \Exception
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
|
public function store(EventTicketFormRequest $request, Event $event, EventTicket $eventTicket)
{
return $this->process($request, $event, $eventTicket);
}
|
Store new event.
@param \Cortex\Bookings\Http\Requests\Adminarea\EventTicketFormRequest $request
@param \Cortex\Bookings\Models\Event $event
@param \Cortex\Bookings\Models\EventTicket $eventTicket
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
|
protected function process(FormRequest $request, Event $event, EventTicket $eventTicket)
{
// Prepare required input fields
$data = $request->validated();
// Save event
$eventTicket->fill($data)->save();
return intend([
'url' => route('adminarea.events.tickets.index', ['event' => $event]),
'with' => ['success' => trans('cortex/foundation::messages.resource_saved', ['resource' => trans('cortex/bookings::common.event_ticket'), 'identifier' => $eventTicket->name])],
]);
}
|
Process stored/updated event.
@param \Illuminate\Foundation\Http\FormRequest $request
@param \Cortex\Bookings\Models\Event $event
@param \Cortex\Bookings\Models\EventTicket $eventTicket
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
|
public function destroy(Event $event, EventTicket $eventTicket)
{
$event->tickets()->where($eventTicket->getKeyName(), $eventTicket->getKey())->first()->delete();
return intend([
'url' => route('adminarea.events.tickets.index', ['event' => $event]),
'with' => ['warning' => trans('cortex/foundation::messages.resource_deleted', ['resource' => trans('cortex/bookings::common.event_ticket'), 'identifier' => $eventTicket->name])],
]);
}
|
Destroy given event.
@param \Cortex\Bookings\Models\Event $event
@param \Cortex\Bookings\Models\EventTicket $eventTicket
@throws \Exception
@return \Illuminate\Http\JsonResponse|\Illuminate\Http\RedirectResponse
|
private function getRequest( array $uriParams ) : ProvidesReadRequestData
{
$cookies = $this->config->getCookies();
$requestData = array_merge( $_GET, $uriParams );
$requestInput = new ReadRequestInput( $requestData );
return new ReadRequest( $this->requestInfo, $cookies, $requestInput );
}
|
@param array $uriParams
@return ProvidesReadRequestData
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.