<commit_before><?php
	/**
	 * @package content
	 */

	/**
	 * The Publish page is where the majority of an Authors time will
	 * be spent in Symphony with adding, editing and removing entries
	 * from Sections. This Page controls the entries table as well as
	 * the Entry creation screens.
	 */
	require_once(TOOLKIT . '/class.administrationpage.php');
	require_once(TOOLKIT . '/class.entrymanager.php');
	require_once(TOOLKIT . '/class.sectionmanager.php');
	require_once(CONTENT . '/class.sortable.php');

	Class contentPublish extends AdministrationPage{

		public $_errors = array();

		public function sort(&$sort, &$order, $params) {
			$section = $params['current-section'];

			if(is_null($sort)){
				$sort = $section->getDefaultSortingField();
			}

			if(is_numeric($sort)){
				if($section->get('entry_order') != $sort || $section->get('entry_order_direction') != $order){
					SectionManager::edit(
						$section->get('id'),
						array('entry_order' => $sort, 'entry_order_direction' => $order)
					);

					$query = '?sort=' . $sort . '&order=' . $order;

					redirect(Administration::instance()->getCurrentPageURL() . $query . $params['filters']);
				}
			}
			else if($sort == 'id'){
				EntryManager::setFetchSortingField('id');
				EntryManager::setFetchSortingDirection($order);
			}
		}

		public function action(){
			$this->__switchboard('action');
		}

		public function __switchboard($type='view'){

			$function = ($type == 'action' ? '__action' : '__view') . ucfirst($this->_context['page']);

			if(!method_exists($this, $function)) {
				// If there is no action function, just return without doing anything
				if($type == 'action') return;

				Administration::instance()->errorPageNotFound();
			}

			$this->$function();
		}

		public function view(){
			$this->__switchboard();
		}

		public function __viewIndex(){
			if(!$section_id = SectionManager::fetchIDFromHandle($this->_context['section_handle'])) {
				Administration::instance()->customError(__('Unknown Section'), __('The Section you are looking for, %s, could not be found.', array('<code>' . $this->_context['section_handle'] . '</code>')));
			}

			$section = SectionManager::fetch($section_id);

			$this->setPageType('table');
			$this->setTitle(__('%1$s &ndash; %2$s', array($section->get('name'), __('Symphony'))));
			$this->Form->setAttribute("class", $this->_context['section_handle']);

			$filters = array();
			$filter_querystring = $prepopulate_querystring = $where = $joins = NULL;
			$current_page = (isset($_REQUEST['pg']) && is_numeric($_REQUEST['pg']) ? max(1, intval($_REQUEST['pg'])) : 1);

			if(isset($_REQUEST['filter'])) {

				// legacy implementation, convert single filter to an array
				// split string in the form ?filter=handle:value
				if(!is_array($_REQUEST['filter'])) {
					list($field_handle, $filter_value) = explode(':', $_REQUEST['filter'], 2);
					$filters[$field_handle] = rawurldecode($filter_value);
				} else {
					$filters = $_REQUEST['filter'];
				}

				foreach($filters as $handle => $value) {
					$field_id = Symphony::Database()->fetchVar('id', 0, sprintf("
						SELECT `f`.`id`
						FROM `tbl_fields` AS `f`
						LEFT JOIN `tbl_sections` AS `s` ON (`s`.`id` = `f`.`parent_section`)
						WHERE f.`element_name` = '%s'
						AND `s`.`handle` = '%s'
						LIMIT 1
					",
						Symphony::Database()->cleanValue($handle),
						$section->get('handle'))
					);

					$field = FieldManager::fetch($field_id);

					if($field instanceof Field) {
						// For deprecated reasons, call the old, typo'd function name until the switch to the
						// properly named buildDSRetrievalSQL function.
						$field->buildDSRetrivalSQL(array($value), $joins, $where, false);
						$filter_querystring .= sprintf("filter[%s]=%s&amp;", $handle, rawurlencode($value));
						$prepopulate_querystring .= sprintf("prepopulate[%d]=%s&amp;", $field_id, rawurlencode($value));
					} else {
						unset($filters[$i]);
					}
				}

				$filter_querystring = preg_replace("/&amp;$/", '', $filter_querystring);
				$prepopulate_querystring = preg_replace("/&amp;$/", '', $prepopulate_querystring);

			}

			Sortable::initialize($this, $entries, $sort, $order, array(
				'current-section' => $section,
				'filters' => ($filter_querystring ? "&amp;" . $filter_querystring : '')
			));

			$this->Form->setAttribute('action', Administration::instance()->getCurrentPageURL(). '?pg=' . $current_page.($filter_querystring ? "&amp;" . $filter_querystring : ''));

			$this->appendSubheading($section->get('name'), array(
				Widget::Anchor(__('Edit Section'), SYMPHONY_URL . '/blueprints/sections/edit/' . $section_id, __('Edit Section Configuration'), 'button'),
				Widget::Anchor(__('Create New'), Administration::instance()->getCurrentPageURL().'new/'.($filter_querystring ? '?' . $prepopulate_querystring : ''), __('Create a new entry'), 'create button', NULL, array('accesskey' => 'c'))
			));

			$entries = EntryManager::fetchByPage($current_page, $section_id, Symphony::Configuration()->get('pagination_maximum_rows', 'symphony'), $where, $joins);

			$visible_columns = $section->fetchVisibleColumns();
			$columns = array();

			if(is_array($visible_columns) && !empty($visible_columns)){

				foreach($visible_columns as $column){
					$columns[] = array(
						'label' => $column->label(),
						'sortable' => $column->isSortable(),
						'handle' => $column->get('id'),
						'attrs' => array(
							'id' => 'field-' . $column->get('id'),
							'class' => 'field-' . $column->get('type')
						)
					);
				}
			}
			else {
				$columns[] = array(
					'label' => __('ID'),
					'sortable' => true,
					'handle' => 'id'
				);
			}

			$aTableHead = Sortable::buildTableHeaders(
				$columns, $sort, $order,
				/* '&amp;pg='. $current_page . */ ($filter_querystring ? "&amp;" . $filter_querystring : '')
			);

			$child_sections = array();
			$associated_sections = $section->fetchAssociatedSections(true);
			if(is_array($associated_sections) && !empty($associated_sections)){
				foreach($associated_sections as $key => $as){
					$child_sections[$key] = SectionManager::fetch($as['child_section_id']);
					$aTableHead[] = array($child_sections[$key]->get('name'), 'col');
				}
			}

			/**
			 * Allows the creation of custom entries tablecolumns. Called
			 * after all the Section Visible columns have been added  as well<commit_msg>Catch DatabaseException on the Publish Index and display a notice to the user. Fixes #841<commit_after><?php
	/**
	 * @package content
	 */

	/**
	 * The Publish page is where the majority of an Authors time will
	 * be spent in Symphony with adding, editing and removing entries
	 * from Sections. This Page controls the entries table as well as
	 * the Entry creation screens.
	 */
	require_once(TOOLKIT . '/class.administrationpage.php');
	require_once(TOOLKIT . '/class.entrymanager.php');
	require_once(TOOLKIT . '/class.sectionmanager.php');
	require_once(CONTENT . '/class.sortable.php');

	Class contentPublish extends AdministrationPage{

		public $_errors = array();

		public function sort(&$sort, &$order, $params) {
			$section = $params['current-section'];

			if(is_null($sort)){
				$sort = $section->getDefaultSortingField();
			}

			if(is_numeric($sort)){
				if($section->get('entry_order') != $sort || $section->get('entry_order_direction') != $order){
					SectionManager::edit(
						$section->get('id'),
						array('entry_order' => $sort, 'entry_order_direction' => $order)
					);

					$query = '?sort=' . $sort . '&order=' . $order;

					redirect(Administration::instance()->getCurrentPageURL() . $query . $params['filters']);
				}
			}
			else if($sort == 'id'){
				EntryManager::setFetchSortingField('id');
				EntryManager::setFetchSortingDirection($order);
			}
		}

		public function action(){
			$this->__switchboard('action');
		}

		public function __switchboard($type='view'){

			$function = ($type == 'action' ? '__action' : '__view') . ucfirst($this->_context['page']);

			if(!method_exists($this, $function)) {
				// If there is no action function, just return without doing anything
				if($type == 'action') return;

				Administration::instance()->errorPageNotFound();
			}

			$this->$function();
		}

		public function view(){
			$this->__switchboard();
		}

		public function __viewIndex(){
			if(!$section_id = SectionManager::fetchIDFromHandle($this->_context['section_handle'])) {
				Administration::instance()->customError(__('Unknown Section'), __('The Section you are looking for, %s, could not be found.', array('<code>' . $this->_context['section_handle'] . '</code>')));
			}

			$section = SectionManager::fetch($section_id);

			$this->setPageType('table');
			$this->setTitle(__('%1$s &ndash; %2$s', array($section->get('name'), __('Symphony'))));
			$this->Form->setAttribute("class", $this->_context['section_handle']);

			$filters = array();
			$filter_querystring = $prepopulate_querystring = $where = $joins = NULL;
			$current_page = (isset($_REQUEST['pg']) && is_numeric($_REQUEST['pg']) ? max(1, intval($_REQUEST['pg'])) : 1);

			if(isset($_REQUEST['filter'])) {

				// legacy implementation, convert single filter to an array
				// split string in the form ?filter=handle:value
				if(!is_array($_REQUEST['filter'])) {
					list($field_handle, $filter_value) = explode(':', $_REQUEST['filter'], 2);
					$filters[$field_handle] = rawurldecode($filter_value);
				} else {
					$filters = $_REQUEST['filter'];
				}

				foreach($filters as $handle => $value) {
					$field_id = Symphony::Database()->fetchVar('id', 0, sprintf("
						SELECT `f`.`id`
						FROM `tbl_fields` AS `f`
						LEFT JOIN `tbl_sections` AS `s` ON (`s`.`id` = `f`.`parent_section`)
						WHERE f.`element_name` = '%s'
						AND `s`.`handle` = '%s'
						LIMIT 1
					",
						Symphony::Database()->cleanValue($handle),
						$section->get('handle'))
					);

					$field = FieldManager::fetch($field_id);

					if($field instanceof Field) {
						// For deprecated reasons, call the old, typo'd function name until the switch to the
						// properly named buildDSRetrievalSQL function.
						$field->buildDSRetrivalSQL(array($value), $joins, $where, false);
						$filter_querystring .= sprintf("filter[%s]=%s&amp;", $handle, rawurlencode($value));
						$prepopulate_querystring .= sprintf("prepopulate[%d]=%s&amp;", $field_id, rawurlencode($value));
					} else {
						unset($filters[$i]);
					}
				}

				$filter_querystring = preg_replace("/&amp;$/", '', $filter_querystring);
				$prepopulate_querystring = preg_replace("/&amp;$/", '', $prepopulate_querystring);

			}

			Sortable::initialize($this, $entries, $sort, $order, array(
				'current-section' => $section,
				'filters' => ($filter_querystring ? "&amp;" . $filter_querystring : '')
			));

			$this->Form->setAttribute('action', Administration::instance()->getCurrentPageURL(). '?pg=' . $current_page.($filter_querystring ? "&amp;" . $filter_querystring : ''));

			$this->appendSubheading($section->get('name'), array(
				Widget::Anchor(__('Edit Section'), SYMPHONY_URL . '/blueprints/sections/edit/' . $section_id, __('Edit Section Configuration'), 'button'),
				Widget::Anchor(__('Create New'), Administration::instance()->getCurrentPageURL().'new/'.($filter_querystring ? '?' . $prepopulate_querystring : ''), __('Create a new entry'), 'create button', NULL, array('accesskey' => 'c'))
			));

			// Check that the filtered query fails that the filter is dropped and an
			// error is logged. #841 ^BA
			try {
				$entries = EntryManager::fetchByPage($current_page, $section_id, Symphony::Configuration()->get('pagination_maximum_rows', 'symphony'), $where, $joins);
			}
			catch(DatabaseException $ex) {
				$this->pageAlert(__('An error occurred while retrieving filtered entries. Showing all entries instead.'), Alert::ERROR);
				$filter_querystring = null;
				Symphony::Log()->pushToLog(sprintf(
						'%s - %s%s%s',
						$section->get('name') . ' Publish Index',
						$ex->getMessage(),
						($ex->getFile() ? " in file " .  $ex->getFile() : null),
						($ex->getLine() ? " on line " . $ex->getLine() : null)
					),
					E_NOTICE, true
				);
				$entries = EntryManager::fetchByPage($current_page, $section_id, Symphony::Configuration()->get('pagination_maximum_rows', 'symphony'));
			}

			$visible_columns = $section->fetchVisibleColumns();
			$columns = array();

			if(is_array($visible_columns) && !empty($visible_columns)){

				foreach($visible_columns as $column){
					$columns[] = array(
						'label' => $column->label(),
						'sortable' => $column->isSortable(),
						'handle' => $column->get('id'),
						'attrs' => array(
							'id' => 'field-' . $column->get('id'),
							'class' => 'field-' . $column->get('type')
						)
					);
				}
			}
			else {
				$columns[] = array(
					'label' => __('ID'),
					'sortable' => true,
					'handle' => 'id'
				);
			}

			$aTableHead = Sortable::buildTableHeaders(
				$columns, $sort, $order,
				($filter_querystring) ? "&amp;" . $filter_querystring : ''
			);

			$child_sections = array();
			$associated_sections = $section->fetchAssociatedSections(true);
			if(is_array($associated_sections) && !empty($associated_sections)){
				foreach($associated_sections as $key => $as){
					$child_sections[$key] = SectionManager::fetch($as['child_section_id']);
					$aTableHead[] = array($child_sections[$key]->get('name'), 'col');
				}
			}

			/**
			 * Allows the creation of custom entries tablecolumns. Called
			 * after all the Section Visible columns have been added  as well
{'fraction_non_alphanumeric': 0.18780828977398217, 'fraction_numerical': 0.0014724287712581904, 'mean_word_length': 4.03670745272525, 'pattern_counts': {'":': 0, '<': 9, '<?xml version=': 0, '>': 124, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '6523444', 'n_tokens_mistral': 5138, 'n_tokens_neox': 4127, 'n_words': 860}