/**
 * Render Windows Azure Storage Plugin Options Screen
 *
 * @param string $mode mode for logged in user (admin/nonadmin)
 *
 * @return void
 */
function show_windows_azure_storage_settings($mode)
{
    $containerCreationStatus = true;
    $message = createContainerIfRequired($containerCreationStatus);
    // Storage Account Settings from db if already set
    //TODO: check POST values first and use these for fallbacks
    $storageAccountName = WindowsAzureStorageUtil::getAccountName();
    $storageAccountKey = WindowsAzureStorageUtil::getAccountKey();
    $httpProxyHost = WindowsAzureStorageUtil::getHttpProxyHost();
    $httpProxyPort = WindowsAzureStorageUtil::getHttpProxyPort();
    $httpProxyUserName = WindowsAzureStorageUtil::getHttpProxyUserName();
    $httpProxyPassword = WindowsAzureStorageUtil::getHttpProxyPassword();
    $defaultContainer = WindowsAzureStorageUtil::getDefaultContainer();
    $newContainerName = null;
    // Use the account settings in the $_POST if this page load is
    // a result of container creation operation.
    if (wp_verify_nonce($_REQUEST['_wpnonce'], 'windows-azure-storage-settings-group-options') && isset($_POST['action2']) && 'update' === $_POST['action2']) {
        //TODO sanitize and set from a loop instead of a bunch of if…then statements
        if (array_key_exists("azure_storage_account_name", $_POST)) {
            $storageAccountName = sanitize_text_field($_POST["azure_storage_account_name"]);
        }
        if (array_key_exists("azure_storage_account_primary_access_key", $_POST)) {
            $storageAccountKey = sanitize_text_field($_POST["azure_storage_account_primary_access_key"]);
        }
        if (array_key_exists("http_proxy_host", $_POST)) {
            $httpProxyHost = sanitize_text_field($_POST["http_proxy_host"]);
        }
        if (array_key_exists("http_proxy_port", $_POST)) {
            $httpProxyPort = absint($_POST["http_proxy_port"]);
        }
        if (array_key_exists("http_proxy_username", $_POST)) {
            $httpProxyUserName = sanitize_text_field($_POST["http_proxy_username"]);
        }
        if (array_key_exists("http_proxy_password", $_POST)) {
            $httpProxyPassword = sanitize_text_field($_POST["http_proxy_password"]);
        }
    }
    // We need to show the container name if the request for
    // container creation fails.
    if (!$containerCreationStatus) {
        $newContainerName = sanitize_text_field($_POST["newcontainer"]);
    }
    $ContainerResult = null;
    try {
        if (!empty($storageAccountName) && !empty($storageAccountKey)) {
            //TODO: store the connection string and use it instead of always generating the client connection this way
            $storageClient = WindowsAzureStorageUtil::getStorageClient($storageAccountName, $storageAccountKey, $httpProxyHost, $httpProxyPort, $httpProxyUserName, $httpProxyPassword);
            $ContainerResult = $storageClient->listContainers();
            $privateContainerWarning = null;
            if (!empty($defaultContainer)) {
                $getContainerAclResult = $storageClient->getContainerAcl($defaultContainer);
                $containerAcl = $getContainerAclResult->getContainerAcl();
                if ($containerAcl->getPublicAccess() === PublicAccessType::NONE) {
                    /* translators: %s is the container name and is used twice */
                    $privateContainerWarning = sprintf(__('Warning: The container "%1$s" is set to "private" and cannot be used.' . 'Please choose a public container as the default, or set the "%1$s" container to ' . '"public" in your Azure Storage settings.', 'windows-azure-storage'), $defaultContainer);
                }
            }
            if (!is_null($privateContainerWarning)) {
                printf('<p style="margin: 10px; color: red;">%s</p>', esc_html($privateContainerWarning));
            }
        }
    } catch (Exception $ex) {
        // Fires if account keys are not yet set
        error_log($ex->getMessage(), E_USER_WARNING);
    }
    ?>
	<table class="form-table" border="0">
		<tr valign="top">
			<th scope="row">
				<label for="storage_account_name" title="Windows Azure Storage Account Name">Store Account Name</label>
			</th>
			<td>
				<input type="text" name="azure_storage_account_name" title="Windows Azure Storage Account Name" value="<?php 
    echo esc_attr($storageAccountName);
    ?>
" />
			</td>
			<td></td>
		</tr>

		<tr valign="top">
			<th scope="row">
				<label for="azure_storage_account_primary_access_key" title="Windows Azure Storage Account Primary Access Key">Primary Access Key</label>
			</th>
			<td>
				<input type="text" name="azure_storage_account_primary_access_key" title="Windows Azure Storage Account Primary Access Key" value="<?php 
    echo esc_attr($storageAccountKey);
    ?>
" />
			</td>
			<td></td>
		</tr>

		<tr valign="top">
			<th scope="row">
				<label for="storage_container_name" title="Default container to be used for storing media files">Default Storage Container</label>
			</th>
			<td WIDTH="80px">
				<select name="default_azure_storage_account_container_name" title="Default container to be used for storing media files" onChange="<?php 
    echo esc_js('onContainerSelectionChanged( false );');
    ?>
">
					<?php 
    if (!empty($ContainerResult) && count($ContainerResult->getContainers()) > 0) {
        foreach ($ContainerResult->getContainers() as $container) {
            ?>
							<option value="<?php 
            echo esc_attr($container->getName());
            ?>
"
								<?php 
            selected($container->getName(), $defaultContainer);
            ?>
>
								<?php 
            echo esc_html($container->getName());
            ?>
							</option>
							<?php 
        }
        if (WindowsAzureStorageUtil::check_action_permissions('create_container')) {
            ?>
							<option value="__newContainer__">&mdash;&thinsp;<?php 
            esc_html_e('Create New Container', 'windows-azure-storage');
            ?>
&thinsp;&mdash;</option>
							<?php 
        }
    }
    ?>
				</select>
			</td>
			<?php 
    if (WindowsAzureStorageUtil::check_action_permissions('create_container')) {
        wp_nonce_field('create_container', 'create_new_container_settings');
        ?>
				<td>
					<div id="divCreateContainer" name="divCreateContainer" style="display:none;">
						<table style="border:1px solid black;">
							<tr>
								<td>
									<label for="newcontainer" title="Name of the new container to create">Create New Container: </label>
								</td>
								<td>
									<input type="text" name="newcontainer" title="Name of the new container to create" value="<?php 
        echo esc_attr($newContainerName);
        ?>
" />
									<input type="button" class="button-primary" value="<?php 
        esc_attr_e('Create', 'windows-azure-storage');
        ?>
" onclick="<?php 
        echo esc_js(sprintf('createContainer("%s");', esc_url($_SERVER['REQUEST_URI'])));
        ?>
" />
								</td>
							</tr>
						</table>
					</div>
				</td>
			<?php 
    }
    ?>
		</tr>
		<tr valign="top">
			<td colspan="3" WIDTH="300" align="center"><?php 
    echo wp_kses_post($message);
    ?>
</td>
		</tr>
		<tr valign="top">
			<th scope="row">
				<label for="cname" title="Use CNAME instead of Windows Azure Blob URL">CNAME</label>
			</th>
			<td colspan="2">
				<input type="url" name="cname" title="Use CNAME instead of Windows Azure Blob URL" value="<?php 
    echo esc_attr(WindowsAzureStorageUtil::getCNAME());
    ?>
" />
				<p class="field-description">
					<?php 
    $notice = __('Note: Use this option if you would like to display image URLs belonging to your domain like <samp>http://MyDomain.com/</samp> instead of <samp>http://YourAccountName.blob.core.windows.net/</samp>.', 'windows-azure-storage');
    echo wp_kses($notice, array('samp' => array()));
    ?>
</p>
				<div id="cname-notice">
					<?php 
    if (is_ssl()) {
        ?>
						<h4><?php 
        echo esc_html_x('Notice', 'verb', 'windows-azure-storage');
        ?>
</h4>
						<p><?php 
        //TODO: add a different notice if 'https' is set, regardless of is_ssl.
        $notice = sprintf(__('Windows Azure Storage <a href="%1$s" title="%2$s">does not currently support ' . 'SSL certificates for custom domain names</a>. ' . 'Since this WordPress site is configured to serve content over HTTPS, ' . 'it\'s recommended that you use the default Azure storage endpoint to avoid ' . 'mixed-content warnings for your visitors.', 'windows-azure-storage'), esc_url('https://feedback.azure.com/forums/217298-storage/suggestions/3007732-make-it-possible-to-use-ssl-on-blob-storage-using'), esc_html__('How can we improve Azure Storage? on Azure Forums', 'windows-azure-storage'));
        echo wp_kses($notice, array('a' => array('href' => array(), 'title' => array())));
        ?>
</p>
					<?php 
    } else {
        ?>
						<p><?php 
        $notice = sprintf(__('This CNAME must start with <samp>http://</samp> and the administrator will have to update <abbr title="%s">DNS</abbr>
 entries accordingly.', 'windows-azure-storage'), _x('Domain Name System', 'The proper name of the Internet name resolution system', 'windows-azure-storage'));
        echo wp_kses($notice, array('samp' => array(), 'abbr' => array('title' => array())));
        ?>
</p>
					<?php 
    }
    ?>
				</div>
			</td>
		</tr>

		<tr valign="top">
			<th scope="row">
				<label for="http_proxy_host" title="Use HTTP proxy server host name if web proxy server is configured">HTTP Proxy Host Name</label>
			</th>
			<td>
				<input type="text" name="http_proxy_host" title="Use HTTP proxy server host name if web proxy server is configured" value="<?php 
    echo esc_attr($httpProxyHost);
    ?>
" />
			</td>
			<td></td>
		</tr>

		<tr valign="top">
			<th scope="row">
				<label for="http_proxy_port" title="Use HTTP proxy port if web proxy server is configured">HTTP Proxy Port</label>
			</th>
			<td>
				<input type="number" name="http_proxy_port" title="Use HTTP proxy port if web proxy server is configured" value="<?php 
    echo esc_attr($httpProxyPort);
    ?>
" />
			</td>
			<td></td>
		</tr>

		<tr valign="top">
			<th scope="row">
				<label for="http_proxy_username" title="Use HTTP proxy user name if credential is required to access web proxy server">HTTP Proxy User Name</label>
			</th>
			<td>
				<input type="text" name="http_proxy_username" title="Use HTTP proxy user name if credential is required to access web proxy server" value="<?php 
    echo esc_attr($httpProxyUserName);
    ?>
" />
			</td>
			<td></td>
		</tr>

		<tr valign="top">
			<th scope="row">
				<label for="http_proxy_password" title="Use HTTP proxy password if credential is required to access web proxy server">HTTP Proxy Password</label>
			</th>
			<td>
				<input type="text" name="http_proxy_password" title="Use HTTP proxy password if credential is required to access web proxy server" value="<?php 
    echo esc_attr($httpProxyPassword);
    ?>
" />
			</td>
			<td></td>
		</tr>

		<tr valign="top">
			<th scope="row">
				<label for="azure_storage_use_for_default_upload" title="Use Windows Azure Storage for default upload">Use Windows Azure Storage for default upload</label>
			</th>
			<td colspan="2">
				<input type="checkbox" name="azure_storage_use_for_default_upload" title="Use Windows Azure Storage for default upload" value="1" id="azure_storage_use_for_default_upload"
					<?php 
    checked((bool) get_option('azure_storage_use_for_default_upload'));
    ?>
 />
				<label for="wp-uploads"> Use Windows Azure Storage when uploading via WordPress' upload tab.</label>
				<br />
				<small>Note: Uncheck this to revert back to using your own web host for storage at anytime.</small>
			</td>
		</tr>
	</table>
	<?php 
    if (empty($ContainerResult) || !$containerCreationStatus || 0 === count($ContainerResult->getContainers())) {
        // 1. If $containerResult object is null means the storage account is not yet set
        // show the create container div
        ?>
		<script type="text/javascript">
			onContainerSelectionChanged( true );
		</script>

		<?php 
    }
}
/**
 * Render Upload Tab in the Windows Azure Storage popup dialog
 *
 * @return void
 */
function windows_azure_storage_dialog_upload_tab()
{
    // remove all registerd filters for the tabs
    unset($GLOBALS['wp_filter']['media_upload_tabs']);
    // register our filter for the tabs
    add_filter("media_upload_tabs", "windows_azure_storage_dialog_add_tab");
    media_upload_header();
    /**
     * The post ID of the originating editor page.
     *
     * Passed via $_GET from the post being edited when the iframe is loaded.
     * If iframe is accessed outside an originating editor, this will be 0 and
     * nonces will fail. :)
     *
     * @var int $post_id
     */
    $post_id = isset($_GET['post_id']) ? (int) $_GET['post_id'] : 0;
    $azure_storage_account_name = WindowsAzureStorageUtil::getAccountName();
    $azure_storage_account_primary_access_key = WindowsAzureStorageUtil::getAccountKey();
    $default_azure_storage_account_container_name = WindowsAzureStorageUtil::getDefaultContainer();
    $uploadMessage = null;
    $uploadSuccess = true;
    if (empty($azure_storage_account_name) || empty($azure_storage_account_primary_access_key)) {
        echo '<h3 style="margin: 10px;">Azure Storage Account not yet configured</h3>';
        echo '<p style="margin: 10px;">Please configure the account in Windows Azure Settings Tab.</p>';
    } else {
        // Set selected container. If none, then use default container
        $selected_container_name = $default_azure_storage_account_container_name;
        if (!empty($_POST['selected_container'])) {
            $selected_container_name = sanitize_text_field($_POST['selected_container']);
        } else {
            if (!empty($_GET['selected_container'])) {
                $selected_container_name = sanitize_text_field($_GET['selected_container']);
            }
        }
        if (empty($selected_container_name)) {
            echo '<p style="margin: 10px; color: red;">Default Azure Storage Container name is not yet configured. Please configure it in the Windows Azure Settings Tab.</p>';
        }
        // Handle file upload
        if (!empty($_POST['action']) && 'upload' === $_POST['action']) {
            // CSRF okay
            if (0 === $_FILES["uploadFileName"]["error"]) {
                if (!file_exists($_FILES['uploadFileName']['tmp_name'])) {
                    echo "<p>Uploaded file " . esc_html($_FILES['uploadFileName']['tmp_name']) . " does not exist</p><br/>";
                } else {
                    $metaData = array('mimetype' => $_FILES['uploadFileName']['type']);
                    if (!empty($_POST["uploadFileTag"])) {
                        $metaData["tag"] = sanitize_text_field($_POST["uploadFileTag"]);
                    }
                    try {
                        if (false === check_admin_referer('upload_blob_' . $post_id, 'upload_blob_nonce') || false === WindowsAzureStorageUtil::check_action_permissions('upload')) {
                            throw new Exception(__('Nonce check failed. Please try again, or contact your site administrator for assistance.', 'windows-azure-storage'));
                        }
                        $blobName = WindowsAzureStorageUtil::uniqueBlobName($selected_container_name, $_FILES['uploadFileName']['name']);
                        WindowsAzureStorageUtil::putBlockBlob($selected_container_name, $blobName, $_FILES['uploadFileName']['tmp_name'], null, $metaData);
                        $uploadMessage = "Successfully uploaded file '" . $blobName . "' to the container '" . $selected_container_name . "'.";
                    } catch (Exception $e) {
                        $uploadSuccess = false;
                        $uploadMessage = "Error in uploading file '" . $_FILES['uploadFileName']['name'] . "', Error: " . $e->getMessage();
                    }
                }
            }
        } else {
            if (!empty($_POST['action']) && 'create' === $_POST['action']) {
                if (!empty($_POST["createContainer"])) {
                    try {
                        if (false === check_admin_referer('upload_create_container_' . $post_id, 'upload_create_container_nonce') || false === WindowsAzureStorageUtil::check_action_permissions('create_container')) {
                            throw new Exception(__('Sorry, you do not have permission to create containers for this
						account. Please contact your site administrator for assistance.', 'windows-azure-storage'));
                        }
                        WindowsAzureStorageUtil::createPublicContainer(sanitize_text_field($_POST["createContainer"]));
                        $uploadMessage = "The container '" . $_POST["createContainer"] . "' successfully created";
                    } catch (Exception $e) {
                        $uploadSuccess = false;
                        $uploadMessage = "Container creation failed: " . $e->getMessage();
                    }
                } else {
                    $uploadSuccess = false;
                    $uploadMessage = "Please specify container name";
                }
            }
        }
        $form_action_url = add_query_arg(array('post_id' => $post_id, 'tab' => 'upload'), MSFT_AZURE_PLUGIN_LEGACY_MEDIA_URL);
        ?>
		<h3 style="margin: 10px;">Upload New File</h3>
		<div id="upload-form">
			<form name="UploadNewFileForm" style="margin: 10px;" method="post" enctype="multipart/form-data" action="<?php 
        echo esc_url($form_action_url);
        ?>
">
				<?php 
        wp_nonce_field('upload_blob_' . $post_id, 'upload_blob_nonce');
        ?>
				<table class="form-table">
					<tr valign="top">
						<th scope="row">
							<label for="selected_container">Container Name :</label>
						</th>
						<td>
							<select name="selected_container" title="Storage container to be used for uploading media files" onChange="<?php 
        echo esc_js('onUpload_ContainerSelectionChanged();');
        ?>
">
								<?php 
        try {
            $storageClient = WindowsAzureStorageUtil::getStorageClient();
            $listContainerResult = $storageClient->listContainers();
            foreach ($listContainerResult->getContainers() as $container) {
                if (empty($selected_container_name)) {
                    $selected_container_name = $container->getName();
                }
                $container_name = $container->getName();
                ?>
										<option value="<?php 
                echo esc_attr($container_name);
                ?>
"
											<?php 
                selected($container_name, $selected_container_name);
                ?>
>
											<?php 
                echo esc_html($container_name);
                ?>
										</option>
									<?php 
            }
            ?>
									<option value="__newContainer__">&mdash;&thinsp;<?php 
            esc_html_e('Create New Container', 'windows-azure-storage');
            ?>
&thinsp;&mdash;</option>
									<?php 
        } catch (Exception $ex) {
            // Fires if account keys are not yet set.
            error_log($ex->getMessage(), E_USER_WARNING);
        }
        ?>
							</select>
						</td>
					</tr>

					<tr valign="top">
						<th scope="row">
							<label for="createContainer" id="lblNewContainer">New Container Name:</label>
						</th>
						<td>
							<input type="text" name="createContainer" value="" />
						</td>
					</tr>
					<tr valign="top">
						<th scope="row">
							<label for="uploadFileTag">Tag:</label>
						</th>
						<td>
							<input type="text" name="uploadFileTag" value="" />
						</td>
					</tr>

					<tr valign="top">
						<th scope="row">
							<label for="uploadFileName">File Name:</label>
						</th>
						<td>
							<input type="file" name="uploadFileName" />
						</td>
					</tr>
				</table>

				<input type='hidden' name='action' value='upload' />
				<?php 
        wp_nonce_field('upload_create_container_' . $post_id, 'upload_create_container_nonce');
        ?>
				<p class="submit">
					<input type="submit" class="button-primary" id="submit" value="<?php 
        esc_attr_e('Upload', 'windows-azure-storage');
        ?>
" />
				</p>
			</form>
		</div>
		<script type="text/javascript">
			onUpload_ContainerSelectionChanged();
		</script>
		<?php 
        //TODO: Use WP classes and markup to create notices
        if (!empty($uploadMessage)) {
            $color = $uploadSuccess ? 'green' : 'red';
            printf('<p style="margin: 10px; color: %1$s;">%2$s</p>', esc_attr($color), wp_kses_post($uploadMessage));
        }
    }
}
/**
 * Add option page for Windows Azure Storage Plugin
 *
 * @return void
 */
function windows_azure_storage_plugin_menu()
{
    if (WindowsAzureStorageUtil::check_action_permissions('change_settings')) {
        add_options_page('Windows Azure Storage Plugin Settings', 'Windows Azure', 'manage_options', 'b5506889-50de-42db-bf63-e9f248ca94e9', 'windows_azure_storage_plugin_options_page');
    }
    // Call register settings function
    add_action('admin_init', 'windows_azure_storage_plugin_register_settings');
}