sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function updateParameter(ChangelanguageNavigationEvent $event) { $currentParam = $this->manager->getParameterName(); $newParam = $this->manager->getParameterName($event->getNavigationItem()->getRootPage()->id); $parameters = $event->getUrlParameterBag(); $attributes = $parameters->getUrlAttributes(); if (!isset($attributes[$currentParam])) { return; } $attributes[$newParam] = $attributes[$currentParam]; unset($attributes[$currentParam]); $parameters->setUrlAttributes($attributes); }
Update the parameter name. @param ChangelanguageNavigationEvent $event
entailment
protected function compile() { $rootCategoryId = (int) $this->news_categoriesRoot; // Set the custom categories either by root ID or by manual selection if ($this->news_customCategories) { $customCategories = StringUtil::deserialize($this->news_categories, true); } else { $subcategories = NewsCategoryModel::findPublishedByPid($rootCategoryId); $customCategories = ($subcategories !== null) ? $subcategories->fetchEach('id') : []; } // Get the subcategories of custom categories if (\count($customCategories) > 0 && $this->news_includeSubcategories) { $customCategories = NewsCategoryModel::getAllSubcategoriesIds($customCategories); } // First, fetch the active categories $this->activeCategories = $this->getActiveCategories($customCategories); // Then, fetch the inactive categories $inactiveCategories = $this->getInactiveCategories($customCategories); // Generate active categories if ($this->activeCategories !== null) { $this->Template->activeCategories = $this->renderNewsCategories($rootCategoryId, $this->activeCategories->fetchEach('id'), true); // Add the canonical URL tag if ($this->news_enableCanonicalUrls) { $GLOBALS['TL_HEAD'][] = sprintf('<link rel="canonical" href="%s">', $GLOBALS['objPage']->getAbsoluteUrl()); } // Add the "reset categories" link if ($this->news_resetCategories) { $this->Template->resetUrl = $this->getTargetPage()->getFrontendUrl(); } } else { $this->Template->activeCategories = ''; $this->Template->resetUrl = false; } // Generate inactive categories if ($inactiveCategories !== null) { $this->Template->inactiveCategories = $this->renderNewsCategories($rootCategoryId, $inactiveCategories->fetchEach('id')); } else { $this->Template->inactiveCategories = ''; } }
Generate the module.
entailment
protected function getActiveCategories(array $customCategories = []) { $param = System::getContainer()->get('codefog_news_categories.manager')->getParameterName(); if (!($aliases = Input::get($param))) { return null; } $aliases = StringUtil::trimsplit(static::getCategorySeparator(), $aliases); $aliases = array_unique(array_filter($aliases)); if (count($aliases) === 0) { return null; } // Get the categories that do have news assigned $models = NewsCategoryModel::findPublishedByArchives($this->news_archives, $customCategories, $aliases); // No models have been found but there are some aliases present if ($models === null && count($aliases) !== 0) { Controller::redirect($this->getTargetPage()->getFrontendUrl()); } // Validate the provided aliases with the categories found if ($models !== null) { $realAliases = []; /** @var NewsCategoryModel $model */ foreach ($models as $model) { $realAliases[] = $this->manager->getCategoryAlias($model, $GLOBALS['objPage']); } if (count(array_diff($aliases, $realAliases)) > 0) { Controller::redirect($this->getTargetPage()->getFrontendUrl(sprintf( '/%s/%s', $this->manager->getParameterName($GLOBALS['objPage']->rootId), implode(static::getCategorySeparator(), $realAliases) ))); } } return $models; }
Get the active categories @param array $customCategories @return Collection|null
entailment
protected function getInactiveCategories(array $customCategories = []) { // Find only the categories that still can display some results combined with active categories if ($this->activeCategories !== null) { $columns = []; $values = []; // Collect the news that match all active categories /** @var NewsCategoryModel $activeCategory */ foreach ($this->activeCategories as $activeCategory) { $criteria = new NewsCriteria(System::getContainer()->get('contao.framework')); try { $criteria->setBasicCriteria($this->news_archives); $criteria->setCategory($activeCategory->id, false, (bool) $this->news_includeSubcategories); } catch (NoNewsException $e) { continue; } $columns = array_merge($columns, $criteria->getColumns()); $values = array_merge($values, $criteria->getValues()); } // Should not happen but you never know if (count($columns) === 0) { return null; } $newsIds = Database::getInstance() ->prepare('SELECT id FROM tl_news WHERE ' . implode(' AND ', $columns)) ->execute($values) ->fetchEach('id') ; if (count($newsIds) === 0) { return null; } $categoryIds = Model::getRelatedValues('tl_news', 'categories', $newsIds); $categoryIds = \array_map('intval', $categoryIds); $categoryIds = \array_unique(\array_filter($categoryIds)); // Include the parent categories if ($this->news_includeSubcategories) { foreach ($categoryIds as $categoryId) { $categoryIds = array_merge($categoryIds, Database::getInstance()->getParentRecords($categoryId, 'tl_news_category')); } } // Remove the active categories, so they are not considered again $categoryIds = array_diff($categoryIds, $this->activeCategories->fetchEach('id')); // Filter by custom categories if (count($customCategories) > 0) { $categoryIds = array_intersect($categoryIds, $customCategories); } if (count($categoryIds) === 0) { return null; } $customCategories = $categoryIds; } return NewsCategoryModel::findPublishedByArchives($this->news_archives, $customCategories); }
Get the inactive categories @param array $customCategories @return Collection|null
entailment
protected function getTargetPage() { static $page; if (null === $page) { if ($this->jumpTo > 0 && (int) $GLOBALS['objPage']->id !== (int) $this->jumpTo && null !== ($target = PageModel::findPublishedById($this->jumpTo)) ) { $page = $target; } else { $page = $GLOBALS['objPage']; } } return $page; }
Get the target page. @return PageModel
entailment
protected function getCurrentNewsCategories() { if (!($alias = Input::getAutoItem('items', false, true)) || null === ($news = NewsModel::findPublishedByParentAndIdOrAlias($alias, $this->news_archives)) ) { return []; } $ids = Model::getRelatedValues('tl_news', 'categories', $news->id); $ids = \array_map('intval', \array_unique($ids)); return $ids; }
Get the category IDs of the current news item. @return array
entailment
protected function renderNewsCategories($pid, array $ids, $isActiveCategories = false) { if (null === ($categories = NewsCategoryModel::findPublishedByIds($ids, $pid))) { return ''; } // Layout template fallback if (!$this->navigationTpl) { $this->navigationTpl = 'nav_newscategories'; } $template = new FrontendTemplate($this->navigationTpl); $template->type = \get_class($this); $template->cssID = $this->cssID; $template->level = 'level_1'; $template->showQuantity = $isActiveCategories ? false : (bool) $this->news_showQuantity; $template->isActiveCategories = $isActiveCategories; $items = []; $activeAliases = []; // Collect the active category parameters if ($this->activeCategories !== null) { /** @var NewsCategoryModel $activeCategory */ foreach ($this->activeCategories as $activeCategory) { $activeAliases[] = $this->manager->getCategoryAlias($activeCategory, $GLOBALS['objPage']); } } $resetUrl = $this->getTargetPage()->getFrontendUrl(); $parameterName = $this->manager->getParameterName($GLOBALS['objPage']->rootId); /** @var NewsCategoryModel $category */ foreach ($categories as $category) { $categoryAlias = $this->manager->getCategoryAlias($category, $GLOBALS['objPage']); // Add/remove the category alias to the active ones if (in_array($categoryAlias, $activeAliases, true)) { $aliases = array_diff($activeAliases, [$categoryAlias]); } else { $aliases = array_merge($activeAliases, [$categoryAlias]); } // Generate the category URL if there are any aliases to add, otherwise use the reset URL if (count($aliases) > 0) { $url = $this->getTargetPage()->getFrontendUrl(sprintf('/%s/%s', $parameterName, implode(static::getCategorySeparator(), $aliases))); } else { $url = $resetUrl; } $items[] = $this->generateItem( $url, $category->getTitle(), $category->getTitle(), $this->generateItemCssClass($category), in_array($categoryAlias, $activeAliases, true), $category ); } // Add first/last/even/odd classes RowClass::withKey('class')->addFirstLast()->addEvenOdd()->applyTo($items); $template->items = $items; return $template->parse(); }
Recursively compile the news categories and return it as HTML string. @param int $pid @param array $ids @param bool $isActiveCategories @return string
entailment
protected function generateItemCssClass(NewsCategoryModel $category) { $cssClasses = [$category->getCssClass()]; // Add the trail class if (\in_array((int) $category->id, $this->manager->getTrailIds($category), true)) { $cssClasses[] = 'trail'; } // Add the news trail class if (\in_array((int) $category->id, $this->currentNewsCategories, true)) { $cssClasses[] = 'news_trail'; } return \implode(' ', $cssClasses); }
Generate the item CSS class. @param NewsCategoryModel $category @return string
entailment
protected function compileYearlyMenu() { $arrData = array(); $time = \Date::floorToMinute(); $newsIds = $this->getFilteredNewsIds(); // Get the dates $objDates = $this->Database->query("SELECT FROM_UNIXTIME(date, '%Y') AS year, COUNT(*) AS count FROM tl_news WHERE pid IN(" . implode(',', array_map('intval', $this->news_archives)) . ")" . ((!BE_USER_LOGGED_IN || TL_MODE == 'BE') ? " AND (start='' OR start<='$time') AND (stop='' OR stop>'" . ($time + 60) . "') AND published='1'" : "") . ((count($newsIds) > 0) ? (" AND id IN (" . implode(',', $newsIds) . ")") : "") . " GROUP BY year ORDER BY year DESC"); while ($objDates->next()) { $arrData[$objDates->year] = $objDates->count; } // Sort the data ($this->news_order == 'ascending') ? ksort($arrData) : krsort($arrData); $arrItems = array(); $count = 0; $limit = count($arrData); // Prepare the navigation foreach ($arrData as $intYear=>$intCount) { $intDate = $intYear; $quantity = sprintf((($intCount < 2) ? $GLOBALS['TL_LANG']['MSC']['entry'] : $GLOBALS['TL_LANG']['MSC']['entries']), $intCount); $arrItems[$intYear]['date'] = $intDate; $arrItems[$intYear]['link'] = $intYear; $arrItems[$intYear]['href'] = $this->strUrl . '?year=' . $intDate; $arrItems[$intYear]['title'] = \StringUtil::specialchars($intYear . ' (' . $quantity . ')'); $arrItems[$intYear]['class'] = trim(((++$count == 1) ? 'first ' : '') . (($count == $limit) ? 'last' : '')); $arrItems[$intYear]['isActive'] = (\Input::get('year') == $intDate); $arrItems[$intYear]['quantity'] = $quantity; } $this->Template->yearly = true; $this->Template->items = $arrItems; $this->Template->showQuantity = ($this->news_showQuantity != ''); }
Generate the yearly menu
entailment
protected function compileMonthlyMenu() { $arrData = array(); $time = \Date::floorToMinute(); $newsIds = $this->getFilteredNewsIds(); // Get the dates $objDates = $this->Database->query("SELECT FROM_UNIXTIME(date, '%Y') AS year, FROM_UNIXTIME(date, '%m') AS month, COUNT(*) AS count FROM tl_news WHERE pid IN(" . implode(',', array_map('intval', $this->news_archives)) . ")" . ((!BE_USER_LOGGED_IN || TL_MODE == 'BE') ? " AND (start='' OR start<='$time') AND (stop='' OR stop>'" . ($time + 60) . "') AND published='1'" : "") . ((count($newsIds) > 0) ? (" AND id IN (" . implode(',', $newsIds) . ")") : "") . " GROUP BY year, month ORDER BY year DESC, month DESC"); while ($objDates->next()) { $arrData[$objDates->year][$objDates->month] = $objDates->count; } // Sort the data foreach (array_keys($arrData) as $key) { ($this->news_order == 'ascending') ? ksort($arrData[$key]) : krsort($arrData[$key]); } ($this->news_order == 'ascending') ? ksort($arrData) : krsort($arrData); $arrItems = array(); // Prepare the navigation foreach ($arrData as $intYear=>$arrMonth) { $count = 0; $limit = count($arrMonth); foreach ($arrMonth as $intMonth=>$intCount) { $intDate = $intYear . $intMonth; $intMonth = (intval($intMonth) - 1); $quantity = sprintf((($intCount < 2) ? $GLOBALS['TL_LANG']['MSC']['entry'] : $GLOBALS['TL_LANG']['MSC']['entries']), $intCount); $arrItems[$intYear][$intMonth]['date'] = $intDate; $arrItems[$intYear][$intMonth]['link'] = $GLOBALS['TL_LANG']['MONTHS'][$intMonth] . ' ' . $intYear; $arrItems[$intYear][$intMonth]['href'] = $this->strUrl . '?month=' . $intDate; $arrItems[$intYear][$intMonth]['title'] = \StringUtil::specialchars($GLOBALS['TL_LANG']['MONTHS'][$intMonth].' '.$intYear . ' (' . $quantity . ')'); $arrItems[$intYear][$intMonth]['class'] = trim(((++$count == 1) ? 'first ' : '') . (($count == $limit) ? 'last' : '')); $arrItems[$intYear][$intMonth]['isActive'] = (\Input::get('month') == $intDate); $arrItems[$intYear][$intMonth]['quantity'] = $quantity; } } $this->Template->items = $arrItems; $this->Template->showQuantity = ($this->news_showQuantity != '') ? true : false; $this->Template->url = $this->strUrl . '?'; $this->Template->activeYear = \Input::get('year'); }
Generate the monthly menu
entailment
protected function generateCategoryUrl() { /** @var $target PageModel */ if ($this->jumpTo && ($target = $this->objModel->getRelated('jumpTo')) instanceof PageModel) { $page = $target; } else { $page = $GLOBALS['objPage']; } $manager = System::getContainer()->get('codefog_news_categories.manager'); /** @var NewsCategoryModel $category */ $category = NewsCategoryModel::findPublishedByIdOrAlias(Input::get($manager->getParameterName())); // Generate the category URL if ($category !== null) { $url = $manager->generateUrl($category, $page); } else { // Generate the regular URL $url = $page->getFrontendUrl(); } return $url; }
Generate the menu URL with category @return string
entailment
protected function getFilteredNewsIds() { try { $criteria = System::getContainer() ->get('codefog_news_categories.news_criteria_builder') ->getCriteriaForMenuModule($this->news_archives, $this); } catch (CategoryNotFoundException $e) { throw new PageNotFoundException($e->getMessage()); } if ($criteria === null) { return []; } $table = $criteria->getNewsModelAdapter()->getTable(); return Database::getInstance() ->prepare("SELECT id FROM $table WHERE " . implode(' AND ', $criteria->getColumns())) ->execute($criteria->getValues()) ->fetchEach('id'); }
Get the filtered news IDs @return array @throws PageNotFoundException
entailment
private function reloadNewsCategoriesWidget(DataContainer $dc) { /** * @var Database * @var Input $input */ $db = $this->framework->createInstance(Database::class); $input = $this->framework->getAdapter(Input::class); $id = $input->get('id'); $field = $dc->inputName = $input->post('name'); // Handle the keys in "edit multiple" mode if ('editAll' === $input->get('act')) { $id = \preg_replace('/.*_([0-9a-zA-Z]+)$/', '$1', $field); $field = \preg_replace('/(.*)_[0-9a-zA-Z]+$/', '$1', $field); } $dc->field = $field; // The field does not exist if (!isset($GLOBALS['TL_DCA'][$dc->table]['fields'][$field])) { $this->logger->log( LogLevel::ERROR, \sprintf('Field "%s" does not exist in DCA "%s"', $field, $dc->table), ['contao' => new ContaoContext(__METHOD__, TL_ERROR)] ); throw new BadRequestHttpException('Bad request'); } $row = null; $value = null; // Load the value if ('overrideAll' !== $input->get('act') && $id > 0 && $db->tableExists($dc->table)) { $row = $db->prepare('SELECT * FROM '.$dc->table.' WHERE id=?')->execute($id); // The record does not exist if ($row->numRows < 1) { $this->logger->log( LogLevel::ERROR, \sprintf('A record with the ID "%s" does not exist in table "%s"', $id, $dc->table), ['contao' => new ContaoContext(__METHOD__, TL_ERROR)] ); throw new BadRequestHttpException('Bad request'); } $value = $row->$field; $dc->activeRecord = $row; } // Call the load_callback if (\is_array($GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['load_callback'])) { /** @var System $systemAdapter */ $systemAdapter = $this->framework->getAdapter(System::class); foreach ($GLOBALS['TL_DCA'][$dc->table]['fields'][$field]['load_callback'] as $callback) { if (\is_array($callback)) { $value = $systemAdapter->importStatic($callback[0])->{$callback[1]}($value, $dc); } elseif (\is_callable($callback)) { $value = $callback($value, $dc); } } } // Set the new value $value = $input->post('value', true); // Convert the selected values if ($value) { /** @var StringUtil $stringUtilAdapter */ $stringUtilAdapter = $this->framework->getAdapter(StringUtil::class); $value = $stringUtilAdapter->trimsplit("\t", $value); $value = \serialize($value); } /** @var NewsCategoriesPickerWidget $strClass */ $strClass = $GLOBALS['BE_FFL']['newsCategoriesPicker']; /** @var NewsCategoriesPickerWidget $objWidget */ $objWidget = new $strClass($strClass::getAttributesFromDca($GLOBALS['TL_DCA'][$dc->table]['fields'][$field], $dc->inputName, $value, $field, $dc->table, $dc)); throw new ResponseException(new Response($objWidget->generate())); }
Reload the news categories widget. @param DataContainer $dc
entailment
public function onLoadCallback(DataContainer $dc) { if (!$dc->id) { return; } /** @var Input $input */ $input = $this->framework->getAdapter(Input::class); // Handle the edit all modes differently if ($input->get('act') === 'editAll' || $input->get('act') === 'overrideAll') { $categories = $this->db->fetchColumn('SELECT categories FROM tl_news_archive WHERE limitCategories=1 AND id=?', [$dc->id]); } else { $categories = $this->db->fetchColumn('SELECT categories FROM tl_news_archive WHERE limitCategories=1 AND id=(SELECT pid FROM tl_news WHERE id=?)', [$dc->id]); } if (!$categories || 0 === \count($categories = StringUtil::deserialize($categories, true))) { return; } $GLOBALS['TL_DCA'][$dc->table]['fields']['categories']['eval']['rootNodes'] = $categories; }
On data container load. Limit the categories set in the news archive settings. @param DataContainer $dc
entailment
public function onSubmitCallback(DataContainer $dc) { // Return if the user is allowed to assign categories or the record is not new if ($this->permissionChecker->canUserAssignCategories() || $dc->activeRecord->tstamp > 0) { return; } $dc->field = 'categories'; $relations = new Relations(); $relations->updateRelatedRecords($this->permissionChecker->getUserDefaultCategories(), $dc); // Reset back the field property $dc->field = null; }
On submit record. Update the category relations. @param DataContainer $dc
entailment
public function onCategoriesOptionsCallback() { /** @var Input $input */ $input = $this->framework->getAdapter(Input::class); // Do not generate the options for other views than listings if ($input->get('act') && $input->get('act') !== 'select') { return []; } return $this->generateOptionsRecursively(); }
On categories options callback @return array
entailment
private function generateOptionsRecursively($pid = 0, $prefix = '') { $options = []; $records = $this->db->fetchAll('SELECT * FROM tl_news_category WHERE pid=? ORDER BY sorting', [$pid]); foreach ($records as $record) { $options[$record['id']] = $prefix . $record['title']; foreach ($this->generateOptionsRecursively($record['id'], $record['title'] . ' / ') as $k => $v) { $options[$k] = $v; } } return $options; }
Generate the options recursively @param int $pid @param string $prefix @return array
entailment
public function getCssClass() { $cssClasses = [ 'news_category_'.$this->id, 'category_'.$this->id, ]; if ($this->cssClass) { $cssClasses[] = $this->cssClass; } return \implode(' ', \array_unique($cssClasses)); }
Get the CSS class. @return string
entailment
public static function findPublishedByArchives(array $archives, array $ids = [], array $aliases = []) { if (0 === \count($archives) || false === ($relation = Relations::getRelation('tl_news', 'categories'))) { return null; } $t = static::getTableAlias(); $values = []; // Start sub select query for relations $subSelect = "SELECT {$relation['related_field']} FROM {$relation['table']} WHERE {$relation['reference_field']} IN (SELECT id FROM tl_news WHERE pid IN (".\implode(',', \array_map('intval', $archives)).')'; // Include only the published news items if (!BE_USER_LOGGED_IN) { $time = Date::floorToMinute(); $subSelect .= ' AND (start=? OR start<=?) AND (stop=? OR stop>?) AND published=?'; $values = \array_merge($values, ['', $time, '', $time + 60, 1]); } // Finish sub select query for relations $subSelect .= ')'; // Columns definition start $columns = ["$t.id IN ($subSelect)"]; // Filter by custom categories if (\count($ids) > 0) { $columns[] = "$t.id IN (".\implode(',', \array_map('intval', $ids)).')'; } // Filter by custom aliases if (\count($aliases) > 0) { $columns[] = "$t.alias IN ('".\implode("','", $aliases)."')"; } if (!BE_USER_LOGGED_IN) { $columns[] = "$t.published=?"; $values[] = 1; } return static::findBy($columns, $values, ['order' => "$t.sorting"]); }
Find published news categories by news criteria. @param array $archives @param array $ids @param array $aliases @return Collection|null
entailment
public static function findPublishedByIdOrAlias($idOrAlias) { $values = []; $columns = []; $t = static::getTableAlias(); // Determine the alias condition if (is_numeric($idOrAlias)) { $columns[] = "$t.id=?"; $values[] = (int) $idOrAlias; } else { if (MultilingualHelper::isActive()) { $columns[] = '(t1.alias=? OR t2.alias=?)'; $values[] = $idOrAlias; $values[] = $idOrAlias; } else { $columns[] = "$t.alias=?"; $values[] = $idOrAlias; } } if (!BE_USER_LOGGED_IN) { $columns[] = "$t.published=?"; $values[] = 1; } return static::findOneBy($columns, $values); }
Find published category by ID or alias. @param string $idOrAlias @return NewsCategoryModel|null
entailment
public static function findPublishedByIds(array $ids, $pid = null) { if (0 === \count($ids)) { return null; } $t = static::getTableAlias(); $columns = ["$t.id IN (".\implode(',', \array_map('intval', $ids)).')']; $values = []; // Filter by pid if (null !== $pid) { $columns[] = "$t.pid=?"; $values[] = $pid; } if (!BE_USER_LOGGED_IN) { $columns[] = "$t.published=?"; $values[] = 1; } return static::findBy($columns, $values, ['order' => "$t.sorting"]); }
Find published news categories by parent ID and IDs. @param array $ids @param int|null $pid @return Collection|null
entailment
public static function findPublishedByPid($pid) { $t = static::getTableAlias(); $columns = ["$t.pid=?"]; $values = [$pid]; if (!BE_USER_LOGGED_IN) { $columns[] = "$t.published=?"; $values[] = 1; } return static::findBy($columns, $values, ['order' => "$t.sorting"]); }
Find published news categories by parent ID. @param int $pid @return Collection|null
entailment
public static function findPublishedByNews($newsId) { if (0 === \count($ids = Model::getRelatedValues('tl_news', 'categories', $newsId))) { return null; } $t = static::getTableAlias(); $columns = ["$t.id IN (".\implode(',', \array_map('intval', \array_unique($ids))).')']; $values = []; if (!BE_USER_LOGGED_IN) { $columns[] = "$t.published=?"; $values[] = 1; } return static::findBy($columns, $values, ['order' => "$t.sorting"]); }
Find the published categories by news. @param int|array $newsId @return Collection|null
entailment
public static function getUsage(array $archives = [], $category = null, $includeSubcategories = false, array $cumulativeCategories = []) { $t = NewsModel::getTable(); // Include the subcategories if (null !== $category && $includeSubcategories) { $category = static::getAllSubcategoriesIds($category); } $ids = Model::getReferenceValues($t, 'categories', $category); // Also filter by cumulative categories if (count($cumulativeCategories) > 0) { $cumulativeIds = null; foreach ($cumulativeCategories as $cumulativeCategory) { $tmp = Model::getReferenceValues($t, 'categories', $cumulativeCategory); // Include the subcategories if ($includeSubcategories) { $tmp = static::getAllSubcategoriesIds($tmp); } if ($cumulativeIds === null) { $cumulativeIds = $tmp; } else { $cumulativeIds = array_intersect($cumulativeIds, $tmp); } } $ids = array_intersect($ids, $cumulativeIds); } if (0 === \count($ids)) { return 0; } $columns = ["$t.id IN (".\implode(',', \array_unique($ids)).')']; $values = []; // Filter by archives if (\count($archives)) { $columns[] = "$t.pid IN (".\implode(',', \array_map('intval', $archives)).')'; } if (!BE_USER_LOGGED_IN) { $time = Date::floorToMinute(); $columns[] = "($t.start=? OR $t.start<=?) AND ($t.stop=? OR $t.stop>?) AND $t.published=?"; $values = \array_merge($values, ['', $time, '', $time + 60, 1]); } return NewsModel::countBy($columns, $values); }
Count the published news by archives. @param array $archives @param int|null $category @param bool $includeSubcategories @param array $cumulativeCategories @return int
entailment
public static function getAllSubcategoriesIds($category) { $ids = Database::getInstance()->getChildRecords($category, static::$strTable, false, (array) $category, (!BE_USER_LOGGED_IN ? 'published=1' : '')); $ids = \array_map('intval', $ids); return $ids; }
Get all subcategory IDs. @param array|int $category @return array
entailment
public static function findMultipleByIds($arrIds, array $arrOptions = []) { if (!MultilingualHelper::isActive()) { return parent::findMultipleByIds($arrIds, $arrOptions); } $t = static::getTableAlias(); if (!isset($arrOptions['order'])) { $arrOptions['order'] = Database::getInstance()->findInSet("$t.id", $arrIds); } return static::findBy(["$t.id IN (".\implode(',', \array_map('intval', $arrIds)).')'], null); }
{@inheritdoc}
entailment
public function generateUrl(NewsCategoryModel $category, PageModel $page, $absolute = false) { $page->loadDetails(); $params = '/'.$this->getParameterName($page->rootId).'/'.$this->getCategoryAlias($category, $page); return $absolute ? $page->getAbsoluteUrl($params) : $page->getFrontendUrl($params); }
Generate the category URL. @param NewsCategoryModel $category @param PageModel $page @param bool $absolute @return string
entailment
public function getImage(NewsCategoryModel $category) { if (null === ($image = $category->getImage()) || !\is_file(TL_ROOT.'/'.$image->path)) { return null; } return $image; }
Get the image. @param NewsCategoryModel $category @return \Contao\FilesModel|null
entailment
public function getCategoryAlias(NewsCategoryModel $category, PageModel $page) { if ($category instanceof Multilingual) { return $category->getAlias($page->language); } return $category->alias; }
Get the category alias @param NewsCategoryModel $category @param PageModel $page @return string
entailment
public function getParameterName($rootId = null) { $rootId = $rootId ?: $GLOBALS['objPage']->rootId; if (!$rootId || null === ($rootPage = PageModel::findByPk($rootId))) { return ''; } return $rootPage->newsCategories_param ?: 'category'; }
Get the parameter name. @param int|null $rootId @return string
entailment
public function getTargetPage(NewsCategoryModel $category) { $pageId = $category->jumpTo; // Inherit the page from parent if there is none set if (!$pageId) { $pid = $category->pid; do { /** @var NewsCategoryModel $parent */ $parent = $category->findByPk($pid); if (null !== $parent) { $pid = $parent->pid; $pageId = $parent->jumpTo; } } while ($pid && !$pageId); } // Get the page model if ($pageId) { /** @var PageModel $pageAdapter */ $pageAdapter = $this->framework->getAdapter(PageModel::class); return $pageAdapter->findPublishedById($pageId); } return null; }
Get the category target page. @param NewsCategoryModel $category @return PageModel|null
entailment
public function getTrailIds(NewsCategoryModel $category) { static $ids; if (!\is_array($ids)) { /** @var Database $db */ $db = $this->framework->createInstance(Database::class); $ids = $db->getParentRecords($category->id, $category->getTable()); $ids = \array_map('intval', \array_unique($ids)); // Remove the current category unset($ids[\array_search($category->id, $ids, true)]); } return $ids; }
Get the category trail IDs. @param NewsCategoryModel $category @return array
entailment
public function isVisibleForModule(NewsCategoryModel $category, Module $module) { // List or archive module if ($category->hideInList && ($module instanceof ModuleNewsList || $module instanceof ModuleNewsArchive)) { return false; } // Reader module if ($category->hideInReader && $module instanceof ModuleNewsReader) { return false; } return true; }
Return true if the category is visible for module. @param NewsCategoryModel $category @param Module $module @return bool
entailment
public function onReplace($tag) { $chunks = trimsplit('::', $tag); if ('news_categories' === $chunks[0]) { /** @var Input $input */ $input = $this->framework->getAdapter(Input::class); if ($alias = $input->get($this->manager->getParameterName())) { /** @var NewsCategoryModel $model */ $model = $this->framework->getAdapter(NewsCategoryModel::class); if (null !== ($category = $model->findPublishedByIdOrAlias($alias))) { $value = $category->{$chunks[1]}; // Convert the binary to UUID for images (#147) if ($chunks[1] === 'image' && $value) { return StringUtil::binToUuid($value); } return $value; } } } return false; }
On replace the insert tags. @param string $tag @return string|bool
entailment
public function canUserAssignCategories() { $user = $this->getUser(); return $user->isAdmin || \in_array('tl_news::categories', $user->alexf, true); }
Return true if the user can assign news categories. @return bool
entailment
public function getUserAllowedRoots() { $user = $this->getUser(); if ($user->isAdmin) { return null; } return \array_map('intval', (array) $user->newscategories_roots); }
Get the user allowed roots. Return null if the user has no limitation. @return array|null
entailment
public function isUserAllowedNewsCategory($categoryId) { if (null === ($roots = $this->getUserAllowedRoots())) { return true; } /** @var Database $db */ $db = $this->framework->createInstance(Database::class); $ids = $db->getChildRecords($roots, 'tl_news_category', false, $roots); $ids = \array_map('intval', $ids); return \in_array((int) $categoryId, $ids, true); }
Return if the user is allowed to manage the news category. @param int $categoryId @return bool
entailment
public function addCategoryToAllowedRoots($categoryId) { if (null === ($roots = $this->getUserAllowedRoots())) { return; } $categoryId = (int) $categoryId; $user = $this->getUser(); /** @var StringUtil $stringUtil */ $stringUtil = $this->framework->getAdapter(StringUtil::class); // Add the permissions on group level if ('custom' !== $user->inherit) { $groups = $this->db->fetchAll('SELECT id, newscategories, newscategories_roots FROM tl_user_group WHERE id IN('.\implode(',', \array_map('intval', $user->groups)).')'); foreach ($groups as $group) { $permissions = $stringUtil->deserialize($group['newscategories'], true); if (\in_array('manage', $permissions, true)) { $categoryIds = $stringUtil->deserialize($group['newscategories_roots'], true); $categoryIds[] = $categoryId; $this->db->update('tl_user_group', ['newscategories_roots' => \serialize($categoryIds)], ['id' => $group['id']]); } } } // Add the permissions on user level if ('group' !== $user->inherit) { $userData = $this->db->fetchAssoc('SELECT newscategories, newscategories_roots FROM tl_user WHERE id=?', [$user->id]); $permissions = $stringUtil->deserialize($userData['newscategories'], true); if (\in_array('manage', $permissions, true)) { $categoryIds = $stringUtil->deserialize($userData['newscategories_roots'], true); $categoryIds[] = $categoryId; $this->db->update('tl_user', ['newscategories_roots' => \serialize($categoryIds)], ['id' => $user->id]); } } // Add the new element to the user object $user->newscategories_roots = \array_merge($roots, [$categoryId]); }
Add the category to allowed roots. @param int $categoryId
entailment
public function getDcaAttributes(PickerConfig $config) { $attributes = ['fieldType' => 'checkbox']; if ($fieldType = $config->getExtra('fieldType')) { $attributes['fieldType'] = $fieldType; } if ($this->supportsValue($config)) { $attributes['value'] = \array_map('intval', \explode(',', $config->getValue())); } if (\is_array($rootNodes = $config->getExtra('rootNodes'))) { $attributes['rootNodes'] = $rootNodes; } return $attributes; }
{@inheritdoc}
entailment
public function getUrl(PickerConfig $config) { // Set the news categories root in session for further reference in onload_callback (see #137) if (\is_array($rootNodes = $config->getExtra('rootNodes'))) { $_SESSION['NEWS_CATEGORIES_ROOT'] = $rootNodes; } else { unset($_SESSION['NEWS_CATEGORIES_ROOT']); } return parent::getUrl($config); }
{@inheritdoc}
entailment
public function supportsContext($context) { if ($this->permissionChecker === null) { return false; } return 'newsCategories' === $context && ($this->permissionChecker->canUserManageCategories() || $this->permissionChecker->canUserAssignCategories()); }
{@inheritdoc}
entailment
public function supportsValue(PickerConfig $config) { foreach (\explode(',', $config->getValue()) as $id) { if (!\is_numeric($id)) { return false; } } return true; }
{@inheritdoc}
entailment
public function generate() { if (TL_MODE === 'BE') { $template = new BackendTemplate('be_wildcard'); $template->wildcard = '### '.Utf8::strtoupper($GLOBALS['TL_LANG']['FMD']['newscategories'][0]).' ###'; $template->title = $this->headline; $template->id = $this->id; $template->link = $this->name; $template->href = 'contao/main.php?do=themes&amp;table=tl_module&amp;act=edit&amp;id='.$this->id; return $template->parse(); } $this->news_archives = $this->sortOutProtected(StringUtil::deserialize($this->news_archives, true)); // Return if there are no archives if (0 === \count($this->news_archives)) { return ''; } $this->manager = System::getContainer()->get('codefog_news_categories.manager'); $this->currentNewsCategories = $this->getCurrentNewsCategories(); return parent::generate(); }
Display a wildcard in the back end. @return string
entailment
protected function compile() { $categories = $this->getCategories(); // Return if no categories are found if (null === $categories) { $this->Template->categories = ''; return; } $param = System::getContainer()->get('codefog_news_categories.manager')->getParameterName(); // Get the active category if (null !== ($activeCategory = NewsCategoryModel::findPublishedByIdOrAlias(Input::get($param)))) { $this->activeCategory = $activeCategory; // Add the canonical URL tag if ($this->news_enableCanonicalUrls) { $GLOBALS['TL_HEAD'][] = sprintf('<link rel="canonical" href="%s">', $GLOBALS['objPage']->getAbsoluteUrl()); } } $ids = []; // Get the parent categories IDs /** @var NewsCategoryModel $category */ foreach ($categories as $category) { $ids = \array_merge($ids, Database::getInstance()->getParentRecords($category->id, $category->getTable())); } $this->Template->categories = $this->renderNewsCategories((int) $this->news_categoriesRoot, \array_unique($ids)); }
Generate the module.
entailment
protected function getCategories() { $customCategories = $this->news_customCategories ? StringUtil::deserialize($this->news_categories, true) : []; // Get the subcategories of custom categories if (\count($customCategories) > 0) { $customCategories = NewsCategoryModel::getAllSubcategoriesIds($customCategories); } // Get all categories whether they have news or not if ($this->news_showEmptyCategories) { if (\count($customCategories) > 0) { $categories = NewsCategoryModel::findPublishedByIds($customCategories); } else { $categories = NewsCategoryModel::findPublished(); } } else { // Get the categories that do have news assigned $categories = NewsCategoryModel::findPublishedByArchives($this->news_archives, $customCategories); } return $categories; }
Get the categories @return Collection|null
entailment
protected function renderNewsCategories($pid, array $ids, $level = 1) { if (null === ($categories = NewsCategoryModel::findPublishedByIds($ids, $pid))) { return ''; } // Layout template fallback if (!$this->navigationTpl) { $this->navigationTpl = 'nav_newscategories'; } $template = new FrontendTemplate($this->navigationTpl); $template->type = \get_class($this); $template->cssID = $this->cssID; $template->level = 'level_'.$level; $template->showQuantity = $this->news_showQuantity; $items = []; // Add the "reset categories" link if ($this->news_resetCategories && 1 === $level) { $items[] = $this->generateItem( $this->getTargetPage()->getFrontendUrl(), $GLOBALS['TL_LANG']['MSC']['resetCategories'][0], $GLOBALS['TL_LANG']['MSC']['resetCategories'][1], 'reset', 0 === \count($this->currentNewsCategories) && null === $this->activeCategory ); } ++$level; /** @var NewsCategoryModel $category */ foreach ($categories as $category) { // Generate the category individual URL or the filter-link if ($this->news_forceCategoryUrl && null !== ($targetPage = $this->manager->getTargetPage($category))) { $url = $targetPage->getFrontendUrl(); } else { $url = $this->manager->generateUrl($category, $this->getTargetPage()); } $items[] = $this->generateItem( $url, $category->getTitle(), $category->getTitle(), $this->generateItemCssClass($category), null !== $this->activeCategory && (int) $this->activeCategory->id === (int) $category->id, $this->renderNewsCategories($category->id, $ids, $level), $category ); } // Add first/last/even/odd classes RowClass::withKey('class')->addFirstLast()->addEvenOdd()->applyTo($items); $template->items = $items; return $template->parse(); }
Recursively compile the news categories and return it as HTML string. @param int $pid @param array $ids @param int $level @return string
entailment
protected function generateItem($url, $link, $title, $cssClass, $isActive, $subitems = '', NewsCategoryModel $category = null) { $data = []; // Set the data from category if (null !== $category) { $data = $category->row(); } $data['isActive'] = $isActive; $data['subitems'] = $subitems; $data['class'] = $cssClass; $data['title'] = StringUtil::specialchars($title); $data['linkTitle'] = StringUtil::specialchars($title); $data['link'] = $link; $data['href'] = ampersand($url); $data['quantity'] = 0; // Add the "active" class if ($isActive) { $data['class'] = \trim($data['class'].' active'); } // Add the "submenu" class if ($subitems) { $data['class'] = \trim($data['class'].' submenu'); } // Add the news quantity if ($this->news_showQuantity) { if (null === $category) { $data['quantity'] = NewsCategoryModel::getUsage($this->news_archives); } else { $data['quantity'] = NewsCategoryModel::getUsage($this->news_archives, $category->id, (bool) $this->news_includeSubcategories); } } // Add the image if (null !== $category && null !== ($image = $this->manager->getImage($category))) { $data['image'] = new \stdClass(); Controller::addImageToTemplate($data['image'], [ 'singleSRC' => $image->path, 'size' => $this->news_categoryImgSize, 'alt' => $title, 'imageTitle' => $title, ]); } else { $data['image'] = null; } return $data; }
Generate the item. @param string $url @param string $link @param string $title @param string $cssClass @param bool $isActive @param string $subitems @param NewsCategoryModel|null $category @return array
entailment
protected function countNewsItems($begin, $end) { if (($criteria = $this->getSearchCriteria($begin, $end)) === null) { return 0; } return NewsModel::countBy($criteria->getColumns(), $criteria->getValues()); }
Count the news items @param int $begin @param int $end @return int
entailment
protected function fetchNewsItems($begin, $end, $limit = null, $offset = null) { if (($criteria = $this->getSearchCriteria($begin, $end)) === null) { return null; } $criteria->setLimit($limit); $criteria->setOffset($offset); return NewsModel::findBy($criteria->getColumns(), $criteria->getValues(), $criteria->getOptions()); }
Fetch the news items @param int $begin @param int $end @param int $limit @param int $offset @return Collection|null
entailment
protected function getSearchCriteria($begin, $end) { try { $criteria = System::getContainer() ->get('codefog_news_categories.news_criteria_builder') ->getCriteriaForArchiveModule($this->news_archives, $begin, $end, $this); } catch (CategoryNotFoundException $e) { throw new PageNotFoundException($e->getMessage()); } return $criteria; }
Get the search criteria @param int $begin @param int $end @return NewsCriteria|null @throws PageNotFoundException
entailment
function getSignature(array $params, $method = null) { ksort($params); unset($params['sign']); unset($params['signature']); array_push($params, $this->secretKey); if ($method) { array_unshift($params, $method); } return hash('sha256', join('{up}', $params)); }
Create SHA-256 digital signature @param array $params @param $method @return string
entailment
public function form($publicKey, $sum, $account, $desc, $currency = 'RUB', $locale = 'ru') { $vitalParams = array( 'account' => $account, 'currency' => $currency, 'desc' => $desc, 'sum' => $sum ); $this->params = array_merge($this->params, $vitalParams); if ($this->secretKey) { $this->params['signature'] = $this->getSignature($vitalParams); } $this->params['locale'] = $locale; return self::FORM_URL . $publicKey . '?' . http_build_query($this->params); }
Get URL for pay through the form @param string $publicKey @param string|float|int $sum @param string $account @param string $desc @param string $currency @param string $locale @return string
entailment
public function setCashItems($items) { $this->params['cashItems'] = base64_encode( json_encode( array_map(function ($item) { /** @var CashItem $item */ return array( 'name' => $item->getName(), 'count' => $item->getCount(), 'price' => $item->getPrice() ); }, $items))); return $this; }
Set list of paid goods @param CashItem[] $items @return UnitPay
entailment
public function api($method, $params = array()) { if (!in_array($method, $this->supportedUnitpayMethods)) { throw new UnexpectedValueException('Method is not supported'); } if (isset($this->requiredUnitpayMethodsParams[$method])) { foreach ($this->requiredUnitpayMethodsParams[$method] as $rParam) { if (!isset($params[$rParam])) { throw new InvalidArgumentException('Param '.$rParam.' is null'); } } } $params['secretKey'] = $this->secretKey; if (empty($params['secretKey'])) { throw new InvalidArgumentException('SecretKey is null'); } $requestUrl = self::API_URL . '?' . http_build_query([ 'method' => $method, 'params' => $params ], null, '&', PHP_QUERY_RFC3986); $response = json_decode(file_get_contents($requestUrl)); if (!is_object($response)) { throw new InvalidArgumentException('Temporary server error. Please try again later.'); } return $response; }
Call API @param $method @param array $params @return object @throws InvalidArgumentException @throws UnexpectedValueException
entailment
public function checkHandlerRequest() { $ip = $this->getIp(); if (!isset($_GET['method'])) { throw new InvalidArgumentException('Method is null'); } if (!isset($_GET['params'])) { throw new InvalidArgumentException('Params is null'); } list($method, $params) = array($_GET['method'], $_GET['params']); if (!in_array($method, $this->supportedPartnerMethods)) { throw new UnexpectedValueException('Method is not supported'); } if (!isset($params['signature']) || $params['signature'] != $this->getSignature($params, $method)) { throw new InvalidArgumentException('Wrong signature'); } /** * IP address check * @link http://help.unitpay.ru/article/67-ip-addresses */ if (!in_array($ip, $this->supportedUnitpayIp)) { throw new InvalidArgumentException('IP address Error'); } return true; }
Check request on handler from UnitPay @return bool @throws InvalidArgumentException @throws UnexpectedValueException
entailment
public function up() { Schema::create(\Config::get('laravel-youtube::table_name'), function(Blueprint $table) { $table->increments('id'); if(\Config::get('laravel-youtube::auth') == true){ $table->integer('user_id'); } $table->text('access_token'); $table->timestamp('created_at'); }); }
Run the migrations. @return void
entailment
public function saveAccessTokenToDB($accessToken) { $data = array( 'access_token' => $accessToken, 'created_at' => \Carbon\Carbon::now(), ); if(\Config::get('laravel-youtube::auth') == true) { $data['user_id'] = \Auth::user()->id; } \DB::table(\Config::get('laravel-youtube::table_name'))->insert($data); }
Saves the access token to the database. @param $accessToken
entailment
public function getUploads($maxResults=50) { $channelsResponse = $this->youtube->channels->listChannels('contentDetails', array( 'mine' => 'true', )); foreach ($channelsResponse['items'] as $channel) { $uploadsListId = $channel['contentDetails']['relatedPlaylists']['uploads']; $playlistItemsResponse = $this->youtube->playlistItems->listPlaylistItems('snippet', array( 'playlistId' => $uploadsListId, 'maxResults' => $maxResults )); $items = []; foreach ($playlistItemsResponse['items'] as $playlistItem) { $video = []; $video['videoId'] = $playlistItem['snippet']['resourceId']['videoId']; $video['title'] = $playlistItem['snippet']['title']; $video['publishedAt'] = $playlistItem['snippet']['publishedAt']; array_push($items, $video); } } return $items; }
/* Return JSON response of uploaded videos @return json
entailment
public function upload(array $data) { $accessToken = $this->client->getAccessToken(); if (is_null($accessToken)) { throw new \Exception('You need an access token to upload'); } // Attempt to refresh the access token if it's expired and save the new one in the database if ($this->client->isAccessTokenExpired()) { $accessToken = json_decode($accessToken); $refreshToken = $accessToken->refresh_token; $this->client->refreshToken($refreshToken); $newAccessToken = $this->client->getAccessToken(); $this->saveAccessTokenToDB($newAccessToken); } $snippet = new \Google_Service_YouTube_VideoSnippet(); if (array_key_exists('title', $data)) { $snippet->setTitle($data['title']); } if (array_key_exists('description', $data)) { $snippet->setDescription($data['description']); } if (array_key_exists('tags', $data)) { $snippet->setTags($data['tags']); } if (array_key_exists('category_id', $data)) { $snippet->setCategoryId($data['category_id']); } $status = new \Google_Service_YouTube_VideoStatus(); if (array_key_exists('status', $data)) { $status->privacyStatus = $data['status']; } $video = new \Google_Service_YouTube_Video(); $video->setSnippet($snippet); $video->setStatus($status); $result = $this->youtube->videos->insert( 'status,snippet', $video, array( 'data' => file_get_contents( $data['video']->getRealPath() ), 'mimeType' => $data['video']->getMimeType(), 'uploadType' => 'multipart' ) ); if (!($result instanceof \Google_Service_YouTube_Video)) { throw new \Exception('Expecting instance of Google_Service_YouTube_Video, got:' . $result); } return $result->getId(); }
Uploads the passed video to the YouTube account identified by the access token in the DB and returns the uploaded video's YouTube Video ID. Attempts to automatically refresh the token if it's expired. @param array $data As is returned from \Input::all() given a form as per the one in views/example.blade.php @return string The ID of the uploaded video @throws \Exception
entailment
public function delete($video_id) { $accessToken = $this->client->getAccessToken(); if (is_null($accessToken)) { throw new \Exception('You need an access token to delete.'); } // Attempt to refresh the access token if it's expired and save the new one in the database if ($this->client->isAccessTokenExpired()) { $accessToken = json_decode($accessToken); $refreshToken = $accessToken->refresh_token; $this->client->refreshToken($refreshToken); $newAccessToken = $this->client->getAccessToken(); $this->saveAccessTokenToDB($newAccessToken); } $result = $this->youtube->videos->delete($video_id); if (!$result) { throw new \Exception("Couldn't delete the video from the youtube account."); } return $result->getId(); }
Deletes a video from the account specified by the Access Token Attempts to automatically refresh the token if it's expired. @param $id of the video to delete @return true if the video was deleted and false if it was not @throws \Exception
entailment
public function revisionLog($action, $table, $id, array $old = [], array $new = [], $user = null) { $user = $this->parseUser($user); $connection = $this->getCurrentConnection(); $format = $connection->getQueryGrammar()->getDateFormat(); $connection->table($this->table)->insert([ 'action' => substr($action, 0, 255), 'table_name' => substr($table, 0, 255), 'row_id' => substr($id, 0, 255), 'old' => json_encode($old), 'new' => json_encode($new), 'user' => substr($user, 0, 255), 'ip' => substr($this->getFromServer('REMOTE_ADDR'), 0, 255) ?: null, 'ip_forwarded' => substr($this->getFromServer('HTTP_X_FORWARDED_FOR'), 0, 255) ?: null, 'created_at' => (new DateTime())->format($format), ]); $this->resetConnection(); }
Log data revisions in the db. @param string $action @param string $table @param int $id @param array $old @param array $new @param string $user
entailment
public function getUser() { if ($user = $this->provider->getUser()) { return ($field = $this->field) ? (string) $user->{$field} : $user->getLogin(); } }
Get identifier of the currently logged in user. @return string|null
entailment
public function hasHistory($timestamp = null) { if ($timestamp) { return (bool) $this->snapshot($timestamp); } return $this->revisions()->exists(); }
Determine if model has history at given timestamp if provided or any at all. @param \DateTime|string $timestamp DateTime|Carbon object or parsable date string @see strtotime() @return bool
entailment
protected function prepareAttributes(array $attributes) { return array_map(function ($attribute) { return ($attribute instanceof DateTime) ? $this->fromDateTime($attribute) : (string) $attribute; }, $attributes); }
Stringify revisionable attributes. @param array $attributes @return array
entailment
protected function getRevisionableItems(array $values) { if (count($this->getRevisionable()) > 0) { return array_intersect_key($values, array_flip($this->getRevisionable())); } return array_diff_key($values, array_flip($this->getNonRevisionable())); }
Get an array of revisionable attributes. @param array $values @return array
entailment
public function wrapRevision($history) { if ($history && $presenter = $this->getRevisionPresenter()) { return $presenter::make($history, $this); } return $history; }
Wrap revision model with the presenter if provided. @param \Sofa\Revisionable\Laravel\Revision|\Illuminate\Database\Eloquent\Collection $history @return \Sofa\Revisionable\Laravel\Presenter|\Sofa\Revisionable\Laravel\Revision
entailment
public function getFieldHistory(string $field) : Collection { return $this->revisions->map(function ($revision) use ($field) : ?array { if ($revision->old($field) == $revision->new($field)) { return null; } return [ 'created_at' => (string) $revision->created_at, 'user_id' => $revision->executor->id ?? null, 'user_email' => $revision->executor->email ?? null, 'old' => $revision->old($field), 'new' => $revision->new($field), ]; })->filter()->values(); }
Get all updates for a given field. @param string $field @return Illuminate\Support\Collection
entailment
protected function bindSentinelProvider() { $this->app->singleton('revisionable.userprovider', function ($app) { $field = $app['config']->get('sofa_revisionable.userfield'); return new Adapters\Sentinel($app['sentinel'], $field); }); }
Bind adapter for Sentinel to the IoC.
entailment
private function bindJwtAuthProvider() { $this->app->singleton('revisionable.userprovider', function ($app) { $field = $app['config']->get('sofa_revisionable.userfield'); return new Adapters\JwtAuth($app['tymon.jwt.auth'], $field); }); }
Bind adapter for JWT Auth to the IoC.
entailment
protected function bindGuardProvider() { $this->app->singleton('revisionable.userprovider', function ($app) { $field = $app['config']->get('sofa_revisionable.userfield'); return new Adapters\Guard($app['auth']->guard(), $field); }); }
Bind adapter for Illuminate Guard to the IoC.
entailment
protected function registerCommands() { $this->app->singleton('revisions.migration', function ($app) { return new RevisionsTableCommand($app['files'], $app['composer']); }); $this->app->singleton('revisions.upgrade5_3', function ($app) { return new RevisionsUpgradeCommand($app['files'], $app['composer']); }); $this->commands([ 'revisions.migration', 'revisions.upgrade5_3', ]); }
Register revisions migration generator command.
entailment
public function getUser() { if ($user = $this->provider) { return ($field = $this->field) ? (string) $user->get($field) : $user->get('id'); } }
Get identifier of the currently logged in user. @return string|null
entailment
public function getUser() { if ($user = $this->provider->user()) { return ($field = $this->field) ? (string) $user->{$field} : $user->getAuthIdentifier(); } }
Get identifier of the currently logged in user. @return string|null
entailment
public function action() { $action = $this->revision->action; return array_get($this->actions, $action, $action); }
Present action field. @return string
entailment
public function getFromRevision($version, $key) { return ($this->isPassedThrough($key)) ? $this->passThrough($version, $key) : array_get($this->{$version}, $key); }
Get value from the revision. @param string $version @param string $key @return mixed
entailment
protected function passThrough($version, $key) { $revisioned = $this->getVersion($version); $needle = $this->passThrough[$key]; return $this->dataGet($revisioned, $needle); }
Get value from the relation. @param string $version @param string $key @return mixed
entailment
protected function dataGet($target, $key) { foreach (explode('.', $key) as $segment) { if (is_object($target) && in_array(Revisionable::class, class_uses_recursive(get_class($target)))) { $target = $this->passThroughRevisionable($target, $segment); } elseif ($target instanceof self || $target instanceof Revision) { $target = $this->passThroughRevision($target, $segment); } elseif ($target instanceof Model) { $target = $this->passThroughModel($target, $segment); } else { $target = null; } if (!$target) { return; } } return $target; }
Get pass through value using dot notation. @param mixed $target @param string $key @return mixed
entailment
protected function passThroughRevision($revision, $key) { $action = $revision->getAttribute('action'); // @todo what about restored??? if (in_array($action, ['created', 'updated'])) { return $revision->new($key); } }
Get pass through value from another revision. @param \Sofa\Revisionable\Revision|\Sofa\Revisionable\Laravel\Presenter $revision @param string $key @return mixed
entailment
protected function getVersion($version) { if (!$this->{$version.'Version'}) { $revisioned = get_class($this->revisioned); $revision = new $revisioned(); $revision->setRawAttributes($this->{$version}); $this->{$version.'Version'} = $revision; } return $this->{$version.'Version'}; }
Get revisioned model with appropriate attributes. @return \Illuminate\Database\Eloquent\Model
entailment
public static function make($revision, $revisioned) { if (is_array($revision)) { return static::makeArray($revision, $revisioned); } if ($revision instanceof Collection) { return static::makeCollection($revision, $revisioned); } if (!$revision || $revision instanceof Model) { return static::makeOne($revision, $revisioned); } throw new \InvalidArgumentException( 'Presenter::make accepts array, collection or single resource, '.gettype($revision).' given.' ); }
Decorate revision model or array/collection of models. @param mixed $revision @param \Illuminate\Database\Eloquent\Model $revisioned @return mixed @throws \InvalidArgumentException
entailment
protected static function getMapCallback($revisioned) { // We need to pass the calling class to the closure scope // instead of calling new static(), since php is going // to instantiate it w/o late static binding (bug). $presenter = get_called_class(); return function ($revision) use ($presenter, $revisioned) { return new $presenter($revision, $revisioned); }; }
Get callback for the array map. @return \Closure
entailment
public function getUser() { if ($user = $this->provider->parseToken()->toUser()) { return ($field = $this->field) ? (string) $user->{$field} : $this->provider->getIdentifier(); } }
Get identifier of the currently logged in user. @return string|null
entailment
protected function log($action, $revisioned) { $old = $new = []; switch ($action) { case 'created': $new = $revisioned->getNewAttributes(); break; case 'deleted': $old = $revisioned->getOldAttributes(); break; case 'updated': $old = $revisioned->getOldAttributes(); $new = $revisioned->getNewAttributes(); break; } $revisioned->revisions()->create([ 'table_name' => $revisioned->getTable(), 'action' => $action, 'user_id' => $this->userProvider->getUserId(), 'user' => $this->userProvider->getUser(), 'old' => json_encode($old), 'new' => json_encode($new), 'ip' => data_get($_SERVER, 'REMOTE_ADDR'), 'ip_forwarded' => data_get($_SERVER, 'HTTP_X_FORWARDED_FOR'), 'created_at' => Carbon::now(), ]); }
Log the revision. @param string $action @param \Illuminate\Database\Eloquent\Model
entailment
public function getActionsAttribute() { if (!$this->relationLoaded('actions')) { $this->load('actions'); } return $this->getRelation('actions')->load('revisioned')->map(function ($revision) { if ($revisioned = $revision->revisioned) { return $revisioned->wrapRevision($revision); } return $revision; }); }
Accessor for actions property. @return \Illuminate\Database\Eloquent\Collection
entailment
public function getDiff() { $diff = []; foreach ($this->getUpdated() as $key) { $diff[$key]['old'] = $this->old($key); $diff[$key]['new'] = $this->new($key); } return $diff; }
Get diff of the old/new arrays. @return array
entailment
public function scopeFor($query, $table) { if ($table instanceof Model) { $table = $table->getTable(); } return $query->where('table_name', $table); }
Query scope for. @link https://laravel.com/docs/eloquent#local-scopes @param \Illuminate\Database\Eloquent\Builder $query @param \Illuminate\Database\Eloquent\Model|string $table @return \Illuminate\Database\Eloquent\Builder
entailment
public function updateFormFields(FieldList $fields, $controller, $formName, $context) { $image = isset($context['Record']) ? $context['Record'] : null; if ($image && $image->appCategory() === 'image') { $fields->insertAfter( 'Title', FocusPointField::create('FocusPoint', $image->fieldLabel('FocusPoint'), $image) ->setReadonly($formName === 'fileSelectForm') ); } }
Add FocusPoint field for selecting focus.
entailment
public function calculateCrop($width, $height, $originalWidth, $originalHeight) { // Work out how to crop the image and provide new focus coordinates $cropData = [ 'CropAxis' => 0, 'CropOffset' => 0, ]; $cropData['x'] = [ 'FocusPoint' => $this->getX(), 'OriginalLength' => $originalWidth, 'TargetLength' => round($width), ]; $cropData['y'] = [ 'FocusPoint' => $this->getY(), 'OriginalLength' => $originalHeight, 'TargetLength' => round($height), ]; // Avoid divide by zero error if (!($cropData['x']['OriginalLength'] > 0 && $cropData['y']['OriginalLength'] > 0)) { return false; } // Work out which axis to crop on $cropAxis = false; $cropData['x']['ScaleRatio'] = $cropData['x']['OriginalLength'] / $cropData['x']['TargetLength']; $cropData['y']['ScaleRatio'] = $cropData['y']['OriginalLength'] / $cropData['y']['TargetLength']; if ($cropData['x']['ScaleRatio'] < $cropData['y']['ScaleRatio']) { // Top and/or bottom of image will be lost $cropAxis = 'y'; $scaleRatio = $cropData['x']['ScaleRatio']; } elseif ($cropData['x']['ScaleRatio'] > $cropData['y']['ScaleRatio']) { // Left and/or right of image will be lost $cropAxis = 'x'; $scaleRatio = $cropData['y']['ScaleRatio']; } $cropData['CropAxis'] = $cropAxis; // Adjust dimensions for cropping if ($cropAxis) { // Focus point offset $focusOffset = $this->focusCoordToOffset($cropData[$cropAxis]['FocusPoint']); // Length after scaling but before cropping $scaledImageLength = floor($cropData[$cropAxis]['OriginalLength'] / $scaleRatio); // Focus point position in pixels $focusPos = floor($focusOffset * $scaledImageLength); // Container center in pixels $frameCenter = floor($cropData[$cropAxis]['TargetLength'] / 2); // Difference beetween focus point and center $focusShift = $focusPos - $frameCenter; // Limit offset so image remains filled $remainder = $scaledImageLength - $focusPos; $croppedRemainder = $cropData[$cropAxis]['TargetLength'] - $frameCenter; if ($remainder < $croppedRemainder) { $focusShift -= $croppedRemainder - $remainder; } if ($focusShift < 0) { $focusShift = 0; } // Set cropping start point $cropData['CropOffset'] = $focusShift; // Update Focus point location for cropped image $newFocusOffset = ($focusPos - $focusShift) / $cropData[$cropAxis]['TargetLength']; $cropData[$cropAxis]['FocusPoint'] = $this->focusOffsetToCoord($newFocusOffset); } return $cropData; }
Caluclate crop data given the desired width and height, as well as original width and height. Calculates required crop coordinates using current FocusX and FocusY @param int $width desired width @param int $height desired height @param int $originalWidth original image width @param int $originalHeight original image height @return array|bool
entailment
public function FocusFill($width, $height, AssetContainer $image, $upscale = true) { if (!$image && $this->record instanceof Image) { $image = $this->record; } $width = intval($width); $height = intval($height); $imgW = $image->getWidth(); $imgH = $image->getHeight(); // Don't enlarge if (!$upscale) { $widthRatio = $imgW / $width; $heightRatio = $imgH / $height; if ($widthRatio < 1 && $widthRatio <= $heightRatio) { $width = $imgW; $height = intval(round($height * $widthRatio)); } elseif ($heightRatio < 1) { $height = $imgH; $width = intval(round($width * $heightRatio)); } } //Only resize if necessary if ($image->isSize($width, $height) && !Config::inst()->get(DBFile::class, 'force_resample')) { return $image; } elseif ($cropData = $this->calculateCrop($width, $height, $imgW, $imgH)) { $variant = $image->variantName(__FUNCTION__, $width, $height, $cropData['CropAxis'], $cropData['CropOffset']); $cropped = $image->manipulateImage($variant, function (Image_Backend $backend) use ($width, $height, $cropData) { $img = null; $cropAxis = $cropData['CropAxis']; $cropOffset = $cropData['CropOffset']; if ($cropAxis == 'x') { //Generate image $img = $backend ->resizeByHeight($height) ->crop(0, $cropOffset, $width, $height); } elseif ($cropAxis == 'y') { //Generate image $img = $backend ->resizeByWidth($width) ->crop($cropOffset, 0, $width, $height); } else { //Generate image without cropping $img = $backend->resize($width, $height); } if (!$img) { return null; } return $img; }); // Update FocusPoint $cropped->FocusPoint = DBField::create_field(static::class, [ 'X' => $cropData['x']['FocusPoint'], 'Y' => $cropData['y']['FocusPoint'] ]); return $cropped; } return null; }
Generate a cropped version of the given image @param int $width desired width @param int $height desired height @param Image $image the image to crop. If not set, the current record will be used @param bool $upscale whether or not upscaling is allowed @return AssetContainer|null
entailment
public function PercentageX() { if ($field = $this->owner->FocusPoint) { return round(DBFocusPoint::focusCoordToOffset($field->getX()) * 100); } return 0; }
Generate a percentage based description of x focus point for use in CSS. Range is 0% - 100%. Example x=.5 translates to 75% Use in templates with {$PercentageX}%. @return int
entailment
public function PercentageY() { if ($field = $this->owner->FocusPoint) { return round(DBFocusPoint::focusCoordToOffset($field->getY()) * 100); } return 0; }
Generate a percentage based description of y focus point for use in CSS. Range is 0% - 100%. Example y=-.5 translates to 75% Use in templates with {$PercentageY}%. @return int
entailment
public function FocusFill($width, $height, $upscale = true) { return $this->owner->FocusPoint->FocusFill($width, $height, $this->owner, $upscale); }
Generate a resized copy of this image with the given width & height, cropping to maintain aspect ratio and focus point. Use in templates with $FocusFill. @param int $width Width to crop to @param int $height Height to crop to @param bool $upscale Will prevent upscaling if set to false @return Image|null
entailment
public static function check() { $collections = self::getCollection(); $jsonLastError = json_last_error(); return isset($jsonLastError) ? $collections[$jsonLastError] : $collections['default']; }
Check for errors. @return array|null
entailment
public static function getCollection() { $collections = [ JSON_ERROR_NONE => null, JSON_ERROR_DEPTH => [ 'message' => 'Maximum stack depth exceeded', 'error-code' => 1, ], JSON_ERROR_STATE_MISMATCH => [ 'message' => 'Underflow or the modes mismatch', 'error-code' => 2, ], JSON_ERROR_CTRL_CHAR => [ 'message' => 'Unexpected control char found', 'error-code' => 3, ], JSON_ERROR_SYNTAX => [ 'message' => 'Syntax error, malformed JSON', 'error-code' => 4, ], JSON_ERROR_UTF8 => [ 'message' => 'Malformed UTF-8 characters', 'error-code' => 5, ], JSON_ERROR_RECURSION => [ 'message' => 'Recursion error in value to be encoded', 'error-code' => 6, ], JSON_ERROR_INF_OR_NAN => [ 'message' => 'Error NAN/INF in value to be encoded', 'error-code' => 7, ], JSON_ERROR_UNSUPPORTED_TYPE => [ 'message' => 'Type value given cannot be encoded', 'error-code' => 8, ], 'default' => [ 'message' => 'Unknown error', 'error-code' => 999, ], ]; if (version_compare(PHP_VERSION, '7.0.0', '>=')) { $collections[JSON_ERROR_INVALID_PROPERTY_NAME] = [ 'message' => 'Name value given cannot be encoded', 'error-code' => 9, ]; $collections[JSON_ERROR_UTF16] = [ 'message' => 'Malformed UTF-16 characters', 'error-code' => 10, ]; } return $collections; }
Get collection of JSON errors. @return array
entailment
public static function arrayToFile($array, $file) { self::createDirectory($file); $lastError = JsonLastError::check(); $json = json_encode($lastError ? $lastError : $array, JSON_PRETTY_PRINT); self::saveFile($file, $json); return is_null($lastError); }
Creating JSON file from array. @param array $array → array to be converted to JSON @param string $file → path to the file @return boolean → true if the file is created without errors
entailment
public static function fileToArray($file) { if (! is_file($file) && ! filter_var($file, FILTER_VALIDATE_URL)) { self::arrayToFile([], $file); } $json = @file_get_contents($file); $array = json_decode($json, true); $lastError = JsonLastError::check(); return $array === null || !is_null($lastError) ? false : $array; }
Save to array the JSON file content. @param string $file → path or external url to JSON file @return array|false
entailment
private static function createDirectory($file) { $basename = is_string($file) ? basename($file) : ''; $path = str_replace($basename, '', $file); if (! empty($path) && ! is_dir($path)) { if (! mkdir($path, 0755, true)) { $message = 'Could not create directory in'; throw new JsonException($message . ' ' . $path); } } }
Create directory recursively if it doesn't exist. @since 1.1.3 @param string $file → path to the directory @throws JsonException → couldn't create directory
entailment
private static function saveFile($file, $json) { if (@file_put_contents($file, $json) === false) { $message = 'Could not create file in'; throw new JsonException($message . ' ' . $file); } }
Save file. @since 1.1.3 @param string $file → path to the file @param string $json → json string @throws JsonException → couldn't create file
entailment
public function save($pathname) { $gif = new Encoder($this->frames, $this->delays, 0, 2, 0, 0, 0, 'bin'); file_put_contents($pathname, $gif->getAnimation()); }
编码并保存当前GIF图片 @param string $pathname 图片名称
entailment
public function readExtensions() { $this->getByte(1); for (; ;) { $this->getByte(1); if (($u = $this->GIF_buffer[0]) == 0x00) { break; } $this->getByte($u); /* * 07.05.2007. * Implemented a new line for a new function * to determine the originaly delays between * frames. * */ if (4 == $u) { $this->GIF_delays[] = ($this->GIF_buffer[1] | $this->GIF_buffer[2] << 8); } } }
/* ::::::::::::::::::::::::::::::::::::::::::::::::::: :: :: GIFReadExtension ( ) ::
entailment