From 75c7e0fc6d973d9eaee739b655f36e62f3ede559 Mon Sep 17 00:00:00 2001 From: Sergey Kukunin Date: Tue, 19 Nov 2013 23:06:47 +0200 Subject: [PATCH 1/4] Implement Templates admin page Create `templates` table in database Add navigation links to Template page Let admin to manage his templates from adminpanel --- public/include/autoloader.inc.php | 2 +- public/include/classes/template.class.php | 98 +++++++++++++++++++ public/include/config/admin_settings.inc.php | 7 +- public/include/pages/admin/templates.inc.php | 53 ++++++++++ .../mpos/admin/templates/default.tpl | 49 ++++++++++ public/templates/mpos/global/navigation.tpl | 1 + sql/000_base_structure.sql | 8 ++ sql/005_create_templates_table.sql | 7 ++ 8 files changed, 218 insertions(+), 7 deletions(-) create mode 100644 public/include/classes/template.class.php create mode 100644 public/include/pages/admin/templates.inc.php create mode 100644 public/templates/mpos/admin/templates/default.tpl create mode 100644 sql/005_create_templates_table.sql diff --git a/public/include/autoloader.inc.php b/public/include/autoloader.inc.php index 361a5f36..99ec89a4 100644 --- a/public/include/autoloader.inc.php +++ b/public/include/autoloader.inc.php @@ -30,6 +30,7 @@ if ($detect->isMobile() && $setting->getValue('website_mobile_theme')) { } define('THEME', $theme); +require_once(CLASS_DIR . '/template.class.php'); // Load smarty now that we have our theme defined require_once(INCLUDE_DIR . '/smarty.inc.php'); @@ -59,5 +60,4 @@ require_once(CLASS_DIR . '/api.class.php'); require_once(INCLUDE_DIR . '/lib/Michelf/Markdown.php'); require_once(INCLUDE_DIR . '/lib/scrypt.php'); - ?> diff --git a/public/include/classes/template.class.php b/public/include/classes/template.class.php new file mode 100644 index 00000000..f57818ae --- /dev/null +++ b/public/include/classes/template.class.php @@ -0,0 +1,98 @@ +debug->append("STA " . __METHOD__, 4); + $aTmpThemes = glob(THEME_DIR . '/*'); + $aThemes = array(); + foreach ($aTmpThemes as $dir) { + if (basename($dir) != 'cache' && basename($dir) != 'compile' && basename($dir) != 'mail') $aThemes[basename($dir)] = basename($dir); + } + return $aThemes; + } + + /** + * Return the content of specific template file + * + * @param $file - file of template related to THEME_DIR + * @return string - content of the template file + */ + public function getTemplateContent($file) { + $this->debug->append("STA " . __METHOD__, 4); + $filepath = THEME_DIR . '/' . $file; + return file_get_contents($filepath); + } + + /** + * Get all possible templates of specific theme + * + * @param $theme - name of the theme + * @return array - list of available templates of theme + */ + public function getTemplateFiles($theme) { + $this->debug->append("STA " . __METHOD__, 4); + $folder = THEME_DIR . '/' . $theme; + + $dir = new RecursiveDirectoryIterator($folder); + $ite = new RecursiveIteratorIterator($dir); + $files = new RegexIterator($ite, '!'.preg_quote($folder, '!').'/(.*\.tpl$)!', RegexIterator::GET_MATCH); + $fileList = array(); + foreach($files as $file) { + $fileList[] = $file[1]; + } + + return $fileList; + } + + /** + * Return specific template form database + * + * @param $template - name (filepath) of the template + * @return array - result from database + */ + public function getEntry($template) { + $this->debug->append("STA " . __METHOD__, 4); + + $stmt = $this->mysqli->prepare("SELECT * FROM $this->table WHERE template = ?"); + if ($stmt && $stmt->bind_param('s', $template) && $stmt->execute() && $result = $stmt->get_result()) + return $result->fetch_assoc(); + + $this->setErrorMessage('Failed to get the template'); + $this->debug->append('Template::getEntry failed: ' . $this->mysqli->error); + return false; + } + + /** + * Update template in database + * + * @param $template - name (filepath) of the template + * @param $content - content of the template + * @param $active - active flag for the template + **/ + public function updateEntry($template, $content, $active=0) { + $this->debug->append("STA " . __METHOD__, 4); + $stmt = $this->mysqli->prepare("INSERT INTO $this->table (`template`, `content`, `active`, `modified_at`) VALUES(?, ?, ?, CURRENT_TIMESTAMP) ON DUPLICATE KEY UPDATE content = VALUES(content), active = VALUES(active), modified_at = CURRENT_TIMESTAMP"); + if ($stmt && $stmt->bind_param('ssi', $template, $content, $active) && $stmt->execute()) + return true; + + $this->setErrorMessage('Database error'); + $this->debug->append('Template::updateEntry failed: ' . $this->mysqli->error); + return false; + } +} + +$template = new Template(); +$template->setDebug($debug); +$template->setMysql($mysqli); diff --git a/public/include/config/admin_settings.inc.php b/public/include/config/admin_settings.inc.php index 731e4ac6..80043580 100644 --- a/public/include/config/admin_settings.inc.php +++ b/public/include/config/admin_settings.inc.php @@ -3,12 +3,7 @@ // Make sure we are called from index.php if (!defined('SECURITY')) die('Hacking attempt'); -// Load a list of themes available -$aTmpThemes = glob(THEME_DIR . '/*'); -$aThemes = array(); -foreach ($aTmpThemes as $dir) { - if (basename($dir) != 'cache' && basename($dir) != 'compile' && basename($dir) != 'mail') $aThemes[basename($dir)] = basename($dir); -} +$aThemes = $template->getThemes(); // Load the settings available in this system $aSettings['website'][] = array( diff --git a/public/include/pages/admin/templates.inc.php b/public/include/pages/admin/templates.inc.php new file mode 100644 index 00000000..6adcea29 --- /dev/null +++ b/public/include/pages/admin/templates.inc.php @@ -0,0 +1,53 @@ +isAuthenticated() || !$user->isAdmin($_SESSION['USERDATA']['id'])) { + header("HTTP/1.1 404 Page not found"); + die("404 Page not found"); +} + +$aThemes = $template->getThemes(); +$aTemplates = $aFlatTemplatesList = array(); +foreach($aThemes as $sTheme) { + $templates = $template->getTemplateFiles($sTheme); + $templatesWithTheme = array(); + foreach($templates as $tpl_name) { + $templatesWithTheme[] = $sTheme."/".$tpl_name; + } + $aFlatTemplatesList = array_merge($aFlatTemplatesList, $templatesWithTheme); + $aTemplates[$sTheme] = array_combine($templatesWithTheme, $templates); +} + +//Fetch current slug and template +$sTemplate = @$_REQUEST['template']; +if(!in_array($sTemplate, $aFlatTemplatesList)) { + $aThemeTemplates = $aTemplates[THEME]; + $sTemplate = array_keys($aThemeTemplates); + $sTemplate = $sTemplate[0]; +} + +$sOriginalTemplate = $template->getTemplateContent($sTemplate); + +if (@$_REQUEST['do'] == 'save') { + if ($template->updateEntry(@$_REQUEST['template'], @$_REQUEST['content'], @$_REQUEST['active'])) { + $_SESSION['POPUP'][] = array('CONTENT' => 'Page updated', 'TYPE' => 'success'); + } else { + $_SESSION['POPUP'][] = array('CONTENT' => 'Page update failed: ' . $template->getError(), 'TYPE' => 'errormsg'); + } +} + +$oDatabaseTemplate = $template->getEntry($sTemplate); + +if ( $oDatabaseTemplate === false ) { + $_SESSION['POPUP'][] = array('CONTENT' => 'Can\'t fetch template from Database. Have you created `templates` table? Run 005_create_templates_table.sql from sql folder', 'TYPE' => 'errormsg'); +} + +$smarty->assign("TEMPLATES", $aTemplates); +$smarty->assign("CURRENT_TEMPLATE", $sTemplate); +$smarty->assign("ORIGINAL_TEMPLATE", $sOriginalTemplate); +$smarty->assign("DATABASE_TEMPLATE", $oDatabaseTemplate); +$smarty->assign("CONTENT", "default.tpl"); +?> diff --git a/public/templates/mpos/admin/templates/default.tpl b/public/templates/mpos/admin/templates/default.tpl new file mode 100644 index 00000000..37eb93ea --- /dev/null +++ b/public/templates/mpos/admin/templates/default.tpl @@ -0,0 +1,49 @@ +
+

Select Page

+
+
+ + +
+ + {html_options name="template" options=$TEMPLATES selected=$CURRENT_TEMPLATE} +
+
+
+ +
+
+
+ +
+

Edit template '{$CURRENT_TEMPLATE}'

+
+ + + + +
+
+ + + + +
+
+ + +
+
+ + +
+
+
+ +
+
+
diff --git a/public/templates/mpos/global/navigation.tpl b/public/templates/mpos/global/navigation.tpl index 13be7f83..b05ae0de 100644 --- a/public/templates/mpos/global/navigation.tpl +++ b/public/templates/mpos/global/navigation.tpl @@ -24,6 +24,7 @@
  • News
  • Reports
  • Pool Workers
  • +
  • Templates
  • {/if} {if $smarty.session.AUTHENTICATED|default} diff --git a/sql/000_base_structure.sql b/sql/000_base_structure.sql index 33f04c4e..70d5c978 100644 --- a/sql/000_base_structure.sql +++ b/sql/000_base_structure.sql @@ -213,6 +213,14 @@ CREATE TABLE IF NOT EXISTS `transactions` ( KEY `archived` (`archived`) ) ENGINE=InnoDB DEFAULT CHARSET=utf8; +CREATE TABLE `templates` ( + `template` varchar(255) NOT NULL, + `active` tinyint(1) NOT NULL DEFAULT 0, + `content` mediumtext, + `modified_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`template`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; + /*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */; /*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */; /*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */; diff --git a/sql/005_create_templates_table.sql b/sql/005_create_templates_table.sql new file mode 100644 index 00000000..6e7646ba --- /dev/null +++ b/sql/005_create_templates_table.sql @@ -0,0 +1,7 @@ +CREATE TABLE `templates` ( + `template` varchar(255) NOT NULL, + `active` tinyint(1) NOT NULL DEFAULT 0, + `content` mediumtext, + `modified_at` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + PRIMARY KEY (`template`) +) ENGINE=InnoDB DEFAULT CHARSET=utf8; From 1aee65859f331ed0a8b439247d56ed61e57b8548 Mon Sep 17 00:00:00 2001 From: Sergey Kukunin Date: Wed, 20 Nov 2013 15:20:24 +0200 Subject: [PATCH 2/4] Make Smarty search template in database first If not, fallback to file template Implement normalizer to convert gettingstarted/../support/default.tpl to support/default.tpl --- public/include/autoloader.inc.php | 1 + public/include/classes/template.class.php | 68 ++++++++++- public/include/smarty.inc.php | 142 ++++++++++++++++++++++ public/index.php | 3 + 4 files changed, 211 insertions(+), 3 deletions(-) diff --git a/public/include/autoloader.inc.php b/public/include/autoloader.inc.php index 99ec89a4..a4663223 100644 --- a/public/include/autoloader.inc.php +++ b/public/include/autoloader.inc.php @@ -30,6 +30,7 @@ if ($detect->isMobile() && $setting->getValue('website_mobile_theme')) { } define('THEME', $theme); +//Required for Smarty require_once(CLASS_DIR . '/template.class.php'); // Load smarty now that we have our theme defined require_once(INCLUDE_DIR . '/smarty.inc.php'); diff --git a/public/include/classes/template.class.php b/public/include/classes/template.class.php index f57818ae..007ddd4b 100644 --- a/public/include/classes/template.class.php +++ b/public/include/classes/template.class.php @@ -6,6 +6,17 @@ if (!defined('SECURITY')) class Template extends Base { protected $table = 'templates'; + /** + * Get filepath for template name based on current PAGE and ACTION + */ + public function getFullpath($name) { + $chunks = array(PAGE); + if( ACTION ) + $chunks[] = ACTION; + $chunks[] = $name; + + return join('/', $chunks); + } /** * Get all available themes @@ -23,6 +34,41 @@ class Template extends Base { return $aThemes; } + /** + * Cached getActiveTemplates method + * + * @see getActiveTemplates + */ + private static $active_templates; + public function cachedGetActiveTemplates() { + if ( is_null(self::$active_templates) ) { + self::$active_templates = $this->getActiveTemplates(); + } + return self::$active_templates; + } + /** + * Return the all active templates as hash, + * where key is template and value is modified_at + * + * @return array - list of active templates + */ + public function getActiveTemplates() { + $this->debug->append("STA " . __METHOD__, 4); + $stmt = $this->mysqli->prepare("SELECT template, modified_at FROM $this->table WHERE active = 1"); + if ($stmt && $stmt->execute() && $result = $stmt->get_result()) { + $rows = $result->fetch_all(MYSQLI_ASSOC); + $hash = array(); + foreach($rows as $row) { + $hash[$row['template']] = strtotime($row['modified_at']); + } + return $hash; + } + + $this->setErrorMessage('Failed to get active templates'); + $this->debug->append('Template::getActiveTemplates failed: ' . $this->mysqli->error); + return false; + } + /** * Return the content of specific template file * @@ -57,15 +103,15 @@ class Template extends Base { } /** - * Return specific template form database + * Return specific template from database * * @param $template - name (filepath) of the template * @return array - result from database */ - public function getEntry($template) { + public function getEntry($template, $columns = "*") { $this->debug->append("STA " . __METHOD__, 4); - $stmt = $this->mysqli->prepare("SELECT * FROM $this->table WHERE template = ?"); + $stmt = $this->mysqli->prepare("SELECT $columns FROM $this->table WHERE template = ?"); if ($stmt && $stmt->bind_param('s', $template) && $stmt->execute() && $result = $stmt->get_result()) return $result->fetch_assoc(); @@ -74,6 +120,22 @@ class Template extends Base { return false; } + /** + * Return last modified time of specific template from database + * + * @param $template - name (filepath) of the template + * @return timestamp - last modified time of template + */ + public function getEntryMTime($template) { + $this->debug->append("STA " . __METHOD__, 4); + + $entry = $this->getEntry($template, "modified_at, active"); + if ( $entry && $entry['active']) + return strtotime($entry['modified_at']); + + return false; + } + /** * Update template in database * diff --git a/public/include/smarty.inc.php b/public/include/smarty.inc.php index dfd1f4f6..20344ccb 100644 --- a/public/include/smarty.inc.php +++ b/public/include/smarty.inc.php @@ -10,6 +10,143 @@ define('SMARTY_DIR', INCLUDE_DIR . '/smarty/libs/'); // Include the actual smarty class file include(SMARTY_DIR . 'Smarty.class.php'); +/** + * Custom Smarty Template Resource for Pages + * Get templates from Database + * Allow admin to manage his templates from Backoffice + */ +class Smarty_Resource_Database extends Smarty_Resource_Custom { + protected $template; + + public function __construct($template) { + $this->template = $template; + } + /** + * Fetch a template and its modification time from database + * + * @param string $name template name + * @param string $source template source + * @param integer $mtime template modification timestamp (epoch) + * @return void + */ + protected function fetch($name, &$source, &$mtime) { + $oTemplate = $this->template->getEntry($this->fullTemplateName($name)); + if ( $oTemplate && $oTemplate['active'] ) { + $source = $oTemplate['content']; + $mtime = strtotime($oTemplate['modified_at']); + } else { + $source = null; + $mtime = null; + } + } + + /** + * Fetch a template's modification time from database + * + * @note implementing this method is optional. Only implement it if modification times can be accessed faster than loading the comple template source. + * @param string $name template name + * @return integer timestamp (epoch) the template was modified + */ + protected function fetchTimestamp($name) { + $templates = $this->template->cachedGetActiveTemplates(); + $mtime = @$templates[$this->fullTemplateName($name)]; + return $mtime ? $mtime : false; + } + + /** + * Prepend THEME name to template name to get valid DB primary key + * + * @param string $name template name + */ + protected function fullTemplateName($name) { + return $this->normalisePath(THEME . "/" . $name); + } + + /** + * Normalise a file path string so that it can be checked safely. + * + * Attempt to avoid invalid encoding bugs by transcoding the path. Then + * remove any unnecessary path components including '.', '..' and ''. + * + * @param $path string + * The path to normalise. + * @return string + * The path, normalised. + * @see https://gist.github.com/thsutton/772287 + */ + protected function normalisePath($path) { + // Process the components + $parts = explode('/', $path); + $safe = array(); + foreach ($parts as $idx => $part) { + if (empty($part) || ('.' == $part)) { + continue; + } elseif ('..' == $part) { + array_pop($safe); + continue; + } else { + $safe[] = $part; + } + } + // Return the "clean" path + $path = implode(DIRECTORY_SEPARATOR, $safe); + return $path; + } + +} + +class Smarty_Resource_Hybrid extends Smarty_Resource { + + protected $databaseResource; + + protected $fileResource; + + public function __construct($dbResource, $fileResource) { + $this->databaseResource = $dbResource; + $this->fileResource = $fileResource; + } + + /** + * populate Source Object with meta data from Resource + * + * @param Smarty_Template_Source $source source object + * @param Smarty_Internal_Template $_template template object + */ + public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template=null) { + $this->databaseResource->populate($source, $_template); + if ( !$source->exists ) { + $source->type = 'file'; + return $this->fileResource->populate($source, $_template); + } + } + + /** + * Load template's source into current template object + * + * @param Smarty_Template_Source $source source object + * @return string template source + * @throws SmartyException if source cannot be loaded + */ + public function getContent(Smarty_Template_Source $source) { + try { + return $this->databaseResource->getContent($source); + } catch(SmartyException $e) { + return $this->fileResource->getContent($source); + } + } + + /** + * Determine basename for compiled filename + * + * @param Smarty_Template_Source $source source object + * @return string resource's basename + */ + public function getBasename(Smarty_Template_Source $source) { + return $this->fileResource->getBasename($source); + } + +} + // We initialize smarty here $debug->append('Instantiating Smarty Object', 3); $smarty = new Smarty; @@ -18,6 +155,11 @@ $smarty = new Smarty; $debug->append('Define Smarty Paths', 3); $smarty->template_dir = BASEPATH . 'templates/' . THEME . '/'; $smarty->compile_dir = BASEPATH . 'templates/compile/'; +$smarty->registerResource('hybrid', new Smarty_Resource_Hybrid( + new Smarty_Resource_Database($template), + new Smarty_Internal_Resource_File() +)); +$smarty->default_resource_type = "hybrid"; $smarty_cache_key = md5(serialize($_REQUEST) . serialize(@$_SESSION['USERDATA']['id'])); // Optional smarty caching, check Smarty documentation for details diff --git a/public/index.php b/public/index.php index db94059e..5a5c8d73 100644 --- a/public/index.php +++ b/public/index.php @@ -80,6 +80,9 @@ if (!empty($action)) { require_once(PAGES_DIR . '/' . $arrPages[$page]); } +define('PAGE', $page); +define('ACTION', $action); + // For our content inclusion $smarty->assign("PAGE", $page); $smarty->assign("ACTION", $action); From 9e2b6da3f085557bf5730978ab1dc436cd067736 Mon Sep 17 00:00:00 2001 From: Sergey Kukunin Date: Thu, 28 Nov 2013 01:53:32 +0200 Subject: [PATCH 3/4] Add disable_template_override variable to Smarty To disable Database Template Overriding and use original files --- public/include/smarty.inc.php | 10 ++++++---- 1 file changed, 6 insertions(+), 4 deletions(-) diff --git a/public/include/smarty.inc.php b/public/include/smarty.inc.php index 20344ccb..673148b5 100644 --- a/public/include/smarty.inc.php +++ b/public/include/smarty.inc.php @@ -113,11 +113,13 @@ class Smarty_Resource_Hybrid extends Smarty_Resource { * @param Smarty_Internal_Template $_template template object */ public function populate(Smarty_Template_Source $source, Smarty_Internal_Template $_template=null) { - $this->databaseResource->populate($source, $_template); - if ( !$source->exists ) { - $source->type = 'file'; - return $this->fileResource->populate($source, $_template); + if ( !@$_REQUEST['disable_template_override'] ) { + $this->databaseResource->populate($source, $_template); + if( $source->exists ) + return; } + $source->type = 'file'; + return $this->fileResource->populate($source, $_template); } /** From f97116b1b22324d78bed910731fc0939fba85fa8 Mon Sep 17 00:00:00 2001 From: Sergey Kukunin Date: Sat, 7 Dec 2013 00:15:21 +0200 Subject: [PATCH 4/4] Show templates tree on Admin Templates page Show active and activated templates in Tree Make templates tree persistent --- public/include/classes/template.class.php | 44 +- public/include/pages/admin/templates.inc.php | 17 +- .../mpos/js/dynatree/GPL-LICENSE.txt | 278 ++ .../mpos/js/dynatree/MIT-License.txt | 7 + .../mpos/js/dynatree/jquery.dynatree.js | 3450 +++++++++++++++++ .../mpos/js/dynatree/jquery.dynatree.min.js | 4 + .../mpos/js/dynatree/skin-vista/icons.gif | Bin 0 -> 5512 bytes .../mpos/js/dynatree/skin-vista/loading.gif | Bin 0 -> 3111 bytes .../js/dynatree/skin-vista/ui.dynatree.css | 453 +++ .../mpos/js/dynatree/skin/icons-rtl.gif | Bin 0 -> 4046 bytes .../mpos/js/dynatree/skin/icons.gif | Bin 0 -> 4041 bytes .../mpos/js/dynatree/skin/loading.gif | Bin 0 -> 570 bytes .../mpos/js/dynatree/skin/ui.dynatree.css | 441 +++ .../mpos/js/dynatree/skin/vline-rtl.gif | Bin 0 -> 842 bytes .../mpos/js/dynatree/skin/vline.gif | Bin 0 -> 844 bytes .../mpos/js/jquery-ui.custom.min.js | 125 + public/site_assets/mpos/js/jquery.cookie.js | 94 + .../mpos/admin/templates/default.tpl | 54 +- .../templates/mpos/admin/templates/tree.tpl | 25 + 19 files changed, 4966 insertions(+), 26 deletions(-) create mode 100644 public/site_assets/mpos/js/dynatree/GPL-LICENSE.txt create mode 100644 public/site_assets/mpos/js/dynatree/MIT-License.txt create mode 100644 public/site_assets/mpos/js/dynatree/jquery.dynatree.js create mode 100644 public/site_assets/mpos/js/dynatree/jquery.dynatree.min.js create mode 100644 public/site_assets/mpos/js/dynatree/skin-vista/icons.gif create mode 100644 public/site_assets/mpos/js/dynatree/skin-vista/loading.gif create mode 100644 public/site_assets/mpos/js/dynatree/skin-vista/ui.dynatree.css create mode 100644 public/site_assets/mpos/js/dynatree/skin/icons-rtl.gif create mode 100644 public/site_assets/mpos/js/dynatree/skin/icons.gif create mode 100644 public/site_assets/mpos/js/dynatree/skin/loading.gif create mode 100644 public/site_assets/mpos/js/dynatree/skin/ui.dynatree.css create mode 100644 public/site_assets/mpos/js/dynatree/skin/vline-rtl.gif create mode 100644 public/site_assets/mpos/js/dynatree/skin/vline.gif create mode 100644 public/site_assets/mpos/js/jquery-ui.custom.min.js create mode 100644 public/site_assets/mpos/js/jquery.cookie.js create mode 100644 public/templates/mpos/admin/templates/tree.tpl diff --git a/public/include/classes/template.class.php b/public/include/classes/template.class.php index 007ddd4b..fe03fe7b 100644 --- a/public/include/classes/template.class.php +++ b/public/include/classes/template.class.php @@ -96,12 +96,54 @@ class Template extends Base { $files = new RegexIterator($ite, '!'.preg_quote($folder, '!').'/(.*\.tpl$)!', RegexIterator::GET_MATCH); $fileList = array(); foreach($files as $file) { - $fileList[] = $file[1]; + $fileList[] = $theme . '/' . $file[1]; } return $fileList; } + /** + * Get tree of all possible templates, where key is filename + * and value is whether array of subfiles if filename is directory + * or true, if filename is file + * + * @param $themes - optional, themes array + * @return array - tree of all templates + */ + public function getTemplatesTree($themes = null) { + if( is_null($themes) ) + $themes = $this->getThemes(); + + $templates = array(); + foreach($themes as $theme) { + $templates[$theme] = $this->_getTemplatesTreeRecursive(THEME_DIR . '/' . $theme); + } + + return $templates; + + } + + private function _getTemplatesTreeRecursive($path) { + if( !is_dir($path) ) { + return preg_match("/\.tpl$/", $path); + } else { + $subfiles = scandir($path); + if ( $subfiles === false ) + return false; + + $files = array(); + foreach($subfiles as $subfile) { + if($subfile == ".." || $subfile == ".") continue; + $subpath = $path . '/' . $subfile; + $subsubfiles = $this->_getTemplatesTreeRecursive($subpath); + if ( !$subsubfiles ) continue; + $files[$subfile] = $subsubfiles; + } + return $files; + } + return array(); + } + /** * Return specific template from database * diff --git a/public/include/pages/admin/templates.inc.php b/public/include/pages/admin/templates.inc.php index 6adcea29..b3c101ea 100644 --- a/public/include/pages/admin/templates.inc.php +++ b/public/include/pages/admin/templates.inc.php @@ -10,23 +10,19 @@ if (!$user->isAuthenticated() || !$user->isAdmin($_SESSION['USERDATA']['id'])) { } $aThemes = $template->getThemes(); -$aTemplates = $aFlatTemplatesList = array(); +$aTemplates = $template->getTemplatesTree($aThemes); +$aActiveTemplates = $template->cachedGetActiveTemplates(); + +$aFlatTemplatesList = array(); foreach($aThemes as $sTheme) { $templates = $template->getTemplateFiles($sTheme); - $templatesWithTheme = array(); - foreach($templates as $tpl_name) { - $templatesWithTheme[] = $sTheme."/".$tpl_name; - } - $aFlatTemplatesList = array_merge($aFlatTemplatesList, $templatesWithTheme); - $aTemplates[$sTheme] = array_combine($templatesWithTheme, $templates); + $aFlatTemplatesList = array_merge($aFlatTemplatesList, $templates); } //Fetch current slug and template $sTemplate = @$_REQUEST['template']; if(!in_array($sTemplate, $aFlatTemplatesList)) { - $aThemeTemplates = $aTemplates[THEME]; - $sTemplate = array_keys($aThemeTemplates); - $sTemplate = $sTemplate[0]; + $sTemplate = $aFlatTemplatesList[0]; } $sOriginalTemplate = $template->getTemplateContent($sTemplate); @@ -46,6 +42,7 @@ if ( $oDatabaseTemplate === false ) { } $smarty->assign("TEMPLATES", $aTemplates); +$smarty->assign("ACTIVE_TEMPLATES", $aActiveTemplates); $smarty->assign("CURRENT_TEMPLATE", $sTemplate); $smarty->assign("ORIGINAL_TEMPLATE", $sOriginalTemplate); $smarty->assign("DATABASE_TEMPLATE", $oDatabaseTemplate); diff --git a/public/site_assets/mpos/js/dynatree/GPL-LICENSE.txt b/public/site_assets/mpos/js/dynatree/GPL-LICENSE.txt new file mode 100644 index 00000000..11dddd00 --- /dev/null +++ b/public/site_assets/mpos/js/dynatree/GPL-LICENSE.txt @@ -0,0 +1,278 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc. + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. diff --git a/public/site_assets/mpos/js/dynatree/MIT-License.txt b/public/site_assets/mpos/js/dynatree/MIT-License.txt new file mode 100644 index 00000000..d70071be --- /dev/null +++ b/public/site_assets/mpos/js/dynatree/MIT-License.txt @@ -0,0 +1,7 @@ +Copyright (c) 2006-2013 Martin Wendt (http://wwWendt.de) + +Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. \ No newline at end of file diff --git a/public/site_assets/mpos/js/dynatree/jquery.dynatree.js b/public/site_assets/mpos/js/dynatree/jquery.dynatree.js new file mode 100644 index 00000000..f70ea32b --- /dev/null +++ b/public/site_assets/mpos/js/dynatree/jquery.dynatree.js @@ -0,0 +1,3450 @@ +/*! **************************************************************************** + jquery.dynatree.js + Dynamic tree view control, with support for lazy loading of branches. + + Copyright (c) 2006-2013, Martin Wendt (http://wwWendt.de) + Dual licensed under the MIT or GPL Version 2 licenses. + http://code.google.com/p/dynatree/wiki/LicenseInfo + + A current version and some documentation is available at + http://dynatree.googlecode.com/ + + @version: 1.2.5 + @date: 2013-11-19T07:42 + + @depends: jquery.js + @depends: jquery.ui.core.js + @depends: jquery.cookie.js +*******************************************************************************/ + +/* jsHint options*/ +// Note: We currently allow eval() to parse the 'data' attribtes, when initializing from HTML. +// TODO: pass jsHint with the options given in grunt.js only. +// The following should not be required: +/*global alert */ +/*jshint nomen:false, smarttabs:true, eqeqeq:false, evil:true, regexp:false */ + +/************************************************************************* + * Debug functions + */ + +var _canLog = true; + +function _log(mode, msg) { + /** + * Usage: logMsg("%o was toggled", this); + */ + if( !_canLog ){ + return; + } + // Remove first argument + var args = Array.prototype.slice.apply(arguments, [1]); + // Prepend timestamp + var dt = new Date(); + var tag = dt.getHours() + ":" + dt.getMinutes() + ":" + + dt.getSeconds() + "." + dt.getMilliseconds(); + args[0] = tag + " - " + args[0]; + + try { + switch( mode ) { + case "info": + window.console.info.apply(window.console, args); + break; + case "warn": + window.console.warn.apply(window.console, args); + break; + default: + window.console.log.apply(window.console, args); + break; + } + } catch(e) { + if( !window.console ){ + _canLog = false; // Permanently disable, when logging is not supported by the browser + }else if(e.number === -2146827850){ + // fix for IE8, where window.console.log() exists, but does not support .apply() + window.console.log(args.join(", ")); + } + } +} + + +function logMsg(msg) { + Array.prototype.unshift.apply(arguments, ["debug"]); + _log.apply(this, arguments); +} + + +// Forward declaration +var getDynaTreePersistData = null; + + + +/************************************************************************* + * Constants + */ +var DTNodeStatus_Error = -1; +var DTNodeStatus_Loading = 1; +var DTNodeStatus_Ok = 0; + + +// Start of local namespace +(function($) { + +/************************************************************************* + * Common tool functions. + */ + +var Class = { + create: function() { + return function() { + this.initialize.apply(this, arguments); + }; + } +}; + +// Tool function to get dtnode from the event target: +function getDtNodeFromElement(el) { + alert("getDtNodeFromElement is deprecated"); + return $.ui.dynatree.getNode(el); +/* + var iMax = 5; + while( el && iMax-- ) { + if(el.dtnode) { return el.dtnode; } + el = el.parentNode; + } + return null; +*/ +} + +function noop() { +} + + +/* Convert number to string and prepend +/-; return empty string for 0.*/ +function offsetString(n){ + return n === 0 ? "" : (( n > 0 ) ? ("+" + n) : ("" + n)); +} + + +/* Check browser version, since $.browser was removed in jQuery 1.9 */ +function _checkBrowser(){ + var matched, browser; + function uaMatch( ua ) { + ua = ua.toLowerCase(); + var match = /(chrome)[ \/]([\w.]+)/.exec( ua ) || + /(webkit)[ \/]([\w.]+)/.exec( ua ) || + /(opera)(?:.*version|)[ \/]([\w.]+)/.exec( ua ) || + /(msie) ([\w.]+)/.exec( ua ) || + ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+)|)/.exec( ua ) || + []; + return { + browser: match[ 1 ] || "", + version: match[ 2 ] || "0" + }; + } + matched = uaMatch( navigator.userAgent ); + browser = {}; + if ( matched.browser ) { + browser[ matched.browser ] = true; + browser.version = matched.version; + } + if ( browser.chrome ) { + browser.webkit = true; + } else if ( browser.webkit ) { + browser.safari = true; + } + return browser; +} + + +/** Compare two dotted version strings (like '10.2.3'). + * @returns {Integer} 0: v1 == v2, -1: v1 < v2, 1: v1 > v2 + */ +function versionCompare(v1, v2) { + var v1parts = ("" + v1).split("."), + v2parts = ("" + v2).split("."), + minLength = Math.min(v1parts.length, v2parts.length), + p1, p2, i; + // Compare tuple pair-by-pair. + for(i = 0; i < minLength; i++) { + // Convert to integer if possible, because "8" > "10". + p1 = parseInt(v1parts[i], 10); + p2 = parseInt(v2parts[i], 10); + if (isNaN(p1)){ p1 = v1parts[i]; } + if (isNaN(p2)){ p2 = v2parts[i]; } + if (p1 == p2) { + continue; + }else if (p1 > p2) { + return 1; + }else if (p1 < p2) { + return -1; + } + // one operand is NaN + return NaN; + } + // The longer tuple is always considered 'greater' + if (v1parts.length === v2parts.length) { + return 0; + } + return (v1parts.length < v2parts.length) ? -1 : 1; +} + + +//var BROWSER = jQuery.browser || _checkBrowser(); +var BROWSER = _checkBrowser(); // issue 440 +var jquerySupports = { + // http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at + positionMyOfs: versionCompare($.ui.version, "1.9") >= 0 //isVersionAtLeast($.ui.version, 1, 9) + }; + + +/************************************************************************* + * Class DynaTreeNode + */ +var DynaTreeNode = Class.create(); + +DynaTreeNode.prototype = { + initialize: function(parent, tree, data) { + /** + * @constructor + */ + this.parent = parent; + this.tree = tree; + if ( typeof data === "string" ){ + data = { title: data }; + } +// if( !data.key ){ + if( data.key == null ){ // test for null OR undefined (issue 420) + data.key = "_" + tree._nodeCount++; + }else{ + data.key = "" + data.key; // issue 371 + } + this.data = $.extend({}, $.ui.dynatree.nodedatadefaults, data); + this.li = null; // not yet created + this.span = null; // not yet created + this.ul = null; // not yet created + this.childList = null; // no subnodes yet + this._isLoading = false; // Lazy content is being loaded + this.hasSubSel = false; + this.bExpanded = false; + this.bSelected = false; + + }, + + toString: function() { + return "DynaTreeNode<" + this.data.key + ">: '" + this.data.title + "'"; + }, + + toDict: function(recursive, callback) { + var node, + dict = $.extend({}, this.data); + dict.activate = ( this.tree.activeNode === this ); + dict.focus = ( this.tree.focusNode === this ); + dict.expand = this.bExpanded; + dict.select = this.bSelected; + if( callback ){ + callback(dict); + } + if( recursive && this.childList ) { + dict.children = []; + for(var i=0, l=this.childList.length; i 1){ + res += cache.tagConnector; + } + // .. else (i.e. for root level) skip expander/connector altogether + } else if( this.hasChildren() !== false ) { + res += cache.tagExpander; + } else { + res += cache.tagConnector; + } + // Checkbox mode + if( opts.checkbox && data.hideCheckbox !== true && !data.isStatusNode ) { + res += cache.tagCheckbox; + } + // folder or doctype icon + if ( data.icon ) { + if (data.icon.charAt(0) === "/"){ + imageSrc = data.icon; + }else{ + imageSrc = opts.imagePath + data.icon; + } + res += ""; + } else if ( data.icon === false ) { + // icon == false means 'no icon' +// noop(); // keep JSLint happy + } else if ( data.iconClass ) { + res += ""; + } else { + // icon == null means 'default icon' + res += cache.tagNodeIcon; + } + // node title + var nodeTitle = ""; + if ( opts.onCustomRender ){ + nodeTitle = opts.onCustomRender.call(tree, this) || ""; + } + if(!nodeTitle){ + var tooltip = data.tooltip ? ' title="' + data.tooltip.replace(/\"/g, '"') + '"' : '', + href = data.href || "#"; + if( opts.noLink || data.noLink ) { + nodeTitle = '' + data.title + ''; +// this.tree.logDebug("nodeTitle: " + nodeTitle); + } else { + nodeTitle = '' + data.title + ''; + } + } + res += nodeTitle; + return res; + }, + + + _fixOrder: function() { + /** + * Make sure, that
  • order matches childList order. + */ + var cl = this.childList; + if( !cl || !this.ul ){ + return; + } + var childLI = this.ul.firstChild; + for(var i=0, l=cl.length-1; i + this.li = this.span = null; + this.ul = document.createElement("ul"); + if( opts.minExpandLevel > 1 ){ + this.ul.className = cn.container + " " + cn.noConnector; + }else{ + this.ul.className = cn.container; + } + } else if( parent ) { + // Create
  • + if( ! this.li ) { + firstTime = true; + this.li = document.createElement("li"); + this.li.dtnode = this; + if( data.key && opts.generateIds ){ + this.li.id = opts.idPrefix + data.key; + } + this.span = document.createElement("span"); + this.span.className = cn.title; + this.li.appendChild(this.span); + + if( !parent.ul ) { + // This is the parent's first child: create UL tag + // (Hidden, because it will be + parent.ul = document.createElement("ul"); + parent.ul.style.display = "none"; + parent.li.appendChild(parent.ul); +// if( opts.minExpandLevel > this.getLevel() ){ +// parent.ul.className = cn.noConnector; +// } + } + // set node connector images, links and text +// this.span.innerHTML = this._getInnerHtml(); + + parent.ul.appendChild(this.li); + } + // set node connector images, links and text + this.span.innerHTML = this._getInnerHtml(); + // Set classes for current status + var cnList = []; + cnList.push(cn.node); + if( data.isFolder ){ + cnList.push(cn.folder); + } + if( this.bExpanded ){ + cnList.push(cn.expanded); + } + if( this.hasChildren() !== false ){ + cnList.push(cn.hasChildren); + } + if( data.isLazy && this.childList === null ){ + cnList.push(cn.lazy); + } + if( isLastSib ){ + cnList.push(cn.lastsib); + } + if( this.bSelected ){ + cnList.push(cn.selected); + } + if( this.hasSubSel ){ + cnList.push(cn.partsel); + } + if( tree.activeNode === this ){ + cnList.push(cn.active); + } + if( data.addClass ){ + cnList.push(data.addClass); + } + // IE6 doesn't correctly evaluate multiple class names, + // so we create combined class names that can be used in the CSS + cnList.push(cn.combinedExpanderPrefix + + (this.bExpanded ? "e" : "c") + + (data.isLazy && this.childList === null ? "d" : "") + + (isLastSib ? "l" : "") + ); + cnList.push(cn.combinedIconPrefix + + (this.bExpanded ? "e" : "c") + + (data.isFolder ? "f" : "") + ); + this.span.className = cnList.join(" "); + + // TODO: we should not set this in the tag also, if we set it here: + this.li.className = isLastSib ? cn.lastsib : ""; + + // Allow tweaking, binding, after node was created for the first time + if(firstTime && opts.onCreate){ + opts.onCreate.call(tree, this, this.span); + } + // Hide children, if node is collapsed +// this.ul.style.display = ( this.bExpanded || !parent ) ? "" : "none"; + // Allow tweaking after node state was rendered + if(opts.onRender){ + opts.onRender.call(tree, this, this.span); + } + } + // Visit child nodes + if( (this.bExpanded || includeInvisible === true) && this.childList ) { + for(var i=0, l=this.childList.length; i b.data.title ? 1 : -1; + var x = a.data.title.toLowerCase(), + y = b.data.title.toLowerCase(); + return x === y ? 0 : x > y ? 1 : -1; + }; + cl.sort(cmp); + if( deep ){ + for(var i=0, l=cl.length; i 0) { + // special case: using ajaxInit + this.childList[0].focus(); + } else { + this.focus(); + } + } + break; + case DTNodeStatus_Loading: + this._isLoading = true; + $(this.span).addClass(this.tree.options.classNames.nodeLoading); + // The root is hidden, so we set a temporary status child + if(!this.parent){ + this._setStatusNode({ + title: this.tree.options.strings.loading + info, + tooltip: tooltip, + addClass: this.tree.options.classNames.nodeWait + }); + } + break; + case DTNodeStatus_Error: + this._isLoading = false; +// $(this.span).addClass(this.tree.options.classNames.nodeError); + this._setStatusNode({ + title: this.tree.options.strings.loadError + info, + tooltip: tooltip, + addClass: this.tree.options.classNames.nodeError + }); + break; + default: + throw "Bad LazyNodeStatus: '" + lts + "'."; + } + }, + + _parentList: function(includeRoot, includeSelf) { + var l = []; + var dtn = includeSelf ? this : this.parent; + while( dtn ) { + if( includeRoot || dtn.parent ){ + l.unshift(dtn); + } + dtn = dtn.parent; + } + return l; + }, + getLevel: function() { + /** + * Return node depth. 0: System root node, 1: visible top-level node. + */ + var level = 0; + var dtn = this.parent; + while( dtn ) { + level++; + dtn = dtn.parent; + } + return level; + }, + + _getTypeForOuterNodeEvent: function(event) { + /** Return the inner node span (title, checkbox or expander) if + * event.target points to the outer span. + * This function should fix issue #93: + * FF2 ignores empty spans, when generating events (returning the parent instead). + */ + var cns = this.tree.options.classNames; + var target = event.target; + // Only process clicks on an outer node span (probably due to a FF2 event handling bug) + if( target.className.indexOf(cns.node) < 0 ) { + return null; + } + // Event coordinates, relative to outer node span: + var eventX = event.pageX - target.offsetLeft; + var eventY = event.pageY - target.offsetTop; + + for(var i=0, l=target.childNodes.length; i= x && eventX <= (x+nx) && eventY >= y && eventY <= (y+ny) ) { +// alert("HIT "+ cn.className); + if( cn.className==cns.title ){ + return "title"; + }else if( cn.className==cns.expander ){ + return "expander"; + }else if( cn.className==cns.checkbox ){ + return "checkbox"; + }else if( cn.className==cns.nodeIcon ){ + return "icon"; + } + } + } + return "prefix"; + }, + + getEventTargetType: function(event) { + // Return the part of a node, that a click event occured on. + // Note: there is no check, if the event was fired on THIS node. + var tcn = event && event.target ? event.target.className : "", + cns = this.tree.options.classNames; + + if( tcn.indexOf(cns.title) >= 0 ){ + return "title"; + }else if( tcn.indexOf(cns.expander) >= 0 ){ + return "expander"; + }else if( tcn.indexOf(cns.checkbox) >= 0 ){ + return "checkbox"; + }else if( tcn.indexOf(cns.nodeIcon) >= 0 ){ + return "icon"; + }else if( tcn.indexOf(cns.empty) >= 0 || tcn.indexOf(cns.vline) >= 0 || tcn.indexOf(cns.connector) >= 0 ){ + return "prefix"; + }else if( tcn.indexOf(cns.node) >= 0 ){ + // FIX issue #93 + return this._getTypeForOuterNodeEvent(event); + } + return null; + }, + + isVisible: function() { + // Return true, if all parents are expanded. + var parents = this._parentList(true, false); + for(var i=0, l=parents.length; ia").focus(); + } catch(e) { } + }, + + isFocused: function() { + return (this.tree.tnFocused === this); + }, + + _activate: function(flag, fireEvents) { + // (De)Activate - but not focus - this node. + this.tree.logDebug("dtnode._activate(%o, fireEvents=%o) - %o", flag, fireEvents, this); + var opts = this.tree.options; + if( this.data.isStatusNode ){ + return; + } + if ( fireEvents && opts.onQueryActivate && opts.onQueryActivate.call(this.tree, flag, this) === false ){ + return; // Callback returned false + } + if( flag ) { + // Activate + if( this.tree.activeNode ) { + if( this.tree.activeNode === this ){ + return; + } + this.tree.activeNode.deactivate(); + } + if( opts.activeVisible ){ + this.makeVisible(); + } + this.tree.activeNode = this; + if( opts.persist ){ + $.cookie(opts.cookieId + "-active", this.data.key, opts.cookie); + } + this.tree.persistence.activeKey = this.data.key; + $(this.span).addClass(opts.classNames.active); + if ( fireEvents && opts.onActivate ){ + opts.onActivate.call(this.tree, this); + } + } else { + // Deactivate + if( this.tree.activeNode === this ) { + if ( opts.onQueryActivate && opts.onQueryActivate.call(this.tree, false, this) === false ){ + return; // Callback returned false + } + $(this.span).removeClass(opts.classNames.active); + if( opts.persist ) { + // Note: we don't pass null, but ''. So the cookie is not deleted. + // If we pass null, we also have to pass a COPY of opts, because $cookie will override opts.expires (issue 84) + $.cookie(opts.cookieId + "-active", "", opts.cookie); + } + this.tree.persistence.activeKey = null; + this.tree.activeNode = null; + if ( fireEvents && opts.onDeactivate ){ + opts.onDeactivate.call(this.tree, this); + } + } + } + }, + + activate: function() { + // Select - but not focus - this node. +// this.tree.logDebug("dtnode.activate(): %o", this); + this._activate(true, true); + }, + + activateSilently: function() { + this._activate(true, false); + }, + + deactivate: function() { +// this.tree.logDebug("dtnode.deactivate(): %o", this); + this._activate(false, true); + }, + + isActive: function() { + return (this.tree.activeNode === this); + }, + + _userActivate: function() { + // Handle user click / [space] / [enter], according to clickFolderMode. + var activate = true; + var expand = false; + if ( this.data.isFolder ) { + switch( this.tree.options.clickFolderMode ) { + case 2: + activate = false; + expand = true; + break; + case 3: + activate = expand = true; + break; + } + } + if( this.parent === null ) { + expand = false; + } + if( expand ) { + this.toggleExpand(); + this.focus(); + } + if( activate ) { + this.activate(); + } + }, + + _setSubSel: function(hasSubSel) { + if( hasSubSel ) { + this.hasSubSel = true; + $(this.span).addClass(this.tree.options.classNames.partsel); + } else { + this.hasSubSel = false; + $(this.span).removeClass(this.tree.options.classNames.partsel); + } + }, + /** + * Fix selection and partsel status, of parent nodes, according to current status of + * end nodes. + */ + _updatePartSelectionState: function() { +// alert("_updatePartSelectionState " + this); +// this.tree.logDebug("_updatePartSelectionState() - %o", this); + var sel; + // Return `true` or `false` for end nodes and remove part-sel flag + if( ! this.hasChildren() ){ + sel = (this.bSelected && !this.data.unselectable && !this.data.isStatusNode); + this._setSubSel(false); + return sel; + } + // Return `true`, `false`, or `undefined` for parent nodes + var i, l, + cl = this.childList, + allSelected = true, + allDeselected = true; + for(i=0, l=cl.length; i jumps to the top + event.preventDefault(); + }, + + _onDblClick: function(event) { +// this.tree.logDebug("dtnode.onDblClick(" + event.type + "): dtnode:" + this + ", button:" + event.button + ", which: " + event.which); + }, + + _onKeydown: function(event) { +// this.tree.logDebug("dtnode.onKeydown(" + event.type + "): dtnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which); + var handled = true, + sib; +// alert("keyDown" + event.which); + + switch( event.which ) { + // charCodes: +// case 43: // '+' + case 107: // '+' + case 187: // '+' @ Chrome, Safari + if( !this.bExpanded ){ this.toggleExpand(); } + break; +// case 45: // '-' + case 109: // '-' + case 189: // '+' @ Chrome, Safari + if( this.bExpanded ){ this.toggleExpand(); } + break; + //~ case 42: // '*' + //~ break; + //~ case 47: // '/' + //~ break; + // case 13: // + // on a focused tag seems to generate a click-event. + // this._userActivate(); + // break; + case 32: // + this._userActivate(); + break; + case 8: // + if( this.parent ){ + this.parent.focus(); + } + break; + case 37: // + if( this.bExpanded ) { + this.toggleExpand(); + this.focus(); +// } else if( this.parent && (this.tree.options.rootVisible || this.parent.parent) ) { + } else if( this.parent && this.parent.parent ) { + this.parent.focus(); + } + break; + case 39: // + if( !this.bExpanded && (this.childList || this.data.isLazy) ) { + this.toggleExpand(); + this.focus(); + } else if( this.childList ) { + this.childList[0].focus(); + } + break; + case 38: // + sib = this.getPrevSibling(); + while( sib && sib.bExpanded && sib.childList ){ + sib = sib.childList[sib.childList.length-1]; + } +// if( !sib && this.parent && (this.tree.options.rootVisible || this.parent.parent) ) + if( !sib && this.parent && this.parent.parent ){ + sib = this.parent; + } + if( sib ){ + sib.focus(); + } + break; + case 40: // + if( this.bExpanded && this.childList ) { + sib = this.childList[0]; + } else { + var parents = this._parentList(false, true); + for(var i=parents.length-1; i>=0; i--) { + sib = parents[i].getNextSibling(); + if( sib ){ break; } + } + } + if( sib ){ + sib.focus(); + } + break; + default: + handled = false; + } + // Return false, if handled, to prevent default processing +// return !handled; + if(handled){ + event.preventDefault(); + } + }, + + _onKeypress: function(event) { + // onKeypress is only hooked to allow user callbacks. + // We don't process it, because IE and Safari don't fire keypress for cursor keys. +// this.tree.logDebug("dtnode.onKeypress(" + event.type + "): dtnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which); + }, + + _onFocus: function(event) { + // Handles blur and focus events. +// this.tree.logDebug("dtnode._onFocus(%o): %o", event, this); + var opts = this.tree.options; + if ( event.type == "blur" || event.type == "focusout" ) { + if ( opts.onBlur ){ + opts.onBlur.call(this.tree, this); + } + if( this.tree.tnFocused ){ + $(this.tree.tnFocused.span).removeClass(opts.classNames.focused); + } + this.tree.tnFocused = null; + if( opts.persist ){ + $.cookie(opts.cookieId + "-focus", "", opts.cookie); + } + } else if ( event.type=="focus" || event.type=="focusin") { + // Fix: sometimes the blur event is not generated + if( this.tree.tnFocused && this.tree.tnFocused !== this ) { + this.tree.logDebug("dtnode.onFocus: out of sync: curFocus: %o", this.tree.tnFocused); + $(this.tree.tnFocused.span).removeClass(opts.classNames.focused); + } + this.tree.tnFocused = this; + if ( opts.onFocus ){ + opts.onFocus.call(this.tree, this); + } + $(this.tree.tnFocused.span).addClass(opts.classNames.focused); + if( opts.persist ){ + $.cookie(opts.cookieId + "-focus", this.data.key, opts.cookie); + } + } + // TODO: return anything? +// return false; + }, + + visit: function(fn, includeSelf) { + // Call fn(node) for all child nodes. Stop iteration, if fn() returns false. + var res = true; + if( includeSelf === true ) { + res = fn(this); + if( res === false || res === "skip" ){ + return res; + } + } + if(this.childList){ + for(var i=0, l=this.childList.length; i reloading %s...", this, keyPath, child); + var self = this; + // Note: this line gives a JSLint warning (Don't make functions within a loop) + /*jshint loopfunc:true */ + child.reloadChildren(function(node, isOk){ + // After loading, look for direct child with that key + if(isOk){ + tree.logDebug("%s._loadKeyPath(%s) -> reloaded %s.", node, keyPath, node); + callback.call(tree, child, "loaded"); + node._loadKeyPath(segList.join(tree.options.keyPathSeparator), callback); + }else{ + tree.logWarning("%s._loadKeyPath(%s) -> reloadChildren() failed.", self, keyPath); + callback.call(tree, child, "error"); + } + }); + // we can ignore it, since it will only be exectuted once, the the loop is ended + // See also http://stackoverflow.com/questions/3037598/how-to-get-around-the-jslint-error-dont-make-functions-within-a-loop + } else { + callback.call(tree, child, "loaded"); + // Look for direct child with that key + child._loadKeyPath(segList.join(tree.options.keyPathSeparator), callback); + } + return; + } + } + } + // Could not find key + // Callback params: child: undefined, the segment, isEndNode (segList.length === 0) + callback.call(tree, undefined, "notfound", seg, segList.length === 0); + tree.logWarning("Node not found: " + seg); + return; + }, + + resetLazy: function() { + // Discard lazy content. + if( this.parent === null ){ + throw "Use tree.reload() instead"; + }else if( ! this.data.isLazy ){ + throw "node.resetLazy() requires lazy nodes."; + } + this.expand(false); + this.removeChildren(); + }, + + _addChildNode: function(dtnode, beforeNode) { + /** + * Internal function to add one single DynatreeNode as a child. + * + */ + var tree = this.tree, + opts = tree.options, + pers = tree.persistence; + +// tree.logDebug("%s._addChildNode(%o)", this, dtnode); + + // --- Update and fix dtnode attributes if necessary + dtnode.parent = this; +// if( beforeNode && (beforeNode.parent !== this || beforeNode === dtnode ) ) +// throw " must be another child of "; + + // --- Add dtnode as a child + if ( this.childList === null ) { + this.childList = []; + } else if( ! beforeNode ) { + // Fix 'lastsib' + if(this.childList.length > 0) { + $(this.childList[this.childList.length-1].span).removeClass(opts.classNames.lastsib); + } + } + if( beforeNode ) { + var iBefore = $.inArray(beforeNode, this.childList); + if( iBefore < 0 ){ + throw " must be a child of "; + } + this.childList.splice(iBefore, 0, dtnode); + } else { + // Append node + this.childList.push(dtnode); + } + + // --- Handle persistence + // Initial status is read from cookies, if persistence is active and + // cookies are already present. + // Otherwise the status is read from the data attributes and then persisted. + var isInitializing = tree.isInitializing(); + if( opts.persist && pers.cookiesFound && isInitializing ) { + // Init status from cookies +// tree.logDebug("init from cookie, pa=%o, dk=%o", pers.activeKey, dtnode.data.key); + if( pers.activeKey === dtnode.data.key ){ + tree.activeNode = dtnode; + } + if( pers.focusedKey === dtnode.data.key ){ + tree.focusNode = dtnode; + } + dtnode.bExpanded = ($.inArray(dtnode.data.key, pers.expandedKeyList) >= 0); + dtnode.bSelected = ($.inArray(dtnode.data.key, pers.selectedKeyList) >= 0); +// tree.logDebug(" key=%o, bSelected=%o", dtnode.data.key, dtnode.bSelected); + } else { + // Init status from data (Note: we write the cookies after the init phase) +// tree.logDebug("init from data"); + if( dtnode.data.activate ) { + tree.activeNode = dtnode; + if( opts.persist ){ + pers.activeKey = dtnode.data.key; + } + } + if( dtnode.data.focus ) { + tree.focusNode = dtnode; + if( opts.persist ){ + pers.focusedKey = dtnode.data.key; + } + } + dtnode.bExpanded = ( dtnode.data.expand === true ); // Collapsed by default + if( dtnode.bExpanded && opts.persist ){ + pers.addExpand(dtnode.data.key); + } + dtnode.bSelected = ( dtnode.data.select === true ); // Deselected by default +/* + Doesn't work, cause pers.selectedKeyList may be null + if( dtnode.bSelected && opts.selectMode==1 + && pers.selectedKeyList && pers.selectedKeyList.length>0 ) { + tree.logWarning("Ignored multi-selection in single-mode for %o", dtnode); + dtnode.bSelected = false; // Fixing bad input data (multi selection for mode:1) + } +*/ + if( dtnode.bSelected && opts.persist ){ + pers.addSelect(dtnode.data.key); + } + } + + // Always expand, if it's below minExpandLevel +// tree.logDebug ("%s._addChildNode(%o), l=%o", this, dtnode, dtnode.getLevel()); + if ( opts.minExpandLevel >= dtnode.getLevel() ) { +// tree.logDebug ("Force expand for %o", dtnode); + this.bExpanded = true; + } + + // In multi-hier mode, update the parents selection state + // issue #82: only if not initializing, because the children may not exist yet +// if( !dtnode.data.isStatusNode && opts.selectMode==3 && !isInitializing ) +// dtnode._fixSelectionState(); + + // In multi-hier mode, update the parents selection state + if( dtnode.bSelected && opts.selectMode==3 ) { + var p = this; + while( p ) { + if( !p.hasSubSel ){ + p._setSubSel(true); + } + p = p.parent; + } + } + // render this node and the new child + if ( tree.bEnableUpdate ){ + this.render(); + } + return dtnode; + }, + + addChild: function(obj, beforeNode) { + /** + * Add a node object as child. + * + * This should be the only place, where a DynaTreeNode is constructed! + * (Except for the root node creation in the tree constructor) + * + * @param obj A JS object (may be recursive) or an array of those. + * @param {DynaTreeNode} beforeNode (optional) sibling node. + * + * Data format: array of node objects, with optional 'children' attributes. + * [ + * { title: "t1", isFolder: true, ... } + * { title: "t2", isFolder: true, ..., + * children: [ + * {title: "t2.1", ..}, + * {..} + * ] + * } + * ] + * A simple object is also accepted instead of an array. + * + */ +// this.tree.logDebug("%s.addChild(%o, %o)", this, obj, beforeNode); + if(typeof(obj) == "string"){ + throw "Invalid data type for " + obj; + }else if( !obj || obj.length === 0 ){ // Passed null or undefined or empty array + return; + }else if( obj instanceof DynaTreeNode ){ + return this._addChildNode(obj, beforeNode); + } + + if( !obj.length ){ // Passed a single data object + obj = [ obj ]; + } + var prevFlag = this.tree.enableUpdate(false); + + var tnFirst = null; + for (var i=0, l=obj.length; i is the request options +// self.tree.logDebug("appendAjax().success"); + var prevPhase = self.tree.phase; + self.tree.phase = "init"; + // postProcess is similar to the standard dataFilter hook, + // but it is also called for JSONP + if( options.postProcess ){ + data = options.postProcess.call(this, data, this.dataType); + } + // Process ASPX WebMethod JSON object inside "d" property + // http://code.google.com/p/dynatree/issues/detail?id=202 + else if (data && data.hasOwnProperty("d")) { + data = (typeof data.d) == "string" ? $.parseJSON(data.d) : data.d; + } + if(!$.isArray(data) || data.length !== 0){ + self.addChild(data, null); + } + self.tree.phase = "postInit"; + if( orgSuccess ){ + orgSuccess.call(options, self, data, textStatus); + } + self.tree.logDebug("trigger " + eventType); + self.tree.$tree.trigger(eventType, [self, true]); + self.tree.phase = prevPhase; + // This should be the last command, so node._isLoading is true + // while the callbacks run + self.setLazyNodeStatus(DTNodeStatus_Ok); + if($.isArray(data) && data.length === 0){ + // Set to [] which is interpreted as 'no children' for lazy + // nodes + self.childList = []; + self.render(); + } + }, + error: function(jqXHR, textStatus, errorThrown){ + // is the request options + self.tree.logWarning("appendAjax failed:", textStatus, ":\n", jqXHR, "\n", errorThrown); + if( orgError ){ + orgError.call(options, self, jqXHR, textStatus, errorThrown); + } + self.tree.$tree.trigger(eventType, [self, false]); + self.setLazyNodeStatus(DTNodeStatus_Error, {info: textStatus, tooltip: "" + errorThrown}); + } + }); + $.ajax(options); + }, + + move: function(targetNode, mode) { + /**Move this node to targetNode. + * mode 'child': append this node as last child of targetNode. + * This is the default. To be compatble with the D'n'd + * hitMode, we also accept 'over'. + * mode 'before': add this node as sibling before targetNode. + * mode 'after': add this node as sibling after targetNode. + */ + var pos; + if(this === targetNode){ + return; + } + if( !this.parent ){ + throw "Cannot move system root"; + } + if(mode === undefined || mode == "over"){ + mode = "child"; + } + var prevParent = this.parent; + var targetParent = (mode === "child") ? targetNode : targetNode.parent; + if( targetParent.isDescendantOf(this) ){ + throw "Cannot move a node to it's own descendant"; + } + // Unlink this node from current parent + if( this.parent.childList.length == 1 ) { + this.parent.childList = this.parent.data.isLazy ? [] : null; + this.parent.bExpanded = false; + } else { + pos = $.inArray(this, this.parent.childList); + if( pos < 0 ){ + throw "Internal error"; + } + this.parent.childList.splice(pos, 1); + } + // Remove from source DOM parent + if(this.parent.ul){ + this.parent.ul.removeChild(this.li); + } + + // Insert this node to target parent's child list + this.parent = targetParent; + if( targetParent.hasChildren() ) { + switch(mode) { + case "child": + // Append to existing target children + targetParent.childList.push(this); + break; + case "before": + // Insert this node before target node + pos = $.inArray(targetNode, targetParent.childList); + if( pos < 0 ){ + throw "Internal error"; + } + targetParent.childList.splice(pos, 0, this); + break; + case "after": + // Insert this node after target node + pos = $.inArray(targetNode, targetParent.childList); + if( pos < 0 ){ + throw "Internal error"; + } + targetParent.childList.splice(pos+1, 0, this); + break; + default: + throw "Invalid mode " + mode; + } + } else { + targetParent.childList = [ this ]; + } + // Parent has no