From 11e9271316c36e8e8fa140e13926b5cf4c37338b Mon Sep 17 00:00:00 2001 From: mdtrooper <tres.14159@gmail.com> Date: Mon, 9 Jun 2014 13:33:55 +0000 Subject: [PATCH] 2014-06-09 Miguel de Dios <miguel.dedios@artica.es> * include/functions_config.php, general/login_page.php: improved the source code style. * godmode/setup/os.builder.php: fixed the form. * godmode/update_manager_xxx/*, godmode/menu.php, include/functions_update_manager.php, include/ajax/update_manager.ajax.php, include/graphs/functions_gd.php, include/graphs/functions_flot.php, include/config_process.php, include/javascript/update_manager.js, include/javascript/jquery.knob.js, include/javascript/jquery.iframe-transport.js, include/javascript/jquery.fileupload.js, images/check-cross.png: first version of new update manager. git-svn-id: https://svn.code.sf.net/p/pandora/code/trunk@10144 c3f86ba8-e40f-0410-aaad-9ba5e7f4b01f --- pandora_console/ChangeLog | 17 + pandora_console/general/login_page.php | 21 +- pandora_console/godmode/menu.php | 4 +- pandora_console/godmode/setup/os.builder.php | 4 +- .../update_manager_xxx/update_manager.css | 141 ++ .../update_manager.offline.php | 49 + .../update_manager.online.php | 58 + .../update_manager.setup.php | 51 + .../update_manager_xxx/update_manager_xxx.php | 66 + pandora_console/images/check-cross.png | Bin 0 -> 1393 bytes .../include/ajax/update_manager.ajax.php | 285 ++++ pandora_console/include/config_process.php | 6 + pandora_console/include/functions_config.php | 3 +- .../include/functions_update_manager.php | 192 +++ .../include/graphs/functions_flot.php | 2 +- .../include/graphs/functions_gd.php | 6 +- .../include/javascript/jquery.fileupload.js | 1367 +++++++++++++++++ .../javascript/jquery.iframe-transport.js | 208 +++ .../include/javascript/jquery.knob.js | 760 +++++++++ .../include/javascript/update_manager.js | 280 ++++ 20 files changed, 3502 insertions(+), 18 deletions(-) create mode 100644 pandora_console/godmode/update_manager_xxx/update_manager.css create mode 100644 pandora_console/godmode/update_manager_xxx/update_manager.offline.php create mode 100644 pandora_console/godmode/update_manager_xxx/update_manager.online.php create mode 100644 pandora_console/godmode/update_manager_xxx/update_manager.setup.php create mode 100644 pandora_console/godmode/update_manager_xxx/update_manager_xxx.php create mode 100755 pandora_console/images/check-cross.png create mode 100644 pandora_console/include/ajax/update_manager.ajax.php create mode 100755 pandora_console/include/functions_update_manager.php create mode 100644 pandora_console/include/javascript/jquery.fileupload.js create mode 100644 pandora_console/include/javascript/jquery.iframe-transport.js create mode 100755 pandora_console/include/javascript/jquery.knob.js create mode 100644 pandora_console/include/javascript/update_manager.js diff --git a/pandora_console/ChangeLog b/pandora_console/ChangeLog index c22ec9c504..4eadc44d41 100644 --- a/pandora_console/ChangeLog +++ b/pandora_console/ChangeLog @@ -1,3 +1,20 @@ +2014-06-09 Miguel de Dios <miguel.dedios@artica.es> + + * include/functions_config.php, general/login_page.php: improved + the source code style. + + * godmode/setup/os.builder.php: fixed the form. + + * godmode/update_manager_xxx/*, godmode/menu.php, + include/functions_update_manager.php, + include/ajax/update_manager.ajax.php, + include/graphs/functions_gd.php, include/graphs/functions_flot.php, + include/config_process.php, include/javascript/update_manager.js, + include/javascript/jquery.knob.js, + include/javascript/jquery.iframe-transport.js, + include/javascript/jquery.fileupload.js, images/check-cross.png: + first version of new update manager. + 2014-06-09 Sergio Martin <sergio.martin@artica.es> * images/login_background.jpg diff --git a/pandora_console/general/login_page.php b/pandora_console/general/login_page.php index 7009b7df2a..bfa39ec2a2 100644 --- a/pandora_console/general/login_page.php +++ b/pandora_console/general/login_page.php @@ -14,22 +14,22 @@ // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. -if(isset($config["homedir"])) { +if (isset($config["homedir"])) { $homedir = $config["homedir"] . '/'; } else { $homedir = ''; } - + include_once($homedir . 'include/functions_ui.php'); include_once($homedir . 'include/functions.php'); include_once($homedir . 'include/functions_html.php'); -if(!isset($login_screen)) { +if (!isset($login_screen)) { $login_screen = 'login'; } -switch($login_screen) { +switch ($login_screen) { case 'login': $logo_link = 'http://www.pandorafms.com'; $logo_title = __('Go to Pandora FMS Website'); @@ -54,6 +54,7 @@ if (!empty ($page) && !empty ($sec)) { $url .= '&'.safe_url_extraclean($key).'='.safe_url_extraclean($value); } } +$login_body_style = ''; // Overrides the default background with the defined by the user if (!empty($config['login_background'])) { $background_url = ui_get_full_url("images/backgrounds/") . $config['login_background']; @@ -67,10 +68,10 @@ echo '<div id="login_inner">'; echo ' <div id="login_in"> <form method="post" action="' . ui_get_full_url('index.php'.$url) . '" >'; - + //TODO: Put branding in variables (external file) or database /* CUSTOM BRANDING STARTS HERE */ - + // Replace the following with your own URL and logo. // A mashup of the Pandora FMS logo and your companies highly preferred echo '<table id="login_layout"><tr><td rowspan=2 style="width: 200px;">'; @@ -86,10 +87,10 @@ echo ' html_print_image ($config['homeurl'] . "/images/pandora_login.png", false, array ("class" => "login_logo", "alt" => "logo", "border" => 0, "title" => $logo_title), false, true); } echo '</a>'; - + // This prints the current pandora console version. // For stable/live function it might be wise to comment it out - + /* CUSTOM BRANDING ENDS HERE */ echo '</td><td>'; echo '<div class="login_links">'; @@ -99,7 +100,7 @@ echo ' echo '</div>'; echo '</td></tr><tr><td>'; - switch($login_screen) { + switch ($login_screen) { case 'login': if (!empty ($page) && !empty ($sec)) { foreach ($_POST as $key => $value) { @@ -129,7 +130,7 @@ echo ' echo '</p>'; break; default: - if(isset($error_info)) { + if (isset($error_info)) { echo '<h1 id="log_title">' . $error_info['title'] . '</h1>'; echo '<div id="error_buttons">'; echo '<a href="index.php">' . html_print_image($config['homeurl'] . '/images/refresh.png', true, array('title' => __('Refresh')), false, true) . '</a>'; diff --git a/pandora_console/godmode/menu.php b/pandora_console/godmode/menu.php index 7251af307e..edf1abdd2e 100644 --- a/pandora_console/godmode/menu.php +++ b/pandora_console/godmode/menu.php @@ -218,6 +218,8 @@ if (check_acl ($config['id_user'], 0, "PM")) { $sub["godmode/setup/os"]["text"] = __('Edit OS'); $sub["godmode/setup/license"]["text"] = __('License'); + $sub["godmode/update_manager_xxx/update_manager_xxx"]["text"] = __('xxxx'); + enterprise_hook ('enterprise_acl_submenu'); enterprise_hook ('skins_submenu'); $sub["extras/pandora_diag"]["text"] = __('Diagnostic info'); @@ -270,7 +272,7 @@ if (check_acl ($config['id_user'], 0, "PM")) { if ($extmenu["name"] == 'DB interface' && !check_acl ($config['id_user'], 0, "DM")) { continue; } - + //Check the ACL for this user if (! check_acl ($config['id_user'], 0, $extmenu['acl'])) { continue; diff --git a/pandora_console/godmode/setup/os.builder.php b/pandora_console/godmode/setup/os.builder.php index 874cd4a119..1e0344a41f 100644 --- a/pandora_console/godmode/setup/os.builder.php +++ b/pandora_console/godmode/setup/os.builder.php @@ -39,7 +39,7 @@ $table->data[2][0] = __('Icon'); $table->data[2][1] = html_print_select($icons, 'icon', $icon, 'show_icon_OS();', __('None'), 0, true); $table->data[2][1] .= ' <span id="icon_image">' . ui_print_os_icon($idOS, false, true) . '</span>'; -echo '<form action="post">'; + html_print_table($table); html_print_input_hidden('id_os', $idOS); @@ -86,7 +86,7 @@ function show_icon_OS() { async: false, timeout: 10000, success: function (data) { - $("#icon_image").html(data); + $("#icon_image").html(data); } }); } diff --git a/pandora_console/godmode/update_manager_xxx/update_manager.css b/pandora_console/godmode/update_manager_xxx/update_manager.css new file mode 100644 index 0000000000..2c0f7014d2 --- /dev/null +++ b/pandora_console/godmode/update_manager_xxx/update_manager.css @@ -0,0 +1,141 @@ +.fileupload_form { + background-color: #373A3D; + background-image: -moz-linear-gradient(center top , #373A3D, #313437); + border-radius: 3px; + font-family: 'PT Sans Narrow',sans-serif; + margin: 20px; + padding: 30px; +} +#drop_file { + background-color: #E6E6E6; + border: 20px solid rgba(0, 0, 0, 0); + border-radius: 3px; + color: #707070; + font-size: 16px; + font-weight: bold; + margin-bottom: 30px; + padding: 40px 50px; + text-align: center; + text-transform: uppercase; +} +#drop_file table { + vertical-align: middle; +} +#drop_file table td, #drop_file table label { + color: #707070; + font-family: 'PT Sans Narrow',sans-serif; + font-size: 16px; + font-weight: bold; + margin-top: 0; + vertical-align: middle; +} +#drop_file table select { + float: none; +} +#drop_file a { + background-color: #FF9933; + border-radius: 2px; + color: #FFFFFF; + cursor: pointer; + display: inline-block; + font-size: 14px; + line-height: 1; + padding: 12px 26px; +} +#drop_file a:hover { + background-color: #FFB972; + text-decoration: none; +} +#drop_file input { + display: none; +} +.fileupload_form ul { + border-bottom: 1px solid #3D4043; + border-top: 1px solid #2B2E31; + list-style: none outside none; + margin: 0 -30px; + padding: 0; +} +.fileupload_form ul li { + background-color: #333639; + background-image: -moz-linear-gradient(center top , #333639, #303335); + border-bottom: 1px solid #2B2E31; + border-top: 1px solid #3D4043; + padding: 15px; + position: relative; +} +.fileupload_form ul li #input-progress { + left: 68px; + position: absolute; +} +.fileupload_form ul li p { + color: #EEEEEE; + font-size: 12px; + font-weight: bold; + left: 95px; + overflow: hidden; + position: absolute; + top: 12px; + white-space: nowrap; +} +.fileupload_form ul li i { + color: #7F7F7F; + display: block; + font-style: normal; + font-weight: normal; +} +.fileupload_form ul li canvas { + left: 13px; + position: absolute; + top: 15px; +} +.fileupload_form ul li span { + background: url("../../images/check-cross.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0); + cursor: pointer; + height: 12px; + position: absolute; + right: 13px; + top: 34px; + width: 15px; +} +.fileupload_form ul li div { + display: block !important; +} +.fileupload_form ul li.working span { + background-position: 0 -12px; + height: 16px; +} +.fileupload_form ul li.loading span { + background: url("../../images/spinner.gif") no-repeat scroll 0 0 rgba(0, 0, 0, 0); + height: 16px; +} +.fileupload_form ul li.suc span { + background: url("../../images/check-cross.png") no-repeat scroll 0 0 rgba(0, 0, 0, 0); + height: 12px; +} +.fileupload_form ul li.suc p { + color: #5A8629; +} +.fileupload_form ul li.error span { + background: url("../../images/check-cross.png") no-repeat scroll 0 -12px rgba(0, 0, 0, 0); + height: 16px; +} +.fileupload_form ul li.error p { + color: #FF3333; +} + +#log_zone { + background-color: #E6E6E6; + border: 20px solid rgba(0, 0, 0, 0); + border-radius: 3px; + color: #707070; + font-size: 12px; + margin-bottom: 30px; + padding: 10px; + text-align: left; +} + +#box_online { + background-color: #E6E6E6; + padding: 10px; +} \ No newline at end of file diff --git a/pandora_console/godmode/update_manager_xxx/update_manager.offline.php b/pandora_console/godmode/update_manager_xxx/update_manager.offline.php new file mode 100644 index 0000000000..9efa394026 --- /dev/null +++ b/pandora_console/godmode/update_manager_xxx/update_manager.offline.php @@ -0,0 +1,49 @@ +<?php + +// Pandora FMS - http://pandorafms.com +// ================================================== +// Copyright (c) 2005-2011 Artica Soluciones Tecnologicas +// Please see http://pandorafms.org for full contribution list + +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; version 2 + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +global $config; + +ui_require_css_file('update_manager', 'godmode/update_manager_xxx/'); + +?> +<script type="text/javascript"> + <?php + echo "var drop_the_package_here_or ='" . __('Drop the package here or') . "';\n"; + echo "var browse_it ='" . __('browse it') . "';\n"; + echo "var the_package_has_been_uploaded_successfully ='" . __('The package has been uploaded successfully.') . "';\n"; + echo "var remember_that_this_package_will ='" . __('Remember that this package will override the actual Pandora FMS files and it is recommended to do a backup before continue with the update.') . "';\n"; + echo "var click_on_the_file_below_to_begin ='" . __('Click on the file below to begin.') . "';\n"; + echo "var updating ='" . __('Updating') . "';\n"; + echo "var package_updated_successfully ='" . __('Package updated successfully.') . "';\n"; + echo "var if_there_are_any_database_change ='" . __('If there are any database change, it will be applied on the next login.') . "';\n"; + echo "var package_not_updated ='" . __('Package not updated.') . "';\n"; + ?> +</script> + +<form id="form-offline_update" method="post" enctype="multipart/form-data" class="fileupload_form"> + <div></div> + <ul></ul> +</form> + +<script src="include/javascript/jquery.fileupload.js"></script> +<script src="include/javascript/jquery.iframe-transport.js"></script> +<script src="include/javascript/jquery.knob.js"></script> + +<script src="include/javascript/update_manager.js"></script> + +<script type="text/javascript"> + form_upload(); +</script> \ No newline at end of file diff --git a/pandora_console/godmode/update_manager_xxx/update_manager.online.php b/pandora_console/godmode/update_manager_xxx/update_manager.online.php new file mode 100644 index 0000000000..675bd63cc8 --- /dev/null +++ b/pandora_console/godmode/update_manager_xxx/update_manager.online.php @@ -0,0 +1,58 @@ +<?php + +// Pandora FMS - http://pandorafms.com +// ================================================== +// Copyright (c) 2005-2011 Artica Soluciones Tecnologicas +// Please see http://pandorafms.org for full contribution list + +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; version 2 + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +global $config; + +ui_require_css_file('update_manager', 'godmode/update_manager_xxx/'); +enterprise_include_once("include/functions_update_manager.php"); + +/* Translators: Do not translade Update Manager, it's the name of the program */ +ui_print_info_message( + '<p>' . + __('The new <a href="http://updatemanager.sourceforge.net">Update Manager</a> client is shipped with Pandora FMS It helps system administrators to update their Pandora FMS automatically, since the Update Manager does the task of getting new modules, new plugins and new features (even full migrations tools for future versions) automatically.') . + '</p>' . + '<p>' . + __('Update Manager is one of the most advanced features of Pandora FMS Enterprise version, for more information visit <a href="http://pandorafms.com">http://pandorafms.com</a>.') . + '</p>' . + '<p>' . + __('Update Manager sends anonymous information about Pandora FMS usage (number of agents and modules running). To disable it, remove remote server address from Update Manager plugin setup.') . + '</p>'); + +echo "<div id='box_online' style='text-align: center;'>"; + echo "<span class='loading' style=''>"; + echo "<img src='images/wait.gif' />"; + echo "</span>"; + + echo "<div class='checking_package' style='width:100%; text-align: center; display: none;'>"; + echo __('Checking for the newest package.'); + echo "</div>"; + + echo "<div class='downloading_package' style='width:100%; text-align: center; display: none;'>"; + echo __('Downloading for the newest package.'); + echo "</div>"; + + echo "<div class='content'></div>"; + + echo "<div class='progressbar' style='display: none;'><img class='progressbar_img' src='' /></div>"; + +echo "</div>"; + +$enterprise = enterprise_hook('update_manager_enterprise_main'); +if ($enterprise == ENTERPRISE_NOT_HOOK) { + //Open view + update_manager_main(); +} +?> \ No newline at end of file diff --git a/pandora_console/godmode/update_manager_xxx/update_manager.setup.php b/pandora_console/godmode/update_manager_xxx/update_manager.setup.php new file mode 100644 index 0000000000..5cbb7bbdd6 --- /dev/null +++ b/pandora_console/godmode/update_manager_xxx/update_manager.setup.php @@ -0,0 +1,51 @@ +<?php + +// Pandora FMS - http://pandorafms.com +// ================================================== +// Copyright (c) 2005-2011 Artica Soluciones Tecnologicas +// Please see http://pandorafms.org for full contribution list + +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; version 2 + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +global $config; + +$url_update_manager = get_parameter('url_update_manager', + $config['url_update_manager']); +$action_update_url_update_manager = (bool)get_parameter( + 'action_update_url_update_manager', 0); + +if ($action_update_url_update_manager) { + $result = config_update_value('url_update_manager', + $url_update_manager); + + ui_print_result_message($result, + __('Succesful Update the url config vars.'), + __('Unsuccesful Update the url config vars.')); +} + +echo '<form method="post" action="index.php?sec=gsetup&sec2=godmode/update_manager_xxx/update_manager_xxx&tab=setup">'; +$table = null; +$table->width = '98%'; + +$table->style[0] = 'font-weight: bolder; vertical-align: top;'; + +$table->data[0][0] = __('URL update manager:'); +$table->data[0][1] = html_print_input_text('url_update_manager', + $url_update_manager, __('URL update manager'), 40, 60, true); + +html_print_input_hidden('action_update_url_update_manager', 1); +html_print_table($table); + +echo '<div class="action-buttons" style="width: '.$table->width.'">'; +html_print_submit_button (__('Update'), 'update_button', false, + 'class="sub upd"'); +echo '</div>'; +echo '</form>'; +?> \ No newline at end of file diff --git a/pandora_console/godmode/update_manager_xxx/update_manager_xxx.php b/pandora_console/godmode/update_manager_xxx/update_manager_xxx.php new file mode 100644 index 0000000000..219f31a637 --- /dev/null +++ b/pandora_console/godmode/update_manager_xxx/update_manager_xxx.php @@ -0,0 +1,66 @@ +<?php + +// Pandora FMS - http://pandorafms.com +// ================================================== +// Copyright (c) 2005-2011 Artica Soluciones Tecnologicas +// Please see http://pandorafms.org for full contribution list + +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation; version 2 + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +global $config; + +//The ajax is in +// include/ajax/update_manager.ajax.php + +$tab = get_parameter('tab', 'online'); + +$buttons = array( + 'setup' => array( + 'active' => ($tab == 'setup') ? true : false, + 'text' => '<a href="index.php?sec=gsetup&sec2=godmode/update_manager_xxx/update_manager_xxx&tab=setup">' . + html_print_image ("images/gm_setup.png", true, array ("title" => __('Options'))) .'</a>'), + 'offline' => array( + 'active' => ($tab == 'offline') ? true : false, + 'text' => '<a href="index.php?sec=gsetup&sec2=godmode/update_manager_xxx/update_manager_xxx&tab=offline">' . + html_print_image ("images/box.disabled.png", true, array ("title" => __('Offline update manager'))) .'</a>'), + 'online' => array( + 'active' => ($tab == 'online') ? true : false, + 'text' => '<a href="index.php?sec=gsetup&sec2=godmode/update_manager_xxx/update_manager_xxx&tab=online">' . + html_print_image("images/op_gis.png", true, array ("title" => __('Online update manager'))) .'</a>') + ); + +switch ($tab) { + case 'setup': + $title = __('Update manager » Setup'); + break; + case 'offline': + $title = __('Update manager » Offline'); + break; + case 'online': + $title = __('Update manager » Online'); + break; +} + +ui_print_page_header($title, + "images/gm_setup.png", false, "", true, $buttons); + +switch ($tab) { + case 'setup': + require("update_manager.setup.php"); + break; + case 'offline': + require("update_manager.offline.php"); + break; + case 'online': + default: + require("update_manager.online.php"); + break; +} +?> \ No newline at end of file diff --git a/pandora_console/images/check-cross.png b/pandora_console/images/check-cross.png new file mode 100755 index 0000000000000000000000000000000000000000..3446eb06394c7c271c36c21b46fafb726846dc9e GIT binary patch literal 1393 zcmeAS@N?(olHy`uVBq!ia0vp^{6H+l!3HEV&ax!|DajJoh?3y^w370~qErUQl>DSr z1<%~X^wgl##FWaylc_cg49qE+ArU1JzCKpT`MG+DAT@dwxdlMo3=B5*6$OdO*{LN8 zNvY|XdA3ULckfqH$V{<S3ODsN@GWpo&B*kqDoPEm@(W3>%1*XSQL?vFu&J;D8jzb> zlBiITo0C^;Rbi_HHrEQs1_|pcDS(xfWZNo192Makpx~Tel&WB=XP}#GU}m6TW~gUq zY+`P1uA^XNU}&IkV5Dzoq-$tyWo%?+V4wg6N<iC+Qqrt~T-=~`0eQAc86_nJR{Hwo z<>h+i#(Mch>H3D2mX;thjEr=FDs+o0^GXscbn}XpVJ5hw7AF^F7L;V>=P7_pOiaoz zEwNPsx)kDt+yY-;xWReF(0~F4nSMoLfxe-hfqrf-$X{U9#U(+h2xnkbT^v$bkg6Y) zTAW{6lnjiIG-a4(VA$ce2&53`8Y};zOkkuW=D6f1m*%GCm3X??DgkBmQZiGlTpis^ zjm=CPUCo`$U5yM4EeuV}fV7jNiHoy|rHMJr3~YLxEX^$q4V;~UI^7HnU5zYV9i5zA zEnQq(jEtRJElgp0J@bl767!N%VfJPM?S<-f!mHQHxhOTUB)=#mKR*YS0s=DfOY(~| z@(UE4gH08}GxJjN%Zovg1M#a%YEfocYKmJ?ey##IbgeS6*iP8j5WOkngqS|iG5VmS zfs|BWLcsI~V!{(XkOR*;sd>QsQUuHxUw?V2F)%PL_H=O!skk*~ioeT|K!M}8%`TdL z6H#3h9J?r6FmtMsQsAjF&82U&To;8}EpeXa>vB<bQb(3&`=%wfU)|?gseGG~x6$Rx z+%wV1Qu_Pb`fESe?SFsfPujiP0e7#~csgja3r^7g+x~&UrfJzGhC>E781KG$&wg?b zD_g~1PBqUM&b$M2+;{LL?fJ*_SHU@Teq&nOKFyUa-U@nu1PffaPt6I{*W<EZ_or~f zbD2|f9;EqnGKAccp8h&VEa%junC;6WADoH~Te`l%^e)HEw=G|pa+q}@Vy`S-bg8Vh z{$%LPG}%dk?;K5EeB!-lrSj#i^8(SD9cK?8yv-Hd!=72duN21i=CaDYkGGY+JC~bY z6sc3cQO}TTqn7?f=jdyu@G03fmVZyisK(_mh}S$lajfM+ZBWEC-{)U$a5$vf>VDJA z7K!mTygR{8`M@fnZL1f@yxAt|kbdTun=9iv-jCW9zp~F6UX@Azx~g;k5tTb(p-*gr zHM-h)6Zy{@KjwCLB&qr)HPCTQYJ;EVGC>>ehn=ss@JyJpy)Q3xp7)xq#}t`LcKp{% czt6<OaOP_!3tQ8c<Df#&)78&qol`;+02mzc9{>OV literal 0 HcmV?d00001 diff --git a/pandora_console/include/ajax/update_manager.ajax.php b/pandora_console/include/ajax/update_manager.ajax.php new file mode 100644 index 0000000000..dbc35ff015 --- /dev/null +++ b/pandora_console/include/ajax/update_manager.ajax.php @@ -0,0 +1,285 @@ +<?php + +// Pandora FMS - http://pandorafms.com +// ================================================== +// Copyright (c) 2005-2010 Artica Soluciones Tecnologicas +// Please see http://pandorafms.org for full contribution list + +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU General Public License +// as published by the Free Software Foundation for version 2. +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +global $config; + +require_once("include/functions_update_manager.php"); +enterprise_include_once("include/functions_update_manager.php"); + +$upload_file = (boolean) get_parameter("upload_file"); +$install_package = (boolean) get_parameter("install_package"); +$check_install_package = (boolean) get_parameter("check_install_package"); +$check_install_enterprise_package = (boolean) get_parameter("check_install_enterprise_package"); +$check_online_packages = (boolean) get_parameter("check_online_packages"); +$check_online_enterprise_packages = (boolean) get_parameter("check_online_enterprise_packages"); +$update_last_package = (boolean) get_parameter("update_last_package"); +$update_last_enterprise_package = (boolean) get_parameter("update_last_enterprise_package"); +$install_package_online = (boolean) get_parameter("install_package_online"); +$install_enterprise_package = (boolean) get_parameter("install_enterprise_package"); +$check_progress_update = (boolean) get_parameter("check_progress_update"); +$check_progress_enterprise_update = (boolean) get_parameter("check_progress_enterprise_update"); +$install_package_step2 = (boolean)get_parameter("install_package_step2"); + +if ($upload_file) { + ob_clean(); + $return = array(); + + if (isset($_FILES['upfile']) && $_FILES['upfile']['error'] == 0) { + + $extension = pathinfo($_FILES['upfile']['name'], PATHINFO_EXTENSION); + + // The package extension should be .oum + if (strtolower($extension) === "oum") { + + $path = $_FILES['upfile']['tmp_name']; + // The package files will be saved in [user temp dir]/pandora_oum/package_name + $destination = sys_get_temp_dir()."/pandora_oum/".$_FILES['upfile']['name']; + // files.txt will have the names of every file of the package + if (file_exists($destination."/files.txt")) { + unlink($destination."/files.txt"); + } + + $zip = new ZipArchive; + // Zip open + if ($zip->open($path) === true) { + // The files will be extracted one by one + for($i = 0; $i < $zip->numFiles; $i++) { + $filename = $zip->getNameIndex($i); + + if ($zip->extractTo($destination, array($filename))) { + // Creates a file with the name of the files extracted + file_put_contents ($destination."/files.txt", $filename."\n", FILE_APPEND | LOCK_EX); + } else { + // Deletes the entire extraction directory if a file can not be extracted + delete_directory($destination); + $return["status"] = "error"; + $return["message"] = __("There was an error extracting the file '".$filename."' from the package."); + echo json_encode($return); + return; + } + } + // Creates a file with the number of files extracted + file_put_contents ($destination."/files.info.txt", $zip->numFiles); + // Zip close + $zip->close(); + + $return["status"] = "success"; + $return["package"] = $destination; + echo json_encode($return); + return; + } else { + $return["status"] = "error"; + $return["message"] = __("The package was not extracted."); + echo json_encode($return); + return; + } + } else { + $return["status"] = "error"; + $return["message"] = __("Invalid extension. The package must have the extension .oum."); + echo json_encode($return); + return; + } + } + + $return["status"] = "error"; + $return["message"] = __("The file was not uploaded succesfully."); + echo json_encode($return); + return; +} + +if ($install_package) { + ob_clean(); + + $package = (string) get_parameter("package"); + $package = trim($package); + + // All files extracted + $files_total = $package . "/files.txt"; + // Files copied + $files_copied = $package . "/files.copied.txt"; + $return = array(); + + if (file_exists($files_copied)) { + unlink($files_copied); + } + + if (file_exists($package)) { + + if ($files_h = fopen($files_total, "r")) { + + while ($line = stream_get_line($files_h, 65535, "\n")) { + $line = trim($line); + + // Tries to move the old file to the directory backup inside the extracted package + if (file_exists($config["homedir"]."/".$line)) { + rename($config["homedir"]."/".$line, $package."/backup/".$line); + } + // Tries to move the new file to the Integria directory + $dirname = dirname($line); + if (!file_exists($config["homedir"]."/".$dirname)) { + $dir_array = explode("/", $dirname); + $temp_dir = ""; + foreach ($dir_array as $dir) { + $temp_dir .= "/".$dir; + if (!file_exists($config["homedir"].$temp_dir)) { + mkdir($config["homedir"].$temp_dir); + } + } + } + if (is_dir($package."/".$line)) { + if (!file_exists($config["homedir"]."/".$line)) { + mkdir($config["homedir"]."/".$line); + file_put_contents($files_copied, $line."\n", FILE_APPEND | LOCK_EX); + } + } else { + if (rename($package."/".$line, $config["homedir"]."/".$line)) { + + // Append the moved file to the copied files txt + if (!file_put_contents($files_copied, $line."\n", FILE_APPEND | LOCK_EX)) { + + // If the copy process fail, this code tries to restore the files backed up before + if ($files_copied_h = fopen($files_copied, "r")) { + while ($line_c = stream_get_line($files_copied_h, 65535, "\n")) { + $line_c = trim($line_c); + if (!rename($package."/backup/".$line, $config["homedir"]."/".$line_c)) { + $backup_status = __("Some of your files might not be recovered."); + } + } + if (!rename($package."/backup/".$line, $config["homedir"]."/".$line)) { + $backup_status = __("Some of your files might not be recovered."); + } + fclose($files_copied_h); + } else { + $backup_status = __("Some of your old files might not be recovered."); + } + + fclose($files_h); + $return["status"] = "error"; + $return["message"]= __("Line '$line' not copied to the progress file.")." ".$backup_status; + echo json_encode($return); + return; + } + } else { + + // If the copy process fail, this code tries to restore the files backed up before + if ($files_copied_h = fopen($files_copied, "r")) { + while ($line_c = stream_get_line($files_copied_h, 65535, "\n")) { + $line_c = trim($line_c); + if (!rename($package."/backup/".$line, $config["homedir"]."/".$line)) { + $backup_status = __("Some of your old files might not be recovered."); + } + } + fclose($files_copied_h); + } else { + $backup_status = __("Some of your files might not be recovered."); + } + + fclose($files_h); + $return["status"] = "error"; + $return["message"]= __("File '$line' not copied.")." ".$backup_status; + echo json_encode($return); + return; + } + } + } + fclose($files_h); + } else { + $return["status"] = "error"; + $return["message"]= __("An error ocurred while reading a file."); + echo json_encode($return); + return; + } + } else { + $return["status"] = "error"; + $return["message"]= __("The package does not exist"); + echo json_encode($return); + return; + } + + $return["status"] = "success"; + echo json_encode($return); + return; +} + +if ($check_install_enterprise_package) { + + check_install_enterprise_package(); + + return; + +} + +if ($check_install_package) { + + return; +} + +if ($check_online_enterprise_packages) { + + update_manager_check_online_enterprise_packages(); + + return; + +} + +if ($check_online_packages) { + + return; +} + +if ($update_last_enterprise_package) { + + update_manager_update_last_enterprise_package(); + + return; + +} + +if ($update_last_package) { + + return; +} + +if ($install_enterprise_package) { + $package = get_parameter('package', ''); + + update_manager_starting_enterprise_update($package, + $config['attachment_store'] . "/downloads/" . $package); + + return; +} + +if ($install_package_online) { + + return; +} + +if ($install_package_step2) { + update_manager_install_package_step2(); + + return; +} + +if ($check_progress_enterprise_update) { + update_manager_check_progress_enterprise(); + + return; +} + +if ($check_progress_update) { + + return; +} +?> \ No newline at end of file diff --git a/pandora_console/include/config_process.php b/pandora_console/include/config_process.php index fede12f0e4..30522bd770 100644 --- a/pandora_console/include/config_process.php +++ b/pandora_console/include/config_process.php @@ -175,6 +175,12 @@ if (!isset($config['inventory_changes_blacklist'])) { $config['inventory_changes_blacklist'] = array(); } +//NEW UPDATE MANAGER URL +if (!isset($config['url_update_manager'])) { + config_update_value('url_update_manager', + 'https://artica.es/integriaupdate4/server.php'); +} + if (defined('METACONSOLE')) { enterprise_include_once('meta/include/functions_users_meta.php'); enterprise_hook('set_meta_user_language'); diff --git a/pandora_console/include/functions_config.php b/pandora_console/include/functions_config.php index 265bf328a6..e87acaced6 100644 --- a/pandora_console/include/functions_config.php +++ b/pandora_console/include/functions_config.php @@ -45,7 +45,8 @@ function config_update_value ($token, $value) { global $config; if ($token == 'list_ACL_IPs_for_API') { - $value = str_replace(array("\r\n", "\r", "\n"), ";", io_safe_output($value)); + $value = str_replace(array("\r\n", "\r", "\n"), ";", + io_safe_output($value)); } if (!isset ($config[$token])) { diff --git a/pandora_console/include/functions_update_manager.php b/pandora_console/include/functions_update_manager.php new file mode 100755 index 0000000000..436c4ac042 --- /dev/null +++ b/pandora_console/include/functions_update_manager.php @@ -0,0 +1,192 @@ +<?php + +// Pandora FMS - http://pandorafms.com +// ================================================== +// Copyright (c) 2005-2009 Artica Soluciones Tecnologicas +// Please see http://pandorafms.org for full contribution list + +// This program is free software; you can redistribute it and/or +// modify it under the terms of the GNU Lesser General Public License +// as published by the Free Software Foundation; version 2 + +// This program is distributed in the hope that it will be useful, +// but WITHOUT ANY WARRANTY; without even the implied warranty of +// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +// GNU General Public License for more details. + +/** + * @package Include + * @subpackage UI + */ + +function update_manager_get_config_values() { + $license = db_get_value('`value`', 'tupdate_settings', '`key`', + 'customer_key'); + $current_update = db_get_value('`value`', 'tupdate_settings', '`key`', + 'current_update'); + $limit_count = db_get_value_sql("SELECT count(*) FROM tagente"); + global $build_version; + global $pandora_version; + + //TO DO + $license = "TESTMIGUEL00B0WAW9BU1QM0RZ2QM0MZ3QN5M41R35S5S1DP"; + $current_update = 11; + + return array( + 'license' => $license, + 'current_update' => $current_update, + 'limit_count' => $limit_count, + 'build' => $build_version, + 'version' => $pandora_version, + ); +} + +//Function to remove dir and files inside +function rrmdir($dir) { + if (is_dir($dir)) { + $objects = scandir($dir); + foreach ($objects as $object) { + if ($object != "." && $object != "..") { + if (filetype($dir."/".$object) == "dir") + rrmdir($dir."/".$object); else unlink($dir."/".$object); + } + } + reset($objects); + rmdir($dir); + } +} + +function update_manager_install_package_step2() { + global $config; + + ob_clean(); + + $package = (string) get_parameter("package"); + $package = trim($package); + + $version = (string)get_parameter("version", 0); + + $path = sys_get_temp_dir() . "/pandora_oum/" . $package; + + // All files extracted + $files_total = $path."/files.txt"; + // Files copied + $files_copied = $path."/files.copied.txt"; + $return = array(); + + if (file_exists($files_copied)) { + unlink($files_copied); + } + + if (file_exists($path)) { + + if ($files_h = fopen($files_total, "r")) { + + while ($line = stream_get_line($files_h, 65535, "\n")) { + + $line = trim($line); + + // Tries to move the old file to the directory backup inside the extracted package + if (file_exists($config["homedir"]."/".$line)) { + rename($config["homedir"]."/".$line, $path."/backup/".$line); + } + // Tries to move the new file to the Integria directory + $dirname = dirname($line); + if (!file_exists($config["homedir"]."/".$dirname)) { + $dir_array = explode("/", $dirname); + $temp_dir = ""; + foreach ($dir_array as $dir) { + $temp_dir .= "/".$dir; + if (!file_exists($config["homedir"].$temp_dir)) { + mkdir($config["homedir"].$temp_dir); + } + } + } + if (is_dir($path."/".$line)) { + if (!file_exists($config["homedir"]."/".$line)) { + mkdir($config["homedir"]."/".$line); + file_put_contents($files_copied, $line."\n", FILE_APPEND | LOCK_EX); + } + } + else { + //Copy the new file + if (rename($path."/".$line, $config["homedir"]."/".$line)) { + + // Append the moved file to the copied files txt + if (!file_put_contents($files_copied, $line."\n", FILE_APPEND | LOCK_EX)) { + + // If the copy process fail, this code tries to restore the files backed up before + if ($files_copied_h = fopen($files_copied, "r")) { + while ($line_c = stream_get_line($files_copied_h, 65535, "\n")) { + $line_c = trim($line_c); + if (!rename($path."/backup/".$line, $config["homedir"]."/".$line_c)) { + $backup_status = __("Some of your files might not be recovered."); + } + } + if (!rename($path."/backup/".$line, $config["homedir"]."/".$line)) { + $backup_status = __("Some of your files might not be recovered."); + } + fclose($files_copied_h); + } else { + $backup_status = __("Some of your old files might not be recovered."); + } + + fclose($files_h); + $return["status"] = "error"; + $return["message"]= __("Line '$line' not copied to the progress file.")." ".$backup_status; + echo json_encode($return); + return; + } + } + else { + // If the copy process fail, this code tries to restore the files backed up before + if ($files_copied_h = fopen($files_copied, "r")) { + while ($line_c = stream_get_line($files_copied_h, 65535, "\n")) { + $line_c = trim($line_c); + if (!rename($path."/backup/".$line, $config["homedir"]."/".$line)) { + $backup_status = __("Some of your old files might not be recovered."); + } + } + fclose($files_copied_h); + } + else { + $backup_status = __("Some of your files might not be recovered."); + } + + fclose($files_h); + $return["status"] = "error"; + $return["message"]= __("File '$line' not copied.")." ".$backup_status; + echo json_encode($return); + return; + } + } + } + fclose($files_h); + } + else { + $return["status"] = "error"; + $return["message"]= __("An error ocurred while reading a file."); + echo json_encode($return); + return; + } + } + else { + $return["status"] = "error"; + $return["message"]= __("The package does not exist"); + echo json_encode($return); + return; + } + + $return["status"] = "success"; + $return["message"]= __("The package is installed."); + echo json_encode($return); + + update_manager_enterprise_set_version($version); + + return; +} + +function update_manager_main() { + +} +?> \ No newline at end of file diff --git a/pandora_console/include/graphs/functions_flot.php b/pandora_console/include/graphs/functions_flot.php index 068a021292..9b71e1a827 100644 --- a/pandora_console/include/graphs/functions_flot.php +++ b/pandora_console/include/graphs/functions_flot.php @@ -395,7 +395,7 @@ function flot_pie_chart ($values, $labels, $width, $height, $water_mark, } $return .= "<script type='text/javascript'>"; - + $return .= "pandoraFlotPie('$graph_id', '$values', '$labels', '$series', '$width', $font_size, $water_mark, '$separator', '$legend_position', '$height', '$colors')"; diff --git a/pandora_console/include/graphs/functions_gd.php b/pandora_console/include/graphs/functions_gd.php index f0804cc60b..e39eb8d3d2 100755 --- a/pandora_console/include/graphs/functions_gd.php +++ b/pandora_console/include/graphs/functions_gd.php @@ -272,7 +272,7 @@ function gd_progress_bar ($width, $height, $progress, $title, $font, $out_of_lim function drawRating($rating, $width, $height, $font, $out_of_lim_str, $mode, $fontsize, $value_text, $color) { global $config; global $REMOTE_ADDR; - + // Round corners defined in global setup if ($config["round_corner"] != 0) { $radius = ($height > 18) ? 8 : 0; @@ -315,7 +315,7 @@ function gd_progress_bar ($width, $height, $progress, $title, $font, $out_of_lim $soft_red_border = ImageColorAllocate($image,255, 154, 84); $other_red = ImageColorAllocate($image,239, 141, 122); $other_red_border = ImageColorAllocate($image,255, 112, 86); - + $x1 = 1; $y1 = 1; $x2 = $ratingbar; @@ -443,7 +443,7 @@ function gd_progress_bar ($width, $height, $progress, $title, $font, $out_of_lim */ drawRating($progress, $width, $height, $font, $out_of_lim_str, $mode, 6, $value_text, $color); - + break; case 2: if ($progress > 100 || $progress < 0) { diff --git a/pandora_console/include/javascript/jquery.fileupload.js b/pandora_console/include/javascript/jquery.fileupload.js new file mode 100644 index 0000000000..16ebb1d959 --- /dev/null +++ b/pandora_console/include/javascript/jquery.fileupload.js @@ -0,0 +1,1367 @@ +/* + * jQuery File Upload Plugin 5.34.0 + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2010, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/MIT + */ + +/*jslint nomen: true, unparam: true, regexp: true */ +/*global define, window, document, location, File, Blob, FormData */ + +(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // Register as an anonymous AMD module: + define([ + 'jquery', + 'jquery.ui.widget' + ], factory); + } else { + // Browser globals: + factory(window.jQuery); + } +}(function ($) { + 'use strict'; + + // Detect file input support, based on + // http://viljamis.com/blog/2012/file-upload-support-on-mobile/ + $.support.fileInput = !(new RegExp( + // Handle devices which give false positives for the feature detection: + '(Android (1\\.[0156]|2\\.[01]))' + + '|(Windows Phone (OS 7|8\\.0))|(XBLWP)|(ZuneWP)|(WPDesktop)' + + '|(w(eb)?OSBrowser)|(webOS)' + + '|(Kindle/(1\\.0|2\\.[05]|3\\.0))' + ).test(window.navigator.userAgent) || + // Feature detection for all other devices: + $('<input type="file">').prop('disabled')); + + // The FileReader API is not actually used, but works as feature detection, + // as e.g. Safari supports XHR file uploads via the FormData API, + // but not non-multipart XHR file uploads: + $.support.xhrFileUpload = !!(window.XMLHttpRequestUpload && window.FileReader); + $.support.xhrFormDataFileUpload = !!window.FormData; + + // Detect support for Blob slicing (required for chunked uploads): + $.support.blobSlice = window.Blob && (Blob.prototype.slice || + Blob.prototype.webkitSlice || Blob.prototype.mozSlice); + + // The fileupload widget listens for change events on file input fields defined + // via fileInput setting and paste or drop events of the given dropZone. + // In addition to the default jQuery Widget methods, the fileupload widget + // exposes the "add" and "send" methods, to add or directly send files using + // the fileupload API. + // By default, files added via file input selection, paste, drag & drop or + // "add" method are uploaded immediately, but it is possible to override + // the "add" callback option to queue file uploads. + $.widget('blueimp.fileupload', { + + options: { + // The drop target element(s), by the default the complete document. + // Set to null to disable drag & drop support: + dropZone: $(document), + // The paste target element(s), by the default the complete document. + // Set to null to disable paste support: + pasteZone: $(document), + // The file input field(s), that are listened to for change events. + // If undefined, it is set to the file input fields inside + // of the widget element on plugin initialization. + // Set to null to disable the change listener. + fileInput: undefined, + // By default, the file input field is replaced with a clone after + // each input field change event. This is required for iframe transport + // queues and allows change events to be fired for the same file + // selection, but can be disabled by setting the following option to false: + replaceFileInput: true, + // The parameter name for the file form data (the request argument name). + // If undefined or empty, the name property of the file input field is + // used, or "files[]" if the file input name property is also empty, + // can be a string or an array of strings: + paramName: undefined, + // By default, each file of a selection is uploaded using an individual + // request for XHR type uploads. Set to false to upload file + // selections in one request each: + singleFileUploads: true, + // To limit the number of files uploaded with one XHR request, + // set the following option to an integer greater than 0: + limitMultiFileUploads: undefined, + // Set the following option to true to issue all file upload requests + // in a sequential order: + sequentialUploads: false, + // To limit the number of concurrent uploads, + // set the following option to an integer greater than 0: + limitConcurrentUploads: undefined, + // Set the following option to true to force iframe transport uploads: + forceIframeTransport: false, + // Set the following option to the location of a redirect url on the + // origin server, for cross-domain iframe transport uploads: + redirect: undefined, + // The parameter name for the redirect url, sent as part of the form + // data and set to 'redirect' if this option is empty: + redirectParamName: undefined, + // Set the following option to the location of a postMessage window, + // to enable postMessage transport uploads: + postMessage: undefined, + // By default, XHR file uploads are sent as multipart/form-data. + // The iframe transport is always using multipart/form-data. + // Set to false to enable non-multipart XHR uploads: + multipart: true, + // To upload large files in smaller chunks, set the following option + // to a preferred maximum chunk size. If set to 0, null or undefined, + // or the browser does not support the required Blob API, files will + // be uploaded as a whole. + maxChunkSize: undefined, + // When a non-multipart upload or a chunked multipart upload has been + // aborted, this option can be used to resume the upload by setting + // it to the size of the already uploaded bytes. This option is most + // useful when modifying the options object inside of the "add" or + // "send" callbacks, as the options are cloned for each file upload. + uploadedBytes: undefined, + // By default, failed (abort or error) file uploads are removed from the + // global progress calculation. Set the following option to false to + // prevent recalculating the global progress data: + recalculateProgress: true, + // Interval in milliseconds to calculate and trigger progress events: + progressInterval: 100, + // Interval in milliseconds to calculate progress bitrate: + bitrateInterval: 500, + // By default, uploads are started automatically when adding files: + autoUpload: true, + + // Error and info messages: + messages: { + uploadedBytes: 'Uploaded bytes exceed file size' + }, + + // Translation function, gets the message key to be translated + // and an object with context specific data as arguments: + i18n: function (message, context) { + message = this.messages[message] || message.toString(); + if (context) { + $.each(context, function (key, value) { + message = message.replace('{' + key + '}', value); + }); + } + return message; + }, + + // Additional form data to be sent along with the file uploads can be set + // using this option, which accepts an array of objects with name and + // value properties, a function returning such an array, a FormData + // object (for XHR file uploads), or a simple object. + // The form of the first fileInput is given as parameter to the function: + formData: function (form) { + return form.serializeArray(); + }, + + // The add callback is invoked as soon as files are added to the fileupload + // widget (via file input selection, drag & drop, paste or add API call). + // If the singleFileUploads option is enabled, this callback will be + // called once for each file in the selection for XHR file uploads, else + // once for each file selection. + // + // The upload starts when the submit method is invoked on the data parameter. + // The data object contains a files property holding the added files + // and allows you to override plugin options as well as define ajax settings. + // + // Listeners for this callback can also be bound the following way: + // .bind('fileuploadadd', func); + // + // data.submit() returns a Promise object and allows to attach additional + // handlers using jQuery's Deferred callbacks: + // data.submit().done(func).fail(func).always(func); + add: function (e, data) { + if (e.isDefaultPrevented()) { + return false; + } + if (data.autoUpload || (data.autoUpload !== false && + $(this).fileupload('option', 'autoUpload'))) { + data.process().done(function () { + data.submit(); + }); + } + }, + + // Other callbacks: + + // Callback for the submit event of each file upload: + // submit: function (e, data) {}, // .bind('fileuploadsubmit', func); + + // Callback for the start of each file upload request: + // send: function (e, data) {}, // .bind('fileuploadsend', func); + + // Callback for successful uploads: + // done: function (e, data) {}, // .bind('fileuploaddone', func); + + // Callback for failed (abort or error) uploads: + // fail: function (e, data) {}, // .bind('fileuploadfail', func); + + // Callback for completed (success, abort or error) requests: + // always: function (e, data) {}, // .bind('fileuploadalways', func); + + // Callback for upload progress events: + // progress: function (e, data) {}, // .bind('fileuploadprogress', func); + + // Callback for global upload progress events: + // progressall: function (e, data) {}, // .bind('fileuploadprogressall', func); + + // Callback for uploads start, equivalent to the global ajaxStart event: + // start: function (e) {}, // .bind('fileuploadstart', func); + + // Callback for uploads stop, equivalent to the global ajaxStop event: + // stop: function (e) {}, // .bind('fileuploadstop', func); + + // Callback for change events of the fileInput(s): + // change: function (e, data) {}, // .bind('fileuploadchange', func); + + // Callback for paste events to the pasteZone(s): + // paste: function (e, data) {}, // .bind('fileuploadpaste', func); + + // Callback for drop events of the dropZone(s): + // drop: function (e, data) {}, // .bind('fileuploaddrop', func); + + // Callback for dragover events of the dropZone(s): + // dragover: function (e) {}, // .bind('fileuploaddragover', func); + + // Callback for the start of each chunk upload request: + // chunksend: function (e, data) {}, // .bind('fileuploadchunksend', func); + + // Callback for successful chunk uploads: + // chunkdone: function (e, data) {}, // .bind('fileuploadchunkdone', func); + + // Callback for failed (abort or error) chunk uploads: + // chunkfail: function (e, data) {}, // .bind('fileuploadchunkfail', func); + + // Callback for completed (success, abort or error) chunk upload requests: + // chunkalways: function (e, data) {}, // .bind('fileuploadchunkalways', func); + + // The plugin options are used as settings object for the ajax calls. + // The following are jQuery ajax settings required for the file uploads: + processData: false, + contentType: false, + cache: false + }, + + // A list of options that require reinitializing event listeners and/or + // special initialization code: + _specialOptions: [ + 'fileInput', + 'dropZone', + 'pasteZone', + 'multipart', + 'forceIframeTransport' + ], + + _blobSlice: $.support.blobSlice && function () { + var slice = this.slice || this.webkitSlice || this.mozSlice; + return slice.apply(this, arguments); + }, + + _BitrateTimer: function () { + this.timestamp = ((Date.now) ? Date.now() : (new Date()).getTime()); + this.loaded = 0; + this.bitrate = 0; + this.getBitrate = function (now, loaded, interval) { + var timeDiff = now - this.timestamp; + if (!this.bitrate || !interval || timeDiff > interval) { + this.bitrate = (loaded - this.loaded) * (1000 / timeDiff) * 8; + this.loaded = loaded; + this.timestamp = now; + } + return this.bitrate; + }; + }, + + _isXHRUpload: function (options) { + return !options.forceIframeTransport && + ((!options.multipart && $.support.xhrFileUpload) || + $.support.xhrFormDataFileUpload); + }, + + _getFormData: function (options) { + var formData; + if (typeof options.formData === 'function') { + return options.formData(options.form); + } + if ($.isArray(options.formData)) { + return options.formData; + } + if ($.type(options.formData) === 'object') { + formData = []; + $.each(options.formData, function (name, value) { + formData.push({name: name, value: value}); + }); + return formData; + } + return []; + }, + + _getTotal: function (files) { + var total = 0; + $.each(files, function (index, file) { + total += file.size || 1; + }); + return total; + }, + + _initProgressObject: function (obj) { + var progress = { + loaded: 0, + total: 0, + bitrate: 0 + }; + if (obj._progress) { + $.extend(obj._progress, progress); + } else { + obj._progress = progress; + } + }, + + _initResponseObject: function (obj) { + var prop; + if (obj._response) { + for (prop in obj._response) { + if (obj._response.hasOwnProperty(prop)) { + delete obj._response[prop]; + } + } + } else { + obj._response = {}; + } + }, + + _onProgress: function (e, data) { + if (e.lengthComputable) { + var now = ((Date.now) ? Date.now() : (new Date()).getTime()), + loaded; + if (data._time && data.progressInterval && + (now - data._time < data.progressInterval) && + e.loaded !== e.total) { + return; + } + data._time = now; + loaded = Math.floor( + e.loaded / e.total * (data.chunkSize || data._progress.total) + ) + (data.uploadedBytes || 0); + // Add the difference from the previously loaded state + // to the global loaded counter: + this._progress.loaded += (loaded - data._progress.loaded); + this._progress.bitrate = this._bitrateTimer.getBitrate( + now, + this._progress.loaded, + data.bitrateInterval + ); + data._progress.loaded = data.loaded = loaded; + data._progress.bitrate = data.bitrate = data._bitrateTimer.getBitrate( + now, + loaded, + data.bitrateInterval + ); + // Trigger a custom progress event with a total data property set + // to the file size(s) of the current upload and a loaded data + // property calculated accordingly: + this._trigger( + 'progress', + $.Event('progress', {delegatedEvent: e}), + data + ); + // Trigger a global progress event for all current file uploads, + // including ajax calls queued for sequential file uploads: + this._trigger( + 'progressall', + $.Event('progressall', {delegatedEvent: e}), + this._progress + ); + } + }, + + _initProgressListener: function (options) { + var that = this, + xhr = options.xhr ? options.xhr() : $.ajaxSettings.xhr(); + // Accesss to the native XHR object is required to add event listeners + // for the upload progress event: + if (xhr.upload) { + $(xhr.upload).bind('progress', function (e) { + var oe = e.originalEvent; + // Make sure the progress event properties get copied over: + e.lengthComputable = oe.lengthComputable; + e.loaded = oe.loaded; + e.total = oe.total; + that._onProgress(e, options); + }); + options.xhr = function () { + return xhr; + }; + } + }, + + _isInstanceOf: function (type, obj) { + // Cross-frame instanceof check + return Object.prototype.toString.call(obj) === '[object ' + type + ']'; + }, + + _initXHRData: function (options) { + var that = this, + formData, + file = options.files[0], + // Ignore non-multipart setting if not supported: + multipart = options.multipart || !$.support.xhrFileUpload, + paramName = options.paramName[0]; + options.headers = $.extend({}, options.headers); + if (options.contentRange) { + options.headers['Content-Range'] = options.contentRange; + } + if (!multipart || options.blob || !this._isInstanceOf('File', file)) { + options.headers['Content-Disposition'] = 'attachment; filename="' + + encodeURI(file.name) + '"'; + } + if (!multipart) { + options.contentType = file.type; + options.data = options.blob || file; + } else if ($.support.xhrFormDataFileUpload) { + if (options.postMessage) { + // window.postMessage does not allow sending FormData + // objects, so we just add the File/Blob objects to + // the formData array and let the postMessage window + // create the FormData object out of this array: + formData = this._getFormData(options); + if (options.blob) { + formData.push({ + name: paramName, + value: options.blob + }); + } else { + $.each(options.files, function (index, file) { + formData.push({ + name: options.paramName[index] || paramName, + value: file + }); + }); + } + } else { + if (that._isInstanceOf('FormData', options.formData)) { + formData = options.formData; + } else { + formData = new FormData(); + $.each(this._getFormData(options), function (index, field) { + formData.append(field.name, field.value); + }); + } + if (options.blob) { + formData.append(paramName, options.blob, file.name); + } else { + $.each(options.files, function (index, file) { + // This check allows the tests to run with + // dummy objects: + if (that._isInstanceOf('File', file) || + that._isInstanceOf('Blob', file)) { + formData.append( + options.paramName[index] || paramName, + file, + file.name + ); + } + }); + } + } + options.data = formData; + } + // Blob reference is not needed anymore, free memory: + options.blob = null; + }, + + _initIframeSettings: function (options) { + var targetHost = $('<a></a>').prop('href', options.url).prop('host'); + // Setting the dataType to iframe enables the iframe transport: + options.dataType = 'iframe ' + (options.dataType || ''); + // The iframe transport accepts a serialized array as form data: + options.formData = this._getFormData(options); + // Add redirect url to form data on cross-domain uploads: + if (options.redirect && targetHost && targetHost !== location.host) { + options.formData.push({ + name: options.redirectParamName || 'redirect', + value: options.redirect + }); + } + }, + + _initDataSettings: function (options) { + if (this._isXHRUpload(options)) { + if (!this._chunkedUpload(options, true)) { + if (!options.data) { + this._initXHRData(options); + } + this._initProgressListener(options); + } + if (options.postMessage) { + // Setting the dataType to postmessage enables the + // postMessage transport: + options.dataType = 'postmessage ' + (options.dataType || ''); + } + } else { + this._initIframeSettings(options); + } + }, + + _getParamName: function (options) { + var fileInput = $(options.fileInput), + paramName = options.paramName; + if (!paramName) { + paramName = []; + fileInput.each(function () { + var input = $(this), + name = input.prop('name') || 'files[]', + i = (input.prop('files') || [1]).length; + while (i) { + paramName.push(name); + i -= 1; + } + }); + if (!paramName.length) { + paramName = [fileInput.prop('name') || 'files[]']; + } + } else if (!$.isArray(paramName)) { + paramName = [paramName]; + } + return paramName; + }, + + _initFormSettings: function (options) { + // Retrieve missing options from the input field and the + // associated form, if available: + if (!options.form || !options.form.length) { + options.form = $(options.fileInput.prop('form')); + // If the given file input doesn't have an associated form, + // use the default widget file input's form: + if (!options.form.length) { + options.form = $(this.options.fileInput.prop('form')); + } + } + options.paramName = this._getParamName(options); + if (!options.url) { + options.url = options.form.prop('action') || location.href; + } + // The HTTP request method must be "POST" or "PUT": + options.type = (options.type || + ($.type(options.form.prop('method')) === 'string' && + options.form.prop('method')) || '' + ).toUpperCase(); + if (options.type !== 'POST' && options.type !== 'PUT' && + options.type !== 'PATCH') { + options.type = 'POST'; + } + if (!options.formAcceptCharset) { + options.formAcceptCharset = options.form.attr('accept-charset'); + } + }, + + _getAJAXSettings: function (data) { + var options = $.extend({}, this.options, data); + this._initFormSettings(options); + this._initDataSettings(options); + return options; + }, + + // jQuery 1.6 doesn't provide .state(), + // while jQuery 1.8+ removed .isRejected() and .isResolved(): + _getDeferredState: function (deferred) { + if (deferred.state) { + return deferred.state(); + } + if (deferred.isResolved()) { + return 'resolved'; + } + if (deferred.isRejected()) { + return 'rejected'; + } + return 'pending'; + }, + + // Maps jqXHR callbacks to the equivalent + // methods of the given Promise object: + _enhancePromise: function (promise) { + promise.success = promise.done; + promise.error = promise.fail; + promise.complete = promise.always; + return promise; + }, + + // Creates and returns a Promise object enhanced with + // the jqXHR methods abort, success, error and complete: + _getXHRPromise: function (resolveOrReject, context, args) { + var dfd = $.Deferred(), + promise = dfd.promise(); + context = context || this.options.context || promise; + if (resolveOrReject === true) { + dfd.resolveWith(context, args); + } else if (resolveOrReject === false) { + dfd.rejectWith(context, args); + } + promise.abort = dfd.promise; + return this._enhancePromise(promise); + }, + + // Adds convenience methods to the data callback argument: + _addConvenienceMethods: function (e, data) { + var that = this, + getPromise = function (data) { + return $.Deferred().resolveWith(that, [data]).promise(); + }; + data.process = function (resolveFunc, rejectFunc) { + if (resolveFunc || rejectFunc) { + data._processQueue = this._processQueue = + (this._processQueue || getPromise(this)) + .pipe(resolveFunc, rejectFunc); + } + return this._processQueue || getPromise(this); + }; + data.submit = function () { + if (this.state() !== 'pending') { + data.jqXHR = this.jqXHR = + (that._trigger( + 'submit', + $.Event('submit', {delegatedEvent: e}), + this + ) !== false) && that._onSend(e, this); + } + return this.jqXHR || that._getXHRPromise(); + }; + data.abort = function () { + if (this.jqXHR) { + return this.jqXHR.abort(); + } + return that._getXHRPromise(); + }; + data.state = function () { + if (this.jqXHR) { + return that._getDeferredState(this.jqXHR); + } + if (this._processQueue) { + return that._getDeferredState(this._processQueue); + } + }; + data.progress = function () { + return this._progress; + }; + data.response = function () { + return this._response; + }; + }, + + // Parses the Range header from the server response + // and returns the uploaded bytes: + _getUploadedBytes: function (jqXHR) { + var range = jqXHR.getResponseHeader('Range'), + parts = range && range.split('-'), + upperBytesPos = parts && parts.length > 1 && + parseInt(parts[1], 10); + return upperBytesPos && upperBytesPos + 1; + }, + + // Uploads a file in multiple, sequential requests + // by splitting the file up in multiple blob chunks. + // If the second parameter is true, only tests if the file + // should be uploaded in chunks, but does not invoke any + // upload requests: + _chunkedUpload: function (options, testOnly) { + options.uploadedBytes = options.uploadedBytes || 0; + var that = this, + file = options.files[0], + fs = file.size, + ub = options.uploadedBytes, + mcs = options.maxChunkSize || fs, + slice = this._blobSlice, + dfd = $.Deferred(), + promise = dfd.promise(), + jqXHR, + upload; + if (!(this._isXHRUpload(options) && slice && (ub || mcs < fs)) || + options.data) { + return false; + } + if (testOnly) { + return true; + } + if (ub >= fs) { + file.error = options.i18n('uploadedBytes'); + return this._getXHRPromise( + false, + options.context, + [null, 'error', file.error] + ); + } + // The chunk upload method: + upload = function () { + // Clone the options object for each chunk upload: + var o = $.extend({}, options), + currentLoaded = o._progress.loaded; + o.blob = slice.call( + file, + ub, + ub + mcs, + file.type + ); + // Store the current chunk size, as the blob itself + // will be dereferenced after data processing: + o.chunkSize = o.blob.size; + // Expose the chunk bytes position range: + o.contentRange = 'bytes ' + ub + '-' + + (ub + o.chunkSize - 1) + '/' + fs; + // Process the upload data (the blob and potential form data): + that._initXHRData(o); + // Add progress listeners for this chunk upload: + that._initProgressListener(o); + jqXHR = ((that._trigger('chunksend', null, o) !== false && $.ajax(o)) || + that._getXHRPromise(false, o.context)) + .done(function (result, textStatus, jqXHR) { + ub = that._getUploadedBytes(jqXHR) || + (ub + o.chunkSize); + // Create a progress event if no final progress event + // with loaded equaling total has been triggered + // for this chunk: + if (currentLoaded + o.chunkSize - o._progress.loaded) { + that._onProgress($.Event('progress', { + lengthComputable: true, + loaded: ub - o.uploadedBytes, + total: ub - o.uploadedBytes + }), o); + } + options.uploadedBytes = o.uploadedBytes = ub; + o.result = result; + o.textStatus = textStatus; + o.jqXHR = jqXHR; + that._trigger('chunkdone', null, o); + that._trigger('chunkalways', null, o); + if (ub < fs) { + // File upload not yet complete, + // continue with the next chunk: + upload(); + } else { + dfd.resolveWith( + o.context, + [result, textStatus, jqXHR] + ); + } + }) + .fail(function (jqXHR, textStatus, errorThrown) { + o.jqXHR = jqXHR; + o.textStatus = textStatus; + o.errorThrown = errorThrown; + that._trigger('chunkfail', null, o); + that._trigger('chunkalways', null, o); + dfd.rejectWith( + o.context, + [jqXHR, textStatus, errorThrown] + ); + }); + }; + this._enhancePromise(promise); + promise.abort = function () { + return jqXHR.abort(); + }; + upload(); + return promise; + }, + + _beforeSend: function (e, data) { + if (this._active === 0) { + // the start callback is triggered when an upload starts + // and no other uploads are currently running, + // equivalent to the global ajaxStart event: + this._trigger('start'); + // Set timer for global bitrate progress calculation: + this._bitrateTimer = new this._BitrateTimer(); + // Reset the global progress values: + this._progress.loaded = this._progress.total = 0; + this._progress.bitrate = 0; + } + // Make sure the container objects for the .response() and + // .progress() methods on the data object are available + // and reset to their initial state: + this._initResponseObject(data); + this._initProgressObject(data); + data._progress.loaded = data.loaded = data.uploadedBytes || 0; + data._progress.total = data.total = this._getTotal(data.files) || 1; + data._progress.bitrate = data.bitrate = 0; + this._active += 1; + // Initialize the global progress values: + this._progress.loaded += data.loaded; + this._progress.total += data.total; + }, + + _onDone: function (result, textStatus, jqXHR, options) { + var total = options._progress.total, + response = options._response; + if (options._progress.loaded < total) { + // Create a progress event if no final progress event + // with loaded equaling total has been triggered: + this._onProgress($.Event('progress', { + lengthComputable: true, + loaded: total, + total: total + }), options); + } + response.result = options.result = result; + response.textStatus = options.textStatus = textStatus; + response.jqXHR = options.jqXHR = jqXHR; + this._trigger('done', null, options); + }, + + _onFail: function (jqXHR, textStatus, errorThrown, options) { + var response = options._response; + if (options.recalculateProgress) { + // Remove the failed (error or abort) file upload from + // the global progress calculation: + this._progress.loaded -= options._progress.loaded; + this._progress.total -= options._progress.total; + } + response.jqXHR = options.jqXHR = jqXHR; + response.textStatus = options.textStatus = textStatus; + response.errorThrown = options.errorThrown = errorThrown; + this._trigger('fail', null, options); + }, + + _onAlways: function (jqXHRorResult, textStatus, jqXHRorError, options) { + // jqXHRorResult, textStatus and jqXHRorError are added to the + // options object via done and fail callbacks + this._trigger('always', null, options); + }, + + _onSend: function (e, data) { + if (!data.submit) { + this._addConvenienceMethods(e, data); + } + var that = this, + jqXHR, + aborted, + slot, + pipe, + options = that._getAJAXSettings(data), + send = function () { + that._sending += 1; + // Set timer for bitrate progress calculation: + options._bitrateTimer = new that._BitrateTimer(); + jqXHR = jqXHR || ( + ((aborted || that._trigger( + 'send', + $.Event('send', {delegatedEvent: e}), + options + ) === false) && + that._getXHRPromise(false, options.context, aborted)) || + that._chunkedUpload(options) || $.ajax(options) + ).done(function (result, textStatus, jqXHR) { + that._onDone(result, textStatus, jqXHR, options); + }).fail(function (jqXHR, textStatus, errorThrown) { + that._onFail(jqXHR, textStatus, errorThrown, options); + }).always(function (jqXHRorResult, textStatus, jqXHRorError) { + that._onAlways( + jqXHRorResult, + textStatus, + jqXHRorError, + options + ); + that._sending -= 1; + that._active -= 1; + if (options.limitConcurrentUploads && + options.limitConcurrentUploads > that._sending) { + // Start the next queued upload, + // that has not been aborted: + var nextSlot = that._slots.shift(); + while (nextSlot) { + if (that._getDeferredState(nextSlot) === 'pending') { + nextSlot.resolve(); + break; + } + nextSlot = that._slots.shift(); + } + } + if (that._active === 0) { + // The stop callback is triggered when all uploads have + // been completed, equivalent to the global ajaxStop event: + that._trigger('stop'); + } + }); + return jqXHR; + }; + this._beforeSend(e, options); + if (this.options.sequentialUploads || + (this.options.limitConcurrentUploads && + this.options.limitConcurrentUploads <= this._sending)) { + if (this.options.limitConcurrentUploads > 1) { + slot = $.Deferred(); + this._slots.push(slot); + pipe = slot.pipe(send); + } else { + this._sequence = this._sequence.pipe(send, send); + pipe = this._sequence; + } + // Return the piped Promise object, enhanced with an abort method, + // which is delegated to the jqXHR object of the current upload, + // and jqXHR callbacks mapped to the equivalent Promise methods: + pipe.abort = function () { + aborted = [undefined, 'abort', 'abort']; + if (!jqXHR) { + if (slot) { + slot.rejectWith(options.context, aborted); + } + return send(); + } + return jqXHR.abort(); + }; + return this._enhancePromise(pipe); + } + return send(); + }, + + _onAdd: function (e, data) { + var that = this, + result = true, + options = $.extend({}, this.options, data), + limit = options.limitMultiFileUploads, + paramName = this._getParamName(options), + paramNameSet, + paramNameSlice, + fileSet, + i; + if (!(options.singleFileUploads || limit) || + !this._isXHRUpload(options)) { + fileSet = [data.files]; + paramNameSet = [paramName]; + } else if (!options.singleFileUploads && limit) { + fileSet = []; + paramNameSet = []; + for (i = 0; i < data.files.length; i += limit) { + fileSet.push(data.files.slice(i, i + limit)); + paramNameSlice = paramName.slice(i, i + limit); + if (!paramNameSlice.length) { + paramNameSlice = paramName; + } + paramNameSet.push(paramNameSlice); + } + } else { + paramNameSet = paramName; + } + data.originalFiles = data.files; + $.each(fileSet || data.files, function (index, element) { + var newData = $.extend({}, data); + newData.files = fileSet ? element : [element]; + newData.paramName = paramNameSet[index]; + that._initResponseObject(newData); + that._initProgressObject(newData); + that._addConvenienceMethods(e, newData); + result = that._trigger( + 'add', + $.Event('add', {delegatedEvent: e}), + newData + ); + return result; + }); + return result; + }, + + _replaceFileInput: function (input) { + var inputClone = input.clone(true); + $('<form></form>').append(inputClone)[0].reset(); + // Detaching allows to insert the fileInput on another form + // without loosing the file input value: + input.after(inputClone).detach(); + // Avoid memory leaks with the detached file input: + $.cleanData(input.unbind('remove')); + // Replace the original file input element in the fileInput + // elements set with the clone, which has been copied including + // event handlers: + this.options.fileInput = this.options.fileInput.map(function (i, el) { + if (el === input[0]) { + return inputClone[0]; + } + return el; + }); + // If the widget has been initialized on the file input itself, + // override this.element with the file input clone: + if (input[0] === this.element[0]) { + this.element = inputClone; + } + }, + + _handleFileTreeEntry: function (entry, path) { + var that = this, + dfd = $.Deferred(), + errorHandler = function (e) { + if (e && !e.entry) { + e.entry = entry; + } + // Since $.when returns immediately if one + // Deferred is rejected, we use resolve instead. + // This allows valid files and invalid items + // to be returned together in one set: + dfd.resolve([e]); + }, + dirReader; + path = path || ''; + if (entry.isFile) { + if (entry._file) { + // Workaround for Chrome bug #149735 + entry._file.relativePath = path; + dfd.resolve(entry._file); + } else { + entry.file(function (file) { + file.relativePath = path; + dfd.resolve(file); + }, errorHandler); + } + } else if (entry.isDirectory) { + dirReader = entry.createReader(); + dirReader.readEntries(function (entries) { + that._handleFileTreeEntries( + entries, + path + entry.name + '/' + ).done(function (files) { + dfd.resolve(files); + }).fail(errorHandler); + }, errorHandler); + } else { + // Return an empy list for file system items + // other than files or directories: + dfd.resolve([]); + } + return dfd.promise(); + }, + + _handleFileTreeEntries: function (entries, path) { + var that = this; + return $.when.apply( + $, + $.map(entries, function (entry) { + return that._handleFileTreeEntry(entry, path); + }) + ).pipe(function () { + return Array.prototype.concat.apply( + [], + arguments + ); + }); + }, + + _getDroppedFiles: function (dataTransfer) { + dataTransfer = dataTransfer || {}; + var items = dataTransfer.items; + if (items && items.length && (items[0].webkitGetAsEntry || + items[0].getAsEntry)) { + return this._handleFileTreeEntries( + $.map(items, function (item) { + var entry; + if (item.webkitGetAsEntry) { + entry = item.webkitGetAsEntry(); + if (entry) { + // Workaround for Chrome bug #149735: + entry._file = item.getAsFile(); + } + return entry; + } + return item.getAsEntry(); + }) + ); + } + return $.Deferred().resolve( + $.makeArray(dataTransfer.files) + ).promise(); + }, + + _getSingleFileInputFiles: function (fileInput) { + fileInput = $(fileInput); + var entries = fileInput.prop('webkitEntries') || + fileInput.prop('entries'), + files, + value; + if (entries && entries.length) { + return this._handleFileTreeEntries(entries); + } + files = $.makeArray(fileInput.prop('files')); + if (!files.length) { + value = fileInput.prop('value'); + if (!value) { + return $.Deferred().resolve([]).promise(); + } + // If the files property is not available, the browser does not + // support the File API and we add a pseudo File object with + // the input value as name with path information removed: + files = [{name: value.replace(/^.*\\/, '')}]; + } else if (files[0].name === undefined && files[0].fileName) { + // File normalization for Safari 4 and Firefox 3: + $.each(files, function (index, file) { + file.name = file.fileName; + file.size = file.fileSize; + }); + } + return $.Deferred().resolve(files).promise(); + }, + + _getFileInputFiles: function (fileInput) { + if (!(fileInput instanceof $) || fileInput.length === 1) { + return this._getSingleFileInputFiles(fileInput); + } + return $.when.apply( + $, + $.map(fileInput, this._getSingleFileInputFiles) + ).pipe(function () { + return Array.prototype.concat.apply( + [], + arguments + ); + }); + }, + + _onChange: function (e) { + var that = this, + data = { + fileInput: $(e.target), + form: $(e.target.form) + }; + this._getFileInputFiles(data.fileInput).always(function (files) { + data.files = files; + if (that.options.replaceFileInput) { + that._replaceFileInput(data.fileInput); + } + if (that._trigger( + 'change', + $.Event('change', {delegatedEvent: e}), + data + ) !== false) { + that._onAdd(e, data); + } + }); + }, + + _onPaste: function (e) { + var items = e.originalEvent && e.originalEvent.clipboardData && + e.originalEvent.clipboardData.items, + data = {files: []}; + if (items && items.length) { + $.each(items, function (index, item) { + var file = item.getAsFile && item.getAsFile(); + if (file) { + data.files.push(file); + } + }); + if (this._trigger( + 'paste', + $.Event('paste', {delegatedEvent: e}), + data + ) !== false) { + this._onAdd(e, data); + } + } + }, + + _onDrop: function (e) { + e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; + var that = this, + dataTransfer = e.dataTransfer, + data = {}; + if (dataTransfer && dataTransfer.files && dataTransfer.files.length) { + e.preventDefault(); + this._getDroppedFiles(dataTransfer).always(function (files) { + data.files = files; + if (that._trigger( + 'drop', + $.Event('drop', {delegatedEvent: e}), + data + ) !== false) { + that._onAdd(e, data); + } + }); + } + }, + + _onDragOver: function (e) { + e.dataTransfer = e.originalEvent && e.originalEvent.dataTransfer; + var dataTransfer = e.dataTransfer; + if (dataTransfer && $.inArray('Files', dataTransfer.types) !== -1 && + this._trigger( + 'dragover', + $.Event('dragover', {delegatedEvent: e}) + ) !== false) { + e.preventDefault(); + dataTransfer.dropEffect = 'copy'; + } + }, + + _initEventHandlers: function () { + if (this._isXHRUpload(this.options)) { + this._on(this.options.dropZone, { + dragover: this._onDragOver, + drop: this._onDrop + }); + this._on(this.options.pasteZone, { + paste: this._onPaste + }); + } + if ($.support.fileInput) { + this._on(this.options.fileInput, { + change: this._onChange + }); + } + }, + + _destroyEventHandlers: function () { + this._off(this.options.dropZone, 'dragover drop'); + this._off(this.options.pasteZone, 'paste'); + this._off(this.options.fileInput, 'change'); + }, + + _setOption: function (key, value) { + var reinit = $.inArray(key, this._specialOptions) !== -1; + if (reinit) { + this._destroyEventHandlers(); + } + this._super(key, value); + if (reinit) { + this._initSpecialOptions(); + this._initEventHandlers(); + } + }, + + _initSpecialOptions: function () { + var options = this.options; + if (options.fileInput === undefined) { + options.fileInput = this.element.is('input[type="file"]') ? + this.element : this.element.find('input[type="file"]'); + } else if (!(options.fileInput instanceof $)) { + options.fileInput = $(options.fileInput); + } + if (!(options.dropZone instanceof $)) { + options.dropZone = $(options.dropZone); + } + if (!(options.pasteZone instanceof $)) { + options.pasteZone = $(options.pasteZone); + } + }, + + _getRegExp: function (str) { + var parts = str.split('/'), + modifiers = parts.pop(); + parts.shift(); + return new RegExp(parts.join('/'), modifiers); + }, + + _isRegExpOption: function (key, value) { + return key !== 'url' && $.type(value) === 'string' && + /^\/.*\/[igm]{0,3}$/.test(value); + }, + + _initDataAttributes: function () { + var that = this, + options = this.options; + // Initialize options set via HTML5 data-attributes: + $.each( + $(this.element[0].cloneNode(false)).data(), + function (key, value) { + if (that._isRegExpOption(key, value)) { + value = that._getRegExp(value); + } + options[key] = value; + } + ); + }, + + _create: function () { + this._initDataAttributes(); + this._initSpecialOptions(); + this._slots = []; + this._sequence = this._getXHRPromise(true); + this._sending = this._active = 0; + this._initProgressObject(this); + this._initEventHandlers(); + }, + + // This method is exposed to the widget API and allows to query + // the number of active uploads: + active: function () { + return this._active; + }, + + // This method is exposed to the widget API and allows to query + // the widget upload progress. + // It returns an object with loaded, total and bitrate properties + // for the running uploads: + progress: function () { + return this._progress; + }, + + // This method is exposed to the widget API and allows adding files + // using the fileupload API. The data parameter accepts an object which + // must have a files property and can contain additional options: + // .fileupload('add', {files: filesList}); + add: function (data) { + var that = this; + if (!data || this.options.disabled) { + return; + } + if (data.fileInput && !data.files) { + this._getFileInputFiles(data.fileInput).always(function (files) { + data.files = files; + that._onAdd(null, data); + }); + } else { + data.files = $.makeArray(data.files); + this._onAdd(null, data); + } + }, + + // This method is exposed to the widget API and allows sending files + // using the fileupload API. The data parameter accepts an object which + // must have a files or fileInput property and can contain additional options: + // .fileupload('send', {files: filesList}); + // The method returns a Promise object for the file upload call. + send: function (data) { + if (data && !this.options.disabled) { + if (data.fileInput && !data.files) { + var that = this, + dfd = $.Deferred(), + promise = dfd.promise(), + jqXHR, + aborted; + promise.abort = function () { + aborted = true; + if (jqXHR) { + return jqXHR.abort(); + } + dfd.reject(null, 'abort', 'abort'); + return promise; + }; + this._getFileInputFiles(data.fileInput).always( + function (files) { + if (aborted) { + return; + } + if (!files.length) { + dfd.reject(); + return; + } + data.files = files; + jqXHR = that._onSend(null, data).then( + function (result, textStatus, jqXHR) { + dfd.resolve(result, textStatus, jqXHR); + }, + function (jqXHR, textStatus, errorThrown) { + dfd.reject(jqXHR, textStatus, errorThrown); + } + ); + } + ); + return this._enhancePromise(promise); + } + data.files = $.makeArray(data.files); + if (data.files.length) { + return this._onSend(null, data); + } + } + return this._getXHRPromise(false, data && data.context); + } + + }); + +})); diff --git a/pandora_console/include/javascript/jquery.iframe-transport.js b/pandora_console/include/javascript/jquery.iframe-transport.js new file mode 100644 index 0000000000..33e2795532 --- /dev/null +++ b/pandora_console/include/javascript/jquery.iframe-transport.js @@ -0,0 +1,208 @@ +/* + * jQuery Iframe Transport Plugin 1.8.0 + * https://github.com/blueimp/jQuery-File-Upload + * + * Copyright 2011, Sebastian Tschan + * https://blueimp.net + * + * Licensed under the MIT license: + * http://www.opensource.org/licenses/MIT + */ + +/*jslint unparam: true, nomen: true */ +/*global define, window, document */ + +(function (factory) { + 'use strict'; + if (typeof define === 'function' && define.amd) { + // Register as an anonymous AMD module: + define(['jquery'], factory); + } else { + // Browser globals: + factory(window.jQuery); + } +}(function ($) { + 'use strict'; + + // Helper variable to create unique names for the transport iframes: + var counter = 0; + + // The iframe transport accepts four additional options: + // options.fileInput: a jQuery collection of file input fields + // options.paramName: the parameter name for the file form data, + // overrides the name property of the file input field(s), + // can be a string or an array of strings. + // options.formData: an array of objects with name and value properties, + // equivalent to the return data of .serializeArray(), e.g.: + // [{name: 'a', value: 1}, {name: 'b', value: 2}] + // options.initialIframeSrc: the URL of the initial iframe src, + // by default set to "javascript:false;" + $.ajaxTransport('iframe', function (options) { + if (options.async) { + // javascript:false as initial iframe src + // prevents warning popups on HTTPS in IE6: + var initialIframeSrc = options.initialIframeSrc || 'javascript:false;', + form, + iframe, + addParamChar; + return { + send: function (_, completeCallback) { + form = $('<form style="display:none;"></form>'); + form.attr('accept-charset', options.formAcceptCharset); + addParamChar = /\?/.test(options.url) ? '&' : '?'; + // XDomainRequest only supports GET and POST: + if (options.type === 'DELETE') { + options.url = options.url + addParamChar + '_method=DELETE'; + options.type = 'POST'; + } else if (options.type === 'PUT') { + options.url = options.url + addParamChar + '_method=PUT'; + options.type = 'POST'; + } else if (options.type === 'PATCH') { + options.url = options.url + addParamChar + '_method=PATCH'; + options.type = 'POST'; + } + // IE versions below IE8 cannot set the name property of + // elements that have already been added to the DOM, + // so we set the name along with the iframe HTML markup: + counter += 1; + iframe = $( + '<iframe src="' + initialIframeSrc + + '" name="iframe-transport-' + counter + '"></iframe>' + ).bind('load', function () { + var fileInputClones, + paramNames = $.isArray(options.paramName) ? + options.paramName : [options.paramName]; + iframe + .unbind('load') + .bind('load', function () { + var response; + // Wrap in a try/catch block to catch exceptions thrown + // when trying to access cross-domain iframe contents: + try { + response = iframe.contents(); + // Google Chrome and Firefox do not throw an + // exception when calling iframe.contents() on + // cross-domain requests, so we unify the response: + if (!response.length || !response[0].firstChild) { + throw new Error(); + } + } catch (e) { + response = undefined; + } + // The complete callback returns the + // iframe content document as response object: + completeCallback( + 200, + 'success', + {'iframe': response} + ); + // Fix for IE endless progress bar activity bug + // (happens on form submits to iframe targets): + $('<iframe src="' + initialIframeSrc + '"></iframe>') + .appendTo(form); + window.setTimeout(function () { + // Removing the form in a setTimeout call + // allows Chrome's developer tools to display + // the response result + form.remove(); + }, 0); + }); + form + .prop('target', iframe.prop('name')) + .prop('action', options.url) + .prop('method', options.type); + if (options.formData) { + $.each(options.formData, function (index, field) { + $('<input type="hidden"/>') + .prop('name', field.name) + .val(field.value) + .appendTo(form); + }); + } + if (options.fileInput && options.fileInput.length && + options.type === 'POST') { + fileInputClones = options.fileInput.clone(); + // Insert a clone for each file input field: + options.fileInput.after(function (index) { + return fileInputClones[index]; + }); + if (options.paramName) { + options.fileInput.each(function (index) { + $(this).prop( + 'name', + paramNames[index] || options.paramName + ); + }); + } + // Appending the file input fields to the hidden form + // removes them from their original location: + form + .append(options.fileInput) + .prop('enctype', 'multipart/form-data') + // enctype must be set as encoding for IE: + .prop('encoding', 'multipart/form-data'); + } + form.submit(); + // Insert the file input fields at their original location + // by replacing the clones with the originals: + if (fileInputClones && fileInputClones.length) { + options.fileInput.each(function (index, input) { + var clone = $(fileInputClones[index]); + $(input).prop('name', clone.prop('name')); + clone.replaceWith(input); + }); + } + }); + form.append(iframe).appendTo(document.body); + }, + abort: function () { + if (iframe) { + // javascript:false as iframe src aborts the request + // and prevents warning popups on HTTPS in IE6. + // concat is used to avoid the "Script URL" JSLint error: + iframe + .unbind('load') + .prop('src', initialIframeSrc); + } + if (form) { + form.remove(); + } + } + }; + } + }); + + // The iframe transport returns the iframe content document as response. + // The following adds converters from iframe to text, json, html, xml + // and script. + // Please note that the Content-Type for JSON responses has to be text/plain + // or text/html, if the browser doesn't include application/json in the + // Accept header, else IE will show a download dialog. + // The Content-Type for XML responses on the other hand has to be always + // application/xml or text/xml, so IE properly parses the XML response. + // See also + // https://github.com/blueimp/jQuery-File-Upload/wiki/Setup#content-type-negotiation + $.ajaxSetup({ + converters: { + 'iframe text': function (iframe) { + return iframe && $(iframe[0].body).text(); + }, + 'iframe json': function (iframe) { + return iframe && $.parseJSON($(iframe[0].body).text()); + }, + 'iframe html': function (iframe) { + return iframe && $(iframe[0].body).html(); + }, + 'iframe xml': function (iframe) { + var xmlDoc = iframe && iframe[0]; + return xmlDoc && $.isXMLDoc(xmlDoc) ? xmlDoc : + $.parseXML((xmlDoc.XMLDocument && xmlDoc.XMLDocument.xml) || + $(xmlDoc.body).html()); + }, + 'iframe script': function (iframe) { + return iframe && $.globalEval($(iframe[0].body).text()); + } + } + }); + +})); diff --git a/pandora_console/include/javascript/jquery.knob.js b/pandora_console/include/javascript/jquery.knob.js new file mode 100755 index 0000000000..e55fb071c3 --- /dev/null +++ b/pandora_console/include/javascript/jquery.knob.js @@ -0,0 +1,760 @@ +/*!jQuery Knob*/ +/** + * Downward compatible, touchable dial + * + * Version: 1.2.0 (15/07/2012) + * Requires: jQuery v1.7+ + * + * Copyright (c) 2012 Anthony Terrien + * Under MIT and GPL licenses: + * http://www.opensource.org/licenses/mit-license.php + * http://www.gnu.org/licenses/gpl.html + * + * Thanks to vor, eskimoblood, spiffistan, FabrizioC + */ +(function($) { + + /** + * Kontrol library + */ + "use strict"; + + /** + * Definition of globals and core + */ + var k = {}, // kontrol + max = Math.max, + min = Math.min; + + k.c = {}; + k.c.d = $(document); + k.c.t = function (e) { + return e.originalEvent.touches.length - 1; + }; + + /** + * Kontrol Object + * + * Definition of an abstract UI control + * + * Each concrete component must call this one. + * <code> + * k.o.call(this); + * </code> + */ + k.o = function () { + var s = this; + + this.o = null; // array of options + this.$ = null; // jQuery wrapped element + this.i = null; // mixed HTMLInputElement or array of HTMLInputElement + this.g = null; // deprecated 2D graphics context for 'pre-rendering' + this.v = null; // value ; mixed array or integer + this.cv = null; // change value ; not commited value + this.x = 0; // canvas x position + this.y = 0; // canvas y position + this.w = 0; // canvas width + this.h = 0; // canvas height + this.$c = null; // jQuery canvas element + this.c = null; // rendered canvas context + this.t = 0; // touches index + this.isInit = false; + this.fgColor = null; // main color + this.pColor = null; // previous color + this.dH = null; // draw hook + this.cH = null; // change hook + this.eH = null; // cancel hook + this.rH = null; // release hook + this.scale = 1; // scale factor + this.relative = false; + this.relativeWidth = false; + this.relativeHeight = false; + this.$div = null; // component div + + this.run = function () { + var cf = function (e, conf) { + var k; + for (k in conf) { + s.o[k] = conf[k]; + } + s.init(); + s._configure() + ._draw(); + }; + + if(this.$.data('kontroled')) return; + this.$.data('kontroled', true); + + this.extend(); + this.o = $.extend( + { + // Config + min : this.$.data('min') || 0, + max : this.$.data('max') || 100, + stopper : true, + readOnly : this.$.data('readonly') || (this.$.attr('readonly') == 'readonly'), + + // UI + cursor : (this.$.data('cursor') === true && 30) + || this.$.data('cursor') + || 0, + thickness : ( + this.$.data('thickness') + && Math.max(Math.min(this.$.data('thickness'), 1), 0.01) + ) + || 0.35, + lineCap : this.$.data('linecap') || 'butt', + width : this.$.data('width') || 200, + height : this.$.data('height') || 200, + displayInput : this.$.data('displayinput') == null || this.$.data('displayinput'), + displayPrevious : this.$.data('displayprevious'), + fgColor : this.$.data('fgcolor') || '#87CEEB', + inputColor: this.$.data('inputcolor'), + font: this.$.data('font') || 'Arial', + fontWeight: this.$.data('font-weight') || 'bold', + inline : false, + step : this.$.data('step') || 1, + + // Hooks + draw : null, // function () {} + change : null, // function (value) {} + cancel : null, // function () {} + release : null, // function (value) {} + error : null // function () {} + }, this.o + ); + + // finalize options + if(!this.o.inputColor) { + this.o.inputColor = this.o.fgColor; + } + + // routing value + if(this.$.is('fieldset')) { + + // fieldset = array of integer + this.v = {}; + this.i = this.$.find('input') + this.i.each(function(k) { + var $this = $(this); + s.i[k] = $this; + s.v[k] = $this.val(); + + $this.bind( + 'change' + , function () { + var val = {}; + val[k] = $this.val(); + s.val(val); + } + ); + }); + this.$.find('legend').remove(); + + } else { + + // input = integer + this.i = this.$; + this.v = this.$.val(); + (this.v == '') && (this.v = this.o.min); + + this.$.bind( + 'change' + , function () { + s.val(s._validate(s.$.val())); + } + ); + + } + + (!this.o.displayInput) && this.$.hide(); + + // adds needed DOM elements (canvas, div) + this.$c = $(document.createElement('canvas')); + if (typeof G_vmlCanvasManager !== 'undefined') { + G_vmlCanvasManager.initElement(this.$c[0]); + } + this.c = this.$c[0].getContext ? this.$c[0].getContext('2d') : null; + if (!this.c) { + this.o.error && this.o.error(); + return; + } + + // hdpi support + this.scale = (window.devicePixelRatio || 1) / + ( + this.c.webkitBackingStorePixelRatio || + this.c.mozBackingStorePixelRatio || + this.c.msBackingStorePixelRatio || + this.c.oBackingStorePixelRatio || + this.c.backingStorePixelRatio || 1 + ); + + // detects relative width / height + this.relativeWidth = ((this.o.width % 1 !== 0) + && this.o.width.indexOf('%')); + this.relativeHeight = ((this.o.height % 1 !== 0) + && this.o.height.indexOf('%')); + + this.relative = (this.relativeWidth || this.relativeHeight); + + // wraps all elements in a div + this.$div = $('<div style="' + + (this.o.inline ? 'display:inline;' : '') + + '"></div>'); + + this.$.wrap(this.$div).before(this.$c); + this.$div = this.$.parent(); + + // computes size and carves the component + this._carve(); + + // prepares props for transaction + if (this.v instanceof Object) { + this.cv = {}; + this.copy(this.v, this.cv); + } else { + this.cv = this.v; + } + + // binds configure event + this.$ + .bind("configure", cf) + .parent() + .bind("configure", cf); + + // finalize init + this._listen() + ._configure() + ._xy() + .init(); + + this.isInit = true; + + // the most important ! + this._draw(); + + return this; + }; + + this._carve = function() { + if(this.relative) { + var w = this.relativeWidth + ? this.$div.parent().width() + * parseInt(this.o.width) / 100 + : this.$div.parent().width(), + h = this.relativeHeight + ? this.$div.parent().height() + * parseInt(this.o.height) / 100 + : this.$div.parent().height(); + + // apply relative + this.w = this.h = Math.min(w, h); + } else { + this.w = this.o.width; + this.h = this.o.height; + } + + // finalize div + this.$div.css({ + 'width': this.w + 'px', + 'height': this.h + 'px' + }); + + // finalize canvas with computed width + this.$c.attr({ + width: this.w, + height: this.h + }); + + // scaling + if (this.scale !== 1) { + this.$c[0].width = this.$c[0].width * this.scale; + this.$c[0].height = this.$c[0].height * this.scale; + this.$c.width(this.w); + this.$c.height(this.h); + } + + return this; + } + + this._draw = function () { + + // canvas pre-rendering + var d = true; + + s.g = s.c; + + s.clear(); + + s.dH + && (d = s.dH()); + + (d !== false) && s.draw(); + + }; + + this._touch = function (e) { + + var touchMove = function (e) { + + var v = s.xy2val( + e.originalEvent.touches[s.t].pageX, + e.originalEvent.touches[s.t].pageY + ); + + if (v == s.cv) return; + + if ( + s.cH + && (s.cH(v) === false) + ) return; + + + s.change(s._validate(v)); + s._draw(); + }; + + // get touches index + this.t = k.c.t(e); + + // First touch + touchMove(e); + + // Touch events listeners + k.c.d + .bind("touchmove.k", touchMove) + .bind( + "touchend.k" + , function () { + k.c.d.unbind('touchmove.k touchend.k'); + + if ( + s.rH + && (s.rH(s.cv) === false) + ) return; + + s.val(s.cv); + } + ); + + return this; + }; + + this._mouse = function (e) { + + var mouseMove = function (e) { + var v = s.xy2val(e.pageX, e.pageY); + if (v == s.cv) return; + + if ( + s.cH + && (s.cH(v) === false) + ) return; + + s.change(s._validate(v)); + s._draw(); + }; + + // First click + mouseMove(e); + + // Mouse events listeners + k.c.d + .bind("mousemove.k", mouseMove) + .bind( + // Escape key cancel current change + "keyup.k" + , function (e) { + if (e.keyCode === 27) { + k.c.d.unbind("mouseup.k mousemove.k keyup.k"); + + if ( + s.eH + && (s.eH() === false) + ) return; + + s.cancel(); + } + } + ) + .bind( + "mouseup.k" + , function (e) { + k.c.d.unbind('mousemove.k mouseup.k keyup.k'); + + if ( + s.rH + && (s.rH(s.cv) === false) + ) return; + + s.val(s.cv); + } + ); + + return this; + }; + + this._xy = function () { + var o = this.$c.offset(); + this.x = o.left; + this.y = o.top; + return this; + }; + + this._listen = function () { + + if (!this.o.readOnly) { + this.$c + .bind( + "mousedown" + , function (e) { + e.preventDefault(); + s._xy()._mouse(e); + } + ) + .bind( + "touchstart" + , function (e) { + e.preventDefault(); + s._xy()._touch(e); + } + ); + + if(this.relative) { + $(window).resize(function() { + s._carve() + .init(); + s._draw(); + }); + } + + this.listen(); + } else { + this.$.attr('readonly', 'readonly'); + } + + return this; + }; + + this._configure = function () { + + // Hooks + if (this.o.draw) this.dH = this.o.draw; + if (this.o.change) this.cH = this.o.change; + if (this.o.cancel) this.eH = this.o.cancel; + if (this.o.release) this.rH = this.o.release; + + if (this.o.displayPrevious) { + this.pColor = this.h2rgba(this.o.fgColor, "0.4"); + this.fgColor = this.h2rgba(this.o.fgColor, "0.6"); + } else { + this.fgColor = this.o.fgColor; + } + + return this; + }; + + this._clear = function () { + this.$c[0].width = this.$c[0].width; + }; + + this._validate = function(v) { + return (~~ (((v < 0) ? -0.5 : 0.5) + (v/this.o.step))) * this.o.step; + }; + + // Abstract methods + this.listen = function () {}; // on start, one time + this.extend = function () {}; // each time configure triggered + this.init = function () {}; // each time configure triggered + this.change = function (v) {}; // on change + this.val = function (v) {}; // on release + this.xy2val = function (x, y) {}; // + this.draw = function () {}; // on change / on release + this.clear = function () { this._clear(); }; + + // Utils + this.h2rgba = function (h, a) { + var rgb; + h = h.substring(1,7) + rgb = [parseInt(h.substring(0,2),16) + ,parseInt(h.substring(2,4),16) + ,parseInt(h.substring(4,6),16)]; + return "rgba(" + rgb[0] + "," + rgb[1] + "," + rgb[2] + "," + a + ")"; + }; + + this.copy = function (f, t) { + for (var i in f) { t[i] = f[i]; } + }; + }; + + + /** + * k.Dial + */ + k.Dial = function () { + k.o.call(this); + + this.startAngle = null; + this.xy = null; + this.radius = null; + this.lineWidth = null; + this.cursorExt = null; + this.w2 = null; + this.PI2 = 2*Math.PI; + + this.extend = function () { + this.o = $.extend( + { + bgColor : this.$.data('bgcolor') || '#EEEEEE', + angleOffset : this.$.data('angleoffset') || 0, + angleArc : this.$.data('anglearc') || 360, + inline : true + }, this.o + ); + }; + + this.val = function (v) { + if (null != v) { + this.cv = this.o.stopper ? max(min(v, this.o.max), this.o.min) : v; + this.v = this.cv; + this.$.val(this.v); + this._draw(); + } else { + return this.v; + } + }; + + this.xy2val = function (x, y) { + var a, ret; + + a = Math.atan2( + x - (this.x + this.w2) + , - (y - this.y - this.w2) + ) - this.angleOffset; + + if(this.angleArc != this.PI2 && (a < 0) && (a > -0.5)) { + // if isset angleArc option, set to min if .5 under min + a = 0; + } else if (a < 0) { + a += this.PI2; + } + + ret = ~~ (0.5 + (a * (this.o.max - this.o.min) / this.angleArc)) + + this.o.min; + + this.o.stopper + && (ret = max(min(ret, this.o.max), this.o.min)); + + return ret; + }; + + this.listen = function () { + // bind MouseWheel + var s = this, + mw = function (e) { + e.preventDefault(); + var ori = e.originalEvent + ,deltaX = ori.detail || ori.wheelDeltaX + ,deltaY = ori.detail || ori.wheelDeltaY + ,v = parseInt(s.$.val()) + (deltaX>0 || deltaY>0 ? s.o.step : deltaX<0 || deltaY<0 ? -s.o.step : 0); + + if ( + s.cH + && (s.cH(v) === false) + ) return; + + s.val(v); + } + , kval, to, m = 1, kv = {37:-s.o.step, 38:s.o.step, 39:s.o.step, 40:-s.o.step}; + + this.$ + .bind( + "keydown" + ,function (e) { + var kc = e.keyCode; + + // numpad support + if(kc >= 96 && kc <= 105) { + kc = e.keyCode = kc - 48; + } + + kval = parseInt(String.fromCharCode(kc)); + + if (isNaN(kval)) { + + (kc !== 13) // enter + && (kc !== 8) // bs + && (kc !== 9) // tab + && (kc !== 189) // - + && e.preventDefault(); + + // arrows + if ($.inArray(kc,[37,38,39,40]) > -1) { + e.preventDefault(); + + var v = parseInt(s.$.val()) + kv[kc] * m; + + s.o.stopper + && (v = max(min(v, s.o.max), s.o.min)); + + s.change(v); + s._draw(); + + // long time keydown speed-up + to = window.setTimeout( + function () { m*=2; } + ,30 + ); + } + } + } + ) + .bind( + "keyup" + ,function (e) { + if (isNaN(kval)) { + if (to) { + window.clearTimeout(to); + to = null; + m = 1; + s.val(s.$.val()); + } + } else { + // kval postcond + (s.$.val() > s.o.max && s.$.val(s.o.max)) + || (s.$.val() < s.o.min && s.$.val(s.o.min)); + } + + } + ); + + this.$c.bind("mousewheel DOMMouseScroll", mw); + this.$.bind("mousewheel DOMMouseScroll", mw) + }; + + this.init = function () { + + if ( + this.v < this.o.min + || this.v > this.o.max + ) this.v = this.o.min; + + this.$.val(this.v); + this.w2 = this.w / 2; + this.cursorExt = this.o.cursor / 100; + this.xy = this.w2 * this.scale; + this.lineWidth = this.xy * this.o.thickness; + this.lineCap = this.o.lineCap; + this.radius = this.xy - this.lineWidth / 2; + + this.o.angleOffset + && (this.o.angleOffset = isNaN(this.o.angleOffset) ? 0 : this.o.angleOffset); + + this.o.angleArc + && (this.o.angleArc = isNaN(this.o.angleArc) ? this.PI2 : this.o.angleArc); + + // deg to rad + this.angleOffset = this.o.angleOffset * Math.PI / 180; + this.angleArc = this.o.angleArc * Math.PI / 180; + + // compute start and end angles + this.startAngle = 1.5 * Math.PI + this.angleOffset; + this.endAngle = 1.5 * Math.PI + this.angleOffset + this.angleArc; + + var s = max( + String(Math.abs(this.o.max)).length + , String(Math.abs(this.o.min)).length + , 2 + ) + 2; + + this.o.displayInput + && this.i.css({ + 'width' : ((this.w / 2 + 4) >> 0) + 'px' + ,'height' : ((this.w / 3) >> 0) + 'px' + ,'position' : 'absolute' + ,'vertical-align' : 'middle' + ,'margin-top' : ((this.w / 3) >> 0) + 'px' + ,'margin-left' : '-' + ((this.w * 3 / 4 + 2) >> 0) + 'px' + ,'border' : 0 + ,'background' : 'none' + ,'font' : this.o.fontWeight + ' ' + ((this.w / s) >> 0) + 'px ' + this.o.font + ,'text-align' : 'center' + ,'color' : this.o.inputColor || this.o.fgColor + ,'padding' : '0px' + ,'-webkit-appearance': 'none' + }) + || this.i.css({ + 'width' : '0px' + ,'visibility' : 'hidden' + }); + }; + + this.change = function (v) { + this.cv = v; + this.$.val(v); + }; + + this.angle = function (v) { + return (v - this.o.min) * this.angleArc / (this.o.max - this.o.min); + }; + + this.draw = function () { + + var c = this.g, // context + a = this.angle(this.cv) // Angle + , sat = this.startAngle // Start angle + , eat = sat + a // End angle + , sa, ea // Previous angles + , r = 1; + + c.lineWidth = this.lineWidth; + + c.lineCap = this.lineCap; + + this.o.cursor + && (sat = eat - this.cursorExt) + && (eat = eat + this.cursorExt); + + c.beginPath(); + c.strokeStyle = this.o.bgColor; + c.arc(this.xy, this.xy, this.radius, this.endAngle, this.startAngle, true); + c.stroke(); + + if (this.o.displayPrevious) { + ea = this.startAngle + this.angle(this.v); + sa = this.startAngle; + this.o.cursor + && (sa = ea - this.cursorExt) + && (ea = ea + this.cursorExt); + + c.beginPath(); + c.strokeStyle = this.pColor; + c.arc(this.xy, this.xy, this.radius, sa, ea, false); + c.stroke(); + r = (this.cv == this.v); + } + + c.beginPath(); + c.strokeStyle = r ? this.o.fgColor : this.fgColor ; + c.arc(this.xy, this.xy, this.radius, sat, eat, false); + c.stroke(); + }; + + this.cancel = function () { + this.val(this.v); + }; + }; + + $.fn.dial = $.fn.knob = function (o) { + return this.each( + function () { + var d = new k.Dial(); + d.o = o; + d.$ = $(this); + d.run(); + } + ).parent(); + }; + +})(jQuery); diff --git a/pandora_console/include/javascript/update_manager.js b/pandora_console/include/javascript/update_manager.js new file mode 100644 index 0000000000..e1867c2cb7 --- /dev/null +++ b/pandora_console/include/javascript/update_manager.js @@ -0,0 +1,280 @@ +function form_upload () { + //Thanks to: http://tutorialzine.com/2013/05/mini-ajax-file-upload-form/ + var ul = $('#form-offline_update ul'); + + $('#form-offline_update div') + .prop("id", "drop_file"); + $('#drop_file') + .html(drop_the_package_here_or + + ' <a>' + browse_it +'</a>' + + '<input name="upfile" type="file" id="file-upfile" accept=".oum" class="sub file" />'); + $('#drop_file a').click(function() { + // Simulate a click on the file input button to show the file browser dialog + $(this).parent().find('input').click(); + }); + + // Initialize the jQuery File Upload plugin + $('#form-offline_update').fileupload({ + + url: 'ajax.php?page=include/ajax/update_manager.ajax&upload_file=true', + + // This element will accept file drag/drop uploading + dropZone: $('#drop_file'), + + // This function is called when a file is added to the queue; + // either via the browse button, or via drag/drop: + add: function (e, data) { + $('#drop_file').slideUp(); + + var tpl = $('<li>' + + '<input type="text" id="input-progress" ' + + 'value="0" data-width="55" data-height="55" '+ + 'data-fgColor="#FF9933" data-readOnly="1" ' + + 'data-bgColor="#3e4043" />' + + '<p></p><span></span>' + + '</li>'); + + // Append the file name and file size + tpl.find('p').text(data.files[0].name) + .append('<i>' + formatFileSize(data.files[0].size) + '</i>'); + + // Add the HTML to the UL element + ul.html(""); + data.context = tpl.appendTo(ul); + + // Initialize the knob plugin + tpl.find('input').val(0); + tpl.find('input').knob({ + 'draw' : function () { + $(this.i).val(this.cv + '%') + } + }); + + // Listen for clicks on the cancel icon + tpl.find('span').click(function() { + + if (tpl.hasClass('working') && typeof jqXHR != 'undefined') { + jqXHR.abort(); + } + + tpl.fadeOut(function() { + tpl.remove(); + $('#drop_file').slideDown(); + }); + + }); + + // Automatically upload the file once it is added to the queue + data.context.addClass('working'); + var jqXHR = data.submit(); + }, + + progress: function(e, data) { + + // Calculate the completion percentage of the upload + var progress = parseInt(data.loaded / data.total * 100, 10); + + // Update the hidden input field and trigger a change + // so that the jQuery knob plugin knows to update the dial + data.context.find('input').val(progress).change(); + + if (progress == 100) { + data.context.removeClass('working'); + // Class loading while the zip is extracted + data.context.addClass('loading'); + } + }, + + fail: function(e, data) { + // Something has gone wrong! + data.context.removeClass('working'); + data.context.removeClass('loading'); + data.context.addClass('error'); + }, + + done: function (e, data) { + + var res = JSON.parse(data.result); + + if (res.status == "success") { + data.context.removeClass('loading'); + data.context.addClass('suc'); + + ul.find('li').find('span').unbind("click"); + + // Transform the file input zone to show messages + $('#drop_file').prop('id', 'log_zone'); + + // Success messages + $('#log_zone').html("<div>" + the_package_has_been_uploaded_successfully + "</div>"); + $('#log_zone').append("<div>" + remember_that_this_package_will + "</div>"); + $('#log_zone').append("<div>" + click_on_the_file_below_to_begin + "</div>"); + + // Show messages + $('#log_zone').slideDown(400, function() { + $('#log_zone').height(75); + $('#log_zone').css("overflow", "auto"); + }); + + // Bind the the begin of the installation to the package li + ul.find('li').css("cursor", "pointer"); + ul.find('li').click(function () { + + ul.find('li').unbind("click"); + ul.find('li').css("cursor", "default"); + + // Change the log zone to show the copied files + $('#log_zone').html(""); + $('#log_zone').slideUp(200, function() { + $('#log_zone').slideDown(200, function() { + $('#log_zone').height(200); + $('#log_zone').css("overflow", "auto"); + }); + }); + + // Changed the data that shows the file li + data.context.find('p').text(updating + "..."); + data.context.find('input').val(0).change(); + + // Begin the installation + install_package(res.package, 'filename'); + }); + } + else { + // Something has gone wrong! + data.context.removeClass('loading'); + data.context.addClass('error'); + ul.find('li').find('span').click( + function() { window.location.reload(); }); + + // Transform the file input zone to show messages + $('#drop_file').prop('id', 'log_zone'); + + // Error messages + $('#log_zone').html("<div>"+res.message+"</div>"); + + // Show error messages + $('#log_zone').slideDown(400, function() { + $('#log_zone').height(75); + $('#log_zone').css("overflow", "auto"); + }); + } + } + + }); + + // Prevent the default action when a file is dropped on the window + $(document).on('drop_file dragover', function (e) { + e.preventDefault(); + }); +} + +// Helper function that formats the file sizes +function formatFileSize(bytes) { + if (typeof bytes !== 'number') { + return ''; + } + + if (bytes >= 1000000000) { + return (bytes / 1000000000).toFixed(2) + ' GB'; + } + + if (bytes >= 1000000) { + return (bytes / 1000000).toFixed(2) + ' MB'; + } + + return (bytes / 1000).toFixed(2) + ' KB'; +} + +function install_package(package) { + var parameters = {}; + parameters['page'] = 'include/ajax/update_manager.ajax'; + parameters['install_package'] = 1; + parameters['package'] = package; + + jQuery.post( + "ajax.php", + parameters, + function (data) { + if (data["status"] == "success") { + install_package_step2(package); + } + else { + $("#box_online .loading").hide(); + $("#box_online .content").html(data['message']); + stop_check_progress = 1; + } + }, + "json" + ); +} + +function install_package (package) { + var parameters = {}; + parameters['page'] = 'include/ajax/update_manager.ajax'; + parameters['install_package'] = 1; + parameters['package'] = package; + + $('#form-offline_update ul').find('li').removeClass('suc'); + $('#form-offline_update ul').find('li').addClass('loading'); + + $.ajax({ + type: 'POST', + url: 'ajax.php', + data: parameters, + dataType: "json", + success: function (data) { + $('#form-offline_update ul').find('li').removeClass('loading'); + if (data.status == "success") { + $('#form-offline_update ul').find('li').addClass('suc'); + $('#form-offline_update ul').find('li').find('p').html(package_updated_successfully) + .append("<i>" + if_there_are_any_database_change + "</i>"); + } + else { + $('#form-offline_update ul').find('li').addClass('error'); + $('#form-offline_update ul').find('li').find('p').html(package_not_updated) + .append("<i>"+data.message+"</i>"); + } + $('#form-offline_update ul').find('li').css("cursor", "pointer"); + $('#form-offline_update ul').find('li').click(function() { + window.location.reload(); + }); + } + }); + + // Check the status of the update + check_install_package(package); +} + +function check_install_package(package) { + var parameters = {}; + parameters['page'] = 'include/ajax/update_manager.ajax'; + parameters['check_install_enterprise_package'] = 1; + parameters['package'] = package; + + $.ajax({ + type: 'POST', + url: 'ajax.php', + data: parameters, + dataType: "json", + success: function(data) { + // Print the updated files and take the scroll to the bottom + $("#log_zone").html(data.info); + $("#log_zone").scrollTop($("#log_zone").prop("scrollHeight")); + + // Change the progress bar + if ($('#form-offline_update ul').find('li').hasClass('suc')) { + $('#form-offline_update').find('ul').find('li').find('input').val(100).trigger('change'); + } else { + $('#form-offline_update').find('ul').find('li').find('input').val(data['progress']).trigger('change'); + } + + // The class loading is present until the update ends + var isInstalling = $('#form-offline_update ul').find('li').hasClass('loading'); + if (data.progress < 100 && isInstalling) { + // Recursive call to check the update status + check_install_enterprise_package(package); + } + } + }) +} \ No newline at end of file