<?php
/*
 * Copyright (c) 2026, Tribal Limited
 * All rights reserved.
 * 
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions are met:
 *     * Redistributions of source code must retain the above copyright
 *       notice, this list of conditions and the following disclaimer.
 *     * Redistributions in binary form must reproduce the above copyright
 *       notice, this list of conditions and the following disclaimer in the
 *       documentation and/or other materials provided with the distribution.
 *     * Neither the name of Zenario, Tribal Limited nor the
 *       names of its contributors may be used to endorse or promote products
 *       derived from this software without specific prior written permission.
 * 
 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
 * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED. IN NO EVENT SHALL TRIBAL LTD BE LIABLE FOR ANY
 * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
 * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
 * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
 * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
if (!defined('NOT_ACCESSED_DIRECTLY')) exit('This file may not be directly accessed');


//The $importantGetRequests should be passed to us in the URL, get them and decode them.
if (empty($_GET['get']) || !($importantGetRequests = json_decode($_GET['get'], true))) {
	$importantGetRequests = [];
}

//Look up details on the content item and version we are displaying the toolbar for
$content = ze\row::get('content_items', true, ['id' => $cID, 'type' => $cType]);
$chain = ze\row::get('translation_chains', true, ['equiv_id' => $content['equiv_id'], 'type' => $cType]);
$version = ze\row::get('content_item_versions', true, ['id' => $cID, 'type' => $cType, 'version' => $cVersion]);
$menuItems = ze\menu::getFromContentItem($cID, $cType, true, false, true, true);

$tagId = $cType. '_'. $cID;
$isMultilingual = ze\lang::count() > 1;
$orgLink = ze\link::absolute(). 'organizer.php?fromCID='. $cID. '&fromCType='. $cType;

if (!$content || !$version) {
	exit;
} else {
	ze\content::setShowableContent($content, $chain, $version, false);
	$layout = ze\layout::details(ze::$layoutId);
	$LayoutIdentifier = ze\layoutAdm::codeName(ze::$layoutId);
	$layout['usage'] = ze\layoutAdm::usage(ze::$layoutId);
	
	$adminToolbar['sections']['layout']['buttons']['settings']['label'] = ze\admin::phrase('Edit [[name]] settings', ['name' => $LayoutIdentifier]);
	$adminToolbar['sections']['layout']['buttons']['settings']['admin_box']['key']['id'] = ze::$layoutId;
	
	//Hide "copy from.." when content type is document.
	if ($cType == 'document') {
		$adminToolbar['sections']['actions']['buttons']['create_draft_by_overwriting']['hidden'] = true;

		//If this is a document, apply the "Rescan" confirmation merge fields...
		if (ze\priv::check('_PRIV_EDIT_DRAFT', $cID, $cType) && isset($adminToolbar['sections']['actions']['buttons']['rescan_extract']['ajax']['confirm']['message'])) {
			$tagFormattedNicely = ze\content::formatTag($cID, $cType);
			ze\lang::applyMergeFields($adminToolbar['sections']['actions']['buttons']['rescan_extract']['ajax']['confirm']['message'], ['tag' => $tagFormattedNicely]);
		}
	} else {
		//... or hide the "Rescan" button otherwise.
		$adminToolbar['sections']['actions']['buttons']['rescan_extract']['hidden'] = true;
	}
	
	//Set the link to Gridmaker
	if (isset($adminToolbar['sections']['layout']['buttons']['edit_body_slots'])) {
		$adminToolbar['sections']['layout']['buttons']['edit_body_slots']['popout']['href'] .= '&id='. ze::$layoutId;
		$adminToolbar['sections']['layout']['buttons']['edit_body_slots']['label'] = ze\admin::phrase('Edit [[name]]', ['name' => $LayoutIdentifier]);
	}
	
	//Don't show the links to edit the header/footer if this layout doesn't use them
	if (!$layout['header_and_footer'] && isset($adminToolbar['sections']['layout']['buttons']['edit_head_slots'])) {
		$adminToolbar['sections']['layout']['buttons']['edit_head_slots']['disabled'] =
		$adminToolbar['sections']['layout']['buttons']['edit_foot_slots']['disabled'] = true;
		$adminToolbar['sections']['layout']['buttons']['edit_head_slots']['tooltip'] =
		$adminToolbar['sections']['layout']['buttons']['edit_foot_slots']['tooltip'] = ze\admin::phrase('This layout does not use the site-wide header/footer.');
	}
	
	if (!ze::$skinId
	 || !($skin = ze\row::get('skins', ['display_name', 'enable_editable_css'], ze::$skinId))
	 || !($skin['enable_editable_css'])) {
		unset($adminToolbar['sections']['layout']['buttons']['edit_skin']);
	
	} elseif (isset($adminToolbar['sections']['layout']['buttons']['edit_skin'])) {
		$adminToolbar['sections']['layout']['buttons']['edit_skin']['admin_box']['key']['skinId'] = ze::$skinId;
		$adminToolbar['sections']['layout']['buttons']['edit_skin']['label'] =
			ze\admin::phrase('Edit skin CSS', $skin);
	}
	
	if (isset($adminToolbar['sections']['layout']['buttons']['settings']['admin_box']['key']['id'])) {
		$adminToolbar['sections']['layout']['buttons']['settings']['admin_box']['key']['id'] = ze::$layoutId;
	}

	//Pinned vs not pinned
	if (ze\row::get('content_types', 'allow_pinned_content', ['content_type_id' => $cType])) {
		if ($version['pinned']) {
			unset($adminToolbar['sections']['icons']['buttons']['not_pinned']);
		} else {
			unset($adminToolbar['sections']['icons']['buttons']['pinned']);
		}
	} else {
		unset($adminToolbar['sections']['icons']['buttons']['not_pinned']);
		unset($adminToolbar['sections']['icons']['buttons']['pinned']);
	}
	
	
	//Show an icon for staging mode if available.
	if (!ze::setting('enable_staging_mode')) {
		unset($adminToolbar['sections']['icons']['buttons']['staging_mode']);
	
	} elseif ($chain['privacy'] != 'public') {
		unset($adminToolbar['sections']['icons']['buttons']['staging_mode']['admin_box']);
		$adminToolbar['sections']['icons']['buttons']['staging_mode']['css_class'] .= ' zenario_at_icon_staging_mode_not_available';
		$adminToolbar['sections']['icons']['buttons']['staging_mode']['tooltip'] =
			ze\admin::phrase('Staging mode can\'t be used for private content items');
	
	} elseif (!ze::$isDraft) {
		unset($adminToolbar['sections']['icons']['buttons']['staging_mode']['admin_box']);
		$adminToolbar['sections']['icons']['buttons']['staging_mode']['css_class'] .= ' zenario_at_icon_staging_mode_not_available';
		$adminToolbar['sections']['icons']['buttons']['staging_mode']['tooltip'] =
			ze\admin::phrase('To use staging mode, create a draft');
	
	} else {
		if ($stagingVersion = ze\row::get('content_item_versions',
			['access_code', 'version'],
			['id' => $cID, 'type' => $cType, 'access_code' => ['!' => null]]
		)) {
			$link = ze\contentAdm::stagingModeLink($cID, $cType, $stagingVersion['access_code']);
		
			$adminToolbar['sections']['icons']['buttons']['staging_mode']['tooltip'] =
				ze\admin::phrase('Staging mode enabled for this version [[version]], using access code [[access_code]], click for options', $stagingVersion);
		
			#$adminToolbar['sections']['icons']['buttons']['staging_mode']['tooltip'] =
			#	ze\admin::phrase('Staging enabled for version [[version]] with code [[access_code]]. Click to copy URL.', $stagingVersion);
			#$adminToolbar['sections']['icons']['buttons']['staging_mode']['onclick'] =
			#	'zenarioA.copy("'. ze\escape::js($link). '");';
			
			$adminToolbar['sections']['icons']['buttons']['staging_mode']['css_class'] .= ' zenario_at_icon_staging_mode_enabled';
		
		} else {
			$adminToolbar['sections']['icons']['buttons']['staging_mode']['css_class'] .= ' zenario_at_icon_staging_mode_disabled';
			$adminToolbar['sections']['icons']['buttons']['staging_mode']['tooltip'] =
				ze\admin::phrase('Click to enable staging mode for this draft');
		}
	}
	
	
	//Featured image
	if ($version['feature_image_id']) {
		$width = $height = $url = false;
		$widthLimit = $heightLimit = 30;

		ze\image::link($width, $height, $url, $version['feature_image_id'], $widthLimit, $heightLimit, 'resize_and_crop', 0, false, $fullPath = true);
		$adminToolbar['sections']['edit']['buttons']['view_items_images']['featured_image_src'] = htmlspecialchars($url);
		$adminToolbar['sections']['edit']['buttons']['view_items_images']['featured_image_alt'] = ze\admin::phrase('Featured image');
	} else {
		$adminToolbar['sections']['edit']['buttons']['view_items_images']['featured_image_alt'] = ze\admin::phrase('No featured image');
	}
	
	//Content item image count
	$inlineImages = ze\row::getArray(
		'inline_images',
		'image_id',
		['foreign_key_to' => 'content', 'foreign_key_id' => $cID, 'foreign_key_char' => $cType, 'foreign_key_version' => $cVersion]
	);

	if ($inlineImages) {
		$adminToolbar['sections']['edit']['buttons']['view_items_images']['record_count'] =
		$adminToolbar['sections']['restricted_editing']['buttons']['view_items_images']['record_count'] = count($inlineImages);
	}
}

if (ze::$status == 'trashed' && $cVersion == ze::$adminVersion) {
	unset($adminToolbar['sections']['actions']['buttons']['rollback_item']);
	unset($adminToolbar['sections']['actions']['buttons']['no_rollback_item']);
	unset($adminToolbar['sections']['actions']['buttons']['cant_start_editing']);
}

if (ze::in(ze::$status, 'hidden', 'trashed') && $cVersion == ze::$adminVersion) {
	unset($adminToolbar['sections']['actions']['buttons']['start_editing']);
} else {
	unset($adminToolbar['sections']['actions']['buttons']['redraft']);
}

if (ze::$status == 'trashed' || ($cVersion < ze::$adminVersion && (!ze::$visitorVersion || $cVersion < ze::$visitorVersion))) {
	unset($adminToolbar['toolbars']['menu1']);
	unset($adminToolbar['sections']['menu1']);
	unset($adminToolbar['sections']['actions']['buttons']['start_editing']);
	unset($adminToolbar['sections']['actions']['buttons']['cant_start_editing']);
}

//Disable the "start editing"/"Redraft" buttons if a draft exists
if (ze::$adminVersion > $cVersion
 && ze::$adminVersion > ze::$visitorVersion) {
	unset($adminToolbar['sections']['actions']['buttons']['start_editing']);
	unset($adminToolbar['sections']['actions']['buttons']['rollback_item']);
} else {
	unset($adminToolbar['sections']['actions']['buttons']['cant_start_editing']);
	unset($adminToolbar['sections']['actions']['buttons']['no_rollback_item']);
}

if (ze::$status == 'trashed' || $cVersion != ze::$adminVersion) {
	unset($adminToolbar['toolbars']['edit']);
	unset($adminToolbar['toolbars']['edit_disabled']);
} else {
	unset($adminToolbar['toolbars']['rollback']);
	unset($adminToolbar['sections']['actions']['buttons']['rollback_item']);
}

//Most recent Version
if ($cVersion == ze::$adminVersion) {
	unset($adminToolbar['sections']['actions']['buttons']['no_rollback_item']);
	unset($adminToolbar['sections']['actions']['buttons']['cant_start_editing']);

} else {
	unset($adminToolbar['toolbars']['edit']);
	unset($adminToolbar['toolbars']['layout']);
	unset($adminToolbar['sections']['slot_controls']['buttons']['item_head']);
	unset($adminToolbar['sections']['slot_controls']['buttons']['item_foot']);
	unset($adminToolbar['sections']['actions']['buttons']['delete_draft']);
	unset($adminToolbar['sections']['actions']['buttons']['hide_content']);
	unset($adminToolbar['sections']['actions']['buttons']['delist']);
	unset($adminToolbar['sections']['actions']['buttons']['relist']);
	unset($adminToolbar['sections']['actions']['buttons']['trash_content']);
	unset($adminToolbar['sections']['actions']['buttons']['create_draft_by_copying']);
	unset($adminToolbar['sections']['actions']['buttons']['create_draft_by_overwriting']);
	unset($adminToolbar['sections']['slot_wand']['buttons']['slot_wand_on']);
	unset($adminToolbar['sections']['slot_wand']['buttons']['slot_wand_off']);
}


$permsOnThisItem = true;
$permsOnThisContentType = true;
if (ze\admin::hasSpecificPerms()) {
	
	$permsOnThisItem = ze\priv::check('_PRIV_EDIT_DRAFT', $cID, $cType);
	$permsOnThisContentType = ze\priv::check('_PRIV_EDIT_DRAFT', false, $cType);
	
	//Check if this admin can edit any of the menu text...
	$canEditSomeMenuText = false;
	foreach ($menuItems as $i => &$menuItem) {
		if (ze\priv::onMenuText('_PRIV_EDIT_MENU_TEXT', $menuItem['id'], $menuItem['language_id'], $menuItem['section_id'])) {
			$canEditSomeMenuText = true;
			break;
		}
	}
	
	//...and if not, don't show the menu toolbar
	if (!$canEditSomeMenuText) {
		$menuItems = [];
		unset($adminToolbar['toolbars']['menu1']);
		unset($adminToolbar['toolbars']['menu_secondary']);
		unset($adminToolbar['sections']['primary_menu_node']);
	}
}

if ($permsOnThisItem) {
	$editToolbar = 'edit';
	unset($adminToolbar['toolbars']['restricted_editing']);
	
	if (!$permsOnThisContentType) {
		unset($adminToolbar['sections']['create']['buttons']['duplicate_content']);
	}
} else {
	$editToolbar = 'restricted_editing';
	unset($adminToolbar['toolbars']['edit']);
	unset($adminToolbar['toolbars']['edit_disabled']);
	unset($adminToolbar['toolbars']['rollback']);
	unset($adminToolbar['sections']['create']['buttons']['duplicate_content']);
}




//Hidden Version
if ($cVersion == ze::$adminVersion && ze::$status == 'hidden') {
	foreach (['edit', 'edit_disabled'] as $toolbar) {
##		if (isset($adminToolbar['toolbars'][$toolbar])) {
##			$adminToolbar['toolbars'][$toolbar]['tooltip'] .= '<br/>'. ze\admin::phrase('This content item is hidden');
##		}
	}
	
	if (isset($adminToolbar['sections']['actions']['buttons']['republish'])) {
		if (!ze\sql::fetchRow('
			SELECT 1
			FROM '. DB_PREFIX. 'content_item_versions
			WHERE published_datetime IS NOT NULL
			  AND published_datetime
			  AND id = '. (int) ze::$cID. '
			  AND `type` = \''. ze\escape::asciiInSQL(ze::$cType). '\'
			LIMIT 1
		')) {
			$adminToolbar['sections']['actions']['buttons']['republish']['label'] = ze\admin::phrase('Publish');
		}
	}

} else {
	unset($adminToolbar['sections']['actions']['buttons']['republish']);
}

if (ze::$adminVersion == 1
 || !ze::in ($cVersion, ze::$visitorVersion, ze::$adminVersion)
 || !ze\row::exists('content_item_versions', [
		'id' => ze::$cID,
		'type' => ze::$cType,
		'version' => ['!' => [ze::$visitorVersion, ze::$adminVersion]]]
)) {
	unset($adminToolbar['sections']['actions']['buttons']['delete_archives']);
}

$menu = ze\menu::getFromContentItem($cID, $cType);

//Draft Version
if ($cVersion == ze::$adminVersion && ze::$isDraft) {
	
##	foreach (['edit', 'edit_disabled'] as $toolbar) {
##		if (isset($adminToolbar['toolbars'][$toolbar])) {
##			
##			if (!empty($adminToolbar['toolbars'][$toolbar]['tooltip'])) {
##				$adminToolbar['toolbars'][$toolbar]['tooltip'] .= '<br/>';
##			}
##			$adminToolbar['toolbars'][$toolbar]['tooltip'] .= ze\admin::phrase('This content item is a draft. Click to edit.');
##		}
##	}
	
	
	$adminToolbar['sections']['edit']['css_class'] = 'zenario_section_orange zenario_section_dark_text';
	
	// First draft
	if ($cVersion == 1) {
		$redirect_page = ze\admin::phrase('the Home page');
		if ($menu && $menu['parent_id']) {
			$redirectContent = ze\row::get('menu_nodes', ['equiv_id', 'content_type'], ['id' => $menu['parent_id']]);
			$redirectCID = $redirectContent['equiv_id'];
			$redrectCType = $redirectContent['content_type'];

			if (!empty($redirectCID) && !empty($redrectCType)) {
				$redirect_page = ze\content::formatTag($redirectCID, $redrectCType, -1, false, true);
			}
		}
		
		$adminToolbar['sections']['edit']['label'] = ze\admin::phrase('First draft');
		$adminToolbar['sections']['actions']['buttons']['delete_draft']['ajax']['confirm']['message'] = ze\admin::phrase("
			Zenario will delete the draft version of this content item. 
			
			As this is version 1, the content item will be permanently deleted and you will be redirected to [[redirect_page]].
			
			Proceed?
		", ['redirect_page' => $redirect_page]);
	} else {
		$adminToolbar['sections']['edit']['label'] = ze\admin::phrase('Draft');
	}

} else {
	unset($adminToolbar['sections']['actions']['buttons']['publish']);
	unset($adminToolbar['sections']['actions']['buttons']['delete_draft']);
	

	//Published Version
	if ((ze::$status == 'unlisted' && $cVersion == ze::$visitorVersion)
	 || (ze::$status == 'unlisted_with_draft' && $cVersion == ze::$visitorVersion)) {
		$adminToolbar['sections']['edit']['css_class'] = 'zenario_section_green zenario_section_dark_text';
		$adminToolbar['sections']['edit']['label'] = ze\admin::phrase('Published unlisted');
		unset($adminToolbar['sections']['actions']['buttons']['no_rollback_item']);
	
	} else
	if ($cVersion == ze::$visitorVersion) {
		$adminToolbar['sections']['edit']['css_class'] = 'zenario_section_green zenario_section_dark_text';
		$adminToolbar['sections']['edit']['label'] = ze\admin::phrase('Published');
		unset($adminToolbar['sections']['actions']['buttons']['no_rollback_item']);
	
	} else
	if ((ze::$status == 'hidden' && $cVersion == ze::$adminVersion)
	 || (ze::$status == 'hidden_with_draft' && $cVersion == ze::$adminVersion - 1)) {
		$adminToolbar['sections']['edit']['css_class'] = 'zenario_section_grey zenario_section_dark_text';
		$adminToolbar['sections']['edit']['label'] = ze\admin::phrase('Hidden');
	
	//Trashed content items
	} else
	if ((ze::$status == 'trashed' && $cVersion == ze::$adminVersion)
	 || (ze::$status == 'trashed_with_draft' && $cVersion == ze::$adminVersion - 1)) {
		$adminToolbar['sections']['edit']['css_class'] = 'zenario_section_brown zenario_section_dark_text';
		$adminToolbar['sections']['edit']['label'] = ze\admin::phrase('Trashed Item');
	
	//Archived/Previous Versions
	} else {
		$adminToolbar['sections']['edit']['css_class'] = 'zenario_section_brown zenario_section_dark_text';
		$adminToolbar['sections']['edit']['label'] = ze\admin::phrase('Bananas version');
	}
}

if (isset($adminToolbar['sections']['actions']['buttons']['delete_archives'])) {
	$sql = "
		SELECT COUNT(*)
		FROM " . DB_PREFIX . "content_items AS c
		INNER JOIN " . DB_PREFIX . "translation_chains AS tc
			ON c.equiv_id = tc.equiv_id
			AND c.type = tc.type
		INNER JOIN " . DB_PREFIX . "content_item_versions AS v
			ON c.id = v.id
			AND c.type = v.type
		WHERE
			v.id = " . (int) $cID . "
			AND v.type = '" . ze\escape::sql($cType) . "'
			AND v.version NOT IN (" . (int) ze::$visitorVersion . ", " . (int) ze::$adminVersion . ")";
	$result = ze\sql::select($sql);
	$archivedVersionsCount = ze\sql::fetchValue($result);
	
	$statusFormattedNicely = '';
	switch (ze::$status) {
		case 'first_draft':
		case 'published_with_draft':
		case 'unlisted_with_draft':
		case 'hidden_with_draft':
		case 'trashed_with_draft':
			$statusFormattedNicely = "Draft";
			break;
		case 'published':
			$statusFormattedNicely = "Published";
			break;
		case 'unlisted':
			$statusFormattedNicely = "Published unlisted";
			break;
		case 'hidden':
			$statusFormattedNicely = "Hidden";
			break;
		case 'trashed':
			$statusFormattedNicely = "Trashed";
			break;
	}
	
	ze\lang::applyMergeFields(
		$adminToolbar['sections']['actions']['buttons']['delete_archives']['ajax']['confirm']['message'],
		['archived_versions_count' => (int) $archivedVersionsCount, 'version' => ze::$adminVersion, 'admin_version_status' => ze\admin::phrase($statusFormattedNicely)]
	);
}


//Content with a draft version
if (ze::$isDraft) {
	unset($adminToolbar['sections']['actions']['buttons']['start_editing']);
	unset($adminToolbar['sections']['actions']['buttons']['rollback_item']);
	unset($adminToolbar['sections']['actions']['buttons']['create_draft_by_copying']);
} else {
	unset($adminToolbar['sections']['actions']['buttons']['create_draft_by_overwriting']);
}

//The current Admin can edit the Content
if (ze\priv::check('_PRIV_EDIT_DRAFT', $cID, $cType)) {
	unset($adminToolbar['toolbars']['edit_disabled']);
} else {
	unset($adminToolbar['toolbars']['edit']);
	unset($adminToolbar['sections']['actions']['buttons']['publish']);
	
	if (isset($adminToolbar['toolbars']['edit_disabled'])) {
		if (ze\content::isDraft(ze::$status) && $cVersion != ze::$adminVersion) {
			$adminToolbar['toolbars']['edit_disabled']['tooltip'] =
				ze\admin::phrase('Editing of this version is disabled because a draft version exists');
		}
	}
}

//Check if deletion is allowed
$allowDelete = null;
if (isset($adminToolbar['sections']['actions']['buttons']['delete_draft'])) {
	$allowDelete = ze\contentAdm::allowDelete($cID, $cType, ze::$status);
	
	if (!$allowDelete) {
		if ($allowDelete === ze\contentAdm::CANT_BECAUSE_SPECIAL_PAGE) {
			$adminToolbar['sections']['actions']['buttons']['delete_draft']['disabled'] = true;
			$adminToolbar['sections']['actions']['buttons']['delete_draft']['disabled_tooltip'] = ze\admin::phrase("You can't delete a special page.");
		} else {
			unset($adminToolbar['sections']['actions']['buttons']['delete_draft']);
		}
	}
}

if (isset($adminToolbar['sections']['actions']['buttons']['delete_media_content_item'])) {
	if (!(ze::in($cType, 'audio', 'document', 'picture', 'video') && ze::$status != 'first_draft')) {
		unset($adminToolbar['sections']['actions']['buttons']['delete_media_content_item']);
	}
}

$allowHide = null;
if (isset($adminToolbar['sections']['actions']['buttons']['hide_content'])) {
	$allowHide = ze\contentAdm::allowHide($cID, $cType, ze::$status);
	
	if (!$allowHide) {
		if ($allowHide === ze\contentAdm::CANT_BECAUSE_SPECIAL_PAGE) {
			$adminToolbar['sections']['actions']['buttons']['hide_content']['disabled'] = true;
			$adminToolbar['sections']['actions']['buttons']['hide_content']['disabled_tooltip'] = ze\admin::phrase("You can't hide this special page.");
		} else {
			unset($adminToolbar['sections']['actions']['buttons']['hide_content']);
		}
	}
}

$allowDelist = null;
$allowRelist = null;
if (isset($adminToolbar['sections']['actions']['buttons']['delist'])) {
	if (ze\content::isUnlisted(ze::$status)) {
		$allowRelist = ze\contentAdm::allowRelist($cID, $cType, ze::$status);
	
		if (!$allowRelist) {
			if ($allowRelist === ze\contentAdm::CANT_BECAUSE_SPECIAL_PAGE) {
				$adminToolbar['sections']['actions']['buttons']['relist']['disabled'] = true;
				$adminToolbar['sections']['actions']['buttons']['relist']['disabled_tooltip'] = ze\admin::phrase("You can't make this special page listed.");
			} else {
				unset($adminToolbar['sections']['actions']['buttons']['relist']);
			}
		}
		unset($adminToolbar['sections']['actions']['buttons']['delist']);
	
	} else {
		$allowDelist = ze\contentAdm::allowDelist($cID, $cType, ze::$status);
		
		if (!$allowDelist) {
			if ($allowDelist === ze\contentAdm::CANT_BECAUSE_SPECIAL_PAGE) {
				$adminToolbar['sections']['actions']['buttons']['delist']['disabled'] = true;
				$adminToolbar['sections']['actions']['buttons']['delist']['disabled_tooltip'] = ze\admin::phrase("You can't make this special page unlisted.");
			} else {
				unset($adminToolbar['sections']['actions']['buttons']['delist']);
			}
		}
		unset($adminToolbar['sections']['actions']['buttons']['relist']);
	}
}

$allowTrash = null;
if (isset($adminToolbar['sections']['actions']['buttons']['trash_content'])) {
	$allowTrash = ze\contentAdm::allowTrash($cID, $cType, ze::$status);
	
	if (!$allowTrash) {
		if ($allowTrash === ze\contentAdm::CANT_BECAUSE_SPECIAL_PAGE) {
			$adminToolbar['sections']['actions']['buttons']['trash_content']['disabled'] = true;
			$adminToolbar['sections']['actions']['buttons']['trash_content']['disabled_tooltip'] = ze\admin::phrase("You can't trash a special page.");
		} else {
			unset($adminToolbar['sections']['actions']['buttons']['trash_content']);
		}
	}
}



//Only show locking info on drafts
$allowCopyingFromOther = true;
if (!ze::$isDraft) {
	unset($adminToolbar['sections']['actions']['buttons']['lock']);
	unset($adminToolbar['sections']['actions']['buttons']['locked']);
	unset($adminToolbar['sections']['actions']['buttons']['unlock']);
	unset($adminToolbar['sections']['actions']['buttons']['force_open']);

//The content item is not locked
} elseif (!$content['lock_owner_id']) {
	$adminToolbar['sections']['edit']['label'] = ze\admin::phrase('Unlocked');
	
	unset($adminToolbar['sections']['actions']['buttons']['locked']);
	unset($adminToolbar['sections']['actions']['buttons']['unlock']);
	unset($adminToolbar['sections']['actions']['buttons']['force_open']);

//The content item is locked
} else {
	$mrg = [
		'name' => htmlspecialchars(ze\admin::formatName($content['lock_owner_id'])),
		'time' => ze\admin::timeDiff(ze\date::now(), $content['locked_datetime'], 300)];
	
	if ($mrg['time'] === true) {
		$mrg['time'] = ze\admin::phrase('< 5 minutes');
	}
	
	//The current Admin has a lock on the content item
	if ($content['lock_owner_id'] && $content['lock_owner_id'] == ($_SESSION['admin_userid'] ?? false)) {
		$adminToolbar['sections']['actions']['buttons']['locked']['label'] = ze\admin::phrase('LOCKED by you');
		
		if ($version['scheduled_publish_datetime']) {
			unset($adminToolbar['sections']['actions']['buttons']['unlock']);
		} else {
			$adminToolbar['sections']['actions']['buttons']['unlock']['tooltip'] =
				ze\admin::phrase('Locked by you [[time]] ago|Click here to unlock', $mrg);
		}
		
		unset($adminToolbar['sections']['actions']['buttons']['lock']);
		unset($adminToolbar['sections']['actions']['buttons']['force_open']);
	
	//The current Admin can remove other's locks
	} elseif (ze\priv::check('_PRIV_CANCEL_CHECKOUT')) {
		$adminToolbar['sections']['actions']['buttons']['locked']['label'] = ze\admin::phrase('LOCKED');
		$adminToolbar['sections']['actions']['css_class'] = 'zenario_section_pink';
		
		if ($version['scheduled_publish_datetime']) {
			unset($adminToolbar['sections']['actions']['buttons']['force_open']);
		} else {
			$adminToolbar['sections']['actions']['buttons']['force_open']['tooltip'] =
				ze\admin::phrase('Locked by [[name]], [[time]] ago|Click here to force-unlock', $mrg);
		}
		
		if (isset($adminToolbar['toolbars']['edit'])) {
			$adminToolbar['toolbars']['edit']['help'] =
				[
					'message' => ze\admin::phrase('This content item is locked by another administrator. Certain functions may not be available.'),
					'message_type' => 'warning'];
		}
		
		unset($adminToolbar['sections']['actions']['buttons']['lock']);
		unset($adminToolbar['sections']['actions']['buttons']['unlock']);
		
		$adminToolbar['lock_warning'] =
			ze\admin::phrase('This content item is locked, you will need to unlock it via the Edit tab before you can make changes.');
		
		$allowCopyingFromOther = false;
	} else {
		$adminToolbar['sections']['actions']['buttons']['locked']['label'] = ze\admin::phrase('LOCKED');
		$adminToolbar['sections']['actions']['css_class'] = 'zenario_section_pink';
		
		$adminToolbar['sections']['actions']['buttons']['locked']['tooltip'] =
			ze\admin::phrase('Locked by [[name]], [[time]] ago', $mrg);
		
		if (isset($adminToolbar['toolbars']['edit'])) {
			$adminToolbar['toolbars']['edit']['help'] =
				[
					'message' => ze\admin::phrase('This content item is locked by another administrator. Certain functions may not be available.'),
					'message_type' => 'warning'];
		}
		
		unset($adminToolbar['sections']['actions']['buttons']['lock']);
		unset($adminToolbar['sections']['actions']['buttons']['unlock']);
		unset($adminToolbar['sections']['actions']['buttons']['force_open']);
		
		$adminToolbar['lock_warning'] =
			ze\admin::phrase('This content item is locked by another administrator, you will not be able to make changes.');
		
		$allowCopyingFromOther = false;
	}
}

if ($cType == 'document' || $cType == 'audio' || $cType == 'video' || !$allowCopyingFromOther) {
	unset($adminToolbar['sections']['actions']['buttons']['create_draft_by_copying']);
	unset($adminToolbar['sections']['actions']['buttons']['create_draft_by_overwriting']);
}


if (isset($adminToolbar['sections']['actions']['buttons']['create_draft_by_copying'])) {
	$adminToolbar['sections']['actions']['buttons']['create_draft_by_copying']['pick_items']['path'] = 'zenario__content/panels/content/refiners/content_type//'. $cType. '//';
}
if (isset($adminToolbar['sections']['actions']['buttons']['create_draft_by_overwriting'])) {
	$adminToolbar['sections']['actions']['buttons']['create_draft_by_overwriting']['pick_items']['path'] = 'zenario__content/panels/content/refiners/content_type//'. $cType. '//';
}

if (isset($adminToolbar['sections']['edit']['buttons']['item_template'])) {
	$adminToolbar['sections']['edit']['buttons']['item_template']['tooltip'] .=
				 ze\admin::phrase('Layout:'). ' '. htmlspecialchars($layout['id_and_name']).
		'<br/>'. ze\admin::phrase('Skin:'). ' '. htmlspecialchars(ze::$skinName);
}


	
//Only allow the admin to open Organizer to manage the images if the latest version of this content item is being viewed.
//If this is a previous version, still show the button, but make it disabled.
if (isset($adminToolbar['sections'][$editToolbar]['buttons']['view_items_images'])) {
	if ($cVersion == ze::$adminVersion) {
		$adminToolbar['sections'][$editToolbar]['buttons']['view_items_images']['organizer_quick']['path'] =
			'zenario__content/panels/content/item_buttons/images//'. $tagId. '//';
	} else {
		unset($adminToolbar['sections'][$editToolbar]['buttons']['view_items_images']['organizer_quick']);
		$adminToolbar['sections'][$editToolbar]['buttons']['view_items_images']['disabled'] = true;
		$adminToolbar['sections'][$editToolbar]['buttons']['view_items_images']['disabled_tooltip'] =
			ze\admin::phrase('Please view the latest version to manage images.');
	}
}

if (isset($adminToolbar['sections']['edit']['buttons']['view_slots'])) {
	$adminToolbar['sections']['edit']['buttons']['view_slots']['organizer_quick']['path'] =
		'zenario__content/panels/content/item_buttons/view_slots//'. $tagId. '//';
}


//Multilingual options
if (isset($adminToolbar['sections']['translations'])) {
	
	//Hide the multilingual section of the toolbar if not in use
	if (!$isMultilingual || ($cVersion != ze::$adminVersion && $cVersion != ze::$visitorVersion)) {
		$adminToolbar['sections']['translations']['hidden'] =
		$adminToolbar['toolbars']['translations']['hidden'] =
		$adminToolbar['sections']['translations_2']['hidden'] = true;

	} else {
		//Loop through every possible language, added a drop-down with options for that language
		$n = 0;
		$ord = 0;
		$counts = [
			'can_create_translation' => 0,
			'can_attach_existing_translation' => 0
		];
		foreach (ze\lang::getLanguages($includeAllLanguages = false, $orderByEnglishName = true, $defaultLangFirst = true) as $lang) {
			//Check to see if there is already a translation
			$translation = ze\row::get(
				'content_items',
				['id', 'type', 'alias', 'status'],
				['equiv_id' => ze::$equivId, 'type' => ze::$cType, 'language_id' => $lang['id']]
			);
			
			$exists = (bool) $translation;
			$isOG = $exists && $translation['id'] == ze::$equivId;
			$isCurrent = $exists && $translation['id'] == ze::$cID;
			$isDefault = $lang['id'] == ze::$defaultLang;
			
			//Select one of the different templates to copy, depending on what the status of the translation is
			if ($exists) {
				$lang['status'] = $translation['status'];
			} else {
				//For admins with limited permissions, do not display any options to create or attach.
				if (ze\priv::onLanguage('_PRIV_EDIT_DRAFT', $lang['id'])) {
					$buttons = $adminToolbar['sections']['translations']['custom_template_buttons_missing_can_create'];
					$counts['can_create_translation']++;
			
				}
			}
			
			if (isset($buttons)) {
				self::processAdminToolbarLanguage($buttons, $lang, $translation, $ord, $n, $isOG, $isDefault, $addWordDefaultToLabel = false, $exists, $importantGetRequests);
				
				$adminToolbar['sections']['translations']['buttons'] = array_merge(
					$adminToolbar['sections']['translations']['buttons'],
					$buttons
				);
				
				unset($buttons);
			}
			
			if ($isCurrent) {
				$adminToolbar['sections']['translations']['buttons']['current_language_button']['label'] = ze\admin::phrase(
					"[[language_name]] ([[language_code]])",
					['language_name' => $lang['english_name'], 'language_code' => $lang['id']]
				);
			}
			
			//Always display every enabled language on the list of "Existing languages",
			//even if this language has already been added to the default/create/attach list.
			if ($exists) {
				$buttons2 = $adminToolbar['sections']['translations']['custom_template_buttons_exists'];
			} else {
				$buttons2 = $adminToolbar['sections']['translations']['custom_template_buttons_missing'];
			}
			self::processAdminToolbarLanguage($buttons2, $lang, $translation, $ord, $n, $isOG, $isDefault, $addWordDefaultToLabel = true, $exists, $importantGetRequests);
			
			$adminToolbar['sections']['translations']['buttons'] = array_merge(
				$adminToolbar['sections']['translations']['buttons'],
				$buttons2
			);
			
			if ($isCurrent) {
				$buttons2[$n . '_go']['label'] .= ' (' . ze\admin::phrase('this item') . ')';
			}
			$adminToolbar['sections']['translations_2']['buttons'] = array_merge(
				$adminToolbar['sections']['translations_2']['buttons'],
				$buttons2
			);
			unset($buttons2);
		}
		
		if ($counts['can_create_translation'] == 0) {
			$adminToolbar['sections']['translations']['buttons']['create_translation_in_dropdown']['hidden'] =
			$adminToolbar['sections']['translations']['buttons']['attach_translation_in_dropdown']['hidden'] = true;
		}
	}
}







//Set up the version history navigation, including a left arrow, the current item in view and a right arrow, with the correct icons and tooltips on each
//Commented out by Tony to reduce clutter... eventually we can remove this I think.
/*
if ($cVersion > 1 && ze\row::exists('content_item_versions', ['id' => $cID, 'type' => $cType, 'version' => $cVersion - 1])) {
	$mrg = ['status' => ze\contentAdm::getContentItemVersionStatus($content, $cVersion - 1), 'prevver' => $cVersion - 1];
	$adminToolbar['sections']['history']['buttons']['content_item_left']['css_class'] = ze\contentAdm::getContentItemVersionToolbarIcon($content, $cVersion - 1, 'zenario_at_prev_version_');
	$adminToolbar['sections']['history']['buttons']['content_item_left']['frontend_link'] = DIRECTORY_INDEX_FILENAME. '?cID='. $cID. '&cType='. $cType. '&cVersion='. ($cVersion - 1);
	$adminToolbar['sections']['history']['buttons']['content_item_left']['label'] = ze\admin::phrase('View older, version [[prevver]] ([[status]])', $mrg);
	
	unset($adminToolbar['sections']['history']['buttons']['no_content_left']);
} else {
	unset($adminToolbar['sections']['history']['buttons']['content_item_left']);
}
*/

$mrg = ['status' => ze\contentAdm::getContentItemVersionStatus($content, $cVersion), 'v' => $cVersion];
//$adminToolbar['sections']['history']['buttons']['content_item_current']['css_class'] = ze\contentAdm::getContentItemVersionToolbarIcon($content, $cVersion, 'zenario_at_current_version_');
//$adminToolbar['sections']['history']['buttons']['content_item_current']['label'] = ze\admin::phrase('This is version [[v]] ([[status]])', $mrg);

//At the top right of the toolbar, show either a Publish button, or the current status if we can't currently publish
if (isset($adminToolbar['sections']['actions']['buttons']['publish'])) {
	unset($adminToolbar['sections']['actions']['buttons']['status_button']);

} else {
	$adminToolbar['sections']['actions']['buttons']['status_button']['css_class'] .= ' '. ze\contentAdm::getContentItemVersionToolbarIcon($content, $cVersion, 'zenario_at_status_button_');
	$adminToolbar['sections']['actions']['buttons']['status_button']['label'] = ze\contentAdm::getContentItemVersionStatusLabel($content, $cVersion);
}

/*
if (ze\row::exists('content_item_versions', ['id' => $cID, 'type' => $cType, 'version' => $cVersion + 1])) {
	$mrg = ['status' => ze\contentAdm::getContentItemVersionStatus($content, $cVersion + 1), 'nextver' => $cVersion + 1];
	$adminToolbar['sections']['history']['buttons']['content_item_right']['css_class'] = ze\contentAdm::getContentItemVersionToolbarIcon($content, $cVersion + 1, 'zenario_at_next_version_');
	$adminToolbar['sections']['history']['buttons']['content_item_right']['frontend_link'] = DIRECTORY_INDEX_FILENAME. '?cID='. $cID. '&cType='. $cType. '&cVersion='. ($cVersion + 1);
	$adminToolbar['sections']['history']['buttons']['content_item_right']['label'] = ze\admin::phrase('View newer, version [[nextver]] ([[status]])', $mrg);

	unset($adminToolbar['sections']['history']['buttons']['no_content_right']);

} else {
	unset($adminToolbar['sections']['history']['buttons']['content_item_right']);
}
*/



if (isset($adminToolbar['sections']['edit'])
 || isset($adminToolbar['sections']['layout'])) {
 	
 	$headAndFoot = ze\row::get(
 		'layouts',
 		['head_html', 'head_visitor_only', 'foot_html', 'foot_visitor_only'],
 		ze::$layoutId);
 	$layout = array_merge($layout, $headAndFoot);
}


if (isset($adminToolbar['sections']['slot_controls']['buttons']['item_head'])) {
	if ($version['head_html'] === null) {
		$adminToolbar['sections']['slot_controls']['buttons']['item_head']['css_class'] = 'head_slot_empty';
		$adminToolbar['sections']['slot_controls']['buttons']['item_head']['tooltip'] = ze\admin::phrase('Empty');
	} else {
		$adminToolbar['sections']['slot_controls']['buttons']['item_head']['css_class'] = 'head_slot_full';
		$adminToolbar['sections']['slot_controls']['buttons']['item_head']['tooltip'] = ze\admin::phrase('Populated');
		
		if ($version['head_visitor_only']) {
			$adminToolbar['sections']['slot_controls']['buttons']['item_head']['tooltip'] .= '<br/>'. ze\admin::phrase("Don't send HTML/JS when in admin mode");
		}
	}
}


if (isset($adminToolbar['sections']['slot_controls']['buttons']['item_foot'])) {
	if ($version['foot_html'] === null) {
 		$adminToolbar['sections']['slot_controls']['buttons']['item_foot']['css_class'] = 'foot_slot_empty';
 		$adminToolbar['sections']['slot_controls']['buttons']['item_foot']['tooltip'] = ze\admin::phrase('Empty');
 	} else {
 		$adminToolbar['sections']['slot_controls']['buttons']['item_foot']['css_class'] = 'foot_slot_full';
 		$adminToolbar['sections']['slot_controls']['buttons']['item_foot']['tooltip'] = ze\admin::phrase('Populated');
 		
 		if ($version['foot_visitor_only']) {
			$adminToolbar['sections']['slot_controls']['buttons']['item_foot']['tooltip'] .= '<br/>'. ze\admin::phrase("Don't send HTML/JS when in admin mode");
		}
 	}
}


if (isset($adminToolbar['sections']['layout'])) {
	$adminToolbar['sections']['layout']['buttons']['id_and_name']['label'] =
		ze\admin::phrase('Layout: [[id_and_name]]', $layout);
	
	if ($layout['usage'] == 1) {
		$adminToolbar['sections']['layout']['buttons']['usage']['label'] =
			ze\admin::phrase('[[usage]] content item uses this layout', $layout);
	} else {
		$adminToolbar['sections']['layout']['buttons']['usage']['label'] =
			ze\admin::phrase('[[usage]] content items use this layout', $layout);
	}
 	
 	$layoutLink =
 	$adminToolbar['sections']['layout']['buttons']['skq']['organizer_quick']['path'] =
 		$layout['status'] == 'active'?
 			'zenario__layouts/panels/layouts//'. ze::$layoutId
 		:	'zenario__layouts/panels/layouts/refiners/archived////'. ze::$layoutId;
 	
 	
 	if ($version['head_overwrite']) {
		if ($layout['head_html'] === null) {
			$adminToolbar['sections']['slot_controls']['buttons']['layout_head']['css_class'] = 'head_slot_empty_overwritten';
	 		$adminToolbar['sections']['slot_controls']['buttons']['layout_head']['tooltip'] = ze\admin::phrase('Empty');
		} else {
			$adminToolbar['sections']['slot_controls']['buttons']['layout_head']['css_class'] = 'head_slot_full_overwritten';
	 		$adminToolbar['sections']['slot_controls']['buttons']['layout_head']['tooltip'] = ze\admin::phrase('Populated');
		}
 		$adminToolbar['sections']['slot_controls']['buttons']['layout_head']['tooltip'] .= '<br/>'. ze\admin::phrase('Is overridden by a more granular entry');
 	} else {
		if ($layout['head_html'] === null) {
			$adminToolbar['sections']['slot_controls']['buttons']['layout_head']['css_class'] = 'head_slot_empty';
	 		$adminToolbar['sections']['slot_controls']['buttons']['layout_head']['tooltip'] = ze\admin::phrase('Empty');
		} else {
			$adminToolbar['sections']['slot_controls']['buttons']['layout_head']['css_class'] = 'head_slot_full';
	 		$adminToolbar['sections']['slot_controls']['buttons']['layout_head']['tooltip'] = ze\admin::phrase('Populated');
		}
 	}
 	if ($layout['head_visitor_only']) {
 		$adminToolbar['sections']['slot_controls']['buttons']['layout_head']['tooltip'] .= '<br/>'. ze\admin::phrase('Not output in admin mode');
 	}
 	$adminToolbar['sections']['slot_controls']['buttons']['layout_head']['label'] = ze\admin::phrase('HTML/JS in <head> for [[name]]', ['name' => $LayoutIdentifier]);
 	
 	
 	
 	if ($version['foot_overwrite']) {
		if ($layout['foot_html'] === null) {
			$adminToolbar['sections']['slot_controls']['buttons']['layout_foot']['css_class'] = 'foot_slot_empty_overwritten';
	 		$adminToolbar['sections']['slot_controls']['buttons']['layout_foot']['tooltip'] = ze\admin::phrase('Empty');
		} else {
			$adminToolbar['sections']['slot_controls']['buttons']['layout_foot']['css_class'] = 'foot_slot_full_overwritten';
	 		$adminToolbar['sections']['slot_controls']['buttons']['layout_foot']['tooltip'] = ze\admin::phrase('Populated');
		}
 		$adminToolbar['sections']['slot_controls']['buttons']['layout_foot']['tooltip'] .= '<br/>'. ze\admin::phrase('Is overridden by a more granular entry');
 	} else {
		if ($layout['foot_html'] === null) {
			$adminToolbar['sections']['slot_controls']['buttons']['layout_foot']['css_class'] = 'foot_slot_empty';
	 		$adminToolbar['sections']['slot_controls']['buttons']['layout_foot']['tooltip'] = ze\admin::phrase('Empty');
		} else {
			$adminToolbar['sections']['slot_controls']['buttons']['layout_foot']['css_class'] = 'foot_slot_full';
	 		$adminToolbar['sections']['slot_controls']['buttons']['layout_foot']['tooltip'] = ze\admin::phrase('Populated');
		}
 	}
 	if ($layout['foot_visitor_only']) {
 		$adminToolbar['sections']['slot_controls']['buttons']['layout_foot']['tooltip'] .= '<br/>'. ze\admin::phrase('Not output in admin mode');
 	}
 	$adminToolbar['sections']['slot_controls']['buttons']['layout_foot']['label'] = ze\admin::phrase('HTML/JS before </body> for [[name]]', ['name' => $LayoutIdentifier]);


	$siteWideHead = ze::setting('sitewide_head');
	$siteWideBody = ze::setting('sitewide_body');
	$siteWideFoot = ze::setting('sitewide_foot');
	$siteWideAnalyticsHtml = ze::setting('sitewide_analytics_html');
	$siteWideSocialMediaHtml = ze::setting('sitewide_social_media_html');

	if ($siteWideHead || $siteWideBody || $siteWideFoot || $siteWideAnalyticsHtml || $siteWideSocialMediaHtml) {
		$adminToolbar['sections']['slot_controls']['buttons']['global']['css_class'] = 'global_slot_full';
		$adminToolbar['sections']['slot_controls']['buttons']['global']['tooltip'] = ze\admin::phrase('Populated');
	} else {
		$adminToolbar['sections']['slot_controls']['buttons']['global']['css_class'] = 'global_slot_empty';
		$adminToolbar['sections']['slot_controls']['buttons']['global']['tooltip'] = ze\admin::phrase('Empty');
	}
	
	//Add a tab-link to view the current layout in Organizer
	if (isset($adminToolbar['toolbars']['layout'])) {
		$adminToolbar['toolbars']['layout']['tab_link'] = [
			'href' => $orgLink. '#'. $layoutLink
		];
	}
}







if (isset($adminToolbar['sections']['primary_menu_node'])) {
	
	//Content that is not in the Menu
	if (empty($menuItems)) {
		if (!empty($adminToolbar['toolbars']['menu1'])
		 && !empty($adminToolbar['sections']['no_menu_nodes'])) {
			$adminToolbar['sections']['menu1'] = $adminToolbar['sections']['no_menu_nodes'];
			$adminToolbar['toolbars']['menu1']['warning_icon'] = 'zenario_link_status zenario_link_status__menu_warning';
			$adminToolbar['toolbars']['menu1']['tooltip'] .= '<br/>'. ze\admin::phrase('
				This content item is not in the menu!<br/>
				Click the "Attach content item to menu" button to attach the item to the menu.
			');
		}
	//Content with at least one Menu Node
	} else {
		
		//For each Menu Node, create a copy of the Menu Section
		$primary = true;
		$unique = false;
		$numberOfMenuItems = 0;
		foreach ($menuItems as $i => &$menuItem) {
			++$numberOfMenuItems;
			
			//Start numbering Menu Nodes from 1, not from 0
			++$i;
			
			if ($i > 1 && isset($adminToolbar['toolbars']['menu_secondary'])) {
				//Add extra tabs for each secondary Menu Node
				$adminToolbar['toolbars']['menu'. $i] = $adminToolbar['toolbars']['menu_secondary'];
				$adminToolbar['toolbars']['menu'. $i]['ord'] .= '.'. str_pad($i, 3, '0', STR_PAD_LEFT);
				$adminToolbar['toolbars']['menu'. $i]['label'] = $i;
				
				if ($menuItem['name'] === null) {
					$adminToolbar['toolbars']['menu'. $i]['warning_icon'] = 'zenario_link_status zenario_link_status__menu_warning';
					$adminToolbar['toolbars']['menu'. $i]['tooltip'] .= '<br/>'. ze\admin::phrase('Warning: text of menu node is missing in this language.');
				}
				
				if (isset($adminToolbar['sections']['menu'. $i]['buttons']['delete'])) {
					if ($childCount = ze\row::count('menu_nodes', ['parent_id' => $menuItem['id']])) {
						$adminToolbar['sections']['menu'. $i]['buttons']['delete']['ajax']['confirm']['message'] .=
							"\n\n".
							ze\admin::phrase('Note, it has [[children]] child node(s)! These, and any further child nodes below them, will be deleted.',
								['children' => $childCount]);
					}
				}
				
				$adminToolbar['sections']['menu'. $i] = $adminToolbar['sections']['secondary_menu_node'];
			
			} else {
				if ($menuItem['name'] === null) {
					$adminToolbar['toolbars']['menu1']['warning_icon'] = 'zenario_link_status zenario_link_status__menu_warning';
					$adminToolbar['toolbars']['menu1']['tooltip'] .= '<br/>'. ze\admin::phrase('Warning: text of menu node missing in this language.');
				}
				
				$adminToolbar['sections']['menu1'] = $adminToolbar['sections']['primary_menu_node'];
			}
			
			if (ze\menu::isUnique($menuItem['redundancy'], $menuItem['equiv_id'], $menuItem['content_type'])) {
				$menuItem['redundancy'] = 'unique';
				$unique = true;
			}

			$adminToolbar['sections']['menu'. $i]['custom__menu_icon_css_class'] = ze\menuAdm::cssClass($menuItem);
			
			
			if (!empty($adminToolbar['sections']['menu'. $i]['buttons'])) {
				foreach ($adminToolbar['sections']['menu'. $i]['buttons'] as $tagName => &$button) {
					if (is_array($button)) {
						foreach (['request', 'key'] as $request) {
							foreach (['admin_box', 'ajax', 'pick_items'] as $action) {
								if (isset($button[$action][$request]['mID'])) {
									$button[$action][$request]['mID'] = $menuItem['id'];
								}
								if (isset($button[$action][$request]['languageId'])) {
									$button[$action][$request]['languageId'] = ze::$langId;
								}
							}
						}
					}
				}
			}
			unset($button);
			
			
			//Get some information on this Menu Node's position/path
			$level = ze\menuAdm::level($menuItem['id']);
			$parent = $menuItem;
			
			$menuPath = [];
			$menuPathWithoutHtml = [];
			$separator = ' › ';
			
			$menuPathArray = ze\menuAdm::path($menuItem['id'], ze::$langId, $separator, $addHome = true, $returnArray = true);
			if ($menuPathArray) {
				$lastElementIndex = count($menuPathArray) - 1;
				$j = 0;
				foreach ($menuPathArray as $menuRow) {
					if ($j == 0 && $menuRow['section_id'] != 1) {
						$j++;
						continue;
					}
					
					$classList = 'zfab_menuPathPreviewNode';
					if ($j == $lastElementIndex) {
						$classList .= ' zenario_textbox_noborder zfab_menuPathPreviewUpdatingNode';
					}
					$j++;
					
					$menuPath[] = '<span class="' . $classList . '">' . htmlspecialchars($menuRow['text']) . '</span>';
					$menuPathWithoutHtml[] = $menuRow['text'];
				}
			}
			
			$menuItem['path'] = implode('', $menuPath);
			
			//Add a fake button with the path information
				//(This will actually be used to display an infobar)
			$adminToolbar['sections']['menu'. $i]['buttons']['menu_section']['label'] = ze\menu::sectionName($menuItem['section_id']);
			$adminToolbar['sections']['menu'. $i]['buttons']['menu_path']['label'] = $menuItem['path'];
			$adminToolbar['sections']['menu'. $i]['buttons']['menu_path']['css_class'] =
				'zenario_at_infobar'.
				($menuItem['parent_id']? '_child' : '_toplevel').
				($primary? '_menuitem' : '_secondary_menuitem').
				(ze\row::exists('menu_nodes', ['parent_id' => $menuItem['id']])? '_with_children' : '_without_children').
				(!empty($menuItem['invisible']) ? ' invisible_menu_node' : '');
		
			$menuLink = ze\menuAdm::organizerLink($menuItem['id'], ze::$langId);
			if (isset($adminToolbar['sections']['menu'. $i]['buttons']['view_menu_node_in_sk']['organizer_quick'])) {
				$adminToolbar['sections']['menu'. $i]['buttons']['view_menu_node_in_sk']['organizer_quick']['path'] = $menuLink;
			}
			
			//If the primary menu node is being shown on the admin toolbar tabs, add a tab-link to view it in Organizer
			if ($primary && isset($adminToolbar['toolbars']['menu'. $i])) {
				$adminToolbar['toolbars']['menu'. $i]['tab_link'] = [
					'href' => $orgLink. '#'. $menuLink
				];
			}
			
			//Check to see if this menu node has any images, and add info on each
			$adminToolbar['sections']['menu'. $i]['images'] = [
				'image' => $menuItem['image_id'],
				'rollover_image' => $menuItem['rollover_image_id']
			];
			
			$adminToolbar['sections']['menu'. $i]['images']['feature_image'] = ze\menu::getMenuNodeFeatureImageId($menuItem['id']);
			
			foreach ($adminToolbar['sections']['menu'. $i]['images'] as &$image) {
				if ($image) {
					if ($image = ze\row::get('files', ['id', 'usage', 'checksum'], $image)) {
						$image['url'] = ze\link::absolute(). 'zenario/file.php?usage='. $image['usage']. '&c='. $image['checksum']. '&og=1';
					}
				}
			}
			
			$primary = false;

			//If a menu node is used as a suggestion for a particular content type,
			//add an extra class.
			if (!empty($menuItem) && $menuItem['restrict_child_content_types'] && ze\priv::onMenuText('_PRIV_EDIT_MENU_TEXT', $menuItem['id'], $menuItem['language_id'], $menuItem['section_id'])) {
				$adminToolbar['toolbars']['menu'. $i]['css_class'] .= ' node_suggest_on';
			}
		}
		
		//If there is only one Menu Node left for this content item, warn that removing it will cause the
		//content item to be detached.
		if (isset($i) && $i ==1 && isset($adminToolbar['sections']['menu'. $i]['buttons']['detach'])) {
			$adminToolbar['sections']['menu'. $i]['buttons']['detach']['ajax']['confirm']['message'] =
				$adminToolbar['sections']['menu'. $i]['buttons']['detach']['ajax']['confirm']['message__orphaned'];
		}
	}
}

unset($adminToolbar['toolbars']['menu_secondary']);
unset($adminToolbar['sections']['no_menu_nodes']);
unset($adminToolbar['sections']['primary_menu_node']);
unset($adminToolbar['sections']['secondary_menu_node']);



if (isset($adminToolbar['sections']['create'])) {
	
	// Create a 'create button' for each content type in the order HTML, News, Events, Others dropdown (Alphabetical)
	$ord = 3;
	foreach (ze\content::getContentTypes(true, true) as $contentTypeId => $contentType) {
		if (ze\priv::check('_PRIV_EDIT_DRAFT', false, $contentTypeId)) {
			$button = [
				'ord' => ++$ord,
				'label' => $contentType['content_type_name_en'],
				'css_class' => 'zenario_create_a_new',
				'appears_in_toolbars' => [
					'create' => true
				],
				'admin_box' => [
					'path' => 'zenario_content',
					'key' => [
						'id' => '',
						'cID' => '',
						'cType' => $contentTypeId,
						'target_cType' => $contentTypeId,
						'create_from_toolbar' => 1,
						'from_cID' => ze::$cID,
						'from_cType' => ze::$cType,
						'target_language_id' => ze::$langId
					]
				]
			];
		
			$adminToolbar['sections']['create']['buttons'][$contentTypeId] = $button;
		}
	}
}




//
//Add information for the status icons at the top right
//

//Set labels and tooltips
$mrg = [
	'tagId' => $tagId,
	'cID' => ze::$cID,
	'cType' => ze::$cType,
	'cVersion' => ze::$cVersion,
	'cType_name' => htmlspecialchars(ze\content::getContentTypeName(ze::$cType)),
	'title' => htmlspecialchars(ze::$pageTitle),
	'alias' => htmlspecialchars(ze::$alias),
	'lang' => ze\lang::name(ze::$langId),
	'wordcount' => (int) ze\row::get('content_items_searchable_cache', 'content_item_text_wordcount', ['content_id' => ze::$cID, 'content_type' => ze::$cType, 'content_version' => ze::$cVersion])
];

if (ze::$cVersion < ze::$visitorVersion) {
	$mrg['status'] = $versionStatus = 'archived';
} elseif (ze::$cVersion == ze::$visitorVersion) {
	$mrg['status'] = $versionStatus = str_replace('_with_draft', '', ze::$status);
} else {
	$versionStatus = ze::$status;
	$mrg['status'] = str_replace('_with_draft', ' with draft', ze::$status);
}

$adminToolbar['sections']['icons']['buttons']['tag_id']['label'] = $tagId;
$adminToolbar['sections']['icons']['buttons']['tag_id']['tooltip'] =
	ze\admin::phrase('Content Type: [[cType_name]]<br/>Tag Id: [[cType]]_[[cID]]', $mrg);

if (ze\content::isSpecialPage(ze::$cID, ze::$cType)) {
	if (isset($allowHide) && !$allowHide) {
		if (isset($allowTrash) && !$allowTrash) {
			$adminToolbar['sections']['icons']['buttons']['tag_id']['tooltip'] .= ze\admin::phrase('<br/>Special page - cannot be trashed or hidden');
		} else {
			$adminToolbar['sections']['icons']['buttons']['tag_id']['tooltip'] .= ze\admin::phrase('<br/>Special page - cannot be hidden');
		}
	} else {
		if (isset($allowTrash) && !$allowTrash) {
			$adminToolbar['sections']['icons']['buttons']['tag_id']['tooltip'] .= ze\admin::phrase('<br/>Special page - cannot be trashed');
		} else {
			$adminToolbar['sections']['icons']['buttons']['tag_id']['tooltip'] .= ze\admin::phrase('<br/>Special page');
		}
	}
	
	if (empty($adminToolbar['sections']['icons']['buttons']['tag_id']['css_class'])) {
		$adminToolbar['sections']['icons']['buttons']['tag_id']['css_class'] = '';
	}
	$adminToolbar['sections']['icons']['buttons']['tag_id']['css_class'] .= ' zenario_at_icon_tag_id_special_page';
}


//Set some meta-info about this content item
$versionClassName = ze\contentAdm::getItemIconClass($content['id'], $content['type'], true, $versionStatus);
$adminToolbar['meta_info']['title'] = ze::$pageTitle;
$adminToolbar['meta_info']['cversion_css_class'] = $versionClassName;

//Add a tab-link to view the current content item in Organizer
foreach (['edit', 'edit_disabled', 'rollback', 'translations'] as $tabName) {
	if (isset($adminToolbar['toolbars'][$tabName])) {
		if ($tabName == 'translations') {
			$adminToolbar['toolbars']['translations']['tab_link'] = [
				'href' => $orgLink. '#'. 'zenario__content/panels/content/refiners/content_type//' . $cType . '//item_buttons/zenario_trans__view//' . $tagId . '//'
			];
			
			//Set the class
			$adminToolbar['toolbars'][$tabName]['css_class'] =
				'organizer_item_image '. $versionClassName;
		} else {
			$adminToolbar['toolbars'][$tabName]['tab_link'] = [
				'href' => $orgLink. '#zenario__content/panels/content/refiners/content_type//'. $cType. '//'. $tagId
			];
			
			//Set the icon
			$adminToolbar['toolbars'][$tabName]['icon_class'] =
				'organizer_item_image '. $versionClassName;
		}
	}
}


// Language
if (!$isMultilingual) {
	unset($adminToolbar['sections']['icons']['buttons']['language_id']);
} else {
	$adminToolbar['sections']['icons']['buttons']['language_id']['label'] = ze::$langId;
	$adminToolbar['sections']['icons']['buttons']['language_id']['tooltip'] = ze\admin::phrase('Language: [[lang]]', $mrg);
}

// Alias
if (!ze::$alias) {
	unset($adminToolbar['sections']['icons']['buttons']['go_to_alias']);
	$adminToolbar['sections']['icons']['buttons']['alias_dropdown']['css_class'] =
		'zenario_at_icon_alias zenario_at_icon_no_alias';
}




$layoutLabel = 'L';
if (ze::$layoutId < 10) {
	$layoutLabel .= '0';
}
$layoutLabel .= ze::$layoutId;
$adminToolbar['sections']['icons']['buttons']['layout_id']['label'] = $layoutLabel;
$sql = '
	SELECT
		COUNT(DISTINCT c.tag_id) AS item_count, 
		l.name, l.status, ct.content_type_name_en AS default_layout_for_ctype
	FROM '.DB_PREFIX.'content_item_versions v
	INNER JOIN '.DB_PREFIX.'layouts l
		ON v.layout_id = l.layout_id
	INNER JOIN '.DB_PREFIX.'content_items c
		ON (v.version = c.admin_version) AND (v.tag_id = c.tag_id)
	LEFT JOIN ' . DB_PREFIX . 'content_types ct
		ON ct.default_layout_id = l.layout_id
	WHERE v.layout_id = '.(int)ze::$layoutId. '
	AND c.status NOT IN ("trashed", "deleted")';
$result = ze\sql::select($sql);
$layoutDetails = ze\sql::fetchAssoc($result);
$layoutName = $layoutDetails['name'];
$layoutItemCount = $layoutDetails['item_count'];

//Check if the only content items using this layout are trashed.
$sql = '
	SELECT
		COUNT(DISTINCT c.tag_id) AS item_count, 
		l.name, l.status, ct.content_type_name_en AS default_layout_for_ctype
	FROM '.DB_PREFIX.'content_item_versions v
	INNER JOIN '.DB_PREFIX.'layouts l
		ON v.layout_id = l.layout_id
	INNER JOIN '.DB_PREFIX.'content_items c
		ON (v.version = c.admin_version) AND (v.tag_id = c.tag_id)
	LEFT JOIN ' . DB_PREFIX . 'content_types ct
		ON ct.default_layout_id = l.layout_id
	WHERE v.layout_id = '.(int)ze::$layoutId. '
	AND c.status = "trashed"';
$result = ze\sql::select($sql);
$layoutDetailsForTrashedItems = ze\sql::fetchAssoc($result);
$layoutTrashedItemCount = $layoutDetailsForTrashedItems['item_count'];

if ($layoutDetails['status'] == 'active') {
	$layoutStatus = '';
} elseif ($layoutDetails['status'] == 'suspended') {
	$layoutStatus = 'Layout is retired';
} elseif(!$layoutDetails['item_count'] && !$layoutDetails['status']) {
	if ($layoutTrashedItemCount) {
		if ($layoutDetailsForTrashedItems['status'] == 'active') {
			$layoutStatus = '';
		} elseif ($layoutDetailsForTrashedItems['status'] == 'suspended') {
			$layoutStatus = 'Layout is retired';
		}
	}
}

$isDefaultForAContentType = $layoutDetails['default_layout_for_ctype'] ? 'Default layout for ' . $layoutDetails['default_layout_for_ctype'] . '<br />' : '';

if ($layoutItemCount) {
	if ($layoutItemCount == 1) {
		$adminToolbar['sections']['icons']['buttons']['layout_id']['tooltip'] = 
			'Layout '.$layoutLabel.'<br />'.$layoutName.'<br />'.$layoutItemCount.' content item uses this layout<br /> '.$layoutStatus.'<br />'.$isDefaultForAContentType;
	} else {
		if ($layoutTrashedItemCount) {
			$adminToolbar['sections']['icons']['buttons']['layout_id']['tooltip'] = 
				'Layout '.$layoutLabel.'<br />'.$layoutName.'<br />'.$layoutItemCount.' content items (' . (int) $layoutTrashedItemCount . ' trashed) use this layout<br /> '.$layoutStatus.'<br />'.$isDefaultForAContentType;
		} else {
			$adminToolbar['sections']['icons']['buttons']['layout_id']['tooltip'] = 
				'Layout '.$layoutLabel.'<br />'.$layoutName.'<br />'.$layoutItemCount.' content items use this layout<br /> '.$layoutStatus.'<br />'.$isDefaultForAContentType;
	}
	}
} else {
	if ($layoutTrashedItemCount) {
		if ($layoutTrashedItemCount == 1) {
			$adminToolbar['sections']['icons']['buttons']['layout_id']['tooltip'] = 
				'Layout '.$layoutLabel.'<br />'.$layoutName.'<br />'.$layoutTrashedItemCount.' trashed content item uses this layout<br /> '.$layoutStatus.'<br />'.$isDefaultForAContentType;
		} else {
			$adminToolbar['sections']['icons']['buttons']['layout_id']['tooltip'] = 
				'Layout '.$layoutLabel.'<br />'.$layoutName.'<br />'.$layoutTrashedItemCount.' content items (all trashed) use this layout<br /> '.$layoutStatus.'<br />'.$isDefaultForAContentType;
		}
	}	
}

$adminToolbar['sections']['icons']['buttons']['layout_id']['tooltip'] .= 'Click to change layout';
	
$adminToolbar['sections']['icons']['buttons']['layout_id']['css_class'] .= ' layout_status_' . $layoutDetails['status'];

$visitorURL = ze\link::toItemWithAlias(
	$cID, $cType, $fullPath = true, $request = '', ze::$alias);

if (isset($adminToolbar['sections']['icons']['buttons']['copy_url'])) {
	$contentItemLink = ze\link::toItem($cID, $cType);
	
	$copyConfirmationMessage = ze\admin::phrase(
		"Copied to clipboard: [[content_item_link]]",
		['content_item_link' => $contentItemLink]
	);
	
	$adminToolbar['sections']['icons']['buttons']['copy_url']['onclick'] =
		//Attempt to copy the cannonical URL to the clipboard when the visitor presses this button
		'zenarioA.copy("'. ze\escape::js($visitorURL). '", "' . ze\escape::js($copyConfirmationMessage) . '");'.
		//Small little hack here:
			//After the URL is copy/pasted, the dropdown stays open which is counter-intuative.
			//However the dropdown is powered by pure CSS and there's no way to close it using JavaScript.
			//So as a workaround, redraw the admin toolbar with the dropdown closed.
		'if (!zenarioA.checkSlotsBeingEdited()) zenarioAT.draw();';
}
if (isset($adminToolbar['sections']['icons']['buttons']['go_to_alias'])) {
	$adminToolbar['sections']['icons']['buttons']['alias']['label'] = ze\admin::phrase('Edit alias "[[alias]]"', ['alias' => (ze::$alias)]);
	$adminToolbar['sections']['icons']['buttons']['go_to_alias']['label'] = ze\admin::phrase('Go to content item via alias', ['alias' => (ze::$alias)]);
	$adminToolbar['sections']['icons']['buttons']['go_to_alias']['frontend_link'] = $visitorURL;
} else {
	$adminToolbar['sections']['icons']['buttons']['alias']['label'] = ze\admin::phrase('Set an alias');
	$adminToolbar['sections']['icons']['buttons']['copy_url']['label'] = ze\admin::phrase('Copy URL to clipboard');
}

if (
	$isMultilingual
	&& $content['id'] != $content['equiv_id']
	&& !ze::setting('translations_different_aliases')
) {
	if ($defaultLangContentItemId = ze\row::get('content_items', 'id', ['equiv_id' => ze::$equivId, 'type' => ze::$cType, 'language_id' => ze::$defaultLang])) {
		$adminToolbar['sections']['icons']['buttons']['alias']['label'] = ze\admin::phrase('View alias "[[alias]]"', ['alias' => (ze::$alias)]);
		$adminToolbar['sections']['edit']['buttons']['alias']['label'] = ze\admin::phrase('View alias');
	}
}

if (!ze\priv::check('_PRIV_EDIT_DRAFT', $cID, $cType)) {
	$adminToolbar['sections']['icons']['buttons']['alias']['hidden'] = true;
}


//Show version information on all relevant versions
$showVersions = [];
$showVersions[$cVersion] = true;
$showVersions[ze::$adminVersion] = true;
$showVersions[ze::$visitorVersion] = true;
$showVersions[ze::$adminVersion - 1] = true;
$showVersions[ze::$visitorVersion - 1] = true;
ksort($showVersions);

$i = 0;
foreach ($showVersions as $showVersion => $dummy) {
	
	if ($showVersion && ($v = ze\row::get('content_item_versions', true, ['id' => $cID, 'type' => $cType, 'version' => $showVersion]))) {
		
		$tuixId = 'version_'. ++$i;
		
		//Come up with a tooltip to show for this version.
		//Come up with a generic tooltip first, depending on what information we have.
		if (!empty($v['published_datetime']) && !empty($v['publisher_id'])) {
			$lastAction = $v['published_datetime'];
			$lastActionBy = $v['publisher_id'];
			$tooltipPhrase = 'Version [[version]], published by [[name]], [[time]] [[date]]';
		
		} elseif (!empty($v['last_modified_datetime']) && !empty($v['last_author_id'])) {
			$lastAction = $v['last_modified_datetime'];
			$lastActionBy = $v['last_author_id'];
			$tooltipPhrase = 'Version [[version]], draft edited by [[name]], [[time]] [[date]]';
		
		} else {
			$lastAction = $v['created_datetime'];
			$lastActionBy = $v['creating_author_id'];
			$tooltipPhrase = 'Version [[version]], draft created by [[name]], [[time]] [[date]]';
		}
		
		//Try to change the icons/tooltip/info specifically for the status
		switch (ze\contentAdm::versionStatus($v['version'], ze::$visitorVersion, ze::$adminVersion, ze::$status)) {
			case 'draft':
				if ($versionChanged = ze\contentAdm::checkIfVersionChanged($v)) {
					$labelPhrase = 'v[[version]] (draft)';
					$tooltipPhrase = 'Version [[version]], draft edited by [[name]], [[time]] [[date]]';
					$cssClass = 'zenario_at_icon_version_draft';
					
					if ($v['last_modified_datetime']) {
						$lastAction = $v['last_modified_datetime'];
						$lastActionBy = $v['last_author_id'];
					} else {
						$lastAction = $v['created_datetime'];
						$lastActionBy = $v['creating_author_id'];
					}

				} else {
					$labelPhrase = 'v[[version]] (draft)';
					
					if ($versionChanged === null) {
						$tooltipPhrase = 'Version [[version]] draft created by [[name]] [[time]] [[date]], no version-controlled changes';
					} else {
						$tooltipPhrase = 'Version [[version]] draft created by [[name]] [[time]] [[date]]';
					}
					
					$cssClass = 'zenario_at_icon_version_draft';
					$lastAction = $v['created_datetime'];
					$lastActionBy = $v['creating_author_id'];
				}
				break;
			
			case 'published':
				$labelPhrase = 'v[[version]] (published)';
				$tooltipPhrase = 'Version [[version]], published by [[name]], [[time]] [[date]]';
				$cssClass = 'zenario_at_icon_version_published';
				$lastAction = $v['published_datetime'];
				$lastActionBy = $v['publisher_id'];
				break;
			
			case 'unlisted':
				$labelPhrase = 'v[[version]] (published unlisted)';
				$tooltipPhrase = 'Version [[version]], published by [[name]], [[time]] [[date]]';
				$cssClass = 'zenario_at_icon_version_published zenario_at_icon_version_published_unlisted';
				$lastAction = $v['published_datetime'];
				$lastActionBy = $v['publisher_id'];
				break;

			case 'hidden':
				$labelPhrase = 'v[[version]] (hidden)';
				$cssClass = 'zenario_at_icon_version_hidden';
				
				if (!empty($v['concealed_datetime']) && !empty($v['concealer_id'])) {
					$lastAction = $v['concealed_datetime'];
					$lastActionBy = $v['concealer_id'];
					$tooltipPhrase = 'Version [[version]], hidden by [[name]], [[time]] [[date]]';
				}
				
				break;
	
			case 'trashed':
				$labelPhrase = 'v[[version]] (trashed)';
				$cssClass = 'zenario_at_icon_version_trashed';
				
				if (!empty($v['concealed_datetime']) && !empty($v['concealer_id'])) {
					$lastAction = $v['concealed_datetime'];
					$lastActionBy = $v['concealer_id'];
					$tooltipPhrase = 'Version [[version]], trashed by [[name]], [[time]] [[date]]';
				}
				
				break;
	
			case 'archived':
				$labelPhrase = 'v[[version]] (archived)';
				$cssClass = 'zenario_at_icon_version_archived';
				
				if (!empty($v['concealed_datetime']) && !empty($v['concealer_id'])) {
					$lastAction = $v['concealed_datetime'];
					$lastActionBy = $v['concealer_id'];
					$tooltipPhrase = 'Version [[version]], archived by [[name]], [[time]] [[date]]';
				
				}
				
				break;
		}
	
		$mrg = [];
		$mrg['version'] = $v['version'];
		$mrg['name'] = htmlspecialchars(ze\admin::formatName($lastActionBy));
		$mrg['time'] = ze\date::formatTime($lastAction, ze::setting('vis_time_format'), true);
		$mrg['date'] = ze\admin::formatDate($lastAction, ze::setting('vis_date_format_med'), true);

		if ($mrg['date'] == ze\admin::formatDate(ze\date::now(), ze::setting('vis_date_format_med'))) {
			$mrg['date'] = ze\admin::phrase('today');
		}
		
		//Only show the status for the most recent version
/*		if ($v['version'] != ze::$adminVersion) {
			$labelPhrase = 'v[[version]]';
		}
*/

		$adminToolbar['sections']['icons']['buttons'][$tuixId]['hidden'] = false;
		$adminToolbar['sections']['icons']['buttons'][$tuixId]['label'] = ze\admin::phrase($labelPhrase, $mrg);
		$adminToolbar['sections']['icons']['buttons'][$tuixId]['tooltip'] = ze\admin::phrase($tooltipPhrase, $mrg);
		$adminToolbar['sections']['icons']['buttons'][$tuixId]['css_class'] .= ' '. $cssClass;
		$adminToolbar['sections']['icons']['buttons'][$tuixId]['frontend_link'] = ze\link::toItem($cID, $cType, false, 'cVersion='. $v['version']);
	
		if ($v['version'] == $cVersion) {
			$adminToolbar['sections']['icons']['buttons'][$tuixId]['css_class'] .= ' zenario_at_icon_version_in_view';
			$adminToolbar['meta_info']['version'] = $adminToolbar['sections']['icons']['buttons'][$tuixId]['tooltip'];
		}
	}
}

//Content item is categorised
if (ze\row::exists('category_item_link', ['equiv_id' => $content['equiv_id'], 'content_type' => $cType])) {
	unset($adminToolbar['sections']['icons']['buttons']['item_categories_none']);
} else {
	unset($adminToolbar['sections']['icons']['buttons']['item_categories_some']);
}

if (isset($adminToolbar['sections']['icons']['buttons']['item_categories_some'])) {
	//If this item is in categories, list them
	$sql = "
		SELECT c.id, c.name
		FROM ". DB_PREFIX. "category_item_link AS cil
		LEFT JOIN ". DB_PREFIX. "categories AS c
		   ON cil.category_id = c.id
		WHERE cil.equiv_id = ". (int) $content['equiv_id']. "
		  AND cil.content_type = '" . ze\escape::asciiInSQL($cType). "'";
	
	$i = 0;
	if ($sql && ($result = ze\sql::select($sql))) {
		while ($row = ze\sql::fetchAssoc($result)) {
			//Make sure the content item is linked to existing categories.
			//Avoid dangling cross references.
			if ($row['id']) {
				if (!$row['name']) {
					$row['name'] = '(unnamed category)';
				}
			} else {
				$row['name'] = '(deleted category)';
			}
			
			$adminToolbar['sections']['icons']['buttons']['item_categories_some']['tooltip'] .=
				($i++? ', ' : ''). htmlspecialchars($row['name'] ?: '(unnamed category)');
		}
	}
}


//Content item type has categories enabled
if (ze\row::exists('content_types', ['enable_categories' => 0, 'content_type_id' => $content['type']])) {
	unset($adminToolbar['sections']['edit']['buttons']['categories']);
	unset($adminToolbar['sections']['icons']['buttons']['item_categories_some']);
	unset($adminToolbar['sections']['icons']['buttons']['item_categories_none']);
}



$linkStatus = false;        
switch (ze::$status) {
	case 'published':
	case 'published_with_draft':
	case 'unlisted':
	case 'unlisted_with_draft':
		$linkStatus = ze::$status;
		
		$perms = ze\content::getShowableContent($content, $chain, $version, $cID, $cType, $cVersion, $checkRequestVars = false, $adminMode = true, $adminsSee400Errors = true);
	
		if ($perms === ZENARIO_401_NOT_LOGGED_IN) {
			$linkStatus .= '_401';
	
		} elseif (!$perms) {
			$linkStatus .= '_403';
		}
		break;

	case 'first_draft':
	case 'hidden_with_draft':
	case 'hidden':
		$linkStatus = 'hidden';
		break;
}

if ($linkStatus) {
	$adminToolbar['toolbars']['preview']['warning_icon'] = 'zenario_link_status zenario_link_status__'. $linkStatus;
}



//If the item is scheduled for publishing, update the label.
if (isset($adminToolbar['sections']['actions']['buttons']['publish'])) {
	$sql = "
		SELECT c.id, c.type, v.scheduled_publish_datetime, c.lock_owner_id
		FROM ". DB_PREFIX. "content_items AS c
		INNER JOIN ". DB_PREFIX. "content_item_versions AS v
		   ON v.id = c.id
		  AND v.type = c.type
		  AND v.version = c.admin_version
		WHERE c.tag_id = '". ze\escape::sql($tagId). "'
		  AND v.scheduled_publish_datetime IS NOT NULL";
	if ($row = ze\sql::fetchAssoc($sql)) {
		$adminToolbar['sections']['actions']['buttons']['publish']['label'] = ze\admin::phrase('Scheduled publishing...');
	}
}
