/**
 * Try to create a container.
 * 
 * @param boolean $success True if the operation succeeded, false otherwise.
 *
 * @return string The message to displayed
 */
function createContainerIfRequired(&$success)
{
    $success = true;
    if (array_key_exists("newcontainer", $_POST)) {
        if (!empty($_POST["newcontainer"])) {
            if (empty($_POST["azure_storage_account_name"]) || empty($_POST["azure_storage_account_primary_access_key"])) {
                $success = false;
                return '<FONT COLOR="red">Please specify Storage Account Name and Primary Access Key to create container</FONT>';
            }
            try {
                $storageClient = WindowsAzureStorageUtil::getStorageClient($_POST["azure_storage_account_name"], $_POST["azure_storage_account_primary_access_key"], $_POST["http_proxy_host"], $_POST["http_proxy_port"], $_POST["http_proxy_username"], $_POST["http_proxy_password"]);
                WindowsAzureStorageUtil::createPublicContainer($_POST["newcontainer"], $storageClient);
                return '<FONT COLOR="green">The container \'' . $_POST["newcontainer"] . '\' successfully created <br/>' . 'To use this container as default container, select it from the above drop down and click \'Save Changes\'</FONT>';
            } catch (Exception $e) {
                $success = false;
                return '<FONT COLOR="red">Container creation failed, Error: ' . $e->getMessage() . '</FONT>';
            }
        }
        $success = false;
        return '<FONT COLOR="red">Please specify name of the container to create</FONT>';
    }
    return null;
}
/**
 * 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();
    $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 {
        $storageClient = WindowsAzureStorageUtil::getStorageClient();
        // 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 = $_POST['selected_container'];
        } else {
            if (!empty($_GET['selected_container'])) {
                $selected_container_name = $_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>';
            $selected_container_name = $first_container_name;
        }
        // Handle file upload
        if (!empty($_POST['action']) && $_POST["action"] == "Upload") {
            if ($_FILES["uploadFileName"]["error"] == 0) {
                if (!file_exists($_FILES['uploadFileName']['tmp_name'])) {
                    echo "<p>Uploaded file " . $_FILES['uploadFileName']['tmp_name'] . " does not exist</p><br/>";
                } else {
                    $metaData = array('mimetype' => $_FILES['uploadFileName']['type']);
                    if (!empty($_POST["uploadFileTag"])) {
                        $metaData["tag"] = $_POST["uploadFileTag"];
                    }
                    try {
                        $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']) && $_POST["action"] == "Create") {
                if (!empty($_POST["createContainer"])) {
                    try {
                        WindowsAzureStorageUtil::createPublicContainer($_POST["createContainer"]);
                        $uploadMessage = "The container '" . $_POST["createContainer"] . "' successfully created";
                    } catch (Exception $e) {
                        $uploadSuccess = false;
                        $uploadMessage = "Container creation failed', Error: " . $e->getMessage();
                    }
                } else {
                    $uploadSuccess = false;
                    $uploadMessage = "Please specify container name";
                }
            }
        }
        ?>
        <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 $_SERVER['REQUEST_URI'];
        ?>
">
                <table class="form-table">
                  <tr valign="top">
                    <th scope="row">
                      <label for="selected_container">Container Name :</label>
                    </th>
                    <td>
                      <select name="selected_container" title="Stoarge container to be used for uploading media files" onChange="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();
                }
                ?>
                    <option value="<?php 
                echo $container->getName();
                ?>
" 
            <?php 
                echo $container->getName() == $selected_container_name ? 'selected="selected"' : '';
                ?>
 >
            <?php 
                echo $container->getName();
                ?>
</option>
<?php 
            }
            ?>
            <option value="<Create New Container>">&lt;Create New Container&gt;</option>
<?php 
        } catch (Exception $ex) {
            // Ignore exception as account keys are not yet set
        }
        ?>
                      </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' />
                <p class="submit">
                    <input type="submit" class="button-primary" id="submit" value="Upload" />
                </p>
            </form>
        </div>
    <script type="text/javascript">
         onUpload_ContainerSelectionChanged();
        </script>
<?php 
        if (!empty($uploadMessage)) {
            $color = $uploadSuccess ? 'green' : 'red';
            echo '<p style="margin: 10px; color: ' . $color . ';">' . $uploadMessage . "</p><br/>";
        }
    }
}
/**
 * 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));
        }
    }
}
/**
 * Try to create a container.
 *
 * @param boolean $success True if the operation succeeded, false otherwise.
 *
 * @return string The message to displayed
 */
function createContainerIfRequired(&$success)
{
    //TODO: remove HTML from returned message string
    //TODO: return message type ('error', 'warning', 'success') with message
    $success = true;
    if (isset($_POST['newcontainer']) && WindowsAzureStorageUtil::check_action_permissions('create_container') && check_admin_referer('create_container', 'create_new_container_settings')) {
        if (!empty($_POST["newcontainer"])) {
            if (empty($_POST["azure_storage_account_name"]) || empty($_POST["azure_storage_account_primary_access_key"])) {
                $success = false;
                return '<FONT COLOR="red">Please specify Storage Account Name and Primary Access Key to create container</FONT>';
            }
            try {
                $storageClient = WindowsAzureStorageUtil::getStorageClient(sanitize_text_field($_POST["azure_storage_account_name"]), sanitize_text_field($_POST["azure_storage_account_primary_access_key"]), sanitize_text_field($_POST["http_proxy_host"]), absint($_POST["http_proxy_port"]), sanitize_text_field($_POST["http_proxy_username"]), sanitize_text_field($_POST["http_proxy_password"]));
                WindowsAzureStorageUtil::createPublicContainer(sanitize_text_field($_POST['newcontainer']), $storageClient);
                return '<FONT COLOR="green">The container \'' . sanitize_text_field($_POST["newcontainer"]) . '\' successfully created <br/>' . 'To use this container as default container, select it from the above drop down and click \'Save Changes\'</FONT>';
            } catch (Exception $e) {
                $success = false;
                return '<FONT COLOR="red">Container creation failed, Error: ' . $e->getMessage() . '</FONT>';
            }
        }
        $success = false;
        return '<FONT COLOR="red">Please specify name of the container to create</FONT>';
    }
    return null;
}