code
stringlengths
1
2.01M
repo_name
stringlengths
3
62
path
stringlengths
1
267
language
stringclasses
231 values
license
stringclasses
13 values
size
int64
1
2.01M
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty debug_console function plugin * * Type: core<br> * Name: display_debug_console<br> * Purpose: display the javascript debug console window * @param array Format: null * @param Smarty */ function smarty_core_display_debug_console($params, &$smarty) { // we must force compile the debug template in case the environment // changed between separate applications. if(empty($smarty->debug_tpl)) { // set path to debug template from SMARTY_DIR $smarty->debug_tpl = SMARTY_DIR . 'debug.tpl'; if($smarty->security && is_file($smarty->debug_tpl)) { $smarty->secure_dir[] = realpath($smarty->debug_tpl); } $smarty->debug_tpl = 'file:' . SMARTY_DIR . 'debug.tpl'; } $_ldelim_orig = $smarty->left_delimiter; $_rdelim_orig = $smarty->right_delimiter; $smarty->left_delimiter = '{'; $smarty->right_delimiter = '}'; $_compile_id_orig = $smarty->_compile_id; $smarty->_compile_id = null; $_compile_path = $smarty->_get_compile_path($smarty->debug_tpl); if ($smarty->_compile_resource($smarty->debug_tpl, $_compile_path)) { ob_start(); $smarty->_include($_compile_path); $_results = ob_get_contents(); ob_end_clean(); } else { $_results = ''; } $smarty->_compile_id = $_compile_id_orig; $smarty->left_delimiter = $_ldelim_orig; $smarty->right_delimiter = $_rdelim_orig; return $_results; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.display_debug_console.php
PHP
asf20
1,583
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * create full directory structure * * @param string $dir */ // $dir function smarty_core_create_dir_structure($params, &$smarty) { if (!file_exists($params['dir'])) { $_open_basedir_ini = ini_get('open_basedir'); if (DIRECTORY_SEPARATOR=='/') { /* unix-style paths */ $_dir = $params['dir']; $_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY); $_new_dir = (substr($_dir, 0, 1)=='/') ? '/' : getcwd().'/'; if($_use_open_basedir = !empty($_open_basedir_ini)) { $_open_basedirs = explode(':', $_open_basedir_ini); } } else { /* other-style paths */ $_dir = str_replace('\\','/', $params['dir']); $_dir_parts = preg_split('!/+!', $_dir, -1, PREG_SPLIT_NO_EMPTY); if (preg_match('!^((//)|([a-zA-Z]:/))!', $_dir, $_root_dir)) { /* leading "//" for network volume, or "[letter]:/" for full path */ $_new_dir = $_root_dir[1]; /* remove drive-letter from _dir_parts */ if (isset($_root_dir[3])) array_shift($_dir_parts); } else { $_new_dir = str_replace('\\', '/', getcwd()).'/'; } if($_use_open_basedir = !empty($_open_basedir_ini)) { $_open_basedirs = explode(';', str_replace('\\', '/', $_open_basedir_ini)); } } /* all paths use "/" only from here */ foreach ($_dir_parts as $_dir_part) { $_new_dir .= $_dir_part; if ($_use_open_basedir) { // do not attempt to test or make directories outside of open_basedir $_make_new_dir = false; foreach ($_open_basedirs as $_open_basedir) { if (substr($_new_dir, 0, strlen($_open_basedir)) == $_open_basedir) { $_make_new_dir = true; break; } } } else { $_make_new_dir = true; } if ($_make_new_dir && !file_exists($_new_dir) && !@mkdir($_new_dir, $smarty->_dir_perms) && !is_dir($_new_dir)) { $smarty->trigger_error("problem creating directory '" . $_new_dir . "'"); return false; } $_new_dir .= '/'; } } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.create_dir_structure.php
PHP
asf20
2,507
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * determines if a resource is trusted or not * * @param string $resource_type * @param string $resource_name * @return boolean */ // $resource_type, $resource_name function smarty_core_is_trusted($params, &$smarty) { $_smarty_trusted = false; if ($params['resource_type'] == 'file') { if (!empty($smarty->trusted_dir)) { $_rp = realpath($params['resource_name']); foreach ((array)$smarty->trusted_dir as $curr_dir) { if (!empty($curr_dir) && is_readable ($curr_dir)) { $_cd = realpath($curr_dir); if (strncmp($_rp, $_cd, strlen($_cd)) == 0 && substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR ) { $_smarty_trusted = true; break; } } } } } else { // resource is not on local file system $_smarty_trusted = call_user_func_array($smarty->_plugins['resource'][$params['resource_type']][0][3], array($params['resource_name'], $smarty)); } return $_smarty_trusted; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.is_trusted.php
PHP
asf20
1,284
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Extract non-cacheable parts out of compiled template and write it * * @param string $compile_path * @param string $template_compiled * @return boolean */ function smarty_core_write_compiled_include($params, &$smarty) { $_tag_start = 'if \(\$this->caching && \!\$this->_cache_including\)\: echo \'\{nocache\:('.$params['cache_serial'].')#(\d+)\}\'; endif;'; $_tag_end = 'if \(\$this->caching && \!\$this->_cache_including\)\: echo \'\{/nocache\:(\\2)#(\\3)\}\'; endif;'; preg_match_all('!('.$_tag_start.'(.*)'.$_tag_end.')!Us', $params['compiled_content'], $_match_source, PREG_SET_ORDER); // no nocache-parts found: done if (count($_match_source)==0) return; // convert the matched php-code to functions $_include_compiled = "<?php /* Smarty version ".$smarty->_version.", created on ".strftime("%Y-%m-%d %H:%M:%S")."\n"; $_include_compiled .= " compiled from " . strtr(urlencode($params['resource_name']), array('%2F'=>'/', '%3A'=>':')) . " */\n\n"; $_compile_path = $params['include_file_path']; $smarty->_cache_serials[$_compile_path] = $params['cache_serial']; $_include_compiled .= "\$this->_cache_serials['".$_compile_path."'] = '".$params['cache_serial']."';\n\n?>"; $_include_compiled .= $params['plugins_code']; $_include_compiled .= "<?php"; $this_varname = ((double)phpversion() >= 5.0) ? '_smarty' : 'this'; for ($_i = 0, $_for_max = count($_match_source); $_i < $_for_max; $_i++) { $_match =& $_match_source[$_i]; $source = $_match[4]; if ($this_varname == '_smarty') { /* rename $this to $_smarty in the sourcecode */ $tokens = token_get_all('<?php ' . $_match[4]); /* remove trailing <?php */ $open_tag = ''; while ($tokens) { $token = array_shift($tokens); if (is_array($token)) { $open_tag .= $token[1]; } else { $open_tag .= $token; } if ($open_tag == '<?php ') break; } for ($i=0, $count = count($tokens); $i < $count; $i++) { if (is_array($tokens[$i])) { if ($tokens[$i][0] == T_VARIABLE && $tokens[$i][1] == '$this') { $tokens[$i] = '$' . $this_varname; } else { $tokens[$i] = $tokens[$i][1]; } } } $source = implode('', $tokens); } /* add function to compiled include */ $_include_compiled .= " function _smarty_tplfunc_$_match[2]_$_match[3](&\$$this_varname) { $source } "; } $_include_compiled .= "\n\n?>"; $_params = array('filename' => $_compile_path, 'contents' => $_include_compiled, 'create_dirs' => true); require_once(SMARTY_CORE_DIR . 'core.write_file.php'); smarty_core_write_file($_params, $smarty); return true; } ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.write_compiled_include.php
PHP
asf20
3,219
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * load a resource plugin * * @param string $type */ // $type function smarty_core_load_resource_plugin($params, &$smarty) { /* * Resource plugins are not quite like the other ones, so they are * handled differently. The first element of plugin info is the array of * functions provided by the plugin, the second one indicates whether * all of them exist or not. */ $_plugin = &$smarty->_plugins['resource'][$params['type']]; if (isset($_plugin)) { if (!$_plugin[1] && count($_plugin[0])) { $_plugin[1] = true; foreach ($_plugin[0] as $_plugin_func) { if (!is_callable($_plugin_func)) { $_plugin[1] = false; break; } } } if (!$_plugin[1]) { $smarty->_trigger_fatal_error("[plugin] resource '" . $params['type'] . "' is not implemented", null, null, __FILE__, __LINE__); } return; } $_plugin_file = $smarty->_get_plugin_filepath('resource', $params['type']); $_found = ($_plugin_file != false); if ($_found) { /* * If the plugin file is found, it -must- provide the properly named * plugin functions. */ include_once($_plugin_file); /* * Locate functions that we require the plugin to provide. */ $_resource_ops = array('source', 'timestamp', 'secure', 'trusted'); $_resource_funcs = array(); foreach ($_resource_ops as $_op) { $_plugin_func = 'smarty_resource_' . $params['type'] . '_' . $_op; if (!function_exists($_plugin_func)) { $smarty->_trigger_fatal_error("[plugin] function $_plugin_func() not found in $_plugin_file", null, null, __FILE__, __LINE__); return; } else { $_resource_funcs[] = $_plugin_func; } } $smarty->_plugins['resource'][$params['type']] = array($_resource_funcs, true); } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.load_resource_plugin.php
PHP
asf20
2,147
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * delete a dir recursively (level=0 -> keep root) * WARNING: no tests, it will try to remove what you tell it! * * @param string $dirname * @param integer $level * @param integer $exp_time * @return boolean */ // $dirname, $level = 1, $exp_time = null function smarty_core_rmdir($params, &$smarty) { if(!isset($params['level'])) { $params['level'] = 1; } if(!isset($params['exp_time'])) { $params['exp_time'] = null; } if($_handle = @opendir($params['dirname'])) { while (false !== ($_entry = readdir($_handle))) { if ($_entry != '.' && $_entry != '..') { if (@is_dir($params['dirname'] . DIRECTORY_SEPARATOR . $_entry)) { $_params = array( 'dirname' => $params['dirname'] . DIRECTORY_SEPARATOR . $_entry, 'level' => $params['level'] + 1, 'exp_time' => $params['exp_time'] ); smarty_core_rmdir($_params, $smarty); } else { $smarty->_unlink($params['dirname'] . DIRECTORY_SEPARATOR . $_entry, $params['exp_time']); } } } closedir($_handle); } if ($params['level']) { return @rmdir($params['dirname']); } return (bool)$_handle; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.rmdir.php
PHP
asf20
1,498
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Retrieves PHP script resource * * sets $php_resource to the returned resource * @param string $resource * @param string $resource_type * @param $php_resource * @return boolean */ function smarty_core_get_php_resource(&$params, &$smarty) { $params['resource_base_path'] = $smarty->trusted_dir; $smarty->_parse_resource_name($params, $smarty); /* * Find out if the resource exists. */ if ($params['resource_type'] == 'file') { $_readable = false; if(file_exists($params['resource_name']) && is_readable($params['resource_name'])) { $_readable = true; } else { // test for file in include_path $_params = array('file_path' => $params['resource_name']); require_once(SMARTY_CORE_DIR . 'core.get_include_path.php'); if(smarty_core_get_include_path($_params, $smarty)) { $_include_path = $_params['new_file_path']; $_readable = true; } } } else if ($params['resource_type'] != 'file') { $_template_source = null; $_readable = is_callable($smarty->_plugins['resource'][$params['resource_type']][0][0]) && call_user_func_array($smarty->_plugins['resource'][$params['resource_type']][0][0], array($params['resource_name'], &$_template_source, &$smarty)); } /* * Set the error function, depending on which class calls us. */ if (method_exists($smarty, '_syntax_error')) { $_error_funcc = '_syntax_error'; } else { $_error_funcc = 'trigger_error'; } if ($_readable) { if ($smarty->security) { require_once(SMARTY_CORE_DIR . 'core.is_trusted.php'); if (!smarty_core_is_trusted($params, $smarty)) { $smarty->$_error_funcc('(secure mode) ' . $params['resource_type'] . ':' . $params['resource_name'] . ' is not trusted'); return false; } } } else { $smarty->$_error_funcc($params['resource_type'] . ':' . $params['resource_name'] . ' is not readable'); return false; } if ($params['resource_type'] == 'file') { $params['php_resource'] = $params['resource_name']; } else { $params['php_resource'] = $_template_source; } return true; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.get_php_resource.php
PHP
asf20
2,467
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Replace cached inserts with the actual results * * @param string $results * @return string */ function smarty_core_process_cached_inserts($params, &$smarty) { preg_match_all('!'.$smarty->_smarty_md5.'{insert_cache (.*)}'.$smarty->_smarty_md5.'!Uis', $params['results'], $match); list($cached_inserts, $insert_args) = $match; for ($i = 0, $for_max = count($cached_inserts); $i < $for_max; $i++) { if ($smarty->debugging) { $_params = array(); require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); $debug_start_time = smarty_core_get_microtime($_params, $smarty); } $args = unserialize($insert_args[$i]); $name = $args['name']; if (isset($args['script'])) { $_params = array('resource_name' => $smarty->_dequote($args['script'])); require_once(SMARTY_CORE_DIR . 'core.get_php_resource.php'); if(!smarty_core_get_php_resource($_params, $smarty)) { return false; } $resource_type = $_params['resource_type']; $php_resource = $_params['php_resource']; if ($resource_type == 'file') { $smarty->_include($php_resource, true); } else { $smarty->_eval($php_resource); } } $function_name = $smarty->_plugins['insert'][$name][0]; if (empty($args['assign'])) { $replace = $function_name($args, $smarty); } else { $smarty->assign($args['assign'], $function_name($args, $smarty)); $replace = ''; } $params['results'] = substr_replace($params['results'], $replace, strpos($params['results'], $cached_inserts[$i]), strlen($cached_inserts[$i])); if ($smarty->debugging) { $_params = array(); require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); $smarty->_smarty_debug_info[] = array('type' => 'insert', 'filename' => 'insert_'.$name, 'depth' => $smarty->_inclusion_depth, 'exec_time' => smarty_core_get_microtime($_params, $smarty) - $debug_start_time); } } return $params['results']; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.process_cached_inserts.php
PHP
asf20
2,464
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * called for included php files within templates * * @param string $smarty_file * @param string $smarty_assign variable to assign the included template's * output into * @param boolean $smarty_once uses include_once if this is true * @param array $smarty_include_vars associative array of vars from * {include file="blah" var=$var} */ // $file, $assign, $once, $_smarty_include_vars function smarty_core_smarty_include_php($params, &$smarty) { $_params = array('resource_name' => $params['smarty_file']); require_once(SMARTY_CORE_DIR . 'core.get_php_resource.php'); smarty_core_get_php_resource($_params, $smarty); $_smarty_resource_type = $_params['resource_type']; $_smarty_php_resource = $_params['php_resource']; if (!empty($params['smarty_assign'])) { ob_start(); if ($_smarty_resource_type == 'file') { $smarty->_include($_smarty_php_resource, $params['smarty_once'], $params['smarty_include_vars']); } else { $smarty->_eval($_smarty_php_resource, $params['smarty_include_vars']); } $smarty->assign($params['smarty_assign'], ob_get_contents()); ob_end_clean(); } else { if ($_smarty_resource_type == 'file') { $smarty->_include($_smarty_php_resource, $params['smarty_once'], $params['smarty_include_vars']); } else { $smarty->_eval($_smarty_php_resource, $params['smarty_include_vars']); } } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.smarty_include_php.php
PHP
asf20
1,602
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * delete an automagically created file by name and id * * @param string $auto_base * @param string $auto_source * @param string $auto_id * @param integer $exp_time * @return boolean */ // $auto_base, $auto_source = null, $auto_id = null, $exp_time = null function smarty_core_rm_auto($params, &$smarty) { if (!@is_dir($params['auto_base'])) return false; if(!isset($params['auto_id']) && !isset($params['auto_source'])) { $_params = array( 'dirname' => $params['auto_base'], 'level' => 0, 'exp_time' => $params['exp_time'] ); require_once(SMARTY_CORE_DIR . 'core.rmdir.php'); $_res = smarty_core_rmdir($_params, $smarty); } else { $_tname = $smarty->_get_auto_filename($params['auto_base'], $params['auto_source'], $params['auto_id']); if(isset($params['auto_source'])) { if (isset($params['extensions'])) { $_res = false; foreach ((array)$params['extensions'] as $_extension) $_res |= $smarty->_unlink($_tname.$_extension, $params['exp_time']); } else { $_res = $smarty->_unlink($_tname, $params['exp_time']); } } elseif ($smarty->use_sub_dirs) { $_params = array( 'dirname' => $_tname, 'level' => 1, 'exp_time' => $params['exp_time'] ); require_once(SMARTY_CORE_DIR . 'core.rmdir.php'); $_res = smarty_core_rmdir($_params, $smarty); } else { // remove matching file names $_handle = opendir($params['auto_base']); $_res = true; while (false !== ($_filename = readdir($_handle))) { if($_filename == '.' || $_filename == '..') { continue; } elseif (substr($params['auto_base'] . DIRECTORY_SEPARATOR . $_filename, 0, strlen($_tname)) == $_tname) { $_res &= (bool)$smarty->_unlink($params['auto_base'] . DIRECTORY_SEPARATOR . $_filename, $params['exp_time']); } } } } return $_res; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.rm_auto.php
PHP
asf20
2,357
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * assemble filepath of requested plugin * * @param string $type * @param string $name * @return string|false */ function smarty_core_assemble_plugin_filepath($params, &$smarty) { static $_filepaths_cache = array(); $_plugin_filename = $params['type'] . '.' . $params['name'] . '.php'; if (isset($_filepaths_cache[$_plugin_filename])) { return $_filepaths_cache[$_plugin_filename]; } $_return = false; foreach ((array)$smarty->plugins_dir as $_plugin_dir) { $_plugin_filepath = $_plugin_dir . DIRECTORY_SEPARATOR . $_plugin_filename; // see if path is relative if (!preg_match("/^([\/\\\\]|[a-zA-Z]:[\/\\\\])/", $_plugin_dir)) { $_relative_paths[] = $_plugin_dir; // relative path, see if it is in the SMARTY_DIR if (@is_readable(SMARTY_DIR . $_plugin_filepath)) { $_return = SMARTY_DIR . $_plugin_filepath; break; } } // try relative to cwd (or absolute) if (@is_readable($_plugin_filepath)) { $_return = $_plugin_filepath; break; } } if($_return === false) { // still not found, try PHP include_path if(isset($_relative_paths)) { foreach ((array)$_relative_paths as $_plugin_dir) { $_plugin_filepath = $_plugin_dir . DIRECTORY_SEPARATOR . $_plugin_filename; $_params = array('file_path' => $_plugin_filepath); require_once(SMARTY_CORE_DIR . 'core.get_include_path.php'); if(smarty_core_get_include_path($_params, $smarty)) { $_return = $_params['new_file_path']; break; } } } } $_filepaths_cache[$_plugin_filename] = $_return; return $_return; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.assemble_plugin_filepath.php
PHP
asf20
1,949
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * write out a file to disk * * @param string $filename * @param string $contents * @param boolean $create_dirs * @return boolean */ function smarty_core_write_file($params, &$smarty) { $_dirname = dirname($params['filename']); if ($params['create_dirs']) { $_params = array('dir' => $_dirname); require_once(SMARTY_CORE_DIR . 'core.create_dir_structure.php'); smarty_core_create_dir_structure($_params, $smarty); } // write to tmp file, then rename it to avoid file locking race condition $_tmp_file = tempnam($_dirname, 'wrt'); if (!($fd = @fopen($_tmp_file, 'wb'))) { $_tmp_file = $_dirname . DIRECTORY_SEPARATOR . uniqid('wrt'); if (!($fd = @fopen($_tmp_file, 'wb'))) { $smarty->trigger_error("problem writing temporary file '$_tmp_file'"); return false; } } fwrite($fd, $params['contents']); fclose($fd); if (DIRECTORY_SEPARATOR == '\\' || !@rename($_tmp_file, $params['filename'])) { // On platforms and filesystems that cannot overwrite with rename() // delete the file before renaming it -- because windows always suffers // this, it is short-circuited to avoid the initial rename() attempt @unlink($params['filename']); @rename($_tmp_file, $params['filename']); } @chmod($params['filename'], $smarty->_file_perms); return true; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.write_file.php
PHP
asf20
1,577
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Get path to file from include_path * * @param string $file_path * @param string $new_file_path * @return boolean * @staticvar array|null */ // $file_path, &$new_file_path function smarty_core_get_include_path(&$params, &$smarty) { static $_path_array = null; if(!isset($_path_array)) { $_ini_include_path = ini_get('include_path'); if(strstr($_ini_include_path,';')) { // windows pathnames $_path_array = explode(';',$_ini_include_path); } else { $_path_array = explode(':',$_ini_include_path); } } foreach ($_path_array as $_include_path) { if (@is_readable($_include_path . DIRECTORY_SEPARATOR . $params['file_path'])) { $params['new_file_path'] = $_include_path . DIRECTORY_SEPARATOR . $params['file_path']; return true; } } return false; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.get_include_path.php
PHP
asf20
1,002
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Replace nocache-tags by results of the corresponding non-cacheable * functions and return it * * @param string $compiled_tpl * @param string $cached_source * @return string */ function smarty_core_process_compiled_include($params, &$smarty) { $_cache_including = $smarty->_cache_including; $smarty->_cache_including = true; $_return = $params['results']; foreach ($smarty->_cache_info['cache_serials'] as $_include_file_path=>$_cache_serial) { $smarty->_include($_include_file_path, true); } foreach ($smarty->_cache_info['cache_serials'] as $_include_file_path=>$_cache_serial) { $_return = preg_replace_callback('!(\{nocache\:('.$_cache_serial.')#(\d+)\})!s', array(&$smarty, '_process_compiled_include_callback'), $_return); } $smarty->_cache_including = $_cache_including; return $_return; } ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.process_compiled_include.php
PHP
asf20
1,025
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Get seconds and microseconds * @return double */ function smarty_core_get_microtime($params, &$smarty) { $mtime = microtime(); $mtime = explode(" ", $mtime); $mtime = (double)($mtime[1]) + (double)($mtime[0]); return ($mtime); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.get_microtime.php
PHP
asf20
360
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty assign_smarty_interface core plugin * * Type: core<br> * Name: assign_smarty_interface<br> * Purpose: assign the $smarty interface variable * @param array Format: null * @param Smarty */ function smarty_core_assign_smarty_interface($params, &$smarty) { if (isset($smarty->_smarty_vars) && isset($smarty->_smarty_vars['request'])) { return; } $_globals_map = array('g' => 'HTTP_GET_VARS', 'p' => 'HTTP_POST_VARS', 'c' => 'HTTP_COOKIE_VARS', 's' => 'HTTP_SERVER_VARS', 'e' => 'HTTP_ENV_VARS'); $_smarty_vars_request = array(); foreach (preg_split('!!', strtolower($smarty->request_vars_order)) as $_c) { if (isset($_globals_map[$_c])) { $_smarty_vars_request = array_merge($_smarty_vars_request, $GLOBALS[$_globals_map[$_c]]); } } $_smarty_vars_request = @array_merge($_smarty_vars_request, $GLOBALS['HTTP_SESSION_VARS']); $smarty->_smarty_vars['request'] = $_smarty_vars_request; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.assign_smarty_interface.php
PHP
asf20
1,258
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Prepend the cache information to the cache file * and write it * * @param string $tpl_file * @param string $cache_id * @param string $compile_id * @param string $results * @return true|null */ // $tpl_file, $cache_id, $compile_id, $results function smarty_core_write_cache_file($params, &$smarty) { // put timestamp in cache header $smarty->_cache_info['timestamp'] = time(); if ($smarty->cache_lifetime > -1){ // expiration set $smarty->_cache_info['expires'] = $smarty->_cache_info['timestamp'] + $smarty->cache_lifetime; } else { // cache will never expire $smarty->_cache_info['expires'] = -1; } // collapse nocache.../nocache-tags if (preg_match_all('!\{(/?)nocache\:[0-9a-f]{32}#\d+\}!', $params['results'], $match, PREG_PATTERN_ORDER)) { // remove everything between every pair of outermost noache.../nocache-tags // and replace it by a single nocache-tag // this new nocache-tag will be replaced by dynamic contents in // smarty_core_process_compiled_includes() on a cache-read $match_count = count($match[0]); $results = preg_split('!(\{/?nocache\:[0-9a-f]{32}#\d+\})!', $params['results'], -1, PREG_SPLIT_DELIM_CAPTURE); $level = 0; $j = 0; for ($i=0, $results_count = count($results); $i < $results_count && $j < $match_count; $i++) { if ($results[$i] == $match[0][$j]) { // nocache tag if ($match[1][$j]) { // closing tag $level--; unset($results[$i]); } else { // opening tag if ($level++ > 0) unset($results[$i]); } $j++; } elseif ($level > 0) { unset($results[$i]); } } $params['results'] = implode('', $results); } $smarty->_cache_info['cache_serials'] = $smarty->_cache_serials; // prepend the cache header info into cache file $_cache_info = serialize($smarty->_cache_info); $params['results'] = strlen($_cache_info) . "\n" . $_cache_info . $params['results']; if (!empty($smarty->cache_handler_func)) { // use cache_handler function call_user_func_array($smarty->cache_handler_func, array('write', &$smarty, &$params['results'], $params['tpl_file'], $params['cache_id'], $params['compile_id'], $smarty->_cache_info['expires'])); } else { // use local cache file if(!@is_writable($smarty->cache_dir)) { // cache_dir not writable, see if it exists if(!@is_dir($smarty->cache_dir)) { $smarty->trigger_error('the $cache_dir \'' . $smarty->cache_dir . '\' does not exist, or is not a directory.', E_USER_ERROR); return false; } $smarty->trigger_error('unable to write to $cache_dir \'' . realpath($smarty->cache_dir) . '\'. Be sure $cache_dir is writable by the web server user.', E_USER_ERROR); return false; } $_auto_id = $smarty->_get_auto_id($params['cache_id'], $params['compile_id']); $_cache_file = $smarty->_get_auto_filename($smarty->cache_dir, $params['tpl_file'], $_auto_id); $_params = array('filename' => $_cache_file, 'contents' => $params['results'], 'create_dirs' => true); require_once(SMARTY_CORE_DIR . 'core.write_file.php'); smarty_core_write_file($_params, $smarty); return true; } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.write_cache_file.php
PHP
asf20
3,647
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Load requested plugins * * @param array $plugins */ // $plugins function smarty_core_load_plugins($params, &$smarty) { foreach ($params['plugins'] as $_plugin_info) { list($_type, $_name, $_tpl_file, $_tpl_line, $_delayed_loading) = $_plugin_info; $_plugin = &$smarty->_plugins[$_type][$_name]; /* * We do not load plugin more than once for each instance of Smarty. * The following code checks for that. The plugin can also be * registered dynamically at runtime, in which case template file * and line number will be unknown, so we fill them in. * * The final element of the info array is a flag that indicates * whether the dynamically registered plugin function has been * checked for existence yet or not. */ if (isset($_plugin)) { if (empty($_plugin[3])) { if (!is_callable($_plugin[0])) { $smarty->_trigger_fatal_error("[plugin] $_type '$_name' is not implemented", $_tpl_file, $_tpl_line, __FILE__, __LINE__); } else { $_plugin[1] = $_tpl_file; $_plugin[2] = $_tpl_line; $_plugin[3] = true; if (!isset($_plugin[4])) $_plugin[4] = true; /* cacheable */ } } continue; } else if ($_type == 'insert') { /* * For backwards compatibility, we check for insert functions in * the symbol table before trying to load them as a plugin. */ $_plugin_func = 'insert_' . $_name; if (function_exists($_plugin_func)) { $_plugin = array($_plugin_func, $_tpl_file, $_tpl_line, true, false); continue; } } $_plugin_file = $smarty->_get_plugin_filepath($_type, $_name); if (! $_found = ($_plugin_file != false)) { $_message = "could not load plugin file '$_type.$_name.php'\n"; } /* * If plugin file is found, it -must- provide the properly named * plugin function. In case it doesn't, simply output the error and * do not fall back on any other method. */ if ($_found) { include_once $_plugin_file; $_plugin_func = 'smarty_' . $_type . '_' . $_name; if (!function_exists($_plugin_func)) { $smarty->_trigger_fatal_error("[plugin] function $_plugin_func() not found in $_plugin_file", $_tpl_file, $_tpl_line, __FILE__, __LINE__); continue; } } /* * In case of insert plugins, their code may be loaded later via * 'script' attribute. */ else if ($_type == 'insert' && $_delayed_loading) { $_plugin_func = 'smarty_' . $_type . '_' . $_name; $_found = true; } /* * Plugin specific processing and error checking. */ if (!$_found) { if ($_type == 'modifier') { /* * In case modifier falls back on using PHP functions * directly, we only allow those specified in the security * context. */ if ($smarty->security && !in_array($_name, $smarty->security_settings['MODIFIER_FUNCS'])) { $_message = "(secure mode) modifier '$_name' is not allowed"; } else { if (!function_exists($_name)) { $_message = "modifier '$_name' is not implemented"; } else { $_plugin_func = $_name; $_found = true; } } } else if ($_type == 'function') { /* * This is a catch-all situation. */ $_message = "unknown tag - '$_name'"; } } if ($_found) { $smarty->_plugins[$_type][$_name] = array($_plugin_func, $_tpl_file, $_tpl_line, true, true); } else { // output error $smarty->_trigger_fatal_error('[plugin] ' . $_message, $_tpl_file, $_tpl_line, __FILE__, __LINE__); } } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.load_plugins.php
PHP
asf20
4,429
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * read a cache file, determine if it needs to be * regenerated or not * * @param string $tpl_file * @param string $cache_id * @param string $compile_id * @param string $results * @return boolean */ // $tpl_file, $cache_id, $compile_id, &$results function smarty_core_read_cache_file(&$params, &$smarty) { static $content_cache = array(); if ($smarty->force_compile) { // force compile enabled, always regenerate return false; } if (isset($content_cache[$params['tpl_file'].','.$params['cache_id'].','.$params['compile_id']])) { list($params['results'], $smarty->_cache_info) = $content_cache[$params['tpl_file'].','.$params['cache_id'].','.$params['compile_id']]; return true; } if (!empty($smarty->cache_handler_func)) { // use cache_handler function call_user_func_array($smarty->cache_handler_func, array('read', &$smarty, &$params['results'], $params['tpl_file'], $params['cache_id'], $params['compile_id'], null)); } else { // use local cache file $_auto_id = $smarty->_get_auto_id($params['cache_id'], $params['compile_id']); $_cache_file = $smarty->_get_auto_filename($smarty->cache_dir, $params['tpl_file'], $_auto_id); $params['results'] = $smarty->_read_file($_cache_file); } if (empty($params['results'])) { // nothing to parse (error?), regenerate cache return false; } $_contents = $params['results']; $_info_start = strpos($_contents, "\n") + 1; $_info_len = (int)substr($_contents, 0, $_info_start - 1); $_cache_info = unserialize(substr($_contents, $_info_start, $_info_len)); $params['results'] = substr($_contents, $_info_start + $_info_len); if ($smarty->caching == 2 && isset ($_cache_info['expires'])){ // caching by expiration time if ($_cache_info['expires'] > -1 && (time() > $_cache_info['expires'])) { // cache expired, regenerate return false; } } else { // caching by lifetime if ($smarty->cache_lifetime > -1 && (time() - $_cache_info['timestamp'] > $smarty->cache_lifetime)) { // cache expired, regenerate return false; } } if ($smarty->compile_check) { $_params = array('get_source' => false, 'quiet'=>true); foreach (array_keys($_cache_info['template']) as $_template_dep) { $_params['resource_name'] = $_template_dep; if (!$smarty->_fetch_resource_info($_params) || $_cache_info['timestamp'] < $_params['resource_timestamp']) { // template file has changed, regenerate cache return false; } } if (isset($_cache_info['config'])) { $_params = array('resource_base_path' => $smarty->config_dir, 'get_source' => false, 'quiet'=>true); foreach (array_keys($_cache_info['config']) as $_config_dep) { $_params['resource_name'] = $_config_dep; if (!$smarty->_fetch_resource_info($_params) || $_cache_info['timestamp'] < $_params['resource_timestamp']) { // config file has changed, regenerate cache return false; } } } } $content_cache[$params['tpl_file'].','.$params['cache_id'].','.$params['compile_id']] = array($params['results'], $_cache_info); $smarty->_cache_info = $_cache_info; return true; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.read_cache_file.php
PHP
asf20
3,604
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * determines if a resource is secure or not. * * @param string $resource_type * @param string $resource_name * @return boolean */ // $resource_type, $resource_name function smarty_core_is_secure($params, &$smarty) { if (!$smarty->security || $smarty->security_settings['INCLUDE_ANY']) { return true; } if ($params['resource_type'] == 'file') { $_rp = realpath($params['resource_name']); if (isset($params['resource_base_path'])) { foreach ((array)$params['resource_base_path'] as $curr_dir) { if ( ($_cd = realpath($curr_dir)) !== false && strncmp($_rp, $_cd, strlen($_cd)) == 0 && substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR ) { return true; } } } if (!empty($smarty->secure_dir)) { foreach ((array)$smarty->secure_dir as $curr_dir) { if ( ($_cd = realpath($curr_dir)) !== false) { if($_cd == $_rp) { return true; } elseif (strncmp($_rp, $_cd, strlen($_cd)) == 0 && substr($_rp, strlen($_cd), 1) == DIRECTORY_SEPARATOR) { return true; } } } } } else { // resource is not on local file system return call_user_func_array( $smarty->_plugins['resource'][$params['resource_type']][0][2], array($params['resource_name'], &$smarty)); } return false; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.is_secure.php
PHP
asf20
1,694
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Handle insert tags * * @param array $args * @return string */ function smarty_core_run_insert_handler($params, &$smarty) { require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); if ($smarty->debugging) { $_params = array(); $_debug_start_time = smarty_core_get_microtime($_params, $smarty); } if ($smarty->caching) { $_arg_string = serialize($params['args']); $_name = $params['args']['name']; if (!isset($smarty->_cache_info['insert_tags'][$_name])) { $smarty->_cache_info['insert_tags'][$_name] = array('insert', $_name, $smarty->_plugins['insert'][$_name][1], $smarty->_plugins['insert'][$_name][2], !empty($params['args']['script']) ? true : false); } return $smarty->_smarty_md5."{insert_cache $_arg_string}".$smarty->_smarty_md5; } else { if (isset($params['args']['script'])) { $_params = array('resource_name' => $smarty->_dequote($params['args']['script'])); require_once(SMARTY_CORE_DIR . 'core.get_php_resource.php'); if(!smarty_core_get_php_resource($_params, $smarty)) { return false; } if ($_params['resource_type'] == 'file') { $smarty->_include($_params['php_resource'], true); } else { $smarty->_eval($_params['php_resource']); } unset($params['args']['script']); } $_funcname = $smarty->_plugins['insert'][$params['args']['name']][0]; $_content = $_funcname($params['args'], $smarty); if ($smarty->debugging) { $_params = array(); require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); $smarty->_smarty_debug_info[] = array('type' => 'insert', 'filename' => 'insert_'.$params['args']['name'], 'depth' => $smarty->_inclusion_depth, 'exec_time' => smarty_core_get_microtime($_params, $smarty) - $_debug_start_time); } if (!empty($params['args']["assign"])) { $smarty->assign($params['args']["assign"], $_content); } else { return $_content; } } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.run_insert_handler.php
PHP
asf20
2,656
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * write the compiled resource * * @param string $compile_path * @param string $compiled_content * @return true */ function smarty_core_write_compiled_resource($params, &$smarty) { if(!@is_writable($smarty->compile_dir)) { // compile_dir not writable, see if it exists if(!@is_dir($smarty->compile_dir)) { $smarty->trigger_error('the $compile_dir \'' . $smarty->compile_dir . '\' does not exist, or is not a directory.', E_USER_ERROR); return false; } $smarty->trigger_error('unable to write to $compile_dir \'' . realpath($smarty->compile_dir) . '\'. Be sure $compile_dir is writable by the web server user.', E_USER_ERROR); return false; } $_params = array('filename' => $params['compile_path'], 'contents' => $params['compiled_content'], 'create_dirs' => true); require_once(SMARTY_CORE_DIR . 'core.write_file.php'); smarty_core_write_file($_params, $smarty); return true; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/internals/core.write_compiled_resource.php
PHP
asf20
1,081
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {config_load} function plugin * * Type: function<br> * Name: config_load<br> * Purpose: load config file vars * @link http://smarty.php.net/manual/en/language.function.config.load.php {config_load} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @author messju mohr <messju at lammfellpuschen dot de> (added use of resources) * @param array Format: * <pre> * array('file' => required config file name, * 'section' => optional config file section to load * 'scope' => local/parent/global * 'global' => overrides scope, setting to parent if true) * </pre> * @param Smarty */ function smarty_function_config_load($params, &$smarty) { if ($smarty->debugging) { $_params = array(); require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); $_debug_start_time = smarty_core_get_microtime($_params, $smarty); } $_file = isset($params['file']) ? $smarty->_dequote($params['file']) : null; $_section = isset($params['section']) ? $smarty->_dequote($params['section']) : null; $_scope = isset($params['scope']) ? $smarty->_dequote($params['scope']) : 'global'; $_global = isset($params['global']) ? $smarty->_dequote($params['global']) : false; if (!isset($_file) || strlen($_file) == 0) { $smarty->trigger_error("missing 'file' attribute in config_load tag", E_USER_ERROR, __FILE__, __LINE__); } if (isset($_scope)) { if ($_scope != 'local' && $_scope != 'parent' && $_scope != 'global') { $smarty->trigger_error("invalid 'scope' attribute value", E_USER_ERROR, __FILE__, __LINE__); } } else { if ($_global) { $_scope = 'parent'; } else { $_scope = 'local'; } } $_params = array('resource_name' => $_file, 'resource_base_path' => $smarty->config_dir, 'get_source' => false); $smarty->_parse_resource_name($_params); $_file_path = $_params['resource_type'] . ':' . $_params['resource_name']; if (isset($_section)) $_compile_file = $smarty->_get_compile_path($_file_path.'|'.$_section); else $_compile_file = $smarty->_get_compile_path($_file_path); if($smarty->force_compile || !file_exists($_compile_file)) { $_compile = true; } elseif ($smarty->compile_check) { $_params = array('resource_name' => $_file, 'resource_base_path' => $smarty->config_dir, 'get_source' => false); $_compile = $smarty->_fetch_resource_info($_params) && $_params['resource_timestamp'] > filemtime($_compile_file); } else { $_compile = false; } if($_compile) { // compile config file if(!is_object($smarty->_conf_obj)) { require_once SMARTY_DIR . $smarty->config_class . '.class.php'; $smarty->_conf_obj = new $smarty->config_class(); $smarty->_conf_obj->overwrite = $smarty->config_overwrite; $smarty->_conf_obj->booleanize = $smarty->config_booleanize; $smarty->_conf_obj->read_hidden = $smarty->config_read_hidden; $smarty->_conf_obj->fix_newlines = $smarty->config_fix_newlines; } $_params = array('resource_name' => $_file, 'resource_base_path' => $smarty->config_dir, $_params['get_source'] = true); if (!$smarty->_fetch_resource_info($_params)) { return; } $smarty->_conf_obj->set_file_contents($_file, $_params['source_content']); $_config_vars = array_merge($smarty->_conf_obj->get($_file), $smarty->_conf_obj->get($_file, $_section)); if(function_exists('var_export')) { $_output = '<?php $_config_vars = ' . var_export($_config_vars, true) . '; ?>'; } else { $_output = '<?php $_config_vars = unserialize(\'' . strtr(serialize($_config_vars),array('\''=>'\\\'', '\\'=>'\\\\')) . '\'); ?>'; } $_params = (array('compile_path' => $_compile_file, 'compiled_content' => $_output, 'resource_timestamp' => $_params['resource_timestamp'])); require_once(SMARTY_CORE_DIR . 'core.write_compiled_resource.php'); smarty_core_write_compiled_resource($_params, $smarty); } else { include($_compile_file); } if ($smarty->caching) { $smarty->_cache_info['config'][$_file] = true; } $smarty->_config[0]['vars'] = @array_merge($smarty->_config[0]['vars'], $_config_vars); $smarty->_config[0]['files'][$_file] = true; if ($_scope == 'parent') { $smarty->_config[1]['vars'] = @array_merge($smarty->_config[1]['vars'], $_config_vars); $smarty->_config[1]['files'][$_file] = true; } else if ($_scope == 'global') { for ($i = 1, $for_max = count($smarty->_config); $i < $for_max; $i++) { $smarty->_config[$i]['vars'] = @array_merge($smarty->_config[$i]['vars'], $_config_vars); $smarty->_config[$i]['files'][$_file] = true; } } if ($smarty->debugging) { $_params = array(); require_once(SMARTY_CORE_DIR . 'core.get_microtime.php'); $smarty->_smarty_debug_info[] = array('type' => 'config', 'filename' => $_file.' ['.$_section.'] '.$_scope, 'depth' => $smarty->_inclusion_depth, 'exec_time' => smarty_core_get_microtime($_params, $smarty) - $_debug_start_time); } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.config_load.php
PHP
asf20
6,158
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_table} function plugin * * Type: function<br> * Name: html_table<br> * Date: Feb 17, 2003<br> * Purpose: make an html table from an array of data<br> * Input:<br> * - loop = array to loop through * - cols = number of categorys, comma separated list of category names * or array of category names * - rows = number of rows * - table_attr = table attributes * - th_attr = table heading attributes (arrays are cycled) * - tr_attr = table row attributes (arrays are cycled) * - td_attr = table cell attributes (arrays are cycled) * - trailpad = value to pad trailing cells with * - caption = text for caption element * - vdir = vertical direction (default: "down", means top-to-bottom) * - hdir = horizontal direction (default: "right", means left-to-right) * - inner = inner loop (default "cols": print $loop line by line, * $loop will be printed category by category otherwise) * * * Examples: * <pre> * {table loop=$data} * {table loop=$data cols=4 tr_attr='"bgcolor=red"'} * {table loop=$data cols="first,second,third" tr_attr=$colors} * </pre> * @author Monte Ohrt <monte at ohrt dot com> * @author credit to Messju Mohr <messju at lammfellpuschen dot de> * @author credit to boots <boots dot smarty at yahoo dot com> * @version 1.1 * @link http://smarty.php.net/manual/en/language.function.html.table.php {html_table} * (Smarty online manual) * @param array * @param Smarty * @return string */ function smarty_function_html_table($params, &$smarty) { $table_attr = 'border="1"'; $tr_attr = ''; $th_attr = ''; $td_attr = ''; $cols = $cols_count = 3; $rows = 3; $trailpad = '&nbsp;'; $vdir = 'down'; $hdir = 'right'; $inner = 'cols'; $caption = ''; if (!isset($params['loop'])) { $smarty->trigger_error("html_table: missing 'loop' parameter"); return; } foreach ($params as $_key=>$_value) { switch ($_key) { case 'loop': $$_key = (array)$_value; break; case 'cols': if (is_array($_value) && !empty($_value)) { $cols = $_value; $cols_count = count($_value); } elseif (!is_numeric($_value) && is_string($_value) && !empty($_value)) { $cols = explode(',', $_value); $cols_count = count($cols); } elseif (!empty($_value)) { $cols_count = (int)$_value; } else { $cols_count = $cols; } break; case 'rows': $$_key = (int)$_value; break; case 'table_attr': case 'trailpad': case 'hdir': case 'vdir': case 'inner': case 'caption': $$_key = (string)$_value; break; case 'tr_attr': case 'td_attr': case 'th_attr': $$_key = $_value; break; } } $loop_count = count($loop); if (empty($params['rows'])) { /* no rows specified */ $rows = ceil($loop_count/$cols_count); } elseif (empty($params['cols'])) { if (!empty($params['rows'])) { /* no cols specified, but rows */ $cols_count = ceil($loop_count/$rows); } } $output = "<table $table_attr>\n"; if (!empty($caption)) { $output .= '<caption>' . $caption . "</caption>\n"; } if (is_array($cols)) { $cols = ($hdir == 'right') ? $cols : array_reverse($cols); $output .= "<thead><tr>\n"; for ($r=0; $r<$cols_count; $r++) { $output .= '<th' . smarty_function_html_table_cycle('th', $th_attr, $r) . '>'; $output .= $cols[$r]; $output .= "</th>\n"; } $output .= "</tr></thead>\n"; } $output .= "<tbody>\n"; for ($r=0; $r<$rows; $r++) { $output .= "<tr" . smarty_function_html_table_cycle('tr', $tr_attr, $r) . ">\n"; $rx = ($vdir == 'down') ? $r*$cols_count : ($rows-1-$r)*$cols_count; for ($c=0; $c<$cols_count; $c++) { $x = ($hdir == 'right') ? $rx+$c : $rx+$cols_count-1-$c; if ($inner!='cols') { /* shuffle x to loop over rows*/ $x = floor($x/$cols_count) + ($x%$cols_count)*$rows; } if ($x<$loop_count) { $output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">" . $loop[$x] . "</td>\n"; } else { $output .= "<td" . smarty_function_html_table_cycle('td', $td_attr, $c) . ">$trailpad</td>\n"; } } $output .= "</tr>\n"; } $output .= "</tbody>\n"; $output .= "</table>\n"; return $output; } function smarty_function_html_table_cycle($name, $var, $no) { if(!is_array($var)) { $ret = $var; } else { $ret = $var[$no % count($var)]; } return ($ret) ? ' '.$ret : ''; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.html_table.php
PHP
asf20
5,530
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {assign} compiler function plugin * * Type: compiler function<br> * Name: assign<br> * Purpose: assign a value to a template variable * @link http://smarty.php.net/manual/en/language.custom.functions.php#LANGUAGE.FUNCTION.ASSIGN {assign} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> (initial author) * @author messju mohr <messju at lammfellpuschen dot de> (conversion to compiler function) * @param string containing var-attribute and value-attribute * @param Smarty_Compiler */ function smarty_compiler_assign($tag_attrs, &$compiler) { $_params = $compiler->_parse_attrs($tag_attrs); if (!isset($_params['var'])) { $compiler->_syntax_error("assign: missing 'var' parameter", E_USER_WARNING); return; } if (!isset($_params['value'])) { $compiler->_syntax_error("assign: missing 'value' parameter", E_USER_WARNING); return; } return "\$this->assign({$_params['var']}, {$_params['value']});"; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/compiler.assign.php
PHP
asf20
1,123
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty count_words modifier plugin * * Type: modifier<br> * Name: count_words<br> * Purpose: count the number of words in a text * @link http://smarty.php.net/manual/en/language.modifier.count.words.php * count_words (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return integer */ function smarty_modifier_count_words($string) { // split text by ' ',\r,\n,\f,\t $split_array = preg_split('/\s+/',$string); // count matches that contain alphanumerics $word_count = preg_grep('/[a-zA-Z0-9\\x80-\\xff]/', $split_array); return count($word_count); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.count_words.php
PHP
asf20
751
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty count_sentences modifier plugin * * Type: modifier<br> * Name: count_sentences * Purpose: count the number of sentences in a text * @link http://smarty.php.net/manual/en/language.modifier.count.paragraphs.php * count_sentences (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return integer */ function smarty_modifier_count_sentences($string) { // find periods with a word before but not after. return preg_match_all('/[^\s]\.(?!\w)/', $string, $match); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.count_sentences.php
PHP
asf20
653
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_checkboxes} function plugin * * File: function.html_checkboxes.php<br> * Type: function<br> * Name: html_checkboxes<br> * Date: 24.Feb.2003<br> * Purpose: Prints out a list of checkbox input types<br> * Input:<br> * - name (optional) - string default "checkbox" * - values (required) - array * - options (optional) - associative array * - checked (optional) - array default not set * - separator (optional) - ie <br> or &nbsp; * - output (optional) - the output next to each checkbox * - assign (optional) - assign the output as an array to this variable * Examples: * <pre> * {html_checkboxes values=$ids output=$names} * {html_checkboxes values=$ids name='box' separator='<br>' output=$names} * {html_checkboxes values=$ids checked=$checked separator='<br>' output=$names} * </pre> * @link http://smarty.php.net/manual/en/language.function.html.checkboxes.php {html_checkboxes} * (Smarty online manual) * @author Christopher Kvarme <christopher.kvarme@flashjab.com> * @author credits to Monte Ohrt <monte at ohrt dot com> * @version 1.0 * @param array * @param Smarty * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_checkboxes($params, &$smarty) { require_once $smarty->_get_plugin_filepath('shared','escape_special_chars'); $name = 'checkbox'; $values = null; $options = null; $selected = null; $separator = ''; $labels = true; $output = null; $extra = ''; foreach($params as $_key => $_val) { switch($_key) { case 'name': case 'separator': $$_key = $_val; break; case 'labels': $$_key = (bool)$_val; break; case 'options': $$_key = (array)$_val; break; case 'values': case 'output': $$_key = array_values((array)$_val); break; case 'checked': case 'selected': $selected = array_map('strval', array_values((array)$_val)); break; case 'checkboxes': $smarty->trigger_error('html_checkboxes: the use of the "checkboxes" attribute is deprecated, use "options" instead', E_USER_WARNING); $options = (array)$_val; break; case 'assign': break; default: if(!is_array($_val)) { $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"'; } else { $smarty->trigger_error("html_checkboxes: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (!isset($options) && !isset($values)) return ''; /* raise error here? */ settype($selected, 'array'); $_html_result = array(); if (isset($options)) { foreach ($options as $_key=>$_val) $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels); } else { foreach ($values as $_i=>$_key) { $_val = isset($output[$_i]) ? $output[$_i] : ''; $_html_result[] = smarty_function_html_checkboxes_output($name, $_key, $_val, $selected, $extra, $separator, $labels); } } if(!empty($params['assign'])) { $smarty->assign($params['assign'], $_html_result); } else { return implode("\n",$_html_result); } } function smarty_function_html_checkboxes_output($name, $value, $output, $selected, $extra, $separator, $labels) { $_output = ''; if ($labels) $_output .= '<label>'; $_output .= '<input type="checkbox" name="' . smarty_function_escape_special_chars($name) . '[]" value="' . smarty_function_escape_special_chars($value) . '"'; if (in_array((string)$value, $selected)) { $_output .= ' checked="checked"'; } $_output .= $extra . ' />' . $output; if ($labels) $_output .= '</label>'; $_output .= $separator; return $_output; } ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.html_checkboxes.php
PHP
asf20
4,381
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty wordwrap modifier plugin * * Type: modifier<br> * Name: wordwrap<br> * Purpose: wrap a string of text at a given length * @link http://smarty.php.net/manual/en/language.modifier.wordwrap.php * wordwrap (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param integer * @param string * @param boolean * @return string */ function smarty_modifier_wordwrap($string,$length=80,$break="\n",$cut=false) { return wordwrap($string,$length,$break,$cut); } ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.wordwrap.php
PHP
asf20
613
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {cycle} function plugin * * Type: function<br> * Name: cycle<br> * Date: May 3, 2002<br> * Purpose: cycle through given values<br> * Input: * - name = name of cycle (optional) * - values = comma separated list of values to cycle, * or an array of values to cycle * (this can be left out for subsequent calls) * - reset = boolean - resets given var to true * - print = boolean - print var or not. default is true * - advance = boolean - whether or not to advance the cycle * - delimiter = the value delimiter, default is "," * - assign = boolean, assigns to template var instead of * printed. * * Examples:<br> * <pre> * {cycle values="#eeeeee,#d0d0d0d"} * {cycle name=row values="one,two,three" reset=true} * {cycle name=row} * </pre> * @link http://smarty.php.net/manual/en/language.function.cycle.php {cycle} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @author credit to Mark Priatel <mpriatel@rogers.com> * @author credit to Gerard <gerard@interfold.com> * @author credit to Jason Sweat <jsweat_php@yahoo.com> * @version 1.3 * @param array * @param Smarty * @return string|null */ function smarty_function_cycle($params, &$smarty) { static $cycle_vars; $name = (empty($params['name'])) ? 'default' : $params['name']; $print = (isset($params['print'])) ? (bool)$params['print'] : true; $advance = (isset($params['advance'])) ? (bool)$params['advance'] : true; $reset = (isset($params['reset'])) ? (bool)$params['reset'] : false; if (!in_array('values', array_keys($params))) { if(!isset($cycle_vars[$name]['values'])) { $smarty->trigger_error("cycle: missing 'values' parameter"); return; } } else { if(isset($cycle_vars[$name]['values']) && $cycle_vars[$name]['values'] != $params['values'] ) { $cycle_vars[$name]['index'] = 0; } $cycle_vars[$name]['values'] = $params['values']; } $cycle_vars[$name]['delimiter'] = (isset($params['delimiter'])) ? $params['delimiter'] : ','; if(is_array($cycle_vars[$name]['values'])) { $cycle_array = $cycle_vars[$name]['values']; } else { $cycle_array = explode($cycle_vars[$name]['delimiter'],$cycle_vars[$name]['values']); } if(!isset($cycle_vars[$name]['index']) || $reset ) { $cycle_vars[$name]['index'] = 0; } if (isset($params['assign'])) { $print = false; $smarty->assign($params['assign'], $cycle_array[$cycle_vars[$name]['index']]); } if($print) { $retval = $cycle_array[$cycle_vars[$name]['index']]; } else { $retval = null; } if($advance) { if ( $cycle_vars[$name]['index'] >= count($cycle_array) -1 ) { $cycle_vars[$name]['index'] = 0; } else { $cycle_vars[$name]['index']++; } } return $retval; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.cycle.php
PHP
asf20
3,192
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty strip_tags modifier plugin * * Type: modifier<br> * Name: strip_tags<br> * Purpose: strip html tags from text * @link http://smarty.php.net/manual/en/language.modifier.strip.tags.php * strip_tags (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param boolean * @return string */ function smarty_modifier_strip_tags($string, $replace_with_space = true) { if ($replace_with_space) return preg_replace('!<[^>]*?>!', ' ', $string); else return strip_tags($string); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.strip_tags.php
PHP
asf20
676
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {debug} function plugin * * Type: function<br> * Name: debug<br> * Date: July 1, 2002<br> * Purpose: popup debug window * @link http://smarty.php.net/manual/en/language.function.debug.php {debug} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @version 1.0 * @param array * @param Smarty * @return string output from {@link Smarty::_generate_debug_output()} */ function smarty_function_debug($params, &$smarty) { if (isset($params['output'])) { $smarty->assign('_smarty_debug_output', $params['output']); } require_once(SMARTY_CORE_DIR . 'core.display_debug_console.php'); return smarty_core_display_debug_console(null, $smarty); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.debug.php
PHP
asf20
835
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty default modifier plugin * * Type: modifier<br> * Name: default<br> * Purpose: designate default value for empty variables * @link http://smarty.php.net/manual/en/language.modifier.default.php * default (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string * @return string */ function smarty_modifier_default($string, $default = '') { if (!isset($string) || $string === '') return $default; else return $string; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.default.php
PHP
asf20
635
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty spacify modifier plugin * * Type: modifier<br> * Name: spacify<br> * Purpose: add spaces between characters in a string * @link http://smarty.php.net/manual/en/language.modifier.spacify.php * spacify (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string * @return string */ function smarty_modifier_spacify($string, $spacify_char = ' ') { return implode($spacify_char, preg_split('//', $string, -1, PREG_SPLIT_NO_EMPTY)); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.spacify.php
PHP
asf20
644
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_radios} function plugin * * File: function.html_radios.php<br> * Type: function<br> * Name: html_radios<br> * Date: 24.Feb.2003<br> * Purpose: Prints out a list of radio input types<br> * Input:<br> * - name (optional) - string default "radio" * - values (required) - array * - options (optional) - associative array * - checked (optional) - array default not set * - separator (optional) - ie <br> or &nbsp; * - output (optional) - the output next to each radio button * - assign (optional) - assign the output as an array to this variable * Examples: * <pre> * {html_radios values=$ids output=$names} * {html_radios values=$ids name='box' separator='<br>' output=$names} * {html_radios values=$ids checked=$checked separator='<br>' output=$names} * </pre> * @link http://smarty.php.net/manual/en/language.function.html.radios.php {html_radios} * (Smarty online manual) * @author Christopher Kvarme <christopher.kvarme@flashjab.com> * @author credits to Monte Ohrt <monte at ohrt dot com> * @version 1.0 * @param array * @param Smarty * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_radios($params, &$smarty) { require_once $smarty->_get_plugin_filepath('shared','escape_special_chars'); $name = 'radio'; $values = null; $options = null; $selected = null; $separator = ''; $labels = true; $label_ids = false; $output = null; $extra = ''; foreach($params as $_key => $_val) { switch($_key) { case 'name': case 'separator': $$_key = (string)$_val; break; case 'checked': case 'selected': if(is_array($_val)) { $smarty->trigger_error('html_radios: the "' . $_key . '" attribute cannot be an array', E_USER_WARNING); } else { $selected = (string)$_val; } break; case 'labels': case 'label_ids': $$_key = (bool)$_val; break; case 'options': $$_key = (array)$_val; break; case 'values': case 'output': $$_key = array_values((array)$_val); break; case 'radios': $smarty->trigger_error('html_radios: the use of the "radios" attribute is deprecated, use "options" instead', E_USER_WARNING); $options = (array)$_val; break; case 'assign': break; default: if(!is_array($_val)) { $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"'; } else { $smarty->trigger_error("html_radios: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (!isset($options) && !isset($values)) return ''; /* raise error here? */ $_html_result = array(); if (isset($options)) { foreach ($options as $_key=>$_val) $_html_result[] = smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids); } else { foreach ($values as $_i=>$_key) { $_val = isset($output[$_i]) ? $output[$_i] : ''; $_html_result[] = smarty_function_html_radios_output($name, $_key, $_val, $selected, $extra, $separator, $labels, $label_ids); } } if(!empty($params['assign'])) { $smarty->assign($params['assign'], $_html_result); } else { return implode("\n",$_html_result); } } function smarty_function_html_radios_output($name, $value, $output, $selected, $extra, $separator, $labels, $label_ids) { $_output = ''; if ($labels) { if($label_ids) { $_id = smarty_function_escape_special_chars(preg_replace('![^\w\-\.]!', '_', $name . '_' . $value)); $_output .= '<label for="' . $_id . '">'; } else { $_output .= '<label>'; } } $_output .= '<input type="radio" name="' . smarty_function_escape_special_chars($name) . '" value="' . smarty_function_escape_special_chars($value) . '"'; if ($labels && $label_ids) $_output .= ' id="' . $_id . '"'; if ((string)$value==$selected) { $_output .= ' checked="checked"'; } $_output .= $extra . ' />' . $output; if ($labels) $_output .= '</label>'; $_output .= $separator; return $_output; } ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.html_radios.php
PHP
asf20
4,841
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {textformat}{/textformat} block plugin * * Type: block function<br> * Name: textformat<br> * Purpose: format text a certain way with preset styles * or custom wrap/indent settings<br> * @link http://smarty.php.net/manual/en/language.function.textformat.php {textformat} * (Smarty online manual) * @param array * <pre> * Params: style: string (email) * indent: integer (0) * wrap: integer (80) * wrap_char string ("\n") * indent_char: string (" ") * wrap_boundary: boolean (true) * </pre> * @author Monte Ohrt <monte at ohrt dot com> * @param string contents of the block * @param Smarty clever simulation of a method * @return string string $content re-formatted */ function smarty_block_textformat($params, $content, &$smarty) { if (is_null($content)) { return; } $style = null; $indent = 0; $indent_first = 0; $indent_char = ' '; $wrap = 80; $wrap_char = "\n"; $wrap_cut = false; $assign = null; foreach ($params as $_key => $_val) { switch ($_key) { case 'style': case 'indent_char': case 'wrap_char': case 'assign': $$_key = (string)$_val; break; case 'indent': case 'indent_first': case 'wrap': $$_key = (int)$_val; break; case 'wrap_cut': $$_key = (bool)$_val; break; default: $smarty->trigger_error("textformat: unknown attribute '$_key'"); } } if ($style == 'email') { $wrap = 72; } // split into paragraphs $_paragraphs = preg_split('![\r\n][\r\n]!',$content); $_output = ''; for($_x = 0, $_y = count($_paragraphs); $_x < $_y; $_x++) { if ($_paragraphs[$_x] == '') { continue; } // convert mult. spaces & special chars to single space $_paragraphs[$_x] = preg_replace(array('!\s+!','!(^\s+)|(\s+$)!'), array(' ',''), $_paragraphs[$_x]); // indent first line if($indent_first > 0) { $_paragraphs[$_x] = str_repeat($indent_char, $indent_first) . $_paragraphs[$_x]; } // wordwrap sentences $_paragraphs[$_x] = wordwrap($_paragraphs[$_x], $wrap - $indent, $wrap_char, $wrap_cut); // indent lines if($indent > 0) { $_paragraphs[$_x] = preg_replace('!^!m', str_repeat($indent_char, $indent), $_paragraphs[$_x]); } } $_output = implode($wrap_char . $wrap_char, $_paragraphs); return $assign ? $smarty->assign($assign, $_output) : $_output; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/block.textformat.php
PHP
asf20
2,843
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty capitalize modifier plugin * * Type: modifier<br> * Name: capitalize<br> * Purpose: capitalize words in the string * @link http://smarty.php.net/manual/en/language.modifiers.php#LANGUAGE.MODIFIER.CAPITALIZE * capitalize (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_modifier_capitalize($string, $uc_digits = false) { smarty_modifier_capitalize_ucfirst(null, $uc_digits); return preg_replace_callback('!\'?\b\w(\w|\')*\b!', 'smarty_modifier_capitalize_ucfirst', $string); } function smarty_modifier_capitalize_ucfirst($string, $uc_digits = null) { static $_uc_digits = false; if(isset($uc_digits)) { $_uc_digits = $uc_digits; return; } if(substr($string[0],0,1) != "'" && !preg_match("!\d!",$string[0]) || $_uc_digits) return ucfirst($string[0]); else return $string[0]; } ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.capitalize.php
PHP
asf20
1,037
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty debug_print_var modifier plugin * * Type: modifier<br> * Name: debug_print_var<br> * Purpose: formats variable contents for display in the console * @link http://smarty.php.net/manual/en/language.modifier.debug.print.var.php * debug_print_var (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array|object * @param integer * @param integer * @return string */ function smarty_modifier_debug_print_var($var, $depth = 0, $length = 40) { $_replace = array( "\n" => '<i>\n</i>', "\r" => '<i>\r</i>', "\t" => '<i>\t</i>' ); switch (gettype($var)) { case 'array' : $results = '<b>Array (' . count($var) . ')</b>'; foreach ($var as $curr_key => $curr_val) { $results .= '<br>' . str_repeat('&nbsp;', $depth * 2) . '<b>' . strtr($curr_key, $_replace) . '</b> =&gt; ' . smarty_modifier_debug_print_var($curr_val, ++$depth, $length); $depth--; } break; case 'object' : $object_vars = get_object_vars($var); $results = '<b>' . get_class($var) . ' Object (' . count($object_vars) . ')</b>'; foreach ($object_vars as $curr_key => $curr_val) { $results .= '<br>' . str_repeat('&nbsp;', $depth * 2) . '<b> -&gt;' . strtr($curr_key, $_replace) . '</b> = ' . smarty_modifier_debug_print_var($curr_val, ++$depth, $length); $depth--; } break; case 'boolean' : case 'NULL' : case 'resource' : if (true === $var) { $results = 'true'; } elseif (false === $var) { $results = 'false'; } elseif (null === $var) { $results = 'null'; } else { $results = htmlspecialchars((string) $var); } $results = '<i>' . $results . '</i>'; break; case 'integer' : case 'float' : $results = htmlspecialchars((string) $var); break; case 'string' : $results = strtr($var, $_replace); if (strlen($var) > $length ) { $results = substr($var, 0, $length - 3) . '...'; } $results = htmlspecialchars('"' . $results . '"'); break; case 'unknown type' : default : $results = strtr((string) $var, $_replace); if (strlen($results) > $length ) { $results = substr($results, 0, $length - 3) . '...'; } $results = htmlspecialchars($results); } return $results; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.debug_print_var.php
PHP
asf20
2,884
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty indent modifier plugin * * Type: modifier<br> * Name: indent<br> * Purpose: indent lines of text * @link http://smarty.php.net/manual/en/language.modifier.indent.php * indent (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param integer * @param string * @return string */ function smarty_modifier_indent($string,$chars=4,$char=" ") { return preg_replace('!^!m',str_repeat($char,$chars),$string); } ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.indent.php
PHP
asf20
567
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {eval} function plugin * * Type: function<br> * Name: eval<br> * Purpose: evaluate a template variable as a template<br> * @link http://smarty.php.net/manual/en/language.function.eval.php {eval} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty */ function smarty_function_eval($params, &$smarty) { if (!isset($params['var'])) { $smarty->trigger_error("eval: missing 'var' parameter"); return; } if($params['var'] == '') { return; } $smarty->_compile_source('evaluated template', $params['var'], $_var_compiled); ob_start(); $smarty->_eval('?>' . $_var_compiled); $_contents = ob_get_contents(); ob_end_clean(); if (!empty($params['assign'])) { $smarty->assign($params['assign'], $_contents); } else { return $_contents; } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.eval.php
PHP
asf20
1,014
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty strip modifier plugin * * Type: modifier<br> * Name: strip<br> * Purpose: Replace all repeated spaces, newlines, tabs * with a single space or supplied replacement string.<br> * Example: {$var|strip} {$var|strip:"&nbsp;"} * Date: September 25th, 2002 * @link http://smarty.php.net/manual/en/language.modifier.strip.php * strip (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @version 1.0 * @param string * @param string * @return string */ function smarty_modifier_strip($text, $replace = ' ') { return preg_replace('!\s+!', $replace, $text); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.strip.php
PHP
asf20
742
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {fetch} plugin * * Type: function<br> * Name: fetch<br> * Purpose: fetch file, web or ftp data and display results * @link http://smarty.php.net/manual/en/language.function.fetch.php {fetch} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty * @return string|null if the assign parameter is passed, Smarty assigns the * result to a template variable */ function smarty_function_fetch($params, &$smarty) { if (empty($params['file'])) { $smarty->_trigger_fatal_error("[plugin] parameter 'file' cannot be empty"); return; } $content = ''; if ($smarty->security && !preg_match('!^(http|ftp)://!i', $params['file'])) { $_params = array('resource_type' => 'file', 'resource_name' => $params['file']); require_once(SMARTY_CORE_DIR . 'core.is_secure.php'); if(!smarty_core_is_secure($_params, $smarty)) { $smarty->_trigger_fatal_error('[plugin] (secure mode) fetch \'' . $params['file'] . '\' is not allowed'); return; } // fetch the file if($fp = @fopen($params['file'],'r')) { while(!feof($fp)) { $content .= fgets ($fp,4096); } fclose($fp); } else { $smarty->_trigger_fatal_error('[plugin] fetch cannot read file \'' . $params['file'] . '\''); return; } } else { // not a local file if(preg_match('!^http://!i',$params['file'])) { // http fetch if($uri_parts = parse_url($params['file'])) { // set defaults $host = $server_name = $uri_parts['host']; $timeout = 30; $accept = "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, */*"; $agent = "Smarty Template Engine ".$smarty->_version; $referer = ""; $uri = !empty($uri_parts['path']) ? $uri_parts['path'] : '/'; $uri .= !empty($uri_parts['query']) ? '?' . $uri_parts['query'] : ''; $_is_proxy = false; if(empty($uri_parts['port'])) { $port = 80; } else { $port = $uri_parts['port']; } if(!empty($uri_parts['user'])) { $user = $uri_parts['user']; } if(!empty($uri_parts['pass'])) { $pass = $uri_parts['pass']; } // loop through parameters, setup headers foreach($params as $param_key => $param_value) { switch($param_key) { case "file": case "assign": case "assign_headers": break; case "user": if(!empty($param_value)) { $user = $param_value; } break; case "pass": if(!empty($param_value)) { $pass = $param_value; } break; case "accept": if(!empty($param_value)) { $accept = $param_value; } break; case "header": if(!empty($param_value)) { if(!preg_match('![\w\d-]+: .+!',$param_value)) { $smarty->_trigger_fatal_error("[plugin] invalid header format '".$param_value."'"); return; } else { $extra_headers[] = $param_value; } } break; case "proxy_host": if(!empty($param_value)) { $proxy_host = $param_value; } break; case "proxy_port": if(!preg_match('!\D!', $param_value)) { $proxy_port = (int) $param_value; } else { $smarty->_trigger_fatal_error("[plugin] invalid value for attribute '".$param_key."'"); return; } break; case "agent": if(!empty($param_value)) { $agent = $param_value; } break; case "referer": if(!empty($param_value)) { $referer = $param_value; } break; case "timeout": if(!preg_match('!\D!', $param_value)) { $timeout = (int) $param_value; } else { $smarty->_trigger_fatal_error("[plugin] invalid value for attribute '".$param_key."'"); return; } break; default: $smarty->_trigger_fatal_error("[plugin] unrecognized attribute '".$param_key."'"); return; } } if(!empty($proxy_host) && !empty($proxy_port)) { $_is_proxy = true; $fp = fsockopen($proxy_host,$proxy_port,$errno,$errstr,$timeout); } else { $fp = fsockopen($server_name,$port,$errno,$errstr,$timeout); } if(!$fp) { $smarty->_trigger_fatal_error("[plugin] unable to fetch: $errstr ($errno)"); return; } else { if($_is_proxy) { fputs($fp, 'GET ' . $params['file'] . " HTTP/1.0\r\n"); } else { fputs($fp, "GET $uri HTTP/1.0\r\n"); } if(!empty($host)) { fputs($fp, "Host: $host\r\n"); } if(!empty($accept)) { fputs($fp, "Accept: $accept\r\n"); } if(!empty($agent)) { fputs($fp, "User-Agent: $agent\r\n"); } if(!empty($referer)) { fputs($fp, "Referer: $referer\r\n"); } if(isset($extra_headers) && is_array($extra_headers)) { foreach($extra_headers as $curr_header) { fputs($fp, $curr_header."\r\n"); } } if(!empty($user) && !empty($pass)) { fputs($fp, "Authorization: BASIC ".base64_encode("$user:$pass")."\r\n"); } fputs($fp, "\r\n"); while(!feof($fp)) { $content .= fgets($fp,4096); } fclose($fp); $csplit = split("\r\n\r\n",$content,2); $content = $csplit[1]; if(!empty($params['assign_headers'])) { $smarty->assign($params['assign_headers'],split("\r\n",$csplit[0])); } } } else { $smarty->_trigger_fatal_error("[plugin] unable to parse Url, check syntax"); return; } } else { // ftp fetch if($fp = @fopen($params['file'],'r')) { while(!feof($fp)) { $content .= fgets ($fp,4096); } fclose($fp); } else { $smarty->_trigger_fatal_error('[plugin] fetch cannot read file \'' . $params['file'] .'\''); return; } } } if (!empty($params['assign'])) { $smarty->assign($params['assign'],$content); } else { return $content; } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.fetch.php
PHP
asf20
8,964
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty plugin * * Type: modifier<br> * Name: nl2br<br> * Date: Feb 26, 2003 * Purpose: convert \r\n, \r or \n to <<br>> * Input:<br> * - contents = contents to replace * - preceed_test = if true, includes preceeding break tags * in replacement * Example: {$text|nl2br} * @link http://smarty.php.net/manual/en/language.modifier.nl2br.php * nl2br (Smarty online manual) * @version 1.0 * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_modifier_nl2br($string) { return nl2br($string); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.nl2br.php
PHP
asf20
717
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty count_paragraphs modifier plugin * * Type: modifier<br> * Name: count_paragraphs<br> * Purpose: count the number of paragraphs in a text * @link http://smarty.php.net/manual/en/language.modifier.count.paragraphs.php * count_paragraphs (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return integer */ function smarty_modifier_count_paragraphs($string) { // count \r or \n characters return count(preg_split('/[\r\n]+/', $string)); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.count_paragraphs.php
PHP
asf20
630
<?php /** * Smarty shared plugin * @package Smarty * @subpackage plugins */ /** * Function: smarty_make_timestamp<br> * Purpose: used by other smarty functions to make a timestamp * from a string. * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_make_timestamp($string) { if(empty($string) && $string != 0) { // use "now": $time = time(); } elseif (preg_match('/^\d{14}$/', $string)) { // it is mysql timestamp format of YYYYMMDDHHMMSS? $time = mktime(substr($string, 8, 2),substr($string, 10, 2),substr($string, 12, 2), substr($string, 4, 2),substr($string, 6, 2),substr($string, 0, 4)); } elseif (is_numeric($string)) { // it is a numeric string, we handle it as timestamp $time = (int)$string; } else { // strtotime should handle it $time = strtotime($string); if ($time == -1 || $time === false) { // strtotime() was not able to parse $string, use "now": $time = time(); } } return $time; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/shared.make_timestamp.php
PHP
asf20
1,229
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_select_date} plugin * * Type: function<br> * Name: html_select_date<br> * Purpose: Prints the dropdowns for date selection. * * ChangeLog:<br> * - 1.0 initial release * - 1.1 added support for +/- N syntax for begin * and end year values. (Monte) * - 1.2 added support for yyyy-mm-dd syntax for * time value. (Jan Rosier) * - 1.3 added support for choosing format for * month values (Gary Loescher) * - 1.3.1 added support for choosing format for * day values (Marcus Bointon) * - 1.3.2 support negative timestamps, force year * dropdown to include given date unless explicitly set (Monte) * - 1.3.4 fix behaviour of 0000-00-00 00:00:00 dates to match that * of 0000-00-00 dates (cybot, boots) * @link http://smarty.php.net/manual/en/language.function.html.select.date.php {html_select_date} * (Smarty online manual) * @version 1.3.4 * @author Andrei Zmievski * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty * @return string */ function smarty_function_html_select_date($params, &$smarty) { require_once $smarty->_get_plugin_filepath('shared','escape_special_chars'); require_once $smarty->_get_plugin_filepath('shared','make_timestamp'); require_once $smarty->_get_plugin_filepath('function','html_options'); /* Default values. */ $prefix = "Date_"; $start_year = strftime("%Y"); $end_year = $start_year; $display_days = true; $display_months = true; $display_years = true; $month_format = "%B"; /* Write months as numbers by default GL */ $month_value_format = "%m"; $day_format = "%02d"; /* Write day values using this format MB */ $day_value_format = "%d"; $year_as_text = false; /* Display years in reverse order? Ie. 2000,1999,.... */ $reverse_years = false; /* Should the select boxes be part of an array when returned from PHP? e.g. setting it to "birthday", would create "birthday[Day]", "birthday[Month]" & "birthday[Year]". Can be combined with prefix */ $field_array = null; /* <select size>'s of the different <select> tags. If not set, uses default dropdown. */ $day_size = null; $month_size = null; $year_size = null; /* Unparsed attributes common to *ALL* the <select>/<input> tags. An example might be in the template: all_extra ='class ="foo"'. */ $all_extra = null; /* Separate attributes for the tags. */ $day_extra = null; $month_extra = null; $year_extra = null; /* Order in which to display the fields. "D" -> day, "M" -> month, "Y" -> year. */ $field_order = 'MDY'; /* String printed between the different fields. */ $field_separator = "\n"; $time = time(); $all_empty = null; $day_empty = null; $month_empty = null; $year_empty = null; $extra_attrs = ''; foreach ($params as $_key=>$_value) { switch ($_key) { case 'prefix': case 'time': case 'start_year': case 'end_year': case 'month_format': case 'day_format': case 'day_value_format': case 'field_array': case 'day_size': case 'month_size': case 'year_size': case 'all_extra': case 'day_extra': case 'month_extra': case 'year_extra': case 'field_order': case 'field_separator': case 'month_value_format': case 'month_empty': case 'day_empty': case 'year_empty': $$_key = (string)$_value; break; case 'all_empty': $$_key = (string)$_value; $day_empty = $month_empty = $year_empty = $all_empty; break; case 'display_days': case 'display_months': case 'display_years': case 'year_as_text': case 'reverse_years': $$_key = (bool)$_value; break; default: if(!is_array($_value)) { $extra_attrs .= ' '.$_key.'="'.smarty_function_escape_special_chars($_value).'"'; } else { $smarty->trigger_error("html_select_date: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (preg_match('!^-\d+$!', $time)) { // negative timestamp, use date() $time = date('Y-m-d', $time); } // If $time is not in format yyyy-mm-dd if (preg_match('/^(\d{0,4}-\d{0,2}-\d{0,2})/', $time, $found)) { $time = $found[1]; } else { // use smarty_make_timestamp to get an unix timestamp and // strftime to make yyyy-mm-dd $time = strftime('%Y-%m-%d', smarty_make_timestamp($time)); } // Now split this in pieces, which later can be used to set the select $time = explode("-", $time); // make syntax "+N" or "-N" work with start_year and end_year if (preg_match('!^(\+|\-)\s*(\d+)$!', $end_year, $match)) { if ($match[1] == '+') { $end_year = strftime('%Y') + $match[2]; } else { $end_year = strftime('%Y') - $match[2]; } } if (preg_match('!^(\+|\-)\s*(\d+)$!', $start_year, $match)) { if ($match[1] == '+') { $start_year = strftime('%Y') + $match[2]; } else { $start_year = strftime('%Y') - $match[2]; } } if (strlen($time[0]) > 0) { if ($start_year > $time[0] && !isset($params['start_year'])) { // force start year to include given date if not explicitly set $start_year = $time[0]; } if($end_year < $time[0] && !isset($params['end_year'])) { // force end year to include given date if not explicitly set $end_year = $time[0]; } } $field_order = strtoupper($field_order); $html_result = $month_result = $day_result = $year_result = ""; $field_separator_count = -1; if ($display_months) { $field_separator_count++; $month_names = array(); $month_values = array(); if(isset($month_empty)) { $month_names[''] = $month_empty; $month_values[''] = ''; } for ($i = 1; $i <= 12; $i++) { $month_names[$i] = strftime($month_format, mktime(0, 0, 0, $i, 1, 2000)); $month_values[$i] = strftime($month_value_format, mktime(0, 0, 0, $i, 1, 2000)); } $month_result .= '<select name='; if (null !== $field_array){ $month_result .= '"' . $field_array . '[' . $prefix . 'Month]"'; } else { $month_result .= '"' . $prefix . 'Month"'; } if (null !== $month_size){ $month_result .= ' size="' . $month_size . '"'; } if (null !== $month_extra){ $month_result .= ' ' . $month_extra; } if (null !== $all_extra){ $month_result .= ' ' . $all_extra; } $month_result .= $extra_attrs . '>'."\n"; $month_result .= smarty_function_html_options(array('output' => $month_names, 'values' => $month_values, 'selected' => (int)$time[1] ? strftime($month_value_format, mktime(0, 0, 0, (int)$time[1], 1, 2000)) : '', 'print_result' => false), $smarty); $month_result .= '</select>'; } if ($display_days) { $field_separator_count++; $days = array(); if (isset($day_empty)) { $days[''] = $day_empty; $day_values[''] = ''; } for ($i = 1; $i <= 31; $i++) { $days[] = sprintf($day_format, $i); $day_values[] = sprintf($day_value_format, $i); } $day_result .= '<select name='; if (null !== $field_array){ $day_result .= '"' . $field_array . '[' . $prefix . 'Day]"'; } else { $day_result .= '"' . $prefix . 'Day"'; } if (null !== $day_size){ $day_result .= ' size="' . $day_size . '"'; } if (null !== $all_extra){ $day_result .= ' ' . $all_extra; } if (null !== $day_extra){ $day_result .= ' ' . $day_extra; } $day_result .= $extra_attrs . '>'."\n"; $day_result .= smarty_function_html_options(array('output' => $days, 'values' => $day_values, 'selected' => $time[2], 'print_result' => false), $smarty); $day_result .= '</select>'; } if ($display_years) { $field_separator_count++; if (null !== $field_array){ $year_name = $field_array . '[' . $prefix . 'Year]'; } else { $year_name = $prefix . 'Year'; } if ($year_as_text) { $year_result .= '<input type="text" name="' . $year_name . '" value="' . $time[0] . '" size="4" maxlength="4"'; if (null !== $all_extra){ $year_result .= ' ' . $all_extra; } if (null !== $year_extra){ $year_result .= ' ' . $year_extra; } $year_result .= ' />'; } else { $years = range((int)$start_year, (int)$end_year); if ($reverse_years) { rsort($years, SORT_NUMERIC); } else { sort($years, SORT_NUMERIC); } $yearvals = $years; if(isset($year_empty)) { array_unshift($years, $year_empty); array_unshift($yearvals, ''); } $year_result .= '<select name="' . $year_name . '"'; if (null !== $year_size){ $year_result .= ' size="' . $year_size . '"'; } if (null !== $all_extra){ $year_result .= ' ' . $all_extra; } if (null !== $year_extra){ $year_result .= ' ' . $year_extra; } $year_result .= $extra_attrs . '>'."\n"; $year_result .= smarty_function_html_options(array('output' => $years, 'values' => $yearvals, 'selected' => $time[0], 'print_result' => false), $smarty); $year_result .= '</select>'; } } // Loop thru the field_order field for ($i = 0; $i <= 2; $i++){ $c = substr($field_order, $i, 1); switch ($c){ case 'D': $html_result .= $day_result; break; case 'M': $html_result .= $month_result; break; case 'Y': $html_result .= $year_result; break; } // Add the field seperator if($i < $field_separator_count) { $html_result .= $field_separator; } } return $html_result; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.html_select_date.php
PHP
asf20
11,955
<?php /** * Smarty shared plugin * @package Smarty * @subpackage plugins */ /** * escape_special_chars common function * * Function: smarty_function_escape_special_chars<br> * Purpose: used by other smarty functions to escape * special chars except for already escaped ones * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_function_escape_special_chars($string) { if(!is_array($string)) { $string = preg_replace('!&(#?\w+);!', '%%%SMARTY_START%%%\\1%%%SMARTY_END%%%', $string); $string = htmlspecialchars($string); $string = str_replace(array('%%%SMARTY_START%%%','%%%SMARTY_END%%%'), array('&',';'), $string); } return $string; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/shared.escape_special_chars.php
PHP
asf20
774
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {popup} function plugin * * Type: function<br> * Name: popup<br> * Purpose: make text pop up in windows via overlib * @link http://smarty.php.net/manual/en/language.function.popup.php {popup} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty * @return string */ function smarty_function_popup($params, &$smarty) { $append = ''; foreach ($params as $_key=>$_value) { switch ($_key) { case 'text': case 'trigger': case 'function': case 'inarray': $$_key = (string)$_value; if ($_key == 'function' || $_key == 'inarray') $append .= ',' . strtoupper($_key) . ",'$_value'"; break; case 'caption': case 'closetext': case 'status': $append .= ',' . strtoupper($_key) . ",'" . str_replace("'","\'",$_value) . "'"; break; case 'fgcolor': case 'bgcolor': case 'textcolor': case 'capcolor': case 'closecolor': case 'textfont': case 'captionfont': case 'closefont': case 'fgbackground': case 'bgbackground': case 'caparray': case 'capicon': case 'background': case 'frame': $append .= ',' . strtoupper($_key) . ",'$_value'"; break; case 'textsize': case 'captionsize': case 'closesize': case 'width': case 'height': case 'border': case 'offsetx': case 'offsety': case 'snapx': case 'snapy': case 'fixx': case 'fixy': case 'padx': case 'pady': case 'timeout': case 'delay': $append .= ',' . strtoupper($_key) . ",$_value"; break; case 'sticky': case 'left': case 'right': case 'center': case 'above': case 'below': case 'noclose': case 'autostatus': case 'autostatuscap': case 'fullhtml': case 'hauto': case 'vauto': case 'mouseoff': case 'followmouse': case 'closeclick': if ($_value) $append .= ',' . strtoupper($_key); break; default: $smarty->trigger_error("[popup] unknown parameter $_key", E_USER_WARNING); } } if (empty($text) && !isset($inarray) && empty($function)) { $smarty->trigger_error("overlib: attribute 'text' or 'inarray' or 'function' required"); return false; } if (empty($trigger)) { $trigger = "onmouseover"; } $retval = $trigger . '="return overlib(\''.preg_replace(array("!'!","![\r\n]!"),array("\'",'\r'),$text).'\''; $retval .= $append . ');"'; if ($trigger == 'onmouseover') $retval .= ' onmouseout="nd();"'; return $retval; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.popup.php
PHP
asf20
3,280
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_options} function plugin * * Type: function<br> * Name: html_options<br> * Input:<br> * - name (optional) - string default "select" * - values (required if no options supplied) - array * - options (required if no values supplied) - associative array * - selected (optional) - string default not set * - output (required if not options supplied) - array * Purpose: Prints the list of <option> tags generated from * the passed parameters * @link http://smarty.php.net/manual/en/language.function.html.options.php {html_image} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_options($params, &$smarty) { require_once $smarty->_get_plugin_filepath('shared','escape_special_chars'); $name = null; $values = null; $options = null; $selected = array(); $output = null; $extra = ''; foreach($params as $_key => $_val) { switch($_key) { case 'name': $$_key = (string)$_val; break; case 'options': $$_key = (array)$_val; break; case 'values': case 'output': $$_key = array_values((array)$_val); break; case 'selected': $$_key = array_map('strval', array_values((array)$_val)); break; default: if(!is_array($_val)) { $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"'; } else { $smarty->trigger_error("html_options: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (!isset($options) && !isset($values)) return ''; /* raise error here? */ $_html_result = ''; if (isset($options)) { foreach ($options as $_key=>$_val) $_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected); } else { foreach ($values as $_i=>$_key) { $_val = isset($output[$_i]) ? $output[$_i] : ''; $_html_result .= smarty_function_html_options_optoutput($_key, $_val, $selected); } } if(!empty($name)) { $_html_result = '<select name="' . $name . '"' . $extra . '>' . "\n" . $_html_result . '</select>' . "\n"; } return $_html_result; } function smarty_function_html_options_optoutput($key, $value, $selected) { if(!is_array($value)) { $_html_result = '<option label="' . smarty_function_escape_special_chars($value) . '" value="' . smarty_function_escape_special_chars($key) . '"'; if (in_array((string)$key, $selected)) $_html_result .= ' selected="selected"'; $_html_result .= '>' . smarty_function_escape_special_chars($value) . '</option>' . "\n"; } else { $_html_result = smarty_function_html_options_optgroup($key, $value, $selected); } return $_html_result; } function smarty_function_html_options_optgroup($key, $values, $selected) { $optgroup_html = '<optgroup label="' . smarty_function_escape_special_chars($key) . '">' . "\n"; foreach ($values as $key => $value) { $optgroup_html .= smarty_function_html_options_optoutput($key, $value, $selected); } $optgroup_html .= "</optgroup>\n"; return $optgroup_html; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.html_options.php
PHP
asf20
3,797
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {popup_init} function plugin * * Type: function<br> * Name: popup_init<br> * Purpose: initialize overlib * @link http://smarty.php.net/manual/en/language.function.popup.init.php {popup_init} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty * @return string */ function smarty_function_popup_init($params, &$smarty) { $zindex = 1000; if (!empty($params['zindex'])) { $zindex = $params['zindex']; } if (!empty($params['src'])) { return '<div id="overDiv" style="position:absolute; visibility:hidden; z-index:'.$zindex.';"></div>' . "\n" . '<script type="text/javascript" language="JavaScript" src="'.$params['src'].'"></script>' . "\n"; } else { $smarty->trigger_error("popup_init: missing src parameter"); } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.popup_init.php
PHP
asf20
979
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty upper modifier plugin * * Type: modifier<br> * Name: upper<br> * Purpose: convert string to uppercase * @link http://smarty.php.net/manual/en/language.modifier.upper.php * upper (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_modifier_upper($string) { return strtoupper($string); } ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.upper.php
PHP
asf20
481
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_image} function plugin * * Type: function<br> * Name: html_image<br> * Date: Feb 24, 2003<br> * Purpose: format HTML tags for the image<br> * Input:<br> * - file = file (and path) of image (required) * - height = image height (optional, default actual height) * - width = image width (optional, default actual width) * - basedir = base directory for absolute paths, default * is environment variable DOCUMENT_ROOT * - path_prefix = prefix for path output (optional, default empty) * * Examples: {html_image file="/images/masthead.gif"} * Output: <img src="/images/masthead.gif" width=400 height=23> * @link http://smarty.php.net/manual/en/language.function.html.image.php {html_image} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @author credits to Duda <duda@big.hu> - wrote first image function * in repository, helped with lots of functionality * @version 1.0 * @param array * @param Smarty * @return string * @uses smarty_function_escape_special_chars() */ function smarty_function_html_image($params, &$smarty) { require_once $smarty->_get_plugin_filepath('shared','escape_special_chars'); $alt = ''; $file = ''; $height = ''; $width = ''; $extra = ''; $prefix = ''; $suffix = ''; $path_prefix = ''; $server_vars = ($smarty->request_use_auto_globals) ? $_SERVER : $GLOBALS['HTTP_SERVER_VARS']; $basedir = isset($server_vars['DOCUMENT_ROOT']) ? $server_vars['DOCUMENT_ROOT'] : ''; foreach($params as $_key => $_val) { switch($_key) { case 'file': case 'height': case 'width': case 'dpi': case 'path_prefix': case 'basedir': $$_key = $_val; break; case 'alt': if(!is_array($_val)) { $$_key = smarty_function_escape_special_chars($_val); } else { $smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; case 'link': case 'href': $prefix = '<a href="' . $_val . '">'; $suffix = '</a>'; break; default: if(!is_array($_val)) { $extra .= ' '.$_key.'="'.smarty_function_escape_special_chars($_val).'"'; } else { $smarty->trigger_error("html_image: extra attribute '$_key' cannot be an array", E_USER_NOTICE); } break; } } if (empty($file)) { $smarty->trigger_error("html_image: missing 'file' parameter", E_USER_NOTICE); return; } if (substr($file,0,1) == '/') { $_image_path = $basedir . $file; } else { $_image_path = $file; } if(!isset($params['width']) || !isset($params['height'])) { if(!$_image_data = @getimagesize($_image_path)) { if(!file_exists($_image_path)) { $smarty->trigger_error("html_image: unable to find '$_image_path'", E_USER_NOTICE); return; } else if(!is_readable($_image_path)) { $smarty->trigger_error("html_image: unable to read '$_image_path'", E_USER_NOTICE); return; } else { $smarty->trigger_error("html_image: '$_image_path' is not a valid image file", E_USER_NOTICE); return; } } if ($smarty->security && ($_params = array('resource_type' => 'file', 'resource_name' => $_image_path)) && (require_once(SMARTY_CORE_DIR . 'core.is_secure.php')) && (!smarty_core_is_secure($_params, $smarty)) ) { $smarty->trigger_error("html_image: (secure) '$_image_path' not in secure directory", E_USER_NOTICE); } if(!isset($params['width'])) { $width = $_image_data[0]; } if(!isset($params['height'])) { $height = $_image_data[1]; } } if(isset($params['dpi'])) { if(strstr($server_vars['HTTP_USER_AGENT'], 'Mac')) { $dpi_default = 72; } else { $dpi_default = 96; } $_resize = $dpi_default/$params['dpi']; $width = round($width * $_resize); $height = round($height * $_resize); } return $prefix . '<img src="'.$path_prefix.$file.'" alt="'.$alt.'" width="'.$width.'" height="'.$height.'"'.$extra.' />' . $suffix; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.html_image.php
PHP
asf20
4,783
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {counter} function plugin * * Type: function<br> * Name: counter<br> * Purpose: print out a counter value * @author Monte Ohrt <monte at ohrt dot com> * @link http://smarty.php.net/manual/en/language.function.counter.php {counter} * (Smarty online manual) * @param array parameters * @param Smarty * @return string|null */ function smarty_function_counter($params, &$smarty) { static $counters = array(); $name = (isset($params['name'])) ? $params['name'] : 'default'; if (!isset($counters[$name])) { $counters[$name] = array( 'start'=>1, 'skip'=>1, 'direction'=>'up', 'count'=>1 ); } $counter =& $counters[$name]; if (isset($params['start'])) { $counter['start'] = $counter['count'] = (int)$params['start']; } if (!empty($params['assign'])) { $counter['assign'] = $params['assign']; } if (isset($counter['assign'])) { $smarty->assign($counter['assign'], $counter['count']); } if (isset($params['print'])) { $print = (bool)$params['print']; } else { $print = empty($counter['assign']); } if ($print) { $retval = $counter['count']; } else { $retval = null; } if (isset($params['skip'])) { $counter['skip'] = $params['skip']; } if (isset($params['direction'])) { $counter['direction'] = $params['direction']; } if ($counter['direction'] == "down") $counter['count'] -= $counter['skip']; else $counter['count'] += $counter['skip']; return $retval; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.counter.php
PHP
asf20
1,772
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty count_characters modifier plugin * * Type: modifier<br> * Name: count_characteres<br> * Purpose: count the number of characters in a text * @link http://smarty.php.net/manual/en/language.modifier.count.characters.php * count_characters (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param boolean include whitespace in the character count * @return integer */ function smarty_modifier_count_characters($string, $include_spaces = false) { if ($include_spaces) return(strlen($string)); return preg_match_all("/[^\s]/",$string, $match); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.count_characters.php
PHP
asf20
743
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Include the {@link shared.make_timestamp.php} plugin */ require_once $smarty->_get_plugin_filepath('shared', 'make_timestamp'); /** * Smarty date_format modifier plugin * * Type: modifier<br> * Name: date_format<br> * Purpose: format datestamps via strftime<br> * Input:<br> * - string: input date string * - format: strftime format for output * - default_date: default date if $string is empty * @link http://smarty.php.net/manual/en/language.modifier.date.format.php * date_format (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string * @param string * @return string|void * @uses smarty_make_timestamp() */ function smarty_modifier_date_format($string, $format = '%b %e, %Y', $default_date = '') { if ($string == 0) { return 0; } elseif ($string != '') { $timestamp = smarty_make_timestamp($string); } elseif ($default_date != '') { $timestamp = smarty_make_timestamp($default_date); } else { return; } if (DIRECTORY_SEPARATOR == '\\') { $_win_from = array('%D', '%h', '%n', '%r', '%R', '%t', '%T'); $_win_to = array('%m/%d/%y', '%b', "\n", '%I:%M:%S %p', '%H:%M', "\t", '%H:%M:%S'); if (strpos($format, '%e') !== false) { $_win_from[] = '%e'; $_win_to[] = sprintf('%\' 2d', date('j', $timestamp)); } if (strpos($format, '%l') !== false) { $_win_from[] = '%l'; $_win_to[] = sprintf('%\' 2d', date('h', $timestamp)); } $format = str_replace($_win_from, $_win_to, $format); } return strftime($format, $timestamp); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.date_format.php
PHP
asf20
1,890
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty replace modifier plugin * * Type: modifier<br> * Name: replace<br> * Purpose: simple search/replace * @link http://smarty.php.net/manual/en/language.modifier.replace.php * replace (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string * @param string * @return string */ function smarty_modifier_replace($string, $search, $replace) { return str_replace($search, $replace, $string); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.replace.php
PHP
asf20
585
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty string_format modifier plugin * * Type: modifier<br> * Name: string_format<br> * Purpose: format strings via sprintf * @link http://smarty.php.net/manual/en/language.modifier.string.format.php * string_format (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string * @return string */ function smarty_modifier_string_format($string, $format) { return sprintf($format, $string); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.string_format.php
PHP
asf20
579
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty cat modifier plugin * * Type: modifier<br> * Name: cat<br> * Date: Feb 24, 2003 * Purpose: catenate a value to a variable * Input: string to catenate * Example: {$var|cat:"foo"} * @link http://smarty.php.net/manual/en/language.modifier.cat.php cat * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @version 1.0 * @param string * @param string * @return string */ function smarty_modifier_cat($string, $cat) { return $string . $cat; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.cat.php
PHP
asf20
623
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty truncate modifier plugin * * Type: modifier<br> * Name: truncate<br> * Purpose: Truncate a string to a certain length if necessary, * optionally splitting in the middle of a word, and * appending the $etc string or inserting $etc into the middle. * @link http://smarty.php.net/manual/en/language.modifier.truncate.php * truncate (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param integer * @param string * @param boolean * @param boolean * @return string */ function smarty_modifier_truncate($string, $length = 80, $etc = '...', $break_words = false, $middle = false) { if ($length == 0) return ''; if (strlen($string) > $length) { $length -= min($length, strlen($etc)); if (!$break_words && !$middle) { $string = preg_replace('/\s+?(\S+)?$/', '', substr($string, 0, $length+1)); } if(!$middle) { return substr($string, 0, $length) . $etc; } else { return substr($string, 0, $length/2) . $etc . substr($string, -$length/2); } } else { return $string; } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.truncate.php
PHP
asf20
1,324
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {assign_debug_info} function plugin * * Type: function<br> * Name: assign_debug_info<br> * Purpose: assign debug info to the template<br> * @author Monte Ohrt <monte at ohrt dot com> * @param array unused in this plugin, this plugin uses {@link Smarty::$_config}, * {@link Smarty::$_tpl_vars} and {@link Smarty::$_smarty_debug_info} * @param Smarty */ function smarty_function_assign_debug_info($params, &$smarty) { $assigned_vars = $smarty->_tpl_vars; ksort($assigned_vars); if (@is_array($smarty->_config[0])) { $config_vars = $smarty->_config[0]; ksort($config_vars); $smarty->assign("_debug_config_keys", array_keys($config_vars)); $smarty->assign("_debug_config_vals", array_values($config_vars)); } $included_templates = $smarty->_smarty_debug_info; $smarty->assign("_debug_keys", array_keys($assigned_vars)); $smarty->assign("_debug_vals", array_values($assigned_vars)); $smarty->assign("_debug_tpls", $included_templates); } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.assign_debug_info.php
PHP
asf20
1,162
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty escape modifier plugin * * Type: modifier<br> * Name: escape<br> * Purpose: Escape the string according to escapement type * @link http://smarty.php.net/manual/en/language.modifier.escape.php * escape (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param html|htmlall|url|quotes|hex|hexentity|javascript * @return string */ function smarty_modifier_escape($string, $esc_type = 'html', $char_set = 'ISO-8859-1') { switch ($esc_type) { case 'html': return htmlspecialchars($string, ENT_QUOTES, $char_set); case 'htmlall': return htmlentities($string, ENT_QUOTES, $char_set); case 'url': return rawurlencode($string); case 'urlpathinfo': return str_replace('%2F','/',rawurlencode($string)); case 'quotes': // escape unescaped single quotes return preg_replace("%(?<!\\\\)'%", "\\'", $string); case 'hex': // escape every character into hex $return = ''; for ($x=0; $x < strlen($string); $x++) { $return .= '%' . bin2hex($string[$x]); } return $return; case 'hexentity': $return = ''; for ($x=0; $x < strlen($string); $x++) { $return .= '&#x' . bin2hex($string[$x]) . ';'; } return $return; case 'decentity': $return = ''; for ($x=0; $x < strlen($string); $x++) { $return .= '&#' . ord($string[$x]) . ';'; } return $return; case 'javascript': // escape quotes and backslashes, newlines, etc. return strtr($string, array('\\'=>'\\\\',"'"=>"\\'",'"'=>'\\"',"\r"=>'\\r',"\n"=>'\\n','</'=>'<\/')); case 'mail': // safe way to display e-mail address on a web page return str_replace(array('@', '.'),array(' [AT] ', ' [DOT] '), $string); case 'nonstd': // escape non-standard chars, such as ms document quotes $_res = ''; for($_i = 0, $_len = strlen($string); $_i < $_len; $_i++) { $_ord = ord(substr($string, $_i, 1)); // non-standard char, escape it if($_ord >= 126){ $_res .= '&#' . $_ord . ';'; } else { $_res .= substr($string, $_i, 1); } } return $_res; default: return $string; } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.escape.php
PHP
asf20
2,751
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {math} function plugin * * Type: function<br> * Name: math<br> * Purpose: handle math computations in template<br> * @link http://smarty.php.net/manual/en/language.function.math.php {math} * (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param array * @param Smarty * @return string */ function smarty_function_math($params, &$smarty) { // be sure equation parameter is present if (empty($params['equation'])) { $smarty->trigger_error("math: missing equation parameter"); return; } $equation = $params['equation']; // make sure parenthesis are balanced if (substr_count($equation,"(") != substr_count($equation,")")) { $smarty->trigger_error("math: unbalanced parenthesis"); return; } // match all vars in equation, make sure all are passed preg_match_all("!(?:0x[a-fA-F0-9]+)|([a-zA-Z][a-zA-Z0-9_]+)!",$equation, $match); $allowed_funcs = array('int','abs','ceil','cos','exp','floor','log','log10', 'max','min','pi','pow','rand','round','sin','sqrt','srand','tan'); foreach($match[1] as $curr_var) { if ($curr_var && !in_array($curr_var, array_keys($params)) && !in_array($curr_var, $allowed_funcs)) { $smarty->trigger_error("math: function call $curr_var not allowed"); return; } } foreach($params as $key => $val) { if ($key != "equation" && $key != "format" && $key != "assign") { // make sure value is not empty if (strlen($val)==0) { $smarty->trigger_error("math: parameter $key is empty"); return; } if (!is_numeric($val)) { $smarty->trigger_error("math: parameter $key: is not numeric"); return; } $equation = preg_replace("/\b$key\b/", " \$params['$key'] ", $equation); } } eval("\$smarty_math_result = ".$equation.";"); if (empty($params['format'])) { if (empty($params['assign'])) { return $smarty_math_result; } else { $smarty->assign($params['assign'],$smarty_math_result); } } else { if (empty($params['assign'])){ printf($params['format'],$smarty_math_result); } else { $smarty->assign($params['assign'],sprintf($params['format'],$smarty_math_result)); } } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.math.php
PHP
asf20
2,579
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty regex_replace modifier plugin * * Type: modifier<br> * Name: regex_replace<br> * Purpose: regular expression search/replace * @link http://smarty.php.net/manual/en/language.modifier.regex.replace.php * regex_replace (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @param string|array * @param string|array * @return string */ function smarty_modifier_regex_replace($string, $search, $replace) { if(is_array($search)) { foreach($search as $idx => $s) $search[$idx] = _smarty_regex_replace_check($s); } else { $search = _smarty_regex_replace_check($search); } return preg_replace($search, $replace, $string); } function _smarty_regex_replace_check($search) { if (($pos = strpos($search,"\0")) !== false) $search = substr($search,0,$pos); if (preg_match('!([a-zA-Z\s]+)$!s', $search, $match) && (strpos($match[1], 'e') !== false)) { /* remove eval-modifier from $search */ $search = substr($search, 0, -strlen($match[1])) . preg_replace('![e\s]+!', '', $match[1]); } return $search; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.regex_replace.php
PHP
asf20
1,255
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty trimwhitespace outputfilter plugin * * File: outputfilter.trimwhitespace.php<br> * Type: outputfilter<br> * Name: trimwhitespace<br> * Date: Jan 25, 2003<br> * Purpose: trim leading white space and blank lines from * template source after it gets interpreted, cleaning * up code and saving bandwidth. Does not affect * <<PRE>></PRE> and <SCRIPT></SCRIPT> blocks.<br> * Install: Drop into the plugin directory, call * <code>$smarty->load_filter('output','trimwhitespace');</code> * from application. * @author Monte Ohrt <monte at ohrt dot com> * @author Contributions from Lars Noschinski <lars@usenet.noschinski.de> * @version 1.3 * @param string * @param Smarty */ function smarty_outputfilter_trimwhitespace($source, &$smarty) { // Pull out the script blocks preg_match_all("!<script[^>]*?>.*?</script>!is", $source, $match); $_script_blocks = $match[0]; $source = preg_replace("!<script[^>]*?>.*?</script>!is", '@@@SMARTY:TRIM:SCRIPT@@@', $source); // Pull out the pre blocks preg_match_all("!<pre[^>]*?>.*?</pre>!is", $source, $match); $_pre_blocks = $match[0]; $source = preg_replace("!<pre[^>]*?>.*?</pre>!is", '@@@SMARTY:TRIM:PRE@@@', $source); // Pull out the textarea blocks preg_match_all("!<textarea[^>]*?>.*?</textarea>!is", $source, $match); $_textarea_blocks = $match[0]; $source = preg_replace("!<textarea[^>]*?>.*?</textarea>!is", '@@@SMARTY:TRIM:TEXTAREA@@@', $source); // remove all leading spaces, tabs and carriage returns NOT // preceeded by a php close tag. $source = trim(preg_replace('/((?<!\?>)\n)[\s]+/m', '\1', $source)); // replace textarea blocks smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:TEXTAREA@@@",$_textarea_blocks, $source); // replace pre blocks smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:PRE@@@",$_pre_blocks, $source); // replace script blocks smarty_outputfilter_trimwhitespace_replace("@@@SMARTY:TRIM:SCRIPT@@@",$_script_blocks, $source); return $source; } function smarty_outputfilter_trimwhitespace_replace($search_str, $replace, &$project) { $_len = strlen($search_str); $_pos = 0; for ($_i=0, $_count=count($replace); $_i<$_count; $_i++) if (($_pos=strpos($project, $search_str, $_pos))!==false) $project = substr_replace($project, $replace[$_i], $_pos, $_len); else break; } ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/outputfilter.trimwhitespace.php
PHP
asf20
2,744
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty lower modifier plugin * * Type: modifier<br> * Name: lower<br> * Purpose: convert string to lowercase * @link http://smarty.php.net/manual/en/language.modifier.lower.php * lower (Smarty online manual) * @author Monte Ohrt <monte at ohrt dot com> * @param string * @return string */ function smarty_modifier_lower($string) { return strtolower($string); } ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/modifier.lower.php
PHP
asf20
481
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {html_select_time} function plugin * * Type: function<br> * Name: html_select_time<br> * Purpose: Prints the dropdowns for time selection * @link http://smarty.php.net/manual/en/language.function.html.select.time.php {html_select_time} * (Smarty online manual) * @author Roberto Berto <roberto@berto.net> * @credits Monte Ohrt <monte AT ohrt DOT com> * @param array * @param Smarty * @return string * @uses smarty_make_timestamp() */ function smarty_function_html_select_time($params, &$smarty) { require_once $smarty->_get_plugin_filepath('shared','make_timestamp'); require_once $smarty->_get_plugin_filepath('function','html_options'); /* Default values. */ $prefix = "Time_"; $time = time(); $display_hours = true; $display_minutes = true; $display_seconds = true; $display_meridian = true; $use_24_hours = true; $minute_interval = 1; $second_interval = 1; /* Should the select boxes be part of an array when returned from PHP? e.g. setting it to "birthday", would create "birthday[Hour]", "birthday[Minute]", "birthday[Seconds]" & "birthday[Meridian]". Can be combined with prefix. */ $field_array = null; $all_extra = null; $hour_extra = null; $minute_extra = null; $second_extra = null; $meridian_extra = null; foreach ($params as $_key=>$_value) { switch ($_key) { case 'prefix': case 'time': case 'field_array': case 'all_extra': case 'hour_extra': case 'minute_extra': case 'second_extra': case 'meridian_extra': $$_key = (string)$_value; break; case 'display_hours': case 'display_minutes': case 'display_seconds': case 'display_meridian': case 'use_24_hours': $$_key = (bool)$_value; break; case 'minute_interval': case 'second_interval': $$_key = (int)$_value; break; default: $smarty->trigger_error("[html_select_time] unknown parameter $_key", E_USER_WARNING); } } $time = smarty_make_timestamp($time); $html_result = ''; if ($display_hours) { $hours = $use_24_hours ? range(0, 23) : range(1, 12); $hour_fmt = $use_24_hours ? '%H' : '%I'; for ($i = 0, $for_max = count($hours); $i < $for_max; $i++) $hours[$i] = sprintf('%02d', $hours[$i]); $html_result .= '<select name='; if (null !== $field_array) { $html_result .= '"' . $field_array . '[' . $prefix . 'Hour]"'; } else { $html_result .= '"' . $prefix . 'Hour"'; } if (null !== $hour_extra){ $html_result .= ' ' . $hour_extra; } if (null !== $all_extra){ $html_result .= ' ' . $all_extra; } $html_result .= '>'."\n"; $html_result .= smarty_function_html_options(array('output' => $hours, 'values' => $hours, 'selected' => strftime($hour_fmt, $time), 'print_result' => false), $smarty); $html_result .= "</select>\n"; } if ($display_minutes) { $all_minutes = range(0, 59); for ($i = 0, $for_max = count($all_minutes); $i < $for_max; $i+= $minute_interval) $minutes[] = sprintf('%02d', $all_minutes[$i]); $selected = intval(floor(strftime('%M', $time) / $minute_interval) * $minute_interval); $html_result .= '<select name='; if (null !== $field_array) { $html_result .= '"' . $field_array . '[' . $prefix . 'Minute]"'; } else { $html_result .= '"' . $prefix . 'Minute"'; } if (null !== $minute_extra){ $html_result .= ' ' . $minute_extra; } if (null !== $all_extra){ $html_result .= ' ' . $all_extra; } $html_result .= '>'."\n"; $html_result .= smarty_function_html_options(array('output' => $minutes, 'values' => $minutes, 'selected' => $selected, 'print_result' => false), $smarty); $html_result .= "</select>\n"; } if ($display_seconds) { $all_seconds = range(0, 59); for ($i = 0, $for_max = count($all_seconds); $i < $for_max; $i+= $second_interval) $seconds[] = sprintf('%02d', $all_seconds[$i]); $selected = intval(floor(strftime('%S', $time) / $second_interval) * $second_interval); $html_result .= '<select name='; if (null !== $field_array) { $html_result .= '"' . $field_array . '[' . $prefix . 'Second]"'; } else { $html_result .= '"' . $prefix . 'Second"'; } if (null !== $second_extra){ $html_result .= ' ' . $second_extra; } if (null !== $all_extra){ $html_result .= ' ' . $all_extra; } $html_result .= '>'."\n"; $html_result .= smarty_function_html_options(array('output' => $seconds, 'values' => $seconds, 'selected' => $selected, 'print_result' => false), $smarty); $html_result .= "</select>\n"; } if ($display_meridian && !$use_24_hours) { $html_result .= '<select name='; if (null !== $field_array) { $html_result .= '"' . $field_array . '[' . $prefix . 'Meridian]"'; } else { $html_result .= '"' . $prefix . 'Meridian"'; } if (null !== $meridian_extra){ $html_result .= ' ' . $meridian_extra; } if (null !== $all_extra){ $html_result .= ' ' . $all_extra; } $html_result .= '>'."\n"; $html_result .= smarty_function_html_options(array('output' => array('AM', 'PM'), 'values' => array('am', 'pm'), 'selected' => strtolower(strftime('%p', $time)), 'print_result' => false), $smarty); $html_result .= "</select>\n"; } return $html_result; } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.html_select_time.php
PHP
asf20
7,262
<?php /** * Smarty plugin * @package Smarty * @subpackage plugins */ /** * Smarty {mailto} function plugin * * Type: function<br> * Name: mailto<br> * Date: May 21, 2002 * Purpose: automate mailto address link creation, and optionally * encode them.<br> * Input:<br> * - address = e-mail address * - text = (optional) text to display, default is address * - encode = (optional) can be one of: * * none : no encoding (default) * * javascript : encode with javascript * * javascript_charcode : encode with javascript charcode * * hex : encode with hexidecimal (no javascript) * - cc = (optional) address(es) to carbon copy * - bcc = (optional) address(es) to blind carbon copy * - project = (optional) e-mail project * - newsgroups = (optional) newsgroup(s) to post to * - followupto = (optional) address(es) to follow up to * - extra = (optional) extra tags for the href link * * Examples: * <pre> * {mailto address="me@domain.com"} * {mailto address="me@domain.com" encode="javascript"} * {mailto address="me@domain.com" encode="hex"} * {mailto address="me@domain.com" project="Hello to you!"} * {mailto address="me@domain.com" cc="you@domain.com,they@domain.com"} * {mailto address="me@domain.com" extra='class="mailto"'} * </pre> * @link http://smarty.php.net/manual/en/language.function.mailto.php {mailto} * (Smarty online manual) * @version 1.2 * @author Monte Ohrt <monte at ohrt dot com> * @author credits to Jason Sweat (added cc, bcc and project functionality) * @param array * @param Smarty * @return string */ function smarty_function_mailto($params, &$smarty) { $extra = ''; if (empty($params['address'])) { $smarty->trigger_error("mailto: missing 'address' parameter"); return; } else { $address = $params['address']; } $text = $address; // netscape and mozilla do not decode %40 (@) in BCC field (bug?) // so, don't encode it. $search = array('%40', '%2C'); $replace = array('@', ','); $mail_parms = array(); foreach ($params as $var=>$value) { switch ($var) { case 'cc': case 'bcc': case 'followupto': if (!empty($value)) $mail_parms[] = $var.'='.str_replace($search,$replace,rawurlencode($value)); break; case 'project': case 'newsgroups': $mail_parms[] = $var.'='.rawurlencode($value); break; case 'extra': case 'text': $$var = $value; default: } } $mail_parm_vals = ''; for ($i=0; $i<count($mail_parms); $i++) { $mail_parm_vals .= (0==$i) ? '?' : '&'; $mail_parm_vals .= $mail_parms[$i]; } $address .= $mail_parm_vals; $encode = (empty($params['encode'])) ? 'none' : $params['encode']; if (!in_array($encode,array('javascript','javascript_charcode','hex','none')) ) { $smarty->trigger_error("mailto: 'encode' parameter must be none, javascript or hex"); return; } if ($encode == 'javascript' ) { $string = 'document.write(\'<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>\');'; $js_encode = ''; for ($x=0; $x < strlen($string); $x++) { $js_encode .= '%' . bin2hex($string[$x]); } return '<script type="text/javascript">eval(unescape(\''.$js_encode.'\'))</script>'; } elseif ($encode == 'javascript_charcode' ) { $string = '<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>'; for($x = 0, $y = strlen($string); $x < $y; $x++ ) { $ord[] = ord($string[$x]); } $_ret = "<script type=\"text/javascript\" language=\"javascript\">\n"; $_ret .= "<!--\n"; $_ret .= "{document.write(String.fromCharCode("; $_ret .= implode(',',$ord); $_ret .= "))"; $_ret .= "}\n"; $_ret .= "//-->\n"; $_ret .= "</script>\n"; return $_ret; } elseif ($encode == 'hex') { preg_match('!^(.*)(\?.*)$!',$address,$match); if(!empty($match[2])) { $smarty->trigger_error("mailto: hex encoding does not work with extra attributes. Try javascript."); return; } $address_encode = ''; for ($x=0; $x < strlen($address); $x++) { if(preg_match('!\w!',$address[$x])) { $address_encode .= '%' . bin2hex($address[$x]); } else { $address_encode .= $address[$x]; } } $text_encode = ''; for ($x=0; $x < strlen($text); $x++) { $text_encode .= '&#x' . bin2hex($text[$x]).';'; } $mailto = "&#109;&#97;&#105;&#108;&#116;&#111;&#58;"; return '<a href="'.$mailto.$address_encode.'" '.$extra.'>'.$text_encode.'</a>'; } else { // no encoding return '<a href="mailto:'.$address.'" '.$extra.'>'.$text.'</a>'; } } /* vim: set expandtab: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/plugins/function.mailto.php
PHP
asf20
5,401
<?php /** * Project: Smarty: the PHP compiling template engine * File: Smarty_Compiler.class.php * * This library 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; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * @link http://www.smarty.net/ * @author Monte Ohrt <monte at ohrt dot com> * @author Andrei Zmievski <andrei@php.net> * @version 2.6.22 * @copyright 2001-2005 New Digital Group, Inc. * @package Smarty */ /* $Id: Smarty_Compiler.class.php 2966 2008-12-08 15:10:03Z monte.ohrt $ */ /** * Template compiling class * @package Smarty */ class Smarty_Compiler extends Smarty { // internal vars /**#@+ * @access private */ var $_folded_blocks = array(); // keeps folded template blocks var $_current_file = null; // the current template being compiled var $_current_line_no = 1; // line number for error messages var $_capture_stack = array(); // keeps track of nested capture buffers var $_plugin_info = array(); // keeps track of plugins to load var $_init_smarty_vars = false; var $_permitted_tokens = array('true','false','yes','no','on','off','null'); var $_db_qstr_regexp = null; // regexps are setup in the constructor var $_si_qstr_regexp = null; var $_qstr_regexp = null; var $_func_regexp = null; var $_reg_obj_regexp = null; var $_var_bracket_regexp = null; var $_num_const_regexp = null; var $_dvar_guts_regexp = null; var $_dvar_regexp = null; var $_cvar_regexp = null; var $_svar_regexp = null; var $_avar_regexp = null; var $_mod_regexp = null; var $_var_regexp = null; var $_parenth_param_regexp = null; var $_func_call_regexp = null; var $_obj_ext_regexp = null; var $_obj_start_regexp = null; var $_obj_params_regexp = null; var $_obj_call_regexp = null; var $_cacheable_state = 0; var $_cache_attrs_count = 0; var $_nocache_count = 0; var $_cache_serial = null; var $_cache_include = null; var $_strip_depth = 0; var $_additional_newline = ""; var $_phpversion = 0; /**#@-*/ /** * The class constructor. */ function Smarty_Compiler() { $this->_phpversion = substr(phpversion(),0,1); // matches double quoted strings: // "foobar" // "foo\"bar" $this->_db_qstr_regexp = '"[^"\\\\]*(?:\\\\.[^"\\\\]*)*"'; // matches single quoted strings: // 'foobar' // 'foo\'bar' $this->_si_qstr_regexp = '\'[^\'\\\\]*(?:\\\\.[^\'\\\\]*)*\''; // matches single or double quoted strings $this->_qstr_regexp = '(?:' . $this->_db_qstr_regexp . '|' . $this->_si_qstr_regexp . ')'; // matches bracket portion of vars // [0] // [foo] // [$bar] $this->_var_bracket_regexp = '\[\$?[\w\.]+\]'; // matches numerical constants // 30 // -12 // 13.22 $this->_num_const_regexp = '(?:\-?\d+(?:\.\d+)?)'; // matches $ vars (not objects): // $foo // $foo.bar // $foo.bar.foobar // $foo[0] // $foo[$bar] // $foo[5][blah] // $foo[5].bar[$foobar][4] $this->_dvar_math_regexp = '(?:[\+\*\/\%]|(?:-(?!>)))'; $this->_dvar_math_var_regexp = '[\$\w\.\+\-\*\/\%\d\>\[\]]'; $this->_dvar_guts_regexp = '\w+(?:' . $this->_var_bracket_regexp . ')*(?:\.\$?\w+(?:' . $this->_var_bracket_regexp . ')*)*(?:' . $this->_dvar_math_regexp . '(?:' . $this->_num_const_regexp . '|' . $this->_dvar_math_var_regexp . ')*)?'; $this->_dvar_regexp = '\$' . $this->_dvar_guts_regexp; // matches config vars: // #foo# // #foobar123_foo# $this->_cvar_regexp = '\#\w+\#'; // matches section vars: // %foo.bar% $this->_svar_regexp = '\%\w+\.\w+\%'; // matches all valid variables (no quotes, no modifiers) $this->_avar_regexp = '(?:' . $this->_dvar_regexp . '|' . $this->_cvar_regexp . '|' . $this->_svar_regexp . ')'; // matches valid variable syntax: // $foo // $foo // #foo# // #foo# // "text" // "text" $this->_var_regexp = '(?:' . $this->_avar_regexp . '|' . $this->_qstr_regexp . ')'; // matches valid object call (one level of object nesting allowed in parameters): // $foo->bar // $foo->bar() // $foo->bar("text") // $foo->bar($foo, $bar, "text") // $foo->bar($foo, "foo") // $foo->bar->foo() // $foo->bar->foo->bar() // $foo->bar($foo->bar) // $foo->bar($foo->bar()) // $foo->bar($foo->bar($blah,$foo,44,"foo",$foo[0].bar)) // $foo->getBar()->getFoo() // $foo->getBar()->foo $this->_obj_ext_regexp = '\->(?:\$?' . $this->_dvar_guts_regexp . ')'; $this->_obj_restricted_param_regexp = '(?:' . '(?:' . $this->_var_regexp . '|' . $this->_num_const_regexp . ')(?:' . $this->_obj_ext_regexp . '(?:\((?:(?:' . $this->_var_regexp . '|' . $this->_num_const_regexp . ')' . '(?:\s*,\s*(?:' . $this->_var_regexp . '|' . $this->_num_const_regexp . '))*)?\))?)*)'; $this->_obj_single_param_regexp = '(?:\w+|' . $this->_obj_restricted_param_regexp . '(?:\s*,\s*(?:(?:\w+|' . $this->_var_regexp . $this->_obj_restricted_param_regexp . ')))*)'; $this->_obj_params_regexp = '\((?:' . $this->_obj_single_param_regexp . '(?:\s*,\s*' . $this->_obj_single_param_regexp . ')*)?\)'; $this->_obj_start_regexp = '(?:' . $this->_dvar_regexp . '(?:' . $this->_obj_ext_regexp . ')+)'; $this->_obj_call_regexp = '(?:' . $this->_obj_start_regexp . '(?:' . $this->_obj_params_regexp . ')?(?:' . $this->_dvar_math_regexp . '(?:' . $this->_num_const_regexp . '|' . $this->_dvar_math_var_regexp . ')*)?)'; // matches valid modifier syntax: // |foo // |@foo // |foo:"bar" // |foo:$bar // |foo:"bar":$foobar // |foo|bar // |foo:$foo->bar $this->_mod_regexp = '(?:\|@?\w+(?::(?:\w+|' . $this->_num_const_regexp . '|' . $this->_obj_call_regexp . '|' . $this->_avar_regexp . '|' . $this->_qstr_regexp .'))*)'; // matches valid function name: // foo123 // _foo_bar $this->_func_regexp = '[a-zA-Z_]\w*'; // matches valid registered object: // foo->bar $this->_reg_obj_regexp = '[a-zA-Z_]\w*->[a-zA-Z_]\w*'; // matches valid parameter values: // true // $foo // $foo|bar // #foo# // #foo#|bar // "text" // "text"|bar // $foo->bar $this->_param_regexp = '(?:\s*(?:' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '|' . $this->_num_const_regexp . '|\w+)(?>' . $this->_mod_regexp . '*)\s*)'; // matches valid parenthesised function parameters: // // "text" // $foo, $bar, "text" // $foo|bar, "foo"|bar, $foo->bar($foo)|bar $this->_parenth_param_regexp = '(?:\((?:\w+|' . $this->_param_regexp . '(?:\s*,\s*(?:(?:\w+|' . $this->_param_regexp . ')))*)?\))'; // matches valid function call: // foo() // foo_bar($foo) // _foo_bar($foo,"bar") // foo123($foo,$foo->bar(),"foo") $this->_func_call_regexp = '(?:' . $this->_func_regexp . '\s*(?:' . $this->_parenth_param_regexp . '))'; } /** * compile a resource * * sets $compiled_content to the compiled source * @param string $resource_name * @param string $source_content * @param string $compiled_content * @return true */ function _compile_file($resource_name, $source_content, &$compiled_content) { if ($this->security) { // do not allow php syntax to be executed unless specified if ($this->php_handling == SMARTY_PHP_ALLOW && !$this->security_settings['PHP_HANDLING']) { $this->php_handling = SMARTY_PHP_PASSTHRU; } } $this->_load_filters(); $this->_current_file = $resource_name; $this->_current_line_no = 1; $ldq = preg_quote($this->left_delimiter, '~'); $rdq = preg_quote($this->right_delimiter, '~'); // run template source through prefilter functions if (count($this->_plugins['prefilter']) > 0) { foreach ($this->_plugins['prefilter'] as $filter_name => $prefilter) { if ($prefilter === false) continue; if ($prefilter[3] || is_callable($prefilter[0])) { $source_content = call_user_func_array($prefilter[0], array($source_content, &$this)); $this->_plugins['prefilter'][$filter_name][3] = true; } else { $this->_trigger_fatal_error("[plugin] prefilter '$filter_name' is not implemented"); } } } /* fetch all special blocks */ $search = "~{$ldq}\*(.*?)\*{$rdq}|{$ldq}\s*literal\s*{$rdq}(.*?){$ldq}\s*/literal\s*{$rdq}|{$ldq}\s*php\s*{$rdq}(.*?){$ldq}\s*/php\s*{$rdq}~s"; preg_match_all($search, $source_content, $match, PREG_SET_ORDER); $this->_folded_blocks = $match; reset($this->_folded_blocks); /* replace special blocks by "{php}" */ $source_content = preg_replace($search.'e', "'" . $this->_quote_replace($this->left_delimiter) . 'php' . "' . str_repeat(\"\n\", substr_count('\\0', \"\n\")) .'" . $this->_quote_replace($this->right_delimiter) . "'" , $source_content); /* Gather all template tags. */ preg_match_all("~{$ldq}\s*(.*?)\s*{$rdq}~s", $source_content, $_match); $template_tags = $_match[1]; /* Split content by template tags to obtain non-template content. */ $text_blocks = preg_split("~{$ldq}.*?{$rdq}~s", $source_content); /* loop through text blocks */ for ($curr_tb = 0, $for_max = count($text_blocks); $curr_tb < $for_max; $curr_tb++) { /* match anything resembling php tags */ if (preg_match_all('~(<\?(?:\w+|=)?|\?>|language\s*=\s*[\"\']?\s*php\s*[\"\']?)~is', $text_blocks[$curr_tb], $sp_match)) { /* replace tags with placeholders to prevent recursive replacements */ $sp_match[1] = array_unique($sp_match[1]); usort($sp_match[1], '_smarty_sort_length'); for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) { $text_blocks[$curr_tb] = str_replace($sp_match[1][$curr_sp],'%%%SMARTYSP'.$curr_sp.'%%%',$text_blocks[$curr_tb]); } /* process each one */ for ($curr_sp = 0, $for_max2 = count($sp_match[1]); $curr_sp < $for_max2; $curr_sp++) { if ($this->php_handling == SMARTY_PHP_PASSTHRU) { /* echo php contents */ $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', '<?php echo \''.str_replace("'", "\'", $sp_match[1][$curr_sp]).'\'; ?>'."\n", $text_blocks[$curr_tb]); } else if ($this->php_handling == SMARTY_PHP_QUOTE) { /* quote php tags */ $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', htmlspecialchars($sp_match[1][$curr_sp]), $text_blocks[$curr_tb]); } else if ($this->php_handling == SMARTY_PHP_REMOVE) { /* remove php tags */ $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', '', $text_blocks[$curr_tb]); } else { /* SMARTY_PHP_ALLOW, but echo non php starting tags */ $sp_match[1][$curr_sp] = preg_replace('~(<\?(?!php|=|$))~i', '<?php echo \'\\1\'?>'."\n", $sp_match[1][$curr_sp]); $text_blocks[$curr_tb] = str_replace('%%%SMARTYSP'.$curr_sp.'%%%', $sp_match[1][$curr_sp], $text_blocks[$curr_tb]); } } } } /* Compile the template tags into PHP code. */ $compiled_tags = array(); for ($i = 0, $for_max = count($template_tags); $i < $for_max; $i++) { $this->_current_line_no += substr_count($text_blocks[$i], "\n"); $compiled_tags[] = $this->_compile_tag($template_tags[$i]); $this->_current_line_no += substr_count($template_tags[$i], "\n"); } if (count($this->_tag_stack)>0) { list($_open_tag, $_line_no) = end($this->_tag_stack); $this->_syntax_error("unclosed tag \{$_open_tag} (opened line $_line_no).", E_USER_ERROR, __FILE__, __LINE__); return; } /* Reformat $text_blocks between 'strip' and '/strip' tags, removing spaces, tabs and newlines. */ $strip = false; for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++) { if ($compiled_tags[$i] == '{strip}') { $compiled_tags[$i] = ''; $strip = true; /* remove leading whitespaces */ $text_blocks[$i + 1] = ltrim($text_blocks[$i + 1]); } if ($strip) { /* strip all $text_blocks before the next '/strip' */ for ($j = $i + 1; $j < $for_max; $j++) { /* remove leading and trailing whitespaces of each line */ $text_blocks[$j] = preg_replace('![\t ]*[\r\n]+[\t ]*!', '', $text_blocks[$j]); if ($compiled_tags[$j] == '{/strip}') { /* remove trailing whitespaces from the last text_block */ $text_blocks[$j] = rtrim($text_blocks[$j]); } $text_blocks[$j] = "<?php echo '" . strtr($text_blocks[$j], array("'"=>"\'", "\\"=>"\\\\")) . "'; ?>"; if ($compiled_tags[$j] == '{/strip}') { $compiled_tags[$j] = "\n"; /* slurped by php, but necessary if a newline is following the closing strip-tag */ $strip = false; $i = $j; break; } } } } $compiled_content = ''; $tag_guard = '%%%SMARTYOTG' . md5(uniqid(rand(), true)) . '%%%'; /* Interleave the compiled contents and text blocks to get the final result. */ for ($i = 0, $for_max = count($compiled_tags); $i < $for_max; $i++) { if ($compiled_tags[$i] == '') { // tag result empty, remove first newline from following text block $text_blocks[$i+1] = preg_replace('~^(\r\n|\r|\n)~', '', $text_blocks[$i+1]); } // replace legit PHP tags with placeholder $text_blocks[$i] = str_replace('<?', $tag_guard, $text_blocks[$i]); $compiled_tags[$i] = str_replace('<?', $tag_guard, $compiled_tags[$i]); $compiled_content .= $text_blocks[$i] . $compiled_tags[$i]; } $compiled_content .= str_replace('<?', $tag_guard, $text_blocks[$i]); // escape php tags created by interleaving $compiled_content = str_replace('<?', "<?php echo '<?' ?>", $compiled_content); $compiled_content = preg_replace("~(?<!')language\s*=\s*[\"\']?\s*php\s*[\"\']?~", "<?php echo 'language=php' ?>", $compiled_content); // recover legit tags $compiled_content = str_replace($tag_guard, '<?', $compiled_content); // remove \n from the end of the file, if any if (strlen($compiled_content) && (substr($compiled_content, -1) == "\n") ) { $compiled_content = substr($compiled_content, 0, -1); } if (!empty($this->_cache_serial)) { $compiled_content = "<?php \$this->_cache_serials['".$this->_cache_include."'] = '".$this->_cache_serial."'; ?>" . $compiled_content; } // run compiled template through postfilter functions if (count($this->_plugins['postfilter']) > 0) { foreach ($this->_plugins['postfilter'] as $filter_name => $postfilter) { if ($postfilter === false) continue; if ($postfilter[3] || is_callable($postfilter[0])) { $compiled_content = call_user_func_array($postfilter[0], array($compiled_content, &$this)); $this->_plugins['postfilter'][$filter_name][3] = true; } else { $this->_trigger_fatal_error("Smarty plugin error: postfilter '$filter_name' is not implemented"); } } } // put header at the top of the compiled template $template_header = "<?php /* Smarty version ".$this->_version.", created on ".strftime("%Y-%m-%d %H:%M:%S")."\n"; $template_header .= " compiled from ".strtr(urlencode($resource_name), array('%2F'=>'/', '%3A'=>':'))." */ ?>"; /* Emit code to load needed plugins. */ $this->_plugins_code = ''; if (count($this->_plugin_info)) { $_plugins_params = "array('plugins' => array("; foreach ($this->_plugin_info as $plugin_type => $plugins) { foreach ($plugins as $plugin_name => $plugin_info) { $_plugins_params .= "array('$plugin_type', '$plugin_name', '" . strtr($plugin_info[0], array("'" => "\\'", "\\" => "\\\\")) . "', $plugin_info[1], "; $_plugins_params .= $plugin_info[2] ? 'true),' : 'false),'; } } $_plugins_params .= '))'; $plugins_code = "<?php require_once(SMARTY_CORE_DIR . 'core.load_plugins.php');\nsmarty_core_load_plugins($_plugins_params, \$this); ?>"; $template_header .= $plugins_code; $this->_plugin_info = array(); $this->_plugins_code = $plugins_code; } if ($this->_init_smarty_vars) { $template_header .= "<?php require_once(SMARTY_CORE_DIR . 'core.assign_smarty_interface.php');\nsmarty_core_assign_smarty_interface(null, \$this); ?>"; $this->_init_smarty_vars = false; } $compiled_content = $template_header . $compiled_content; return true; } /** * Compile a template tag * * @param string $template_tag * @return string */ function _compile_tag($template_tag) { /* Matched comment. */ if (substr($template_tag, 0, 1) == '*' && substr($template_tag, -1) == '*') return ''; /* Split tag into two three parts: command, command modifiers and the a. */ if(! preg_match('~^(?:(' . $this->_num_const_regexp . '|' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '|\/?' . $this->_reg_obj_regexp . '|\/?' . $this->_func_regexp . ')(' . $this->_mod_regexp . '*)) (?:\s+(.*))?$ ~xs', $template_tag, $match)) { $this->_syntax_error("unrecognized tag: $template_tag", E_USER_ERROR, __FILE__, __LINE__); } $tag_command = $match[1]; $tag_modifier = isset($match[2]) ? $match[2] : null; $tag_args = isset($match[3]) ? $match[3] : null; if (preg_match('~^' . $this->_num_const_regexp . '|' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '$~', $tag_command)) { /* tag name is a variable or object */ $_return = $this->_parse_var_props($tag_command . $tag_modifier); return "<?php echo $_return; ?>" . $this->_additional_newline; } /* If the tag name is a registered object, we process it. */ if (preg_match('~^\/?' . $this->_reg_obj_regexp . '$~', $tag_command)) { return $this->_compile_registered_object_tag($tag_command, $this->_parse_attrs($tag_args), $tag_modifier); } switch ($tag_command) { case 'include': return $this->_compile_include_tag($tag_args); case 'include_php': return $this->_compile_include_php_tag($tag_args); case 'if': $this->_push_tag('if'); return $this->_compile_if_tag($tag_args); case 'else': list($_open_tag) = end($this->_tag_stack); if ($_open_tag != 'if' && $_open_tag != 'elseif') $this->_syntax_error('unexpected {else}', E_USER_ERROR, __FILE__, __LINE__); else $this->_push_tag('else'); return '<?php else: ?>'; case 'elseif': list($_open_tag) = end($this->_tag_stack); if ($_open_tag != 'if' && $_open_tag != 'elseif') $this->_syntax_error('unexpected {elseif}', E_USER_ERROR, __FILE__, __LINE__); if ($_open_tag == 'if') $this->_push_tag('elseif'); return $this->_compile_if_tag($tag_args, true); case '/if': $this->_pop_tag('if'); return '<?php endif; ?>'; case 'capture': return $this->_compile_capture_tag(true, $tag_args); case '/capture': return $this->_compile_capture_tag(false); case 'ldelim': return $this->left_delimiter; case 'rdelim': return $this->right_delimiter; case 'section': $this->_push_tag('section'); return $this->_compile_section_start($tag_args); case 'sectionelse': $this->_push_tag('sectionelse'); return "<?php endfor; else: ?>"; break; case '/section': $_open_tag = $this->_pop_tag('section'); if ($_open_tag == 'sectionelse') return "<?php endif; ?>"; else return "<?php endfor; endif; ?>"; case 'foreach': $this->_push_tag('foreach'); return $this->_compile_foreach_start($tag_args); break; case 'foreachelse': $this->_push_tag('foreachelse'); return "<?php endforeach; else: ?>"; case '/foreach': $_open_tag = $this->_pop_tag('foreach'); if ($_open_tag == 'foreachelse') return "<?php endif; unset(\$_from); ?>"; else return "<?php endforeach; endif; unset(\$_from); ?>"; break; case 'strip': case '/strip': if (substr($tag_command, 0, 1)=='/') { $this->_pop_tag('strip'); if (--$this->_strip_depth==0) { /* outermost closing {/strip} */ $this->_additional_newline = "\n"; return '{' . $tag_command . '}'; } } else { $this->_push_tag('strip'); if ($this->_strip_depth++==0) { /* outermost opening {strip} */ $this->_additional_newline = ""; return '{' . $tag_command . '}'; } } return ''; case 'php': /* handle folded tags replaced by {php} */ list(, $block) = each($this->_folded_blocks); $this->_current_line_no += substr_count($block[0], "\n"); /* the number of matched elements in the regexp in _compile_file() determins the type of folded tag that was found */ switch (count($block)) { case 2: /* comment */ return ''; case 3: /* literal */ return "<?php echo '" . strtr($block[2], array("'"=>"\'", "\\"=>"\\\\")) . "'; ?>" . $this->_additional_newline; case 4: /* php */ if ($this->security && !$this->security_settings['PHP_TAGS']) { $this->_syntax_error("(secure mode) php tags not permitted", E_USER_WARNING, __FILE__, __LINE__); return; } return '<?php ' . $block[3] .' ?>'; } break; case 'insert': return $this->_compile_insert_tag($tag_args); default: if ($this->_compile_compiler_tag($tag_command, $tag_args, $output)) { return $output; } else if ($this->_compile_block_tag($tag_command, $tag_args, $tag_modifier, $output)) { return $output; } else if ($this->_compile_custom_tag($tag_command, $tag_args, $tag_modifier, $output)) { return $output; } else { $this->_syntax_error("unrecognized tag '$tag_command'", E_USER_ERROR, __FILE__, __LINE__); } } } /** * compile the custom compiler tag * * sets $output to the compiled custom compiler tag * @param string $tag_command * @param string $tag_args * @param string $output * @return boolean */ function _compile_compiler_tag($tag_command, $tag_args, &$output) { $found = false; $have_function = true; /* * First we check if the compiler function has already been registered * or loaded from a plugin file. */ if (isset($this->_plugins['compiler'][$tag_command])) { $found = true; $plugin_func = $this->_plugins['compiler'][$tag_command][0]; if (!is_callable($plugin_func)) { $message = "compiler function '$tag_command' is not implemented"; $have_function = false; } } /* * Otherwise we need to load plugin file and look for the function * inside it. */ else if ($plugin_file = $this->_get_plugin_filepath('compiler', $tag_command)) { $found = true; include_once $plugin_file; $plugin_func = 'smarty_compiler_' . $tag_command; if (!is_callable($plugin_func)) { $message = "plugin function $plugin_func() not found in $plugin_file\n"; $have_function = false; } else { $this->_plugins['compiler'][$tag_command] = array($plugin_func, null, null, null, true); } } /* * True return value means that we either found a plugin or a * dynamically registered function. False means that we didn't and the * compiler should now emit code to load custom function plugin for this * tag. */ if ($found) { if ($have_function) { $output = call_user_func_array($plugin_func, array($tag_args, &$this)); if($output != '') { $output = '<?php ' . $this->_push_cacheable_state('compiler', $tag_command) . $output . $this->_pop_cacheable_state('compiler', $tag_command) . ' ?>'; } } else { $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__); } return true; } else { return false; } } /** * compile block function tag * * sets $output to compiled block function tag * @param string $tag_command * @param string $tag_args * @param string $tag_modifier * @param string $output * @return boolean */ function _compile_block_tag($tag_command, $tag_args, $tag_modifier, &$output) { if (substr($tag_command, 0, 1) == '/') { $start_tag = false; $tag_command = substr($tag_command, 1); } else $start_tag = true; $found = false; $have_function = true; /* * First we check if the block function has already been registered * or loaded from a plugin file. */ if (isset($this->_plugins['block'][$tag_command])) { $found = true; $plugin_func = $this->_plugins['block'][$tag_command][0]; if (!is_callable($plugin_func)) { $message = "block function '$tag_command' is not implemented"; $have_function = false; } } /* * Otherwise we need to load plugin file and look for the function * inside it. */ else if ($plugin_file = $this->_get_plugin_filepath('block', $tag_command)) { $found = true; include_once $plugin_file; $plugin_func = 'smarty_block_' . $tag_command; if (!function_exists($plugin_func)) { $message = "plugin function $plugin_func() not found in $plugin_file\n"; $have_function = false; } else { $this->_plugins['block'][$tag_command] = array($plugin_func, null, null, null, true); } } if (!$found) { return false; } else if (!$have_function) { $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__); return true; } /* * Even though we've located the plugin function, compilation * happens only once, so the plugin will still need to be loaded * at runtime for future requests. */ $this->_add_plugin('block', $tag_command); if ($start_tag) $this->_push_tag($tag_command); else $this->_pop_tag($tag_command); if ($start_tag) { $output = '<?php ' . $this->_push_cacheable_state('block', $tag_command); $attrs = $this->_parse_attrs($tag_args); $_cache_attrs=''; $arg_list = $this->_compile_arg_list('block', $tag_command, $attrs, $_cache_attrs); $output .= "$_cache_attrs\$this->_tag_stack[] = array('$tag_command', array(".implode(',', $arg_list).')); '; $output .= '$_block_repeat=true;' . $this->_compile_plugin_call('block', $tag_command).'($this->_tag_stack[count($this->_tag_stack)-1][1], null, $this, $_block_repeat);'; $output .= 'while ($_block_repeat) { ob_start(); ?>'; } else { $output = '<?php $_block_content = ob_get_contents(); ob_end_clean(); '; $_out_tag_text = $this->_compile_plugin_call('block', $tag_command).'($this->_tag_stack[count($this->_tag_stack)-1][1], $_block_content, $this, $_block_repeat)'; if ($tag_modifier != '') { $this->_parse_modifiers($_out_tag_text, $tag_modifier); } $output .= '$_block_repeat=false;echo ' . $_out_tag_text . '; } '; $output .= " array_pop(\$this->_tag_stack); " . $this->_pop_cacheable_state('block', $tag_command) . '?>'; } return true; } /** * compile custom function tag * * @param string $tag_command * @param string $tag_args * @param string $tag_modifier * @return string */ function _compile_custom_tag($tag_command, $tag_args, $tag_modifier, &$output) { $found = false; $have_function = true; /* * First we check if the custom function has already been registered * or loaded from a plugin file. */ if (isset($this->_plugins['function'][$tag_command])) { $found = true; $plugin_func = $this->_plugins['function'][$tag_command][0]; if (!is_callable($plugin_func)) { $message = "custom function '$tag_command' is not implemented"; $have_function = false; } } /* * Otherwise we need to load plugin file and look for the function * inside it. */ else if ($plugin_file = $this->_get_plugin_filepath('function', $tag_command)) { $found = true; include_once $plugin_file; $plugin_func = 'smarty_function_' . $tag_command; if (!function_exists($plugin_func)) { $message = "plugin function $plugin_func() not found in $plugin_file\n"; $have_function = false; } else { $this->_plugins['function'][$tag_command] = array($plugin_func, null, null, null, true); } } if (!$found) { return false; } else if (!$have_function) { $this->_syntax_error($message, E_USER_WARNING, __FILE__, __LINE__); return true; } /* declare plugin to be loaded on display of the template that we compile right now */ $this->_add_plugin('function', $tag_command); $_cacheable_state = $this->_push_cacheable_state('function', $tag_command); $attrs = $this->_parse_attrs($tag_args); $_cache_attrs = ''; $arg_list = $this->_compile_arg_list('function', $tag_command, $attrs, $_cache_attrs); $output = $this->_compile_plugin_call('function', $tag_command).'(array('.implode(',', $arg_list)."), \$this)"; if($tag_modifier != '') { $this->_parse_modifiers($output, $tag_modifier); } if($output != '') { $output = '<?php ' . $_cacheable_state . $_cache_attrs . 'echo ' . $output . ';' . $this->_pop_cacheable_state('function', $tag_command) . "?>" . $this->_additional_newline; } return true; } /** * compile a registered object tag * * @param string $tag_command * @param array $attrs * @param string $tag_modifier * @return string */ function _compile_registered_object_tag($tag_command, $attrs, $tag_modifier) { if (substr($tag_command, 0, 1) == '/') { $start_tag = false; $tag_command = substr($tag_command, 1); } else { $start_tag = true; } list($object, $obj_comp) = explode('->', $tag_command); $arg_list = array(); if(count($attrs)) { $_assign_var = false; foreach ($attrs as $arg_name => $arg_value) { if($arg_name == 'assign') { $_assign_var = $arg_value; unset($attrs['assign']); continue; } if (is_bool($arg_value)) $arg_value = $arg_value ? 'true' : 'false'; $arg_list[] = "'$arg_name' => $arg_value"; } } if($this->_reg_objects[$object][2]) { // smarty object argument format $args = "array(".implode(',', (array)$arg_list)."), \$this"; } else { // traditional argument format $args = implode(',', array_values($attrs)); if (empty($args)) { $args = ''; } } $prefix = ''; $postfix = ''; $newline = ''; if(!is_object($this->_reg_objects[$object][0])) { $this->_trigger_fatal_error("registered '$object' is not an object" , $this->_current_file, $this->_current_line_no, __FILE__, __LINE__); } elseif(!empty($this->_reg_objects[$object][1]) && !in_array($obj_comp, $this->_reg_objects[$object][1])) { $this->_trigger_fatal_error("'$obj_comp' is not a registered component of object '$object'", $this->_current_file, $this->_current_line_no, __FILE__, __LINE__); } elseif(method_exists($this->_reg_objects[$object][0], $obj_comp)) { // method if(in_array($obj_comp, $this->_reg_objects[$object][3])) { // block method if ($start_tag) { $prefix = "\$this->_tag_stack[] = array('$obj_comp', $args); "; $prefix .= "\$_block_repeat=true; \$this->_reg_objects['$object'][0]->$obj_comp(\$this->_tag_stack[count(\$this->_tag_stack)-1][1], null, \$this, \$_block_repeat); "; $prefix .= "while (\$_block_repeat) { ob_start();"; $return = null; $postfix = ''; } else { $prefix = "\$_obj_block_content = ob_get_contents(); ob_end_clean(); \$_block_repeat=false;"; $return = "\$this->_reg_objects['$object'][0]->$obj_comp(\$this->_tag_stack[count(\$this->_tag_stack)-1][1], \$_obj_block_content, \$this, \$_block_repeat)"; $postfix = "} array_pop(\$this->_tag_stack);"; } } else { // non-block method $return = "\$this->_reg_objects['$object'][0]->$obj_comp($args)"; } } else { // property $return = "\$this->_reg_objects['$object'][0]->$obj_comp"; } if($return != null) { if($tag_modifier != '') { $this->_parse_modifiers($return, $tag_modifier); } if(!empty($_assign_var)) { $output = "\$this->assign('" . $this->_dequote($_assign_var) ."', $return);"; } else { $output = 'echo ' . $return . ';'; $newline = $this->_additional_newline; } } else { $output = ''; } return '<?php ' . $prefix . $output . $postfix . "?>" . $newline; } /** * Compile {insert ...} tag * * @param string $tag_args * @return string */ function _compile_insert_tag($tag_args) { $attrs = $this->_parse_attrs($tag_args); $name = $this->_dequote($attrs['name']); if (empty($name)) { return $this->_syntax_error("missing insert name", E_USER_ERROR, __FILE__, __LINE__); } if (!preg_match('~^\w+$~', $name)) { return $this->_syntax_error("'insert: 'name' must be an insert function name", E_USER_ERROR, __FILE__, __LINE__); } if (!empty($attrs['script'])) { $delayed_loading = true; } else { $delayed_loading = false; } foreach ($attrs as $arg_name => $arg_value) { if (is_bool($arg_value)) $arg_value = $arg_value ? 'true' : 'false'; $arg_list[] = "'$arg_name' => $arg_value"; } $this->_add_plugin('insert', $name, $delayed_loading); $_params = "array('args' => array(".implode(', ', (array)$arg_list)."))"; return "<?php require_once(SMARTY_CORE_DIR . 'core.run_insert_handler.php');\necho smarty_core_run_insert_handler($_params, \$this); ?>" . $this->_additional_newline; } /** * Compile {include ...} tag * * @param string $tag_args * @return string */ function _compile_include_tag($tag_args) { $attrs = $this->_parse_attrs($tag_args); $arg_list = array(); if (empty($attrs['file'])) { $this->_syntax_error("missing 'file' attribute in include tag", E_USER_ERROR, __FILE__, __LINE__); } foreach ($attrs as $arg_name => $arg_value) { if ($arg_name == 'file') { $include_file = $arg_value; continue; } else if ($arg_name == 'assign') { $assign_var = $arg_value; continue; } if (is_bool($arg_value)) $arg_value = $arg_value ? 'true' : 'false'; $arg_list[] = "'$arg_name' => $arg_value"; } $output = '<?php '; if (isset($assign_var)) { $output .= "ob_start();\n"; } $output .= "\$_smarty_tpl_vars = \$this->_tpl_vars;\n"; $_params = "array('smarty_include_tpl_file' => " . $include_file . ", 'smarty_include_vars' => array(".implode(',', (array)$arg_list)."))"; $output .= "\$this->_smarty_include($_params);\n" . "\$this->_tpl_vars = \$_smarty_tpl_vars;\n" . "unset(\$_smarty_tpl_vars);\n"; if (isset($assign_var)) { $output .= "\$this->assign(" . $assign_var . ", ob_get_contents()); ob_end_clean();\n"; } $output .= ' ?>'; return $output; } /** * Compile {include ...} tag * * @param string $tag_args * @return string */ function _compile_include_php_tag($tag_args) { $attrs = $this->_parse_attrs($tag_args); if (empty($attrs['file'])) { $this->_syntax_error("missing 'file' attribute in include_php tag", E_USER_ERROR, __FILE__, __LINE__); } $assign_var = (empty($attrs['assign'])) ? '' : $this->_dequote($attrs['assign']); $once_var = (empty($attrs['once']) || $attrs['once']=='false') ? 'false' : 'true'; $arg_list = array(); foreach($attrs as $arg_name => $arg_value) { if($arg_name != 'file' AND $arg_name != 'once' AND $arg_name != 'assign') { if(is_bool($arg_value)) $arg_value = $arg_value ? 'true' : 'false'; $arg_list[] = "'$arg_name' => $arg_value"; } } $_params = "array('smarty_file' => " . $attrs['file'] . ", 'smarty_assign' => '$assign_var', 'smarty_once' => $once_var, 'smarty_include_vars' => array(".implode(',', $arg_list)."))"; return "<?php require_once(SMARTY_CORE_DIR . 'core.smarty_include_php.php');\nsmarty_core_smarty_include_php($_params, \$this); ?>" . $this->_additional_newline; } /** * Compile {section ...} tag * * @param string $tag_args * @return string */ function _compile_section_start($tag_args) { $attrs = $this->_parse_attrs($tag_args); $arg_list = array(); $output = '<?php '; $section_name = $attrs['name']; if (empty($section_name)) { $this->_syntax_error("missing section name", E_USER_ERROR, __FILE__, __LINE__); } $output .= "unset(\$this->_sections[$section_name]);\n"; $section_props = "\$this->_sections[$section_name]"; foreach ($attrs as $attr_name => $attr_value) { switch ($attr_name) { case 'loop': $output .= "{$section_props}['loop'] = is_array(\$_loop=$attr_value) ? count(\$_loop) : max(0, (int)\$_loop); unset(\$_loop);\n"; break; case 'show': if (is_bool($attr_value)) $show_attr_value = $attr_value ? 'true' : 'false'; else $show_attr_value = "(bool)$attr_value"; $output .= "{$section_props}['show'] = $show_attr_value;\n"; break; case 'name': $output .= "{$section_props}['$attr_name'] = $attr_value;\n"; break; case 'max': case 'start': $output .= "{$section_props}['$attr_name'] = (int)$attr_value;\n"; break; case 'step': $output .= "{$section_props}['$attr_name'] = ((int)$attr_value) == 0 ? 1 : (int)$attr_value;\n"; break; default: $this->_syntax_error("unknown section attribute - '$attr_name'", E_USER_ERROR, __FILE__, __LINE__); break; } } if (!isset($attrs['show'])) $output .= "{$section_props}['show'] = true;\n"; if (!isset($attrs['loop'])) $output .= "{$section_props}['loop'] = 1;\n"; if (!isset($attrs['max'])) $output .= "{$section_props}['max'] = {$section_props}['loop'];\n"; else $output .= "if ({$section_props}['max'] < 0)\n" . " {$section_props}['max'] = {$section_props}['loop'];\n"; if (!isset($attrs['step'])) $output .= "{$section_props}['step'] = 1;\n"; if (!isset($attrs['start'])) $output .= "{$section_props}['start'] = {$section_props}['step'] > 0 ? 0 : {$section_props}['loop']-1;\n"; else { $output .= "if ({$section_props}['start'] < 0)\n" . " {$section_props}['start'] = max({$section_props}['step'] > 0 ? 0 : -1, {$section_props}['loop'] + {$section_props}['start']);\n" . "else\n" . " {$section_props}['start'] = min({$section_props}['start'], {$section_props}['step'] > 0 ? {$section_props}['loop'] : {$section_props}['loop']-1);\n"; } $output .= "if ({$section_props}['show']) {\n"; if (!isset($attrs['start']) && !isset($attrs['step']) && !isset($attrs['max'])) { $output .= " {$section_props}['total'] = {$section_props}['loop'];\n"; } else { $output .= " {$section_props}['total'] = min(ceil(({$section_props}['step'] > 0 ? {$section_props}['loop'] - {$section_props}['start'] : {$section_props}['start']+1)/abs({$section_props}['step'])), {$section_props}['max']);\n"; } $output .= " if ({$section_props}['total'] == 0)\n" . " {$section_props}['show'] = false;\n" . "} else\n" . " {$section_props}['total'] = 0;\n"; $output .= "if ({$section_props}['show']):\n"; $output .= " for ({$section_props}['index'] = {$section_props}['start'], {$section_props}['iteration'] = 1; {$section_props}['iteration'] <= {$section_props}['total']; {$section_props}['index'] += {$section_props}['step'], {$section_props}['iteration']++):\n"; $output .= "{$section_props}['rownum'] = {$section_props}['iteration'];\n"; $output .= "{$section_props}['index_prev'] = {$section_props}['index'] - {$section_props}['step'];\n"; $output .= "{$section_props}['index_next'] = {$section_props}['index'] + {$section_props}['step'];\n"; $output .= "{$section_props}['first'] = ({$section_props}['iteration'] == 1);\n"; $output .= "{$section_props}['last'] = ({$section_props}['iteration'] == {$section_props}['total']);\n"; $output .= "?>"; return $output; } /** * Compile {foreach ...} tag. * * @param string $tag_args * @return string */ function _compile_foreach_start($tag_args) { $attrs = $this->_parse_attrs($tag_args); $arg_list = array(); if (empty($attrs['from'])) { return $this->_syntax_error("foreach: missing 'from' attribute", E_USER_ERROR, __FILE__, __LINE__); } $from = $attrs['from']; if (empty($attrs['item'])) { return $this->_syntax_error("foreach: missing 'item' attribute", E_USER_ERROR, __FILE__, __LINE__); } $item = $this->_dequote($attrs['item']); if (!preg_match('~^\w+$~', $item)) { return $this->_syntax_error("foreach: 'item' must be a variable name (literal string)", E_USER_ERROR, __FILE__, __LINE__); } if (isset($attrs['key'])) { $key = $this->_dequote($attrs['key']); if (!preg_match('~^\w+$~', $key)) { return $this->_syntax_error("foreach: 'key' must to be a variable name (literal string)", E_USER_ERROR, __FILE__, __LINE__); } $key_part = "\$this->_tpl_vars['$key'] => "; } else { $key = null; $key_part = ''; } if (isset($attrs['name'])) { $name = $attrs['name']; } else { $name = null; } $output = '<?php '; $output .= "\$_from = $from; if (!is_array(\$_from) && !is_object(\$_from)) { settype(\$_from, 'array'); }"; if (isset($name)) { $foreach_props = "\$this->_foreach[$name]"; $output .= "{$foreach_props} = array('total' => count(\$_from), 'iteration' => 0);\n"; $output .= "if ({$foreach_props}['total'] > 0):\n"; $output .= " foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n"; $output .= " {$foreach_props}['iteration']++;\n"; } else { $output .= "if (count(\$_from)):\n"; $output .= " foreach (\$_from as $key_part\$this->_tpl_vars['$item']):\n"; } $output .= '?>'; return $output; } /** * Compile {capture} .. {/capture} tags * * @param boolean $start true if this is the {capture} tag * @param string $tag_args * @return string */ function _compile_capture_tag($start, $tag_args = '') { $attrs = $this->_parse_attrs($tag_args); if ($start) { $buffer = isset($attrs['name']) ? $attrs['name'] : "'default'"; $assign = isset($attrs['assign']) ? $attrs['assign'] : null; $append = isset($attrs['append']) ? $attrs['append'] : null; $output = "<?php ob_start(); ?>"; $this->_capture_stack[] = array($buffer, $assign, $append); } else { list($buffer, $assign, $append) = array_pop($this->_capture_stack); $output = "<?php \$this->_smarty_vars['capture'][$buffer] = ob_get_contents(); "; if (isset($assign)) { $output .= " \$this->assign($assign, ob_get_contents());"; } if (isset($append)) { $output .= " \$this->append($append, ob_get_contents());"; } $output .= "ob_end_clean(); ?>"; } return $output; } /** * Compile {if ...} tag * * @param string $tag_args * @param boolean $elseif if true, uses elseif instead of if * @return string */ function _compile_if_tag($tag_args, $elseif = false) { /* Tokenize args for 'if' tag. */ preg_match_all('~(?> ' . $this->_obj_call_regexp . '(?:' . $this->_mod_regexp . '*)? | # valid object call ' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)? | # var or quoted string \-?0[xX][0-9a-fA-F]+|\-?\d+(?:\.\d+)?|\.\d+|!==|===|==|!=|<>|<<|>>|<=|>=|\&\&|\|\||\(|\)|,|\!|\^|=|\&|\~|<|>|\||\%|\+|\-|\/|\*|\@ | # valid non-word token \b\w+\b | # valid word token \S+ # anything else )~x', $tag_args, $match); $tokens = $match[0]; if(empty($tokens)) { $_error_msg = $elseif ? "'elseif'" : "'if'"; $_error_msg .= ' statement requires a'; $this->_syntax_error($_error_msg, E_USER_ERROR, __FILE__, __LINE__); } // make sure we have balanced parenthesis $token_count = array_count_values($tokens); if(isset($token_count['(']) && $token_count['('] != $token_count[')']) { $this->_syntax_error("unbalanced parenthesis in if statement", E_USER_ERROR, __FILE__, __LINE__); } $is_arg_stack = array(); for ($i = 0; $i < count($tokens); $i++) { $token = &$tokens[$i]; switch (strtolower($token)) { case '!': case '%': case '!==': case '==': case '===': case '>': case '<': case '!=': case '<>': case '<<': case '>>': case '<=': case '>=': case '&&': case '||': case '|': case '^': case '&': case '~': case ')': case ',': case '+': case '-': case '*': case '/': case '@': break; case 'eq': $token = '=='; break; case 'ne': case 'neq': $token = '!='; break; case 'lt': $token = '<'; break; case 'le': case 'lte': $token = '<='; break; case 'gt': $token = '>'; break; case 'ge': case 'gte': $token = '>='; break; case 'and': $token = '&&'; break; case 'or': $token = '||'; break; case 'not': $token = '!'; break; case 'mod': $token = '%'; break; case '(': array_push($is_arg_stack, $i); break; case 'is': /* If last token was a ')', we operate on the parenthesized expression. The start of the expression is on the stack. Otherwise, we operate on the last encountered token. */ if ($tokens[$i-1] == ')') { $is_arg_start = array_pop($is_arg_stack); if ($is_arg_start != 0) { if (preg_match('~^' . $this->_func_regexp . '$~', $tokens[$is_arg_start-1])) { $is_arg_start--; } } } else $is_arg_start = $i-1; /* Construct the argument for 'is' expression, so it knows what to operate on. */ $is_arg = implode(' ', array_slice($tokens, $is_arg_start, $i - $is_arg_start)); /* Pass all tokens from next one until the end to the 'is' expression parsing function. The function will return modified tokens, where the first one is the result of the 'is' expression and the rest are the tokens it didn't touch. */ $new_tokens = $this->_parse_is_expr($is_arg, array_slice($tokens, $i+1)); /* Replace the old tokens with the new ones. */ array_splice($tokens, $is_arg_start, count($tokens), $new_tokens); /* Adjust argument start so that it won't change from the current position for the next iteration. */ $i = $is_arg_start; break; default: if(preg_match('~^' . $this->_func_regexp . '$~', $token) ) { // function call if($this->security && !in_array($token, $this->security_settings['IF_FUNCS'])) { $this->_syntax_error("(secure mode) '$token' not allowed in if statement", E_USER_ERROR, __FILE__, __LINE__); } } elseif(preg_match('~^' . $this->_var_regexp . '$~', $token) && (strpos('+-*/^%&|', substr($token, -1)) === false) && isset($tokens[$i+1]) && $tokens[$i+1] == '(') { // variable function call $this->_syntax_error("variable function call '$token' not allowed in if statement", E_USER_ERROR, __FILE__, __LINE__); } elseif(preg_match('~^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . '*)$~', $token)) { // object or variable $token = $this->_parse_var_props($token); } elseif(is_numeric($token)) { // number, skip it } else { $this->_syntax_error("unidentified token '$token'", E_USER_ERROR, __FILE__, __LINE__); } break; } } if ($elseif) return '<?php elseif ('.implode(' ', $tokens).'): ?>'; else return '<?php if ('.implode(' ', $tokens).'): ?>'; } function _compile_arg_list($type, $name, $attrs, &$cache_code) { $arg_list = array(); if (isset($type) && isset($name) && isset($this->_plugins[$type]) && isset($this->_plugins[$type][$name]) && empty($this->_plugins[$type][$name][4]) && is_array($this->_plugins[$type][$name][5]) ) { /* we have a list of parameters that should be cached */ $_cache_attrs = $this->_plugins[$type][$name][5]; $_count = $this->_cache_attrs_count++; $cache_code = "\$_cache_attrs =& \$this->_smarty_cache_attrs('$this->_cache_serial','$_count');"; } else { /* no parameters are cached */ $_cache_attrs = null; } foreach ($attrs as $arg_name => $arg_value) { if (is_bool($arg_value)) $arg_value = $arg_value ? 'true' : 'false'; if (is_null($arg_value)) $arg_value = 'null'; if ($_cache_attrs && in_array($arg_name, $_cache_attrs)) { $arg_list[] = "'$arg_name' => (\$this->_cache_including) ? \$_cache_attrs['$arg_name'] : (\$_cache_attrs['$arg_name']=$arg_value)"; } else { $arg_list[] = "'$arg_name' => $arg_value"; } } return $arg_list; } /** * Parse is expression * * @param string $is_arg * @param array $tokens * @return array */ function _parse_is_expr($is_arg, $tokens) { $expr_end = 0; $negate_expr = false; if (($first_token = array_shift($tokens)) == 'not') { $negate_expr = true; $expr_type = array_shift($tokens); } else $expr_type = $first_token; switch ($expr_type) { case 'even': if (isset($tokens[$expr_end]) && $tokens[$expr_end] == 'by') { $expr_end++; $expr_arg = $tokens[$expr_end++]; $expr = "!(1 & ($is_arg / " . $this->_parse_var_props($expr_arg) . "))"; } else $expr = "!(1 & $is_arg)"; break; case 'odd': if (isset($tokens[$expr_end]) && $tokens[$expr_end] == 'by') { $expr_end++; $expr_arg = $tokens[$expr_end++]; $expr = "(1 & ($is_arg / " . $this->_parse_var_props($expr_arg) . "))"; } else $expr = "(1 & $is_arg)"; break; case 'div': if (@$tokens[$expr_end] == 'by') { $expr_end++; $expr_arg = $tokens[$expr_end++]; $expr = "!($is_arg % " . $this->_parse_var_props($expr_arg) . ")"; } else { $this->_syntax_error("expecting 'by' after 'div'", E_USER_ERROR, __FILE__, __LINE__); } break; default: $this->_syntax_error("unknown 'is' expression - '$expr_type'", E_USER_ERROR, __FILE__, __LINE__); break; } if ($negate_expr) { $expr = "!($expr)"; } array_splice($tokens, 0, $expr_end, $expr); return $tokens; } /** * Parse attribute string * * @param string $tag_args * @return array */ function _parse_attrs($tag_args) { /* Tokenize tag attributes. */ preg_match_all('~(?:' . $this->_obj_call_regexp . '|' . $this->_qstr_regexp . ' | (?>[^"\'=\s]+) )+ | [=] ~x', $tag_args, $match); $tokens = $match[0]; $attrs = array(); /* Parse state: 0 - expecting attribute name 1 - expecting '=' 2 - expecting attribute value (not '=') */ $state = 0; foreach ($tokens as $token) { switch ($state) { case 0: /* If the token is a valid identifier, we set attribute name and go to state 1. */ if (preg_match('~^\w+$~', $token)) { $attr_name = $token; $state = 1; } else $this->_syntax_error("invalid attribute name: '$token'", E_USER_ERROR, __FILE__, __LINE__); break; case 1: /* If the token is '=', then we go to state 2. */ if ($token == '=') { $state = 2; } else $this->_syntax_error("expecting '=' after attribute name '$last_token'", E_USER_ERROR, __FILE__, __LINE__); break; case 2: /* If token is not '=', we set the attribute value and go to state 0. */ if ($token != '=') { /* We booleanize the token if it's a non-quoted possible boolean value. */ if (preg_match('~^(on|yes|true)$~', $token)) { $token = 'true'; } else if (preg_match('~^(off|no|false)$~', $token)) { $token = 'false'; } else if ($token == 'null') { $token = 'null'; } else if (preg_match('~^' . $this->_num_const_regexp . '|0[xX][0-9a-fA-F]+$~', $token)) { /* treat integer literally */ } else if (!preg_match('~^' . $this->_obj_call_regexp . '|' . $this->_var_regexp . '(?:' . $this->_mod_regexp . ')*$~', $token)) { /* treat as a string, double-quote it escaping quotes */ $token = '"'.addslashes($token).'"'; } $attrs[$attr_name] = $token; $state = 0; } else $this->_syntax_error("'=' cannot be an attribute value", E_USER_ERROR, __FILE__, __LINE__); break; } $last_token = $token; } if($state != 0) { if($state == 1) { $this->_syntax_error("expecting '=' after attribute name '$last_token'", E_USER_ERROR, __FILE__, __LINE__); } else { $this->_syntax_error("missing attribute value", E_USER_ERROR, __FILE__, __LINE__); } } $this->_parse_vars_props($attrs); return $attrs; } /** * compile multiple variables and section properties tokens into * PHP code * * @param array $tokens */ function _parse_vars_props(&$tokens) { foreach($tokens as $key => $val) { $tokens[$key] = $this->_parse_var_props($val); } } /** * compile single variable and section properties token into * PHP code * * @param string $val * @param string $tag_attrs * @return string */ function _parse_var_props($val) { $val = trim($val); if(preg_match('~^(' . $this->_obj_call_regexp . '|' . $this->_dvar_regexp . ')(' . $this->_mod_regexp . '*)$~', $val, $match)) { // $ variable or object $return = $this->_parse_var($match[1]); $modifiers = $match[2]; if (!empty($this->default_modifiers) && !preg_match('~(^|\|)smarty:nodefaults($|\|)~',$modifiers)) { $_default_mod_string = implode('|',(array)$this->default_modifiers); $modifiers = empty($modifiers) ? $_default_mod_string : $_default_mod_string . '|' . $modifiers; } $this->_parse_modifiers($return, $modifiers); return $return; } elseif (preg_match('~^' . $this->_db_qstr_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) { // double quoted text preg_match('~^(' . $this->_db_qstr_regexp . ')('. $this->_mod_regexp . '*)$~', $val, $match); $return = $this->_expand_quoted_text($match[1]); if($match[2] != '') { $this->_parse_modifiers($return, $match[2]); } return $return; } elseif(preg_match('~^' . $this->_num_const_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) { // numerical constant preg_match('~^(' . $this->_num_const_regexp . ')('. $this->_mod_regexp . '*)$~', $val, $match); if($match[2] != '') { $this->_parse_modifiers($match[1], $match[2]); return $match[1]; } } elseif(preg_match('~^' . $this->_si_qstr_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) { // single quoted text preg_match('~^(' . $this->_si_qstr_regexp . ')('. $this->_mod_regexp . '*)$~', $val, $match); if($match[2] != '') { $this->_parse_modifiers($match[1], $match[2]); return $match[1]; } } elseif(preg_match('~^' . $this->_cvar_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) { // config var return $this->_parse_conf_var($val); } elseif(preg_match('~^' . $this->_svar_regexp . '(?:' . $this->_mod_regexp . '*)$~', $val)) { // section var return $this->_parse_section_prop($val); } elseif(!in_array($val, $this->_permitted_tokens) && !is_numeric($val)) { // literal string return $this->_expand_quoted_text('"' . strtr($val, array('\\' => '\\\\', '"' => '\\"')) .'"'); } return $val; } /** * expand quoted text with embedded variables * * @param string $var_expr * @return string */ function _expand_quoted_text($var_expr) { // if contains unescaped $, expand it if(preg_match_all('~(?:\`(?<!\\\\)\$' . $this->_dvar_guts_regexp . '(?:' . $this->_obj_ext_regexp . ')*\`)|(?:(?<!\\\\)\$\w+(\[[a-zA-Z0-9]+\])*)~', $var_expr, $_match)) { $_match = $_match[0]; $_replace = array(); foreach($_match as $_var) { $_replace[$_var] = '".(' . $this->_parse_var(str_replace('`','',$_var)) . ')."'; } $var_expr = strtr($var_expr, $_replace); $_return = preg_replace('~\.""|(?<!\\\\)""\.~', '', $var_expr); } else { $_return = $var_expr; } // replace double quoted literal string with single quotes $_return = preg_replace('~^"([\s\w]+)"$~',"'\\1'",$_return); // escape dollar sign if not printing a var $_return = preg_replace('~\$(\W)~',"\\\\\$\\1",$_return); return $_return; } /** * parse variable expression into PHP code * * @param string $var_expr * @param string $output * @return string */ function _parse_var($var_expr) { $_has_math = false; $_has_php4_method_chaining = false; $_math_vars = preg_split('~('.$this->_dvar_math_regexp.'|'.$this->_qstr_regexp.')~', $var_expr, -1, PREG_SPLIT_DELIM_CAPTURE); if(count($_math_vars) > 1) { $_first_var = ""; $_complete_var = ""; $_output = ""; // simple check if there is any math, to stop recursion (due to modifiers with "xx % yy" as parameter) foreach($_math_vars as $_k => $_math_var) { $_math_var = $_math_vars[$_k]; if(!empty($_math_var) || is_numeric($_math_var)) { // hit a math operator, so process the stuff which came before it if(preg_match('~^' . $this->_dvar_math_regexp . '$~', $_math_var)) { $_has_math = true; if(!empty($_complete_var) || is_numeric($_complete_var)) { $_output .= $this->_parse_var($_complete_var); } // just output the math operator to php $_output .= $_math_var; if(empty($_first_var)) $_first_var = $_complete_var; $_complete_var = ""; } else { $_complete_var .= $_math_var; } } } if($_has_math) { if(!empty($_complete_var) || is_numeric($_complete_var)) $_output .= $this->_parse_var($_complete_var); // get the modifiers working (only the last var from math + modifier is left) $var_expr = $_complete_var; } } // prevent cutting of first digit in the number (we _definitly_ got a number if the first char is a digit) if(is_numeric(substr($var_expr, 0, 1))) $_var_ref = $var_expr; else $_var_ref = substr($var_expr, 1); if(!$_has_math) { // get [foo] and .foo and ->foo and (...) pieces preg_match_all('~(?:^\w+)|' . $this->_obj_params_regexp . '|(?:' . $this->_var_bracket_regexp . ')|->\$?\w+|\.\$?\w+|\S+~', $_var_ref, $match); $_indexes = $match[0]; $_var_name = array_shift($_indexes); /* Handle $smarty.* variable references as a special case. */ if ($_var_name == 'smarty') { /* * If the reference could be compiled, use the compiled output; * otherwise, fall back on the $smarty variable generated at * run-time. */ if (($smarty_ref = $this->_compile_smarty_ref($_indexes)) !== null) { $_output = $smarty_ref; } else { $_var_name = substr(array_shift($_indexes), 1); $_output = "\$this->_smarty_vars['$_var_name']"; } } elseif(is_numeric($_var_name) && is_numeric(substr($var_expr, 0, 1))) { // because . is the operator for accessing arrays thru inidizes we need to put it together again for floating point numbers if(count($_indexes) > 0) { $_var_name .= implode("", $_indexes); $_indexes = array(); } $_output = $_var_name; } else { $_output = "\$this->_tpl_vars['$_var_name']"; } foreach ($_indexes as $_index) { if (substr($_index, 0, 1) == '[') { $_index = substr($_index, 1, -1); if (is_numeric($_index)) { $_output .= "[$_index]"; } elseif (substr($_index, 0, 1) == '$') { if (strpos($_index, '.') !== false) { $_output .= '[' . $this->_parse_var($_index) . ']'; } else { $_output .= "[\$this->_tpl_vars['" . substr($_index, 1) . "']]"; } } else { $_var_parts = explode('.', $_index); $_var_section = $_var_parts[0]; $_var_section_prop = isset($_var_parts[1]) ? $_var_parts[1] : 'index'; $_output .= "[\$this->_sections['$_var_section']['$_var_section_prop']]"; } } else if (substr($_index, 0, 1) == '.') { if (substr($_index, 1, 1) == '$') $_output .= "[\$this->_tpl_vars['" . substr($_index, 2) . "']]"; else $_output .= "['" . substr($_index, 1) . "']"; } else if (substr($_index,0,2) == '->') { if(substr($_index,2,2) == '__') { $this->_syntax_error('call to internal object members is not allowed', E_USER_ERROR, __FILE__, __LINE__); } elseif($this->security && substr($_index, 2, 1) == '_') { $this->_syntax_error('(secure) call to private object member is not allowed', E_USER_ERROR, __FILE__, __LINE__); } elseif (substr($_index, 2, 1) == '$') { if ($this->security) { $this->_syntax_error('(secure) call to dynamic object member is not allowed', E_USER_ERROR, __FILE__, __LINE__); } else { $_output .= '->{(($_var=$this->_tpl_vars[\''.substr($_index,3).'\']) && substr($_var,0,2)!=\'__\') ? $_var : $this->trigger_error("cannot access property \\"$_var\\"")}'; } } else { if ($this->_phpversion < 5) { $_has_php4_method_chaining = true; $_output .= "; \$_foo = \$_foo"; } $_output .= $_index; } } elseif (substr($_index, 0, 1) == '(') { $_index = $this->_parse_parenth_args($_index); $_output .= $_index; } else { $_output .= $_index; } } } if ($_has_php4_method_chaining) { $_tmp = str_replace("'","\'",'$_foo = '.$_output.'; return $_foo;'); return "eval('".$_tmp."')"; } else { return $_output; } } /** * parse a in function call parenthesis * * @param string $parenth_args * @return string */ function _parse_parenth_args($parenth_args) { preg_match_all('~' . $this->_param_regexp . '~',$parenth_args, $match); $orig_vals = $match = $match[0]; $this->_parse_vars_props($match); $replace = array(); for ($i = 0, $count = count($match); $i < $count; $i++) { $replace[$orig_vals[$i]] = $match[$i]; } return strtr($parenth_args, $replace); } /** * parse configuration variable expression into PHP code * * @param string $conf_var_expr */ function _parse_conf_var($conf_var_expr) { $parts = explode('|', $conf_var_expr, 2); $var_ref = $parts[0]; $modifiers = isset($parts[1]) ? $parts[1] : ''; $var_name = substr($var_ref, 1, -1); $output = "\$this->_config[0]['vars']['$var_name']"; $this->_parse_modifiers($output, $modifiers); return $output; } /** * parse section property expression into PHP code * * @param string $section_prop_expr * @return string */ function _parse_section_prop($section_prop_expr) { $parts = explode('|', $section_prop_expr, 2); $var_ref = $parts[0]; $modifiers = isset($parts[1]) ? $parts[1] : ''; preg_match('!%(\w+)\.(\w+)%!', $var_ref, $match); $section_name = $match[1]; $prop_name = $match[2]; $output = "\$this->_sections['$section_name']['$prop_name']"; $this->_parse_modifiers($output, $modifiers); return $output; } /** * parse modifier chain into PHP code * * sets $output to parsed modified chain * @param string $output * @param string $modifier_string */ function _parse_modifiers(&$output, $modifier_string) { preg_match_all('~\|(@?\w+)((?>:(?:'. $this->_qstr_regexp . '|[^|]+))*)~', '|' . $modifier_string, $_match); list(, $_modifiers, $modifier_arg_strings) = $_match; for ($_i = 0, $_for_max = count($_modifiers); $_i < $_for_max; $_i++) { $_modifier_name = $_modifiers[$_i]; if($_modifier_name == 'smarty') { // skip smarty modifier continue; } preg_match_all('~:(' . $this->_qstr_regexp . '|[^:]+)~', $modifier_arg_strings[$_i], $_match); $_modifier_args = $_match[1]; if (substr($_modifier_name, 0, 1) == '@') { $_map_array = false; $_modifier_name = substr($_modifier_name, 1); } else { $_map_array = true; } if (empty($this->_plugins['modifier'][$_modifier_name]) && !$this->_get_plugin_filepath('modifier', $_modifier_name) && function_exists($_modifier_name)) { if ($this->security && !in_array($_modifier_name, $this->security_settings['MODIFIER_FUNCS'])) { $this->_trigger_fatal_error("[plugin] (secure mode) modifier '$_modifier_name' is not allowed" , $this->_current_file, $this->_current_line_no, __FILE__, __LINE__); } else { $this->_plugins['modifier'][$_modifier_name] = array($_modifier_name, null, null, false); } } $this->_add_plugin('modifier', $_modifier_name); $this->_parse_vars_props($_modifier_args); if($_modifier_name == 'default') { // supress notifications of default modifier vars and args if(substr($output, 0, 1) == '$') { $output = '@' . $output; } if(isset($_modifier_args[0]) && substr($_modifier_args[0], 0, 1) == '$') { $_modifier_args[0] = '@' . $_modifier_args[0]; } } if (count($_modifier_args) > 0) $_modifier_args = ', '.implode(', ', $_modifier_args); else $_modifier_args = ''; if ($_map_array) { $output = "((is_array(\$_tmp=$output)) ? \$this->_run_mod_handler('$_modifier_name', true, \$_tmp$_modifier_args) : " . $this->_compile_plugin_call('modifier', $_modifier_name) . "(\$_tmp$_modifier_args))"; } else { $output = $this->_compile_plugin_call('modifier', $_modifier_name)."($output$_modifier_args)"; } } } /** * add plugin * * @param string $type * @param string $name * @param boolean? $delayed_loading */ function _add_plugin($type, $name, $delayed_loading = null) { if (!isset($this->_plugin_info[$type])) { $this->_plugin_info[$type] = array(); } if (!isset($this->_plugin_info[$type][$name])) { $this->_plugin_info[$type][$name] = array($this->_current_file, $this->_current_line_no, $delayed_loading); } } /** * Compiles references of type $smarty.foo * * @param string $indexes * @return string */ function _compile_smarty_ref(&$indexes) { /* Extract the reference name. */ $_ref = substr($indexes[0], 1); foreach($indexes as $_index_no=>$_index) { if (substr($_index, 0, 1) != '.' && $_index_no<2 || !preg_match('~^(\.|\[|->)~', $_index)) { $this->_syntax_error('$smarty' . implode('', array_slice($indexes, 0, 2)) . ' is an invalid reference', E_USER_ERROR, __FILE__, __LINE__); } } switch ($_ref) { case 'now': $compiled_ref = 'time()'; $_max_index = 1; break; case 'foreach': array_shift($indexes); $_var = $this->_parse_var_props(substr($indexes[0], 1)); $_propname = substr($indexes[1], 1); $_max_index = 1; switch ($_propname) { case 'index': array_shift($indexes); $compiled_ref = "(\$this->_foreach[$_var]['iteration']-1)"; break; case 'first': array_shift($indexes); $compiled_ref = "(\$this->_foreach[$_var]['iteration'] <= 1)"; break; case 'last': array_shift($indexes); $compiled_ref = "(\$this->_foreach[$_var]['iteration'] == \$this->_foreach[$_var]['total'])"; break; case 'show': array_shift($indexes); $compiled_ref = "(\$this->_foreach[$_var]['total'] > 0)"; break; default: unset($_max_index); $compiled_ref = "\$this->_foreach[$_var]"; } break; case 'section': array_shift($indexes); $_var = $this->_parse_var_props(substr($indexes[0], 1)); $compiled_ref = "\$this->_sections[$_var]"; break; case 'get': $compiled_ref = ($this->request_use_auto_globals) ? '$_GET' : "\$GLOBALS['HTTP_GET_VARS']"; break; case 'post': $compiled_ref = ($this->request_use_auto_globals) ? '$_POST' : "\$GLOBALS['HTTP_POST_VARS']"; break; case 'cookies': $compiled_ref = ($this->request_use_auto_globals) ? '$_COOKIE' : "\$GLOBALS['HTTP_COOKIE_VARS']"; break; case 'env': $compiled_ref = ($this->request_use_auto_globals) ? '$_ENV' : "\$GLOBALS['HTTP_ENV_VARS']"; break; case 'server': $compiled_ref = ($this->request_use_auto_globals) ? '$_SERVER' : "\$GLOBALS['HTTP_SERVER_VARS']"; break; case 'session': $compiled_ref = ($this->request_use_auto_globals) ? '$_SESSION' : "\$GLOBALS['HTTP_SESSION_VARS']"; break; /* * These cases are handled either at run-time or elsewhere in the * compiler. */ case 'request': if ($this->request_use_auto_globals) { $compiled_ref = '$_REQUEST'; break; } else { $this->_init_smarty_vars = true; } return null; case 'capture': return null; case 'template': $compiled_ref = "'$this->_current_file'"; $_max_index = 1; break; case 'version': $compiled_ref = "'$this->_version'"; $_max_index = 1; break; case 'const': if ($this->security && !$this->security_settings['ALLOW_CONSTANTS']) { $this->_syntax_error("(secure mode) constants not permitted", E_USER_WARNING, __FILE__, __LINE__); return; } array_shift($indexes); if (preg_match('!^\.\w+$!', $indexes[0])) { $compiled_ref = '@' . substr($indexes[0], 1); } else { $_val = $this->_parse_var_props(substr($indexes[0], 1)); $compiled_ref = '@constant(' . $_val . ')'; } $_max_index = 1; break; case 'config': $compiled_ref = "\$this->_config[0]['vars']"; $_max_index = 3; break; case 'ldelim': $compiled_ref = "'$this->left_delimiter'"; break; case 'rdelim': $compiled_ref = "'$this->right_delimiter'"; break; default: $this->_syntax_error('$smarty.' . $_ref . ' is an unknown reference', E_USER_ERROR, __FILE__, __LINE__); break; } if (isset($_max_index) && count($indexes) > $_max_index) { $this->_syntax_error('$smarty' . implode('', $indexes) .' is an invalid reference', E_USER_ERROR, __FILE__, __LINE__); } array_shift($indexes); return $compiled_ref; } /** * compiles call to plugin of type $type with name $name * returns a string containing the function-name or method call * without the paramter-list that would have follow to make the * call valid php-syntax * * @param string $type * @param string $name * @return string */ function _compile_plugin_call($type, $name) { if (isset($this->_plugins[$type][$name])) { /* plugin loaded */ if (is_array($this->_plugins[$type][$name][0])) { return ((is_object($this->_plugins[$type][$name][0][0])) ? "\$this->_plugins['$type']['$name'][0][0]->" /* method callback */ : (string)($this->_plugins[$type][$name][0][0]).'::' /* class callback */ ). $this->_plugins[$type][$name][0][1]; } else { /* function callback */ return $this->_plugins[$type][$name][0]; } } else { /* plugin not loaded -> auto-loadable-plugin */ return 'smarty_'.$type.'_'.$name; } } /** * load pre- and post-filters */ function _load_filters() { if (count($this->_plugins['prefilter']) > 0) { foreach ($this->_plugins['prefilter'] as $filter_name => $prefilter) { if ($prefilter === false) { unset($this->_plugins['prefilter'][$filter_name]); $_params = array('plugins' => array(array('prefilter', $filter_name, null, null, false))); require_once(SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins($_params, $this); } } } if (count($this->_plugins['postfilter']) > 0) { foreach ($this->_plugins['postfilter'] as $filter_name => $postfilter) { if ($postfilter === false) { unset($this->_plugins['postfilter'][$filter_name]); $_params = array('plugins' => array(array('postfilter', $filter_name, null, null, false))); require_once(SMARTY_CORE_DIR . 'core.load_plugins.php'); smarty_core_load_plugins($_params, $this); } } } } /** * Quote subpattern references * * @param string $string * @return string */ function _quote_replace($string) { return strtr($string, array('\\' => '\\\\', '$' => '\\$')); } /** * display Smarty syntax error * * @param string $error_msg * @param integer $error_type * @param string $file * @param integer $line */ function _syntax_error($error_msg, $error_type = E_USER_ERROR, $file=null, $line=null) { $this->_trigger_fatal_error("syntax error: $error_msg", $this->_current_file, $this->_current_line_no, $file, $line, $error_type); } /** * check if the compilation changes from cacheable to * non-cacheable state with the beginning of the current * plugin. return php-code to reflect the transition. * @return string */ function _push_cacheable_state($type, $name) { $_cacheable = !isset($this->_plugins[$type][$name]) || $this->_plugins[$type][$name][4]; if ($_cacheable || 0<$this->_cacheable_state++) return ''; if (!isset($this->_cache_serial)) $this->_cache_serial = md5(uniqid('Smarty')); $_ret = 'if ($this->caching && !$this->_cache_including): echo \'{nocache:' . $this->_cache_serial . '#' . $this->_nocache_count . '}\'; endif;'; return $_ret; } /** * check if the compilation changes from non-cacheable to * cacheable state with the end of the current plugin return * php-code to reflect the transition. * @return string */ function _pop_cacheable_state($type, $name) { $_cacheable = !isset($this->_plugins[$type][$name]) || $this->_plugins[$type][$name][4]; if ($_cacheable || --$this->_cacheable_state>0) return ''; return 'if ($this->caching && !$this->_cache_including): echo \'{/nocache:' . $this->_cache_serial . '#' . ($this->_nocache_count++) . '}\'; endif;'; } /** * push opening tag-name, file-name and line-number on the tag-stack * @param string the opening tag's name */ function _push_tag($open_tag) { array_push($this->_tag_stack, array($open_tag, $this->_current_line_no)); } /** * pop closing tag-name * raise an error if this stack-top doesn't match with the closing tag * @param string the closing tag's name * @return string the opening tag's name */ function _pop_tag($close_tag) { $message = ''; if (count($this->_tag_stack)>0) { list($_open_tag, $_line_no) = array_pop($this->_tag_stack); if ($close_tag == $_open_tag) { return $_open_tag; } if ($close_tag == 'if' && ($_open_tag == 'else' || $_open_tag == 'elseif' )) { return $this->_pop_tag($close_tag); } if ($close_tag == 'section' && $_open_tag == 'sectionelse') { $this->_pop_tag($close_tag); return $_open_tag; } if ($close_tag == 'foreach' && $_open_tag == 'foreachelse') { $this->_pop_tag($close_tag); return $_open_tag; } if ($_open_tag == 'else' || $_open_tag == 'elseif') { $_open_tag = 'if'; } elseif ($_open_tag == 'sectionelse') { $_open_tag = 'section'; } elseif ($_open_tag == 'foreachelse') { $_open_tag = 'foreach'; } $message = " expected {/$_open_tag} (opened line $_line_no)."; } $this->_syntax_error("mismatched tag {/$close_tag}.$message", E_USER_ERROR, __FILE__, __LINE__); } } /** * compare to values by their string length * * @access private * @param string $a * @param string $b * @return 0|-1|1 */ function _smarty_sort_length($a, $b) { if($a == $b) return 0; if(strlen($a) == strlen($b)) return ($a > $b) ? -1 : 1; return (strlen($a) > strlen($b)) ? -1 : 1; } /* vim: set et: */ ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/Smarty_Compiler.class.php
PHP
asf20
95,645
<?php /** * Config_File class. * * This library 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; either * version 2.1 of the License, or (at your option) any later version. * * This library 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 * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * For questions, help, comments, discussion, etc., please join the * Smarty mailing list. Send a blank e-mail to * smarty-discussion-subscribe@googlegroups.com * * @link http://www.smarty.net/ * @version 2.6.22 * @copyright Copyright: 2001-2005 New Digital Group, Inc. * @author Andrei Zmievski <andrei@php.net> * @access public * @package Smarty */ /* $Id: Config_File.class.php 2786 2008-09-18 21:04:38Z Uwe.Tews $ */ /** * Config file reading class * @package Smarty */ class Config_File { /**#@+ * Options * @var boolean */ /** * Controls whether variables with the same name overwrite each other. */ var $overwrite = true; /** * Controls whether config values of on/true/yes and off/false/no get * converted to boolean values automatically. */ var $booleanize = true; /** * Controls whether hidden config sections/vars are read from the file. */ var $read_hidden = true; /** * Controls whether or not to fix mac or dos formatted newlines. * If set to true, \r or \r\n will be changed to \n. */ var $fix_newlines = true; /**#@-*/ /** @access private */ var $_config_path = ""; var $_config_data = array(); /**#@-*/ /** * Constructs a new config file class. * * @param string $config_path (optional) path to the config files */ function Config_File($config_path = NULL) { if (isset($config_path)) $this->set_path($config_path); } /** * Set the path where configuration files can be found. * * @param string $config_path path to the config files */ function set_path($config_path) { if (!empty($config_path)) { if (!is_string($config_path) || !file_exists($config_path) || !is_dir($config_path)) { $this->_trigger_error_msg("Bad config file path '$config_path'"); return; } if(substr($config_path, -1) != DIRECTORY_SEPARATOR) { $config_path .= DIRECTORY_SEPARATOR; } $this->_config_path = $config_path; } } /** * Retrieves config info based on the file, section, and variable name. * * @param string $file_name config file to get info for * @param string $section_name (optional) section to get info for * @param string $var_name (optional) variable to get info for * @return string|array a value or array of values */ function get($file_name, $section_name = NULL, $var_name = NULL) { if (empty($file_name)) { $this->_trigger_error_msg('Empty config file name'); return; } else { $file_name = $this->_config_path . $file_name; if (!isset($this->_config_data[$file_name])) $this->load_file($file_name, false); } if (!empty($var_name)) { if (empty($section_name)) { return $this->_config_data[$file_name]["vars"][$var_name]; } else { if(isset($this->_config_data[$file_name]["sections"][$section_name]["vars"][$var_name])) return $this->_config_data[$file_name]["sections"][$section_name]["vars"][$var_name]; else return array(); } } else { if (empty($section_name)) { return (array)$this->_config_data[$file_name]["vars"]; } else { if(isset($this->_config_data[$file_name]["sections"][$section_name]["vars"])) return (array)$this->_config_data[$file_name]["sections"][$section_name]["vars"]; else return array(); } } } /** * Retrieves config info based on the key. * * @param $file_name string config key (filename/section/var) * @return string|array same as get() * @uses get() retrieves information from config file and returns it */ function &get_key($config_key) { list($file_name, $section_name, $var_name) = explode('/', $config_key, 3); $result = &$this->get($file_name, $section_name, $var_name); return $result; } /** * Get all loaded config file names. * * @return array an array of loaded config file names */ function get_file_names() { return array_keys($this->_config_data); } /** * Get all section names from a loaded file. * * @param string $file_name config file to get section names from * @return array an array of section names from the specified file */ function get_section_names($file_name) { $file_name = $this->_config_path . $file_name; if (!isset($this->_config_data[$file_name])) { $this->_trigger_error_msg("Unknown config file '$file_name'"); return; } return array_keys($this->_config_data[$file_name]["sections"]); } /** * Get all global or section variable names. * * @param string $file_name config file to get info for * @param string $section_name (optional) section to get info for * @return array an array of variables names from the specified file/section */ function get_var_names($file_name, $section = NULL) { if (empty($file_name)) { $this->_trigger_error_msg('Empty config file name'); return; } else if (!isset($this->_config_data[$file_name])) { $this->_trigger_error_msg("Unknown config file '$file_name'"); return; } if (empty($section)) return array_keys($this->_config_data[$file_name]["vars"]); else return array_keys($this->_config_data[$file_name]["sections"][$section]["vars"]); } /** * Clear loaded config data for a certain file or all files. * * @param string $file_name file to clear config data for */ function clear($file_name = NULL) { if ($file_name === NULL) $this->_config_data = array(); else if (isset($this->_config_data[$file_name])) $this->_config_data[$file_name] = array(); } /** * Load a configuration file manually. * * @param string $file_name file name to load * @param boolean $prepend_path whether current config path should be * prepended to the filename */ function load_file($file_name, $prepend_path = true) { if ($prepend_path && $this->_config_path != "") $config_file = $this->_config_path . $file_name; else $config_file = $file_name; ini_set('track_errors', true); $fp = @fopen($config_file, "r"); if (!is_resource($fp)) { $this->_trigger_error_msg("Could not open config file '$config_file'"); return false; } $contents = ($size = filesize($config_file)) ? fread($fp, $size) : ''; fclose($fp); $this->_config_data[$config_file] = $this->parse_contents($contents); return true; } /** * Store the contents of a file manually. * * @param string $config_file file name of the related contents * @param string $contents the file-contents to parse */ function set_file_contents($config_file, $contents) { $this->_config_data[$config_file] = $this->parse_contents($contents); return true; } /** * parse the source of a configuration file manually. * * @param string $contents the file-contents to parse */ function parse_contents($contents) { if($this->fix_newlines) { // fix mac/dos formatted newlines //ȥ //$contents = preg_replace('!\r\n?!', "\n", $contents); $contents = preg_replace('!\r\n?!', "\n", $contents); } $config_data = array(); $config_data['sections'] = array(); $config_data['vars'] = array(); /* reference to fill with data */ $vars =& $config_data['vars']; /* parse file line by line */ preg_match_all('!^.*\r?\n?!m', $contents, $match); $lines = $match[0]; for ($i=0, $count=count($lines); $i<$count; $i++) { $line = $lines[$i]; if (empty($line)) continue; if ( substr($line, 0, 1) == '[' && preg_match('!^\[(.*?)\]!', $line, $match) ) { /* section found */ if (substr($match[1], 0, 1) == '.') { /* hidden section */ if ($this->read_hidden) { $section_name = substr($match[1], 1); } else { /* break reference to $vars to ignore hidden section */ unset($vars); $vars = array(); continue; } } else { $section_name = $match[1]; } if (!isset($config_data['sections'][$section_name])) $config_data['sections'][$section_name] = array('vars' => array()); $vars =& $config_data['sections'][$section_name]['vars']; continue; } if (preg_match('/^\s*(\.?\w+)\s*=\s*(.*)/s', $line, $match)) { /* variable found */ $var_name = rtrim($match[1]); if (strpos($match[2], '"""') === 0) { /* handle multiline-value */ $lines[$i] = substr($match[2], 3); $var_value = ''; while ($i<$count) { if (($pos = strpos($lines[$i], '"""')) === false) { $var_value .= $lines[$i++]; } else { /* end of multiline-value */ $var_value .= substr($lines[$i], 0, $pos); break; } } $booleanize = false; } else { /* handle simple value */ $var_value = preg_replace('/^([\'"])(.*)\1$/', '\2', rtrim($match[2])); $booleanize = $this->booleanize; } $this->_set_config_var($vars, $var_name, $var_value, $booleanize); } /* else unparsable line / means it is a comment / means ignore it */ } return $config_data; } /**#@+ @access private */ /** * @param array &$container * @param string $var_name * @param mixed $var_value * @param boolean $booleanize determines whether $var_value is converted to * to true/false */ function _set_config_var(&$container, $var_name, $var_value, $booleanize) { if (substr($var_name, 0, 1) == '.') { if (!$this->read_hidden) return; else $var_name = substr($var_name, 1); } if (!preg_match("/^[a-zA-Z_]\w*$/", $var_name)) { $this->_trigger_error_msg("Bad variable name '$var_name'"); return; } if ($booleanize) { if (preg_match("/^(on|true|yes)$/i", $var_value)) $var_value = true; else if (preg_match("/^(off|false|no)$/i", $var_value)) $var_value = false; } if (!isset($container[$var_name]) || $this->overwrite) $container[$var_name] = $var_value; else { settype($container[$var_name], 'array'); $container[$var_name][] = $var_value; } } /** * @uses trigger_error() creates a PHP warning/error * @param string $error_msg * @param integer $error_type one of */ function _trigger_error_msg($error_msg, $error_type = E_USER_WARNING) { trigger_error("Config_File error: $error_msg", $error_type); } /**#@-*/ } ?>
01cms
01cms/branches/1.0/01mvc/lib/Smarty/Config_File.class.php
PHP
asf20
13,374
{* Smarty *} {* debug.tpl, last updated version 2.1.0 *} {assign_debug_info} {capture assign=debug_output} <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <title>Smarty Debug Console</title> {literal} <style type="text/css"> /* <![CDATA[ */ body, h1, h2, td, th, p { font-family: sans-serif; font-weight: normal; font-size: 0.9em; margin: 1px; padding: 0; } h1 { margin: 0; text-align: left; padding: 2px; background-color: #f0c040; color: black; font-weight: bold; font-size: 1.2em; } h2 { background-color: #9B410E; color: white; text-align: left; font-weight: bold; padding: 2px; border-top: 1px solid black; } body { background: black; } p, table, div { background: #f0ead8; } p { margin: 0; font-style: italic; text-align: center; } table { width: 100%; } th, td { font-family: monospace; vertical-align: top; text-align: left; width: 50%; } td { color: green; } .odd { background-color: #eeeeee; } .even { background-color: #fafafa; } .exectime { font-size: 0.8em; font-style: italic; } #table_assigned_vars th { color: blue; } #table_config_vars th { color: maroon; } /* ]]> */ </style> {/literal} </head> <body> <h1>Smarty Debug Console</h1> <h2>included templates &amp; config files (load time in seconds)</h2> <div> {section name=templates loop=$_debug_tpls} {section name=indent loop=$_debug_tpls[templates].depth}&nbsp;&nbsp;&nbsp;{/section} <font color={if $_debug_tpls[templates].type eq "template"}brown{elseif $_debug_tpls[templates].type eq "insert"}black{else}green{/if}> {$_debug_tpls[templates].filename|escape:html}</font> {if isset($_debug_tpls[templates].exec_time)} <span class="exectime"> ({$_debug_tpls[templates].exec_time|string_format:"%.5f"}) {if %templates.index% eq 0}(total){/if} </span> {/if} <br /> {sectionelse} <p>no templates included</p> {/section} </div> <h2>assigned template variables</h2> <table id="table_assigned_vars"> {section name=vars loop=$_debug_keys} <tr class="{cycle values="odd,even"}"> <th>{ldelim}${$_debug_keys[vars]|escape:'html'}{rdelim}</th> <td>{$_debug_vals[vars]|@debug_print_var}</td></tr> {sectionelse} <tr><td><p>no template variables assigned</p></td></tr> {/section} </table> <h2>assigned config file variables (outer template scope)</h2> <table id="table_config_vars"> {section name=config_vars loop=$_debug_config_keys} <tr class="{cycle values="odd,even"}"> <th>{ldelim}#{$_debug_config_keys[config_vars]|escape:'html'}#{rdelim}</th> <td>{$_debug_config_vals[config_vars]|@debug_print_var}</td></tr> {sectionelse} <tr><td><p>no config vars assigned</p></td></tr> {/section} </table> </body> </html> {/capture} {if isset($_smarty_debug_output) and $_smarty_debug_output eq "html"} {$debug_output} {else} <script type="text/javascript"> // <![CDATA[ if ( self.name == '' ) {ldelim} var title = 'Console'; {rdelim} else {ldelim} var title = 'Console_' + self.name; {rdelim} _smarty_console = window.open("",title.value,"width=680,height=600,resizable,scrollbars=yes"); _smarty_console.document.write('{$debug_output|escape:'javascript'}'); _smarty_console.document.close(); // ]]> </script> {/if}
01cms
01cms/branches/1.0/01mvc/lib/Smarty/debug.tpl
Smarty
asf20
3,562
<?php /** * 基类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class Base { private static $instance; protected function __construct () { self::$instance = & $this; } public static function &i () { return self::$instance; } }
01cms
01cms/branches/1.0/01mvc/lib/Base.php
PHP
asf20
398
<?php /** * 文件上传类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class Upload { public $maxSize = 0; public $maxWidth = 0; public $maxHeight = 0; public $allowedTypes = ""; public $fileTemp = ""; public $fileName = ""; public $origName = ""; public $fileType = ""; public $fileSize = ""; public $fileExt = ""; public $uploadPath = ""; public $overwrite = FALSE; public $isImage = FALSE; public $imageWidth = ''; public $imageHeight = ''; public $imageType = ''; public $imageSizeStr = ''; public $errorMsg = ''; public $mimes = array(); public $removeSpaces = TRUE; public $tempPrefix = "temp_file_"; function initialize ($config = array()) { $defaults = array('maxSize'=>0, 'maxWidth'=>0, 'maxHeight'=>0, 'allowedTypes'=>"", 'fileTemp'=>"", 'fileName'=>"", 'origName'=>"", 'fileType'=>"", 'fileSize'=>"", 'fileExt'=>"", 'uploadPath'=>"", 'overwrite'=>FALSE, 'encryptName'=>FALSE, 'isImage'=>FALSE, 'imageWidth'=>'', 'imageHeight'=>'', 'imageType'=>'', 'imageSizeStr'=>'', 'errorMsg'=>'', 'mimes'=>array(), 'removeSpaces'=>TRUE, 'xssClean'=>FALSE, 'tempPrefix'=>"temp_file_"); foreach ($defaults as $key => $val) { if (isset($config[$key])) { $method = 'set' . ucfirst($key); if (method_exists($this, $method)) { $this->$method($config[$key]); } else { $this->$key = $config[$key]; } } else { $this->$key = $val; } } } function doUpload ($field = 'userfile') { if (! isset($_FILES[$field])) { $this->setError('您还没有选择要上传的文件'); return FALSE; } if (! $this->validateUploadPath()) { return FALSE; } if (! is_uploaded_file($_FILES[$field]['tmp_name'])) { $error = (! isset($_FILES[$field]['error'])) ? 4 : $_FILES[$field]['error']; switch ($error) { case 1: $this->setError('文件大小超过了最大限制'); break; case 2: $this->setError('文件大小超过了最大限制'); break; case 3: $this->setError('文件未全部上传'); break; case 4: $this->setError('您还没有选择要上传的文件'); break; case 6: $this->setError('临时目录不存在'); break; case 7: $this->setError('文件不可写'); break; default: $this->setError('找不到文件'); break; } return FALSE; } $this->fileTemp = $_FILES[$field]['tmp_name']; //$this->fileName = $_FILES[$field]['name']; $this->fileSize = $_FILES[$field]['size']; $this->fileType = preg_replace("/^(.+?);.*$/", "\\1", $_FILES[$field]['type']); $this->fileType = strtolower($this->fileType); $this->fileExt = $this->getExtension($_FILES[$field]['name']); if ($this->fileSize > 0) { $this->fileSize = round($this->fileSize / 1024, 2); } if (! $this->isAllowedFiletype()) { $this->setError('禁止上传的文件类型'); return FALSE; } if (! $this->isAllowedFilesize()) { $this->setError('文件大小超过了最大限'); return FALSE; } $this->fileName = $this->getFileName(); if (! @copy($this->fileTemp, $this->uploadPath . $this->fileName)) { if (! @move_uploaded_file($this->fileTemp, $this->uploadPath . $this->fileName)) { $this->setError('upload_destination_error'); return FALSE; } } $this->setImageProperties($this->uploadPath . $this->fileName); return TRUE; } function data () { return array('fileName'=>$this->fileName, 'fileType'=>$this->fileType, 'file_path'=>$this->uploadPath, 'fullPath'=>$this->uploadPath . $this->fileName, 'rawName'=>str_replace($this->fileExt, '', $this->fileName), 'origName'=>$this->origName, 'fileExt'=>$this->fileExt, 'fileSize'=>$this->fileSize, 'isImage'=>$this->isImage(), 'imageWidth'=>$this->imageWidth, 'imageHeight'=>$this->imageHeight, 'imageType'=>$this->imageType, 'imageSizeStr'=>$this->imageSizeStr); } function setUploadPath ($path) { // Make sure it has a trailing slash $this->uploadPath = rtrim($path, '/') . '/'; } function getFileName () { if ($this->fileName == '') { $this->fileName = date('YmdHis') . mt_rand(100, 999); } return $this->fileName . '.' . $this->fileExt; } function setFileName ($fileName) { $this->fileName = $fileName; } function setMaxFilesize ($n) { $this->maxSize = ((int) $n < 0) ? 0 : (int) $n; } function setMaxWidth ($n) { $this->maxWidth = ((int) $n < 0) ? 0 : (int) $n; } function setMaxHeight ($n) { $this->maxHeight = ((int) $n < 0) ? 0 : (int) $n; } function setAllowedTypes ($types) { $this->allowedTypes = explode('|', $types); } function setImageProperties ($path = '') { if (! $this->isImage()) { return; } if (function_exists('getimagesize')) { if (FALSE !== ($D = @getimagesize($path))) { $types = array(1=>'gif', 2=>'jpeg', 3=>'png'); $this->image_width = $D['0']; $this->image_height = $D['1']; $this->imageType = (! isset($types[$D['2']])) ? 'unknown' : $types[$D['2']]; $this->imageSizeStr = $D['3']; } } } function isImage () { $imgType = array('gif', 'jpeg', 'png', 'jpg'); return (in_array(strtolower($this->fileExt), $imgType)) ? TRUE : FALSE; } function isAllowedFiletype () { if (count($this->allowedTypes) == 0 or ! is_array($this->allowedTypes)) { $this->setError('没有设置允许上传的文件类型'); return FALSE; } if (in_array(strtolower($this->fileExt), $this->allowedTypes)) { return TRUE; } return FALSE; } function isAllowedFilesize () { if ($this->maxSize != 0 and $this->fileSize > $this->maxSize) { return FALSE; } else { return TRUE; } } function validateUploadPath () { if ($this->uploadPath == '') { $this->setError('没有设置文件保存路径'); return FALSE; } if (function_exists('realpath') and @realpath($this->uploadPath) !== FALSE) { $this->uploadPath = str_replace("\\", "/", realpath($this->uploadPath)); } if (! @is_dir($this->uploadPath)) { $this->setError('文件保存路径不是一个目录'); return FALSE; } if (! is_writable($this->uploadPath)) { $this->setError('文件保存路径不可写'); return FALSE; } $this->uploadPath = preg_replace('/(.+?)\/*$/', "\\1/", $this->uploadPath); return TRUE; } function getExtension ($filename) { $x = explode('.', $filename); return end($x); } function setError ($msg) { if (is_array($msg)) { foreach ($msg as $val) { $this->errorMsg .= ' ' . $val; } } else { $this->errorMsg = $msg; } } } // END Upload Class
01cms
01cms/branches/1.0/01mvc/lib/Upload.php
PHP
asf20
8,803
<?php /** * 验证 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class Filter { /** * 检查Email地址 * * @param string $value * @return bool */ public static function isEmail ($value) { return preg_match('/^([a-zA-Z0-9]|[._])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/', $value); } /** * 检查6-20位不含空格密码的格式 * * @param string $value * @return bool */ public static function isPwd ($value) { return preg_match('/^[^\s]{6,20}$/', $value); } /* * 检查用户名的格式 * 4-20字母、数字、下划线或减号的组合, 首字符必须为字母或数字 */ public static function isName ($value) { return preg_match('/^[A-Za-z0-9][A-Za-z0-9_\-]{3,19}$/', $value); } /** * 日期 * 支持格式 2009-5-1 2009/5/1 2009-05-01 2009/05/01 2009.1.1 2009.01.01 * @param string $value * @return bool */ public static function isDateTime ($value) { return preg_match('/^((((1[6-9]|[2-9]\d)\d{2})(\-|\/|\.)(0?[13578]|1[02])(\-|\/|\.)(0?[1-9]|[12]\d|3[01]))|(((1[6-9]|[2-9]\d)\d{2})(\-|\/|\.)(0?[13456789]|1[012])(\-|\/|\.)(0?[1-9]|[12]\d|30))|(((1[6-9]|[2-9]\d)\d{2})(\-|\/|\.)0?2(\-|\/|\.)(0?[1-9]|1\d|2[0-8]))|(((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))(\-|\/|\.)0?2(\-|\/|\.)29))$/', $value); } /* * 检查数字 */ public static function isNumber ($value) { return preg_match('/^([+-]?)\d*\.?\d+$/', $value); } /** * 检验字符串格式是否是1,2,3,4这种格式 */ public static function isDotStr ($value) { return preg_match("/^([0-9]+,)+$/", $value . ","); //偷懒了,补上咯逗号 } /** * 将字符串格式化为1,2,3,4这种形式 * * @param mix $value * @return string */ public static function formatdot ($value) { $value = preg_replace("/[^\d]+/", ",", $value); $value = preg_replace("/^,|,$/", "", $value); return $value; } /** * 检查URL链接 * 支持格式 http://www.01cms.com https://www.01cms.com ftp://www.01cms.com www.01cms.com * * @param string $value * @return bool */ public static function isURL ($value) { return preg_match('/^((http[s]?|ftp)\:\/\/)?([a-z0-9][a-z0-9\-]+\.)?[a-z0-9][a-z0-9\-]+[a-z0-9](\.[a-z]{2,4})+(\/[a-z0-9\.\,\-\_\%\?\=\&]?)?$/i', $value); } /** * 检查是否为中文 * * @param string $value * @return string */ public static function isChinese ($value) { return preg_match('/^[\x7f-\xff]+$/', $value); } /** * 检查身份证 * 15 位的:以一位数字1-9开头,后面是14位数字 * 18位的:以一位数字1-9开头,后面是16位数字,最后一位是[0-9x] * * @param string $value * @return bool */ public static function isCard ($value) { return preg_match('/^[1-9]([0-9]{14}|[0-9]{16}[0-9x])$/i', $value); } /** * utf-8下字符串长度 * * @param string $str * @return int */ public static function len ($str) { $count = 0; for ($i = 0; $i < strlen($str); $i ++) { $value = ord($str[$i]); if ($value > 127) { $count ++; if ($value >= 192 && $value <= 223) $i ++; elseif ($value >= 224 && $value <= 239) $i = $i + 2; elseif ($value >= 240 && $value <= 247) $i = $i + 3; else die('Not a UTF-8 compatible string'); } $count ++; } return $count; } /** * 检验真实姓名 * * @param string $name * @return bool */ public static function isRealName ($name) { if (strlen(trim($name)) < 2 || strlen(trim($name)) > 10) { return false; } for ($i = 0; $i < strlen($name); $i ++) { if (ord(substr($name, $i, 1)) <= 0xa0) { return false; } } return true; } }
01cms
01cms/branches/1.0/01mvc/lib/Filter.php
PHP
asf20
4,596
<?php /** * 动态分页类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class Pagination { public $baseUrl = ''; public $totalRows = ''; public $pageSize = 20; public $numLinks = 5; public $curPage = 0; public $firstLink = '&lsaquo; 首页'; public $nextLink = '下一页'; public $prevLink = '上一页'; public $lastLink = '尾页 &rsaquo;'; public $pageParam = 1; public $fullTagOpen = ''; public $fullTagClose = ''; public $firstTagOpen = ''; public $firstTagClose = '&nbsp;'; public $lastTagOpen = '&nbsp;'; public $lastTagClose = ''; public $curTagOpen = '&nbsp;<strong>'; public $curTagClose = '</strong>'; public $nextTagOpen = '&nbsp;'; public $nextTagClose = '&nbsp;'; public $prevTagOpen = '&nbsp;'; public $prevTagClose = ''; public $numTagOpen = '&nbsp;'; public $numTagClose = ''; public $pageQueryString = FALSE; public $queryStringSegment = 'pageSize'; public $Base; function __construct () { $this->Base = & Base::i(); } function initialize ($params = array()) { if (count($params) > 0) { foreach ($params as $key => $val) { if (isset($this->$key)) { $this->$key = $val; } } } } function createLinks ($params) { if (count($params) > 0) { $this->initialize($params); } if (empty($this->baseUrl)) { $this->baseUrl = BOOT_URL . '/' . $this->Base->c . '/' . $this->Base->m; for ($i = 0; $i < $this->pageParam; $i ++) { if (! isset($this->Base->p[$i])) { $this->Base->p[$i] = 0; } $this->baseUrl .= '/' . $this->Base->p[$i]; } } if (empty($_SERVER['QUERY_STRING'])) { $queryString = ''; } else { $queryString = '?' . $_SERVER['QUERY_STRING']; } if ($this->totalRows == 0 or $this->pageSize == 0) { $this->Base->pagesCode = '<span>没有记录</span>'; return ''; } $numPages = ceil($this->totalRows / $this->pageSize); if ($numPages == 1) { $this->Base->pagesCode = '<span>共1页</span>'; return ''; } if (isset($this->Base->p[$this->pageParam]) && $this->Base->p[$this->pageParam] > 0) { $this->curPage = $this->Base->p[$this->pageParam]; $this->curPage = (int) $this->curPage; } $this->numLinks = (int) $this->numLinks; if ($this->numLinks < 1) { showError('Your number of links must be a positive number.'); } if (! is_numeric($this->curPage)) { $this->curPage = 0; } if ($this->curPage > $this->totalRows) { $this->curPage = ($numPages - 1) * $this->pageSize; } $uriPageNumber = $this->curPage; $this->curPage = floor(($this->curPage / $this->pageSize) + 1); $start = (($this->curPage - $this->numLinks) > 0) ? $this->curPage - ($this->numLinks - 1) : 1; $end = (($this->curPage + $this->numLinks) < $numPages) ? $this->curPage + $this->numLinks : $numPages; $this->baseUrl = rtrim($this->baseUrl, '/') . '/'; $output = ''; if ($this->curPage > $this->numLinks) { $output .= $this->firstTagOpen . '<a href="' . $this->baseUrl . $queryString . '">' . $this->firstLink . '</a>' . $this->firstTagClose; } if ($this->curPage != 1) { $i = $uriPageNumber - $this->pageSize; if ($i == 0) { $i = ''; } $output .= $this->prevTagOpen . '<a href="' . $this->baseUrl . $i . $queryString . '">' . $this->prevLink . '</a>' . $this->prevTagClose; } for ($loop = $start - 1; $loop <= $end; $loop ++) { $i = ($loop * $this->pageSize) - $this->pageSize; if ($i >= 0) { if ($this->curPage == $loop) { $output .= $this->curTagOpen . $loop . $this->curTagClose; // Current page } else { $n = ($i == 0) ? '' : $i; $output .= $this->numTagOpen . '<a href="' . $this->baseUrl . $n . $queryString . '">' . $loop . '</a>' . $this->numTagClose; } } } if ($this->curPage < $numPages) { $output .= $this->nextTagOpen . '<a href="' . $this->baseUrl . ($this->curPage * $this->pageSize) . $queryString . '">' . $this->nextLink . '</a>' . $this->nextTagClose; } if (($this->curPage + $this->numLinks) < $numPages) { $i = (($numPages * $this->pageSize) - $this->pageSize); $output .= $this->lastTagOpen . '<a href="' . $this->baseUrl . $i . $queryString . '">' . $this->lastLink . '</a>' . $this->lastTagClose; } $output = preg_replace("#([^:])//+#", "\\1/", $output); $output = $this->fullTagOpen . $output . $this->fullTagClose; if ($this->pageSize > 1) { $output .= " <span>({$this->pageSize}条/页 共{$this->totalRows}条/{$numPages}页)</span> "; } $this->Base->pagesCode = $output; return ''; } } /* End of file /01CMS/01mvc/lib/Pagination.php */
01cms
01cms/branches/1.0/01mvc/lib/Pagination.php
PHP
asf20
6,195
<?php /** * 数据库常规动作类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class Action { public $goUrl; private $data; private $id; private $Base; private $stayTime; private $templateSuffix; private $Db; private $js; function __construct () { $this->Base = & Base::i(); $this->Db = isset($this->Base->Db) && is_object($this->Base->Db) ? $this->Base->Db : $this->Base->Load->model('Db'); $this->templateSuffix = empty($this->Base->templateSuffix) ? '' : $this->Base->templateSuffix; $this->id = empty($this->Base->id) ? 0 : ereg_replace('[^0-9,]', '', $this->Base->id); $this->data = empty($this->Base->data) ? array() : $this->Base->data; $this->js = empty($this->Base->js) ? 0 : $this->Base->js; } function lists () { if (empty($this->Base->lists)) { $this->Base->lists = $this->Db->lists(); if (isset($this->Base->dealListsModelMethod)) { $method = $this->Base->dealListsModelMethod; $this->Base->lists = $this->Db->{$method}($this->Base->lists); }else if (isset($this->Base->dealListsControllerMethod)) { $method = $this->Base->dealListsControllerMethod; $this->Base->lists = $this->Base->{$method}($this->Base->lists); } } $this->Base->Load->view('smarty', $this->templateSuffix); } function add () { $this->Base->Load->view('smarty', 'add' . $this->templateSuffix); } function insert () { $status = $this->Db->insert($this->data, $this->Db->table); if ($status) { response('操作成功', TRUE, $this->js); } else { response('操作失败', FALSE, $this->js); } } function mod () { $this->Base->data = $this->Db->getRow("SELECT * FROM `{$this->Db->table}` WHERE `id` = '{$this->id}'"); $this->Base->Load->view('smarty', 'mod' . $this->templateSuffix); } function update () { $status = $this->Db->update($this->data, $this->id); if ($status) { response('操作成功', TRUE, $this->js); } else { response('操作失败', FALSE, $this->js); } } function del () { if (strpos($this->id, ',') !== FALSE) { $ids = explode(',', $this->id); $status = TRUE; foreach ($ids as $id) { $sta = $this->Db->delete($id); if (! $sta) { $status = FALSE; } } } else { $status = $this->Db->delete($this->id); } if ($status) { response('删除成功', TRUE, $this->js); } else { response('操作失败', FALSE, $this->js); } } function ordering () { $ids = explode(',', $this->id); $i = 0; $status = TRUE; foreach ($ids as $id) { $status = $this->Db->update(array('ordering' => $i), "id = {$id}"); if (! $status) { $status = FALSE; } $i ++; } if ($status) { response('成功更新排序', TRUE, $this->js); } else { response('排序更新失败', FALSE, $this->js); } } } /* End of file /01CMS/01mvc/lib/Action.php */
01cms
01cms/branches/1.0/01mvc/lib/Action.php
PHP
asf20
4,031
<?php /** * 程序测试类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class Test { public $startTime = 0; public $stopTime = 0; public $spentTime = 0; /** * 初始化 * * @return void * @access public */ function init () { $this->startTime = 0; $this->endTime = 0; $this->spentTime = 0; } /** * 开始时间 * * @return void * @access public */ function startTime () { $this->startTime = microtime(); } /** * 结束时间 * * @return void * @access public */ function stopTime () { $this->stopTime = microtime(); } /** * 所用时间 * * @return string * @access public */ function spentTime () { if ($this->spentTime) { return $this->spentTime; } else { $startMicro = substr($this->startTime, 0, 10); $startSecond = substr($this->startTime, 11, 10); $stopMicro = substr($this->stopTime, 0, 10); $stopSecond = substr($this->stopTime, 11, 10); $start = doubleval($startMicro) + $startSecond; $stop = doubleval($stopMicro) + $stopSecond; $this->spentTime = $stop - $start; return substr($this->spentTime, 0, 8) . "(s)"; } } }
01cms
01cms/branches/1.0/01mvc/lib/Test.php
PHP
asf20
1,366
<?php /** * 控制器基类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class Controller extends Base { function __construct () { parent::__construct(); $this->Load = & $GLOBALS['Load']; $this->Uri = & $GLOBALS['Uri']; $this->c = & $GLOBALS['c']; $this->m = & $GLOBALS['m']; $this->p = & $GLOBALS['p']; } /** * 动作调度 * * @param string $action lists|add|insert|mod|update|del * @return void * @access protected */ protected function action ($action) { $this->Action = lib('Action'); if (empty($action) || ! method_exists($this->Action, $action)) { showError('404'); } $this->Action->$action(); } } // END
01cms
01cms/branches/1.0/01mvc/lib/Controller.php
PHP
asf20
822
<?php /** * URI分析类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class Uri { private $className; private $methodName; private $param; private $pathInfo = ''; function __construct () { if (! empty($_GET['i'])) { $this->pathInfo = $_GET['i']; } else if (! empty($_SERVER['PATH_INFO'])) { $this->pathInfo = $_SERVER['PATH_INFO']; } if ($this->pathInfo != '') { $this->pathInfo = trim($this->pathInfo, '/'); $urlSuffix = $GLOBALS['Load']->config['urlSuffix']; if (! empty($urlSuffix)) { $this->pathInfo = preg_replace($urlSuffix . '$', '', $this->pathInfo); } $uriArr = explode("/", $this->pathInfo); $segments = array(); foreach ($uriArr as $val) { $val = trim($this->filterSegment($val)); if ($val != '') { $segments[] = $val; } } $this->className = empty($segments[0]) ? '' : ucfirst($segments[0]); $this->methodName = empty($segments[1]) ? '' : $segments[1]; $this->param = isset($segments[2]) ? array_slice($segments, 2) : array(); } } private function filterSegment ($str) { if (substr($str, 0, 1) == '_') { showError('Bad Request'); } $bad = array('$', '(', ')', '%28', '%29'); $good = array('&#36;', '&#40;', '&#41;', '&#40;', '&#41;'); $str = str_replace($bad, $good, $str); $str = slashQuotes($str); return $str; } public function getClassName () { return empty($this->className) ? 'index' : strtolower($this->className); } public function getMethodName () { return empty($this->methodName) ? 'index' : $this->methodName; } public function getParam () { return $this->param; } public function getPathInfo () { return $this->pathInfo; } }
01cms
01cms/branches/1.0/01mvc/lib/Uri.php
PHP
asf20
2,299
<?php /** * 文档模型 - 模型类 * * @package 01CMS * @subpackage admin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class ChannelModel { public $id; public $data; /** * 调用getAddData()方法后,文档分页内容的总页数会缓存到这个属性 * * @var int */ public $countContentPages; function __construct ($id = 0) { if ($id > 0) { $channel = $this->getData(); $this->id = $id; $this->data = isset($channel[$id]) ? $channel[$id] : array(); } } function getData () { if (data('archiveChannel') === FALSE) { $this->writeChannel(); } return data('archiveChannel'); } /** * 获取模型附加字段 * * @return object * @access public */ function getAddFields () { return model('Db')->getRows("SELECT * FROM @@__archive_field where channelId={$this->id}"); } /** * 获取文章的型模型附加内容 * * @param int $archiveId * @return array * @access public */ function getAddData ($archiveId, $page = 1) { $data = model('Db')->getRows("SELECT * FROM @@__archive_channel_{$this->tableId} where archiveId={$archiveId}"); if ($page != 1) { $channelTables = explode(',', Base::i()->Load->var['pagesContentChannel']); $isPages = in_array($this->tableId, $channelTables) ? 1 : 0; if ($isPages) { $this->countContentPages = count($data); if ($this->countContentPages > 1 && $page == - 1) { $pageDelimiter = addslashes(Base::i()->Load->var['pageDelimiter']); for ($i = 1; $i < $this->countContentPages; $i ++) { $data[0]->content .= $pageDelimiter . $data[$i]->content; } } else if ($page > 1) { $page = ($page > $this->countContentPages) ? $this->countContentPages : $page; $data[0]->content = $data[$page]->content; } } } if (empty($data)) { showError('无法读取模型附加数据'); } return $data[0]; } function delete () { $Db = model('Db'); $categories = $Db->getRows('SELECT id FROM @@__archive_category WHERE channelId = ' . $this->id); foreach ($categories as $category) { $Db->delete("categoryId = {$category->id}", '@@__archive_archive'); } $Db->delete("channelId = {$this->id}", '@@__archive_category'); $Db->delete("channelId = {$this->id}", '@@__archive_field'); $Db->delete("id = {$this->id}", '@@__archive_channel'); $Db->query("DROP TABLE `@@__archive_channel_{$this->tableId}`;"); $this->writeChannel(); } /** * 文档模型数据写入文件 */ function writeChannel () { $Db = model('Db'); $channels = $Db->getRows('SELECT * FROM @@__archive_channel'); $channelsData = array(); foreach ($channels as $channel) { $categories = $Db->getRows("SELECT id FROM @@__archive_category WHERE channelId = {$channel->id}"); $categoryIds = ''; foreach ($categories as $category) { $categoryIds .= empty($categoryIds) ? $category->id : ',' . $category->id; } $channelsData[$channel->id] = array('name'=>$channel->name, 'tableId'=>$channel->tableId, 'fieldList'=>$channel->fieldList, 'categoryIds'=>$categoryIds); } lib('Write')->phpArray(SYS_PATH . '/data/archiveChannel.php', $channelsData); } /** * 更新文档模型的字段列表 * * @param int $channelId * @return void */ function updateFiledList () { $Db = model('Db'); $Db->query("SELECT field,emptyTip FROM @@__archive_field where channelId={$this->id}"); $fieldList = ''; while ($row = $Db->getNextRow()) { if ($fieldList != '') { $fieldList .= empty($row->emptyTip) ? ",{$row->field}" : ",{$row->field}|{$row->emptyTip}"; } else { $fieldList = empty($row->emptyTip) ? "{$row->field}" : "{$row->field}|{$row->emptyTip}"; } } $Db->query("UPDATE @@__archive_channel set fieldList='{$fieldList}' where id = {$this->id}"); $this->writeChannel(); } public function __get ($key) { if (isset($this->$key)) { return $this->$key; } else if (isset($this->data[$key])) { return $this->data[$key]; } else { return ''; } } }
01cms
01cms/branches/1.0/01mvc/model/ChannelModel.php
PHP
asf20
5,476
<?php /** * 系统设置模型类 * * @package 01CMS * @subpackage admin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class HtmlModel { private $Db; function __construct () { $this->Db = model('Db'); } /** * 获取HTML * * @param string $tplName * @return string * @access public */ public static function getHtml ($tplName) { restore_error_handler(); $style = Base::i()->Load->var['style']; $Smarty = lib('Smarty'); $Smarty->compile_dir = APP_PATH . '/data/compile/' . Base::i()->c . '/' . Base::i()->m; if (! file_exists($Smarty->compile_dir)) { makeDirs($Smarty->compile_dir); } $Smarty->plugins_dir = array(APP_PATH . '/plugin', SYS_PATH . '/plugin', SYS_PATH . '/lib/Smarty/plugins'); $Smarty->template_dir = ROOT_PATH . '/template/' . $style; $Smarty->left_delimiter = '{:'; $Smarty->assign_by_ref('i', Base::i()); return $Smarty->fetch($tplName); } function indexHtml ($type = 'show') { $html = $this->getHtml(Base::i()->Load->var['homepageTemplateName']); if ($type == 'show') { echo $html; } else if ($type == 'write') { file_put_contents(ROOT_PATH . '/' . Base::i()->Load->var['homepageFileName'], $html); } } /** * 生成栏目HTML * * @param int $id * @return void * @access public */ function writeCategoryHtml ($id) { $Category = model('Category', $id); if (! empty($Category->data)) { Base::i()->id = $id; Base::i()->data = $Category->data; if (empty($Category->allSonId)) { $where = "categoryId = {$id}"; } else { $where = "categoryId in ({$id},{$Category->allSonId})"; } $pageSize = $Category->pageSize; $count = $this->Db->getOne("select count(*) as num from @@__archive_archive where pass = 1 AND {$where}"); $pages = ceil($count / $pageSize); $page = 1; do { $start = $pageSize * ($page - 1); $lists = $this->Db->getRows("select * from @@__archive_archive where pass = 1 AND {$where} order by ordering desc limit {$start}, {$pageSize}"); Base::i()->lists = model('Archive')->setArchiveFlag($lists); lib('StaticPages')->createLinks(array('fileId'=>'list', 'curPage'=>$page, 'pageSize'=>$pageSize, 'baseUrl'=>'/' . $Category->alias, 'totalPages'=>$pages)); $html = $this->getHtml($Category->categoryTemplateName); $fileName = ($page == 1) ? 'index.html' : "list{$page}.html"; $filePath = ROOT_PATH . Base::i()->Load->var['htmlSaveDir'] . '/' . $Category->alias; makeDirs($filePath); file_put_contents("{$filePath}/{$fileName}", $html); $page ++; } while ($page <= $pages); } } /** * 输出栏目HTML * * @param int $id * @return void * @access public */ function showCategoryHtml ($id, $start = 0) { $Category = model('Category', $id); if (! empty($Category->data)) { Base::i()->id = $id; Base::i()->data = $Category->data; if (empty($Category->allSonId)) { $where = "categoryId = {$id}"; } else { $where = "categoryId in ({$id},{$Category->allSonId})"; } $pageSize = $Category->pageSize; $count = $this->Db->getOne("select count(*) as num from @@__archive_archive where pass = 1 AND {$where}"); $lists = $this->Db->getRows("select * from @@__archive_archive where pass = 1 AND {$where} order by ordering desc limit {$start}, {$pageSize}"); Base::i()->lists = model('Archive')->setArchiveFlag($lists); $baseUrl = BOOT_URL . '/category/' . $id; lib('Pagination')->createLinks(array('baseUrl'=>$baseUrl, 'totalRows'=>$count, 'pageSize'=>$pageSize)); echo $this->getHtml($Category->categoryTemplateName); } else { showError('404'); } } /** * 生成文档HTML * * @param int $id * @return void * @access public */ function writeArchiveHtml ($id) { $Archive = model('Archive', $id); if (! empty($Archive->data)) { $Category = model('Category', $Archive->categoryId); $Channel = model('Channel', $Category->channelId); $count = $this->Db->getOne("SELECT count(*) FROM @@__archive_channel_{$Channel->tableId} where archiveId={$id}"); $archiveUrl = empty($Archive->fileName) ? $Category->archiveUrl : $Archive->fileName; $archiveUrl = str_replace('[id]', $Archive->id, $archiveUrl); $archiveUrl = str_replace('[alias]', $Category->alias, $archiveUrl); $archiveUrl = str_replace('%Y', date('Y', $Archive->addTime), $archiveUrl); $archiveUrl = str_replace('%m', date('m', $Archive->addTime), $archiveUrl); $archiveUrl = str_replace('%d', date('d', $Archive->addTime), $archiveUrl); $Archive->url = $archiveUrl; $baseName = basename($archiveUrl); $baseUrl = dirname($archiveUrl); $strrpos = strrpos($baseName, '.'); $fileId = substr($baseName, 0, $strrpos); $fileExt = substr($baseName, $strrpos); makeDirs(ROOT_PATH . $baseUrl); $pagesConfig = array(); $pagesConfig['firstFileName'] = $baseName; $pagesConfig['fileId'] = $fileId . '_'; $pagesConfig['pageSize'] = 1; $pagesConfig['baseUrl'] = $baseUrl; $pagesConfig['fileExt'] = $fileExt; $pagesConfig['totalPages'] = $count; $this->Db->query("SELECT * FROM @@__archive_channel_{$Channel->tableId} where archiveId={$id}", 'archive'); $page = 1; while ($data = $this->Db->getNextRow('archive')) { $pagesConfig['curPage'] = $page; foreach ($data as $k => $v) { if (! in_array($k, array('id', 'archiveId', 'categoryId'))) { $Archive->{$k} = $v; } } Base::i()->show = $Archive; lib('StaticPages')->createLinks($pagesConfig); $templateName = empty($Archive->templateName) ? $Category->archiveTemplateName : $Archive->templateName; $html = $this->getHtml($templateName); $fileName = ($page == 1) ? $baseName : $pagesConfig['fileId'] . $page . $fileExt; $fileName = ROOT_PATH . $baseUrl . '/' . $fileName; file_put_contents($fileName, $html); $page ++; } } } /** * 输出文档HTML * * @param int $id * @return void * @access public */ function showArchiveHtml ($id, $start = 0) { $Archive = model('Archive', $id); if (isset($Archive->id) && $Archive->id > 0) { $Category = model('Category', $Archive->categoryId); $Channel = model('Channel', $Category->channelId); $data = $this->Db->getRows("SELECT * FROM @@__archive_channel_{$Channel->tableId} where archiveId={$id}"); $count = count($data); $data = $data[$start]; foreach ($data as $k => $v) { if (! in_array($k, array('id', 'archiveId', 'categoryId'))) { $Archive->{$k} = $v; } } Base::i()->show = $Archive; $baseUrl = BOOT_URL . '/archive/' . $id; lib('Pagination')->createLinks(array('baseUrl'=>$baseUrl, 'totalRows'=>$count, 'pageSize'=>1)); $templateName = empty($Archive->templateName) ? $Category->archiveTemplateName : $Archive->templateName; echo $this->getHtml($templateName); } else { showError('404'); } } /** * 输出单页文档HTML * * @param int $id * @return void * @access public */ function showSingleHtml ($id) { $Archive = model('Single', $id); if (isset($Archive->id) && $Archive->id > 0) { Base::i()->show = $Archive; echo $this->getHtml($Archive->template); } else { showError('404'); } } /** * 生成单页文档HTML * * @param string $ids * @return void * @access public */ function writeSingleHtml ($ids) { $ids = explode(',', $ids); $i = 0; foreach ($ids as $id) { $Archive = model('Single', $id); if (isset($Archive->id) && $Archive->id > 0) { Base::i()->show = $Archive; $html = $this->getHtml($Archive->template); $filePath = ROOT_PATH . dirname($Archive->fileName); makeDirs($filePath); file_put_contents(ROOT_PATH . '/' . $Archive->fileName, $html); } $i ++; } return $i; } /** * 生成单页文档HTML * * @param int $id * @return void * @access public */ function writeAllSingleHtml () { $this->Db->query("select id from @@__archive_single", 'singleId'); $i = 0; while($single = $this->Db->getNextRow('singleId')) { $this->writeSingleHtml($single->id); $i ++; } return $i; } }
01cms
01cms/branches/1.0/01mvc/model/HtmlModel.php
PHP
asf20
11,217
<?php /** * 用户抽像模型 - 模型类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ abstract class UserAbstractModel { private $error; protected $prefix; protected $Db; public $fields; public $username = ''; public $userid = 0; function __construct () { $this->setUserTypePrefix($this->prefix); $this->Db = model('Db'); } abstract protected function setUserTypePrefix (); /** * 获取错误信息 * * @return string * @access public */ public function getError () { return $this->error; } /** * 设置错误信息 * * @return string * @access void */ public function setError ($error) { $this->error = $error; } /** * 获取用户信息 * * @param string $where * @param string $field * @return object * @access public */ function getUser ($where = 1, $field = '*') { return $this->Db->getRow("SELECT {$field} FROM @@__{$this->prefix}user WHERE {$where}"); } /** * 通过用户组ID获取用户组信息 * * @param string $where * @param string $field * @return object * @access public */ function getGroup ($where = 1, $field = '*') { return $this->Db->getRow("SELECT {$field} FROM @@__{$this->prefix}group WHERE {$where}"); } /** * 获取全部用户组信息 * * @param string $field * @return object * @access public */ function getGroups ($field = '*') { return $this->Db->getRows("SELECT {$field} FROM @@__{$this->prefix}group"); } /** * 获取全部权限信息 * * @param string $field * @return object * @access public */ function getAuths ($field = '*') { return $this->Db->getRows("SELECT {$field} FROM @@__{$this->prefix}auth ORDER BY ordering ASC"); } /** * 添加用户 * * @return string * @access public */ public function addUser ($data) { $user = $this->getUser("username = '{$data['username']}'", 'id'); if (count($user) > 0) { $this->setError("用户名 {$data['username']} 已存在,请使用其它用户名"); return FALSE; } $data['password'] = encrypt($data['password']); $data['regTime'] = TIME; $data['loginTime'] = TIME; $data['loginIp'] = getIp(); $data['loginNum'] = 0; return $this->Db->insert($data, '@@__' . $this->prefix . 'user'); } /** * 修改用户 * * @return string * @access public */ public function modUser ($data) { $user = $this->getUser("username = '{$data['username']}' AND id != {$data['id']}", 'id'); if (count($user) > 0) { $this->setError("用户名 {$data['username']} 已存在,请使用其它用户名"); return FALSE; } if (! empty($data['password'])) { $data['password'] = encrypt($data['password']); } return $this->Db->update($data, "id = {$data['id']}", '@@__' . $this->prefix . 'user'); } /** * 添加管理组 * * @return string * @access public */ public function addGroup ($data) { $user = $this->getGroup("name = '{$data['name']}'", 'id'); if (count($user) > 0) { $this->setError("组名 {$data['name']} 已存在,请使用其它用户名"); return FALSE; } return $this->Db->insert($data, '@@__' . $this->prefix . 'group'); } /** * 修改组别 * * @return string * @access public */ public function modGroup ($data) { $group = $this->getGroup("name = '{$data['name']}' AND id != {$data['id']}", 'id'); if (count($group) > 0) { $this->setError("组名 {$data['name']} 已存在,请使用其它用户名"); return FALSE; } return $this->Db->update($data, "id = {$data['id']}", '@@__' . $this->prefix . 'group'); } /** * 通过用户组ID获取菜单信息 * * @return array * @access public */ function getMenu () { $groupId = $this->fields->groupId; $menus = $this->Db->getRows("SELECT * FROM @@__{$this->prefix}menu order by ordering asc;", 0, 'array'); $auths = $this->Db->getRow("SELECT auth FROM @@__{$this->prefix}group WHERE id={$groupId}"); $data = array(); $i = 0; foreach ($menus as $menu) { $items = explode("\n", str_replace("\r\n", "\n", $menu['items'])); $dataItems = array(); foreach ($items as $item) { $itemArr = explode('|', $item); $item1 = explode(',', $itemArr[0]); $item1[1] = strpos($item1[1], 'http://') === FALSE ? BOOT_URL . '/' . $item1[1] : $item1[1]; if ($auths->auth == '**' || $this->checkAuth($auths->auth, $item1[1])) { if (isset($itemArr[1])) { $item2 = explode(',', $itemArr[1]); $item2[1] = strpos($item2[1], 'http://') === FALSE ? BOOT_URL . '/' . $item2[1] : $item2[1]; if ($auths->auth == '**' || $this->checkAuth($auths->auth, $item2[1])) { $item1 = array($item1[0], $item1[1], $item2[0], $item2[1]); } } $dataItems[] = $item1; } else { continue; } } if (empty($dataItems)) { continue; } else { $data[$i]['id'] = $menu['id']; $data[$i]['title'] = $menu['title']; $data[$i]['items'] = $dataItems; $data[$i]['hidden'] = $menu['hidden'] ? 'hidden' : ''; $i ++; } } return $data; } /** * 登陆 * * @param array $data * @return bool * @access public */ public function login ($data) { $user = $this->getUser("username = '{$data['username']}'"); if (empty($user)) { $this->error = "用户{$data['username']}不存在"; return FALSE; } if (encrypt($data['password']) != $user->password) { $this->error = '密码不正确'; return FALSE; } if (! isset($user->username)) { $this->error = "用户{$data['username']}不存在"; return FALSE; } $this->fields = $user; $this->Db->query("UPDATE @@__" . $this->prefix . "user SET loginTime = " . TIME . ",loginIp = '" . getIp() . "',loginNum = loginNum + 1 WHERE id = {$this->fields->id}"); return $this->setLogin(); } private function setLogin () { $time = 7200000; $status1 = Session::putCookie($this->prefix . 'username', $this->fields->username, $time); $status2 = Session::putCookie($this->prefix . 'loginTime', TIME, $time); $status3 = Session::putCookie($this->prefix . 'check', encrypt($this->fields->username . $this->fields->password), $time); return $status1 && $status2 && $status3; } /** * 登出 * * @return void * @access public */ public function logout () { $status1 = Session::dropCookie($this->prefix . 'username'); $status2 = Session::dropCookie($this->prefix . 'check'); $status3 = Session::dropCookie($this->prefix . 'loginTime'); return $status1 && $status2 && $status3; } /** * 检测登陆 * * @return bool * @access public */ public function isLogined () { $username = Session::getCookie($this->prefix . 'username'); if (! empty($username)) { $this->fields = $this->getUser("username = '{$username}'"); if (Session::getCookie($this->prefix . 'check') == encrypt($username . $this->fields->password)) { $group = $this->getGroup("id = {$this->fields->groupId}"); $this->fields->group = $group->name; $this->fields->auth = $group->auth; $this->username = $this->fields->username; $this->userid = $this->fields->id; if (time() - Session::getCookie($this->prefix . 'loginTime') > 180) { $this->setLogin(); } return TRUE; } } return FALSE; } /** * 检测权限 * * @param string $authStr * @param string $uriStr * @return bool * @access public */ public function checkAuth ($authStr = '', $uriStr = '') { if (empty($authStr)) { $authStr = $this->fields->auth; } $uriStr = str_replace(BOOT_URL . '/', '', $uriStr); $authArr = explode(',', $authStr); if (in_array('**', $authArr)) { return true; } if (empty($uriStr)) { $uriStr = Base::i()->Uri->getPathInfo(); } $uriArr = explode('/', $uriStr); $authArr = array_filter($authArr, "notEmpty"); $return = FALSE; foreach ($authArr as $segmentStr) { $segmentArr = explode('/', $segmentStr); $count = count($segmentArr); for ($j = 0; $j < $count; $j ++) { if ($segmentArr[$j] == '*') { $return = true; break; } else if ((! isset($segmentArr[$j])) || (! isset($uriArr[$j])) || (strtolower($segmentArr[$j]) != strtolower($uriArr[$j]))) { break; } } } return $return; } function __get($name) { return isset($this->$name) ? $this->$name : $this->fields->$name; } }
01cms
01cms/branches/1.0/01mvc/model/UserAbstractModel.php
PHP
asf20
11,201
<?php /** * 文档 - 数据模型 * * @package 01CMS * @subpackage admin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class ArchiveModel { public $id; public $data; private $Db; function __construct ($id = 0) { $this->Db = model('Db'); if ($id > 0) { $this->id = $id; $this->data = $this->getArchiveById($id); } } /** * 通过文档ID获取文档 * * @param int $id * @return object * @access public */ function getArchiveById ($id) { return $this->Db->getRow("SELECT * FROM @@__archive_archive where id={$id}"); } /** * 获取文档ID,主要用于HTML更新 * * @param string $where * @param int $page * @param int $pageSize * @return object * @access public */ function getArchiveIds ($where = 1, $page = 1, $pageSize = 20) { $start = ($page - 1) * $pageSize; return $this->Db->getRows("SELECT id FROM @@__archive_archive WHERE {$where} LIMIT {$start}, {$pageSize}"); } /** * 计算文档总数,用于HTML更新 * * @param string $where * @return int * @access public */ function countArchives ($where = 1) { return $this->Db->getOne("SELECT count(*) FROM @@__archive_archive WHERE pass = 1 AND {$where}"); } /** * 获取文档列表 * * @param array $params * @return object * @access public */ function getArchives ($params) { $start = empty($params['start']) ? 0 : $params['start']; $whereFlag = empty($params['flag']) ? '' : "and FIND_IN_SET('{$params['flag']}',flag)>0"; $size = empty($params['size']) ? 30 : $params['size']; $order = empty($params['order']) ? 'ordering desc' : $params['order']; if (empty($params['categoryId'])) { $whereCategoryId = ''; } else { $Category = model('Category'); $Category->categoryIds = ''; $Category->getChildIds($params['categoryId'], TRUE); $whereCategoryId = empty($Category->categoryIds) ? "and categoryId = {$params['categoryId']}" : "and categoryId in ({$params['categoryId']},{$Category->categoryIds})"; } return $this->Db->getRows("SELECT * FROM @@__archive_archive where pass = 1 $whereCategoryId $whereFlag order by $order limit {$start}, {$size}"); } /** * 处理文档属性 * * @param array $lists * @return array * @access public */ function setArchiveFlag ($lists) { $count = count($lists); for ($i = 0; $i < $count; $i ++) { $Category = model('Category',$lists[$i]->categoryId); $lists[$i]->title = htmlspecialchars($lists[$i]->title); $flag = explode(',', $lists[$i]->flag); if (in_array('p', $flag)) { $lists[$i]->title .= '[图]'; } $lists[$i]->categoryName = $Category->name; if (in_array('b', $flag)) { $lists[$i]->title = '<b>' . $lists[$i]->title . '</b>'; } if (! empty($lists[$i]->color) && $lists[$i]->color != '#000000') { $lists[$i]->title = '<font color="' . $lists[$i]->color . '">' . $lists[$i]->title . '</font>'; } if (in_array('j', $flag)) { $lists[$i]->staticUrl = $lists[$i]->activeUrl = $lists[$i]->url = $lists[$i]->redirectUrl; } else { $staticUrl = empty($lists[$i]->fileName) ? $Category->archiveUrl : $lists[$i]->fileName; $staticUrl = str_replace('[id]', $lists[$i]->id, $staticUrl); $staticUrl = str_replace('[alias]', $Category->alias, $staticUrl); $staticUrl = str_replace('%Y', date('Y', $lists[$i]->addTime), $staticUrl); $staticUrl = str_replace('%m', date('m', $lists[$i]->addTime), $staticUrl); $staticUrl = str_replace('%d', date('d', $lists[$i]->addTime), $staticUrl); $staticUrl = ROOT_DIR . $staticUrl; $lists[$i]->staticUrl = $staticUrl; $lists[$i]->activeUrl = BOOT_URL . '/data/archive/' . $lists[$i]->id; $lists[$i]->url = defined('staticHtml') ? $staticUrl : $lists[$i]->activeUrl; } } return $lists; } /** * 添加文档 * * @param array $data * @param array $addData * @param string $tableId * @return bool * @access public */ function insertArchive ($data, $addData, $tableId) { $addData['archiveId'] = $this->Db->insert($data, '@@__archive_archive'); $addData['categoryId'] = $data['categoryId']; $pageDelimiter = addslashes(Base::i()->Load->var['pageDelimiter']); $channelTables = explode(',', Base::i()->Load->var['pagesContentChannel']); $isPages = in_array($tableId, $channelTables) ? 1 : 0; if ($isPages && strpos($addData['content'], $pageDelimiter) !== FALSE) { $items = explode($pageDelimiter, $addData['content']); foreach ($items as $item) { $addData['content'] = $item; $this->Db->insert($addData, '@@__archive_channel_' . $tableId); } } else { $this->Db->insert($addData, '@@__archive_channel_' . $tableId); } } /** * 更新文档 * * @param array $data * @param array $addData * @param string $tableId * @param int $id * @return bool * @access public */ function updateArchive ($data, $addData, $tableId, $id) { $this->Db->update($data, "id={$id}", '@@__archive_archive'); $pageDelimiter = addslashes(Base::i()->Load->var['pageDelimiter']); $channelTables = explode(',', Base::i()->Load->var['pagesContentChannel']); $isPages = in_array($tableId, $channelTables) ? 1 : 0; if ($isPages && strpos($addData['content'], $pageDelimiter) !== FALSE) { $items = explode($pageDelimiter, $addData['content']); $ids = $this->Db->getRows("SELECT id, archiveId, categoryId FROM @@__archive_channel_{$tableId} where archiveId={$id}"); $countItems = count($items); $countIds = count($ids); for ($i = 0; $i < $countItems; $i ++) { if ($i < $countIds) { $addData['content'] = $items[$i]; $this->Db->update($addData, "id={$ids[$i]->id}", '@@__archive_channel_' . $tableId); } else { $addData['archiveId'] = $ids[0]->archiveId; $addData['categoryId'] = $ids[0]->categoryId; $addData['content'] = $items[$i]; $this->Db->insert($addData, '@@__archive_channel_' . $tableId); } } if ($countIds > $countItems) { $limitNum = $countIds - $countItems; $this->Db->query("delete from @@__archive_channel_{$tableId} order by id desc limit {$limitNum}"); } } else { $this->Db->update($addData, "archiveId={$id}", '@@__archive_channel_' . $tableId); } } function delArchive ($ids) { $items = explode(',', $ids); $category = data('archiveCategory'); $channel = data('archiveChannel'); foreach ($items as $id) { $archive = $this->getArchiveById($id); $curCategory = $category[$archive->categoryId]; $curChannel = $channel[$curCategory['channelId']]; $this->Db->del("id={$id}", '@@__archive_archive'); $this->Db->del("archiveId={$id}", '@@__archive_channel_' . $curChannel['tableId']); } } public function __get ($key) { if(isset($this->$key)) { return $this->$key; } else if(isset($this->data->$key)) { return $this->data->$key; } else { return ''; } } }
01cms
01cms/branches/1.0/01mvc/model/ArchiveModel.php
PHP
asf20
8,982
<?php /** * 文档栏目 - 数据模型 * * @package 01CMS * @subpackage admin * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class CategoryModel { public $id; public $data; /** * 栏目递归获取父类目时,栏目数据累加到这个属性 * * @var int */ public $parentCategory = array(); /** * 栏目递归获取子类目时,栏目ID累加到这个属性 * * @var int */ public $categoryIds = ''; private $Db; /** * 栏目递归获取子类目时,栏目数据累加到这个属性 * * @var int */ private $listArray = array(); function __construct ($id = 0) { if (intval($id) > 0) { $category = $this->getData(); $this->id = $id; $this->data = isset($category[$id]) ? $category[$id] : array(); } $this->Db = model('Db'); } function getData () { if (data('archiveCategory') === FALSE) { $this->writeChannel(); } return data('archiveCategory'); } /** * 获取父类 * * @param int $id * @param int $all [1|0] * @param int $onlyInner [0|1] */ function getParent ($id, $sign = 0) { if ($sign == 0) { $this->parentCategory = array(); $sign = 1; } $id = intval($id); $this->Db->query("SELECT * FROM @@__archive_category WHERE id={$id} AND type != 0", $id); while ($row = $this->Db->getNextRow($id)) { $this->parentCategory[] = $row; $this->getParent($row->parentId, $sign); } } /** * 获取类目子ID * * @param int $parentId [0] * @param int $all [1|0] * @param int $onlyInner [0|1] */ function getChildIds ($parentId = 0, $all = 1, $onlyInner = 0, $sign = 0) { if ($sign == 0) { $this->parentCategory = array(); $sign = 1; } $parentId = intval($parentId); $type = $onlyInner ? "AND type != 0" : ''; $this->Db->query("SELECT id FROM @@__archive_category WHERE isHidden = 0 AND parentId={$parentId} {$type}", $parentId); while ($row = $this->Db->getNextRow($parentId)) { if ($this->categoryIds == '') { $this->categoryIds = $row->id; } else { $this->categoryIds .= ',' . $row->id; } if ($all) { $this->getChildIds($row->id, $all, $sign); } } } /** * 获取子类目 * * @param int $parentId 父ID[0] * @param int $recursion 是否递归[0|1] * @param int $onlyInner 是否递归[0|1] * @param int $logicSign 是否添加逻辑标记[1|0] * @param string $separation [└─] * @param string $addSeparation [─] * @return object */ function getChildren ($parentId = 0, $recursion = 0, $onlyInner = 0, $logicSign = 1, $separation = '└─', $addSeparation = '─', $where = '1') { $parentId = intval($parentId); $this->listArray = array(); $type = $onlyInner ? "AND type != 0" : ''; $this->Db->query("SELECT * FROM @@__archive_category WHERE {$where} AND parentId ={$parentId} {$type} ORDER BY ordering ASC", 'children'); while ($row = $this->Db->getNextRow('children')) { $this->listArray[] = $row; if ($recursion) { $this->getLogicCategory($row->id, $type, $logicSign, $separation, $addSeparation, $where); } } return $this->listArray; } /** * 仅供getChildren()调用 */ function getLogicCategory ($id, $type, $logicSign, $separation, $addSeparation, $where) { $this->Db->query("SELECT * FROM @@__archive_category where $where AND parentId={$id} {$type} ORDER BY ordering ASC", 'logic' . $id); while ($row = $this->Db->getNextRow('logic' . $id)) { if ($logicSign) { $row->name = $separation . $row->name; } $this->listArray[] = $row; $this->getLogicCategory($row->id, $type, $logicSign, $separation . $addSeparation, $addSeparation); } } function delete () { if ($this->allSonIds != '') { $this->Db->delete("categoryId in ({$this->id},{$this->allSonIds})", '@@__archive_archive'); $this->Db->delete("id in ({$this->id},{$this->allSonIds})", '@@__archive_category'); } else { $this->Db->delete("categoryId in ({$this->id})", '@@__archive_archive'); $this->Db->delete("id in ({$this->id})", '@@__archive_category'); } $this->writeCategory(); } function writeCategory () { $category = array(); $ids = array(); $this->Db->query('select * from `@@__archive_category`', 'category'); while ($row = $this->Db->getNextRow('category')) { $alias = empty($row->alias) ? $row->id : preg_replace('/[^a-zA-Z0-9-_]/i', '', $row->alias); $ids[$alias] = $row->id; $category[$row->id] = array('name'=>$row->name, 'isHidden'=>$row->isHidden, 'type'=>$row->type, 'alias'=>$alias, 'channelId'=>$row->channelId, 'pageSize'=>$row->pageSize, 'categoryTemplateName'=>$row->categoryTemplateName, 'archiveTemplateName'=>$row->archiveTemplateName, 'archiveUrl'=>$row->archiveUrl, 'link'=>$row->link); $this->categoryIds = ''; $this->getChildIds($row->id, FALSE); $category[$row->id]['sonIds'] = $this->categoryIds; $this->categoryIds = ''; $this->getChildIds($row->id, true); $category[$row->id]['allSonIds'] = $this->categoryIds; } $category['ids'] = $ids; lib('Write')->phpArray(SYS_PATH . '/data/archiveCategory.php', $category); model('Channel')->writeChannel(); } public function __get ($key) { if (isset($this->$key)) { return $this->$key; } else if (isset($this->data[$key])) { return $this->data[$key]; } else { return ''; } } }
01cms
01cms/branches/1.0/01mvc/model/CategoryModel.php
PHP
asf20
7,026
<?php /** * 数据库 - 模型类 * * @package 01CMS * @subpackage system * @author rolong at vip.qq.com * @version 1.0.0 * @link http://www.01cms.com */ class DbModel extends Base { public $debug = FALSE; public $prefix; public $insertId = 0; public $table; public $linkId; protected $sql; protected $result = array(); protected $primaryKey = 'id'; function __construct () { $parentName = get_class($this); $Base = Base::i(); foreach (array_keys(get_object_vars($Base)) as $key) { if ((! isset($this->$key) || $this->$key == 'table') && $key != $parentName) { $this->$key = NULL; $this->$key = & $Base->$key; } } if (empty($this->table)) { $c = strtolower($this->c); $this->table = "@@__{$c}_{$this->m}"; } $this->connect($this->Load->config['mysql']); } /** * 连接数据库 * * @param array $config * @return void * @access public */ function connect ($config) { $this->prefix = $config['prefix']; if ($config['pconnect']) { $this->linkId = mysql_pconnect($config['hostname'], $config['username'], $config['password']); } else { $this->linkId = mysql_connect($config['hostname'], $config['username'], $config['password']); } if (! $this->linkId) { showError("No MySql connection!"); } mysql_select_db($config['database']); mysql_query("SET NAMES '{$config['charset']}', character_set_client=binary, sql_mode='' ;", $this->linkId); } /** * 运行SQL语句 * * @param string $sql * @param mix $id * @return bool * @access public */ function query ($sql = '', $id = 0) { if ($sql != '') { $this->setSql($sql); } if ($this->sql == '') { showError('The sql string is empty!'); } if ($this->debug) { $Test = lib('Test'); $Test->init(); $Test->startTime(); $this->result[$id] = mysql_query($this->sql, $this->linkId); $Test->stopTime(); echo "<br />---------------{$Test->spentTime()}---------------<br />{$this->sql}<br />"; } else { $this->result[$id] = mysql_query($this->sql, $this->linkId); } if ($this->result[$id] === false) { showError(mysql_error() . " <br /><br />Error sql: " . $this->sql); } return true; } /** * 获取运行SQL语句后影响的行数 * * @return int * @access public */ function getAffectedRows () { return mysql_affected_rows(); } /** * 获取MySQL错误 * * @return int * @access public */ function getError () { return mysql_error(); } /** * 设置SQL语句前缀 * * @param string $sql * @return int * @access public */ function setSql ($sql) { $this->sql = str_replace("@@__", $this->prefix, $sql); } /** * 取出一条记录中第一列的值 * * @param string $sql * @return string * @access public */ function getOne ($sql) { $this->query($sql, 'one'); $row = mysql_fetch_array($this->result['one'], MYSQL_NUM); return isset($row['0']) ? $row['0'] : FALSE; } /** * 取出一条记录,如果参数$sql为一个数字,读取id等于这个参数值的记录 * * @param string $sql * @param mix $id * @param string $type [array|object] * @return array (返回一维数组) * @access public */ function getRow ($sql, $id = 0, $type = '', $resultType = MYSQL_ASSOC) { if (is_numeric($sql)) { $sql = "SELECT * FROM {$this->table} WHERE {$this->primaryKey} = {$sql} LIMIT 1"; } if (! eregi('limit', $sql)) { $this->setSql(eregi_replace("[,;]$", '', trim($sql)) . " limit 1;"); } else { $this->setSql($sql); } $this->query('', $id); $row = $this->getNextRow($id, $type, $resultType); if (empty($row)) { return array(); } else { mysql_free_result($this->result[$id]); return $row; } } /** * 取出多条记录 * * @param string $sql * @param mix $id * @param string $type (array|object) * @return array (返回二维数组) * @access public */ function getRows ($sql, $id = 0, $type = '', $resultType = MYSQL_ASSOC) { $this->setSql($sql); $this->query('', $id); while ($row = $this->getNextRow($id, $type, $resultType)) { $rows[] = $row; } if (! isset($rows)) { return array(); } mysql_free_result($this->result[$id]); return $rows; } /** * 取出下一条记录 * * @param mix $id * @param string $type (object|array) * @return array (一维数组|对象) * @access public */ function getNextRow ($id = 0, $type = '', $resultType = MYSQL_ASSOC) { if (! isset($this->result[$id])) { return false; } else { if (strtolower($type) == 'array') { $data = mysql_fetch_array($this->result[$id], $resultType); if (! empty($data)) { foreach ($data as $key => $value) { if (strpos($value, '\\') !== FALSE) { $data["{$key}"] = stripslashes($value); } } } return $data; } else { $data = mysql_fetch_object($this->result[$id]); if (! empty($data)) { foreach ($data as $key => $value) { if (strpos($value, '\\') !== FALSE) { $data->{$key} = stripslashes($value); } } } return $data; } } } /** * 插入记录 * * @param array $data * @param string $table * @return Insert id or false * @access public */ function insert ($data, $table = '') { if ($table == '') { $table = $this->table; } $values = ''; $fields = ''; $fieldInsertedCount = 0; foreach ($data as $name => $value) { $fields .= "`" . $name . "`, "; $value = mysql_real_escape_string($value); $values .= "'" . $value . "', "; $fieldInsertedCount ++; } if ($fieldInsertedCount <= 0) { return false; } $fields = substr($fields, 0, - 2); $values = substr($values, 0, - 2); $status = $this->query('insert into ' . $table . ' (' . $fields . ') values (' . ($values) . ')'); if ($status) { return mysql_insert_id(); } return FALSE; } /** * 更新记录 * * @param array $data * @param string $where * @param string $table * @return bool * @access public */ function update ($data, $where, $table = '') { if (is_numeric($where)) { $where = $this->primaryKey . '=' . $where; } if ($table == '') { $table = $this->table; } $str = ''; $count = 0; foreach ($data as $name => $value) { $value = mysql_real_escape_string($value); $str .= "`{$name}` = '{$value}', "; $count ++; } if ($count <= 0) { return false; } $str = substr($str, 0, - 2); return $this->query("update {$table} set {$str} where {$where}"); } function del ($where, $table = '') { return $this->delete($where, $table); } /** * 删除记录 * * @param string $where * @param string $table * @return bool * @access public */ function delete ($where, $table = '') { if (is_numeric($where)) { $where = $this->primaryKey . '=' . $where; } if ($table == '') { $table = $this->table; } return $this->query("DELETE FROM {$table} WHERE {$where}"); } /** * 数据分页列表 * * @return array * @access public */ function lists () { $Base = Base::i(); if (! empty($Base->table)) { $this->table = $Base->table; } if (empty($this->where)) { $this->where = empty($Base->where) ? '' : 'WHERE ' . $Base->where; } else { $this->where = 'WHERE ' . $this->where; } if (empty($this->mainSql)) { $this->mainSql = empty($Base->mainSql) ? "SELECT * FROM `{$this->table}`" : $Base->mainSql; } if (empty($this->countSql)) { $this->countSql = empty($Base->mainSql) ? "SELECT count(*) as num FROM `{$this->table}` {$this->where}" : $Base->mainSql; } if (empty($this->order)) { $this->order = empty($Base->order) ? '' : 'ORDER BY ' . $Base->order; } else { $this->order = 'ORDER BY ' . $this->order; } if (empty($this->pageParam)) { $this->pageParam = empty($Base->pageParam) ? 1 : $Base->pageParam; } if (empty($this->pageSize)) { $this->pageSize = empty($Base->pageSize) ? 20 : $Base->pageSize; } if (empty($this->start)) { if (isset($Base->start)) { $this->start = $Base->start; } else { $this->start = isset($this->p[$this->pageParam]) ? $this->p[$this->pageParam] : 0; } } $this->start = ($this->start > 0) ? intval($this->start) : 0; if (empty($this->baseUrl)) { $this->baseUrl = empty($Base->baseUrl) ? '' : $Base->baseUrl; } $count = $this->getRow($this->countSql); lib('Pagination')->createLinks(array('pageParam'=>$this->pageParam, 'baseUrl'=>$this->baseUrl, 'totalRows'=>$count->num, 'pageSize'=>$this->pageSize)); return $this->getRows("{$this->mainSql} {$this->where} {$this->order} LIMIT {$this->start}, {$this->pageSize}"); } /** * 更新排序 * * @param string $ids 用逗号隔开,如:1,2,3 * @param string $table * @return void * @access public */ function ordering ($ids, $table = '') { if (empty($table)) { $table = $this->table; } $i = 0; $ids = explode(',', $ids); foreach ($ids as $id) { $status = $this->update(array('ordering'=>$i), "id = {$id}", $table); if (! $status) { return FALSE; } $i ++; } return TRUE; } } // END
01cms
01cms/branches/1.0/01mvc/model/DbModel.php
PHP
asf20
13,069
@charset "utf-8"; /* CSS Document */ body{font-size:12px;color:#333;font-family:宋体,Verdana;margin:0;padding:0; background:#666;} a:link,a:visited{text-decoration:underline;color:#000;} a:hover,a:active{text-decoration:underline;color:#000;} .clear{ clear:both; height:auto; padding:0; margin:0;} .blank5{ clear:both; height:5px;} .hidden{ display:none;} img{ border:0;} input{border:1px solid #ccc} textarea{width:100%;border:1px solid #ccc} form{ padding:0; margin:0;} .wrapper{ width:960px; margin:0 auto; background:#fff; } .position{ padding:10px 15px 5px 15px;} /*头部*/ .head{width:960px; height:56px;background:#efefef; } .head .logo{ padding:16px; } .head .info{ float:right; padding:16px; overflow:visible;} .head .info a:link, .head .info a:visited{text-decoration:underline;padding:3px; height:20px;background:none;} .head .info a:hover, .head .info a:active{text-decoration:none; padding:3px; background:#000; color:#fff;overflow:visible;} /*导航*/ .nav{ width:936px; color:#ccc; padding:6px 12px 6px 12px; background:#333; } .nav a:link,.nav a:visited{text-decoration:underline;color:#eee; padding:2px;} .nav a:hover,.nav a:active{text-decoration:none;color:#000; padding:2px; background:#fff;} .nav .menu a{ margin:0 3px;} .nav form{ float:right;} .nav input{ background:#ddd; height:13px;} /*底部*/ .foot { background:#333; width:920px; padding:20px; clear:both; color:#ccc;} .foot a:link,.foot a:visited{ color:#ccc;text-decoration:none;} .foot a:hover,.foot a:active{ color:#fff;text-decoration:underline;} /*首页*/ .index .left{ width:740px; float:left;} .index .left dl{padding:12px 0px 0px 12px; line-height:18px; margin:0; width:352px; float:left; } .index .left dl em { float:right; font-style:normal;} .index .left dl a:link,.index .left dl a:visited{ color:#333; font-weight:normal;text-decoration:none;} .index .left dl a:hover,.index .left dl a:active{ color:#000;font-weight:normal;text-decoration:underline;} .index .left dt{background:#eee url(ui-bg_glass_75_e6e6e6_1x400.png) 50% 50%; font-weight:bold; padding:5px; text-indent:3px;} .index .left dd{ padding:5px; margin:0; border-bottom:1px dotted #ccc; line-height:22px; height:21px; overflow:hidden; text-indent:7px; background:url(ico1.gif) no-repeat 4px 14px;} .index .left .flash{ margin:12px 12px 0px 12px; width:716px;} .index .left .picture{width:716px;} .index .left .picture dd{ padding:8px 0px 0px 5px; margin:0; border-bottom:1px dotted #ccc; background:none;line-height:normal; height:auto;} .index .left .picture dd ul{ padding:0; margin:0; } .index .left .picture dd li{ float:left; text-align:center; list-style:none; width:140px; padding:0; margin:0;} .index .left .picture dd li img{ width:128px; height:96px; padding:1px; border:1px solid #ccc; margin-bottom:5px;} .index .left .picture dd li div{ width:128px; height:18px; line-height:18px; overflow:hidden;} .index .panel{width:220px; float:left;background:#f3f3f3;} .index .panel h3{ margin:0;font-size:12px; padding:10px 10px 0px 25px;background:url(arrow.png) no-repeat 10px 10px;} .index .panel ul{ padding:0; margin:5px;} .index .panel li{line-height:22px; height:22px; overflow:hidden; list-style:none; padding:0px 0px 0px 15px;background:url(ico1.gif) no-repeat 7px 10px; } .index .panel li a:link,.index .panel li a:visited{ color:#000; text-decoration:none;} .index .panel li a:hover,.index .panel li a:active{ color:#000;text-decoration:underline;} /*列表*/ .list .left{ width:740px; float:left;} .list h1{ font-size:18px; padding:15px 15px 0px 15px; margin:0; font-weight:bold;} .list .left dl{padding:15px 15px 0px 15px; line-height:18px; margin:0;} .list .left dt a:link,.list .left dt a:visited{font-size:13px; font-weight:bold;} .list .left dt em { float:right; background:url(comment.gif) no-repeat 0 2px;padding-left:20px; font-style:normal;} .list .left dt em a:link,.list .left dt em a:visited,dt em { color:#666; font-weight:normal;} .list .left dt em a:hover,.list .left dt em a:active{ color:#000;font-weight:normal;} .list .left dd{ padding:5px 0; margin:0; border-bottom:1px dotted #ccc;} .list .right{width:220px; float:left;background:#f3f3f3;} .list .right h1{ margin:0;font-size:12px; padding:10px 10px 0px 25px;background:url(arrow.png) no-repeat 10px 10px;} .list .right ul{ padding:0; margin:5px;} .list .right li{line-height:22px; height:22px; overflow:hidden; list-style:none; padding:0px 0px 0px 15px;background:url(ico1.gif) no-repeat 7px 10px; } .list .right li a:link,.list .right li a:visited{ color:#000; text-decoration:none;} .list .right li a:hover,.list .right li a:active{ color:#000;text-decoration:underline;} /*显示*/ .show .left{ width:630px; float:left; font-size:12px;} .show .left h1{ font-size:16px; font-weight:bold; text-align:center;margin:12px 0;} .show .left .info{ padding:0px 0px 5px 0px; margin:0 10px; border-bottom:1px dashed #ccc; text-align:center;} .show .left .desc{padding:10px; margin:15px; background:#fafafa; border:1px dotted #ccc;line-height:20px;} .show .left .content{ padding:0 15px; line-height:20px; font-size:13px; width:600px; overflow:hidden;} .show .middle{width:158px; float:left;background:#eaeaea;border-left:#ccc solid 1px; border-right:#ccc solid 1px;} .show .middle h1{ margin:0;font-size:13px; padding:10px 10px 0px 6px;} .show .middle ul{ padding:0; margin:5px;} .show .middle li{line-height:18px; border-bottom:1px dotted #ccc; text-indent:8px; list-style:none; padding:6px 3px 3px 3px; background:url(ico3.gif) no-repeat 3px 12px;} .show .middle li a:link,.show .middle li a:visited{ color:#333; text-decoration:none;} .show .middle li a:hover,.show .middle li a:active{ color:#000;text-decoration:underline;} .show .right{width:170px; float:left;background:#f9f9f9;} .show .right h1{ margin:0;font-size:12px; padding:10px 10px 0px 25px;background:url(arrow.png) no-repeat 10px 10px;} .show .right ul{ padding:0; margin:5px;} .show .right li{line-height:22px; list-style:none; padding:0px 0px 0px 15px;background:url(ico1.gif) no-repeat 7px 10px; } .show .right li a:link,.show .right li a:visited{ color:#000; text-decoration:none;} .show .right li a:hover,.show .right li a:active{ color:#000;text-decoration:underline;}
01cms
01cms/branches/1.0/public/default/style.css
CSS
asf20
6,281
/* * jQuery UI 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI */ ;jQuery.ui || (function($) { var _remove = $.fn.remove, isFF2 = $.browser.mozilla && (parseFloat($.browser.version) < 1.9); //Helper functions and ui object $.ui = { version: "1.7.2", // $.ui.plugin is deprecated. Use the proxy pattern instead. plugin: { add: function(module, option, set) { var proto = $.ui[module].prototype; for(var i in set) { proto.plugins[i] = proto.plugins[i] || []; proto.plugins[i].push([option, set[i]]); } }, call: function(instance, name, args) { var set = instance.plugins[name]; if(!set || !instance.element[0].parentNode) { return; } for (var i = 0; i < set.length; i++) { if (instance.options[set[i][0]]) { set[i][1].apply(instance.element, args); } } } }, contains: function(a, b) { return document.compareDocumentPosition ? a.compareDocumentPosition(b) & 16 : a !== b && a.contains(b); }, hasScroll: function(el, a) { //If overflow is hidden, the element might have extra content, but the user wants to hide it if ($(el).css('overflow') == 'hidden') { return false; } var scroll = (a && a == 'left') ? 'scrollLeft' : 'scrollTop', has = false; if (el[scroll] > 0) { return true; } // TODO: determine which cases actually cause this to happen // if the element doesn't have the scroll set, see if it's possible to // set the scroll el[scroll] = 1; has = (el[scroll] > 0); el[scroll] = 0; return has; }, isOverAxis: function(x, reference, size) { //Determines when x coordinate is over "b" element axis return (x > reference) && (x < (reference + size)); }, isOver: function(y, x, top, left, height, width) { //Determines when x, y coordinates is over "b" element return $.ui.isOverAxis(y, top, height) && $.ui.isOverAxis(x, left, width); }, keyCode: { BACKSPACE: 8, CAPS_LOCK: 20, COMMA: 188, CONTROL: 17, DELETE: 46, DOWN: 40, END: 35, ENTER: 13, ESCAPE: 27, HOME: 36, INSERT: 45, LEFT: 37, NUMPAD_ADD: 107, NUMPAD_DECIMAL: 110, NUMPAD_DIVIDE: 111, NUMPAD_ENTER: 108, NUMPAD_MULTIPLY: 106, NUMPAD_SUBTRACT: 109, PAGE_DOWN: 34, PAGE_UP: 33, PERIOD: 190, RIGHT: 39, SHIFT: 16, SPACE: 32, TAB: 9, UP: 38 } }; // WAI-ARIA normalization if (isFF2) { var attr = $.attr, removeAttr = $.fn.removeAttr, ariaNS = "http://www.w3.org/2005/07/aaa", ariaState = /^aria-/, ariaRole = /^wairole:/; $.attr = function(elem, name, value) { var set = value !== undefined; return (name == 'role' ? (set ? attr.call(this, elem, name, "wairole:" + value) : (attr.apply(this, arguments) || "").replace(ariaRole, "")) : (ariaState.test(name) ? (set ? elem.setAttributeNS(ariaNS, name.replace(ariaState, "aaa:"), value) : attr.call(this, elem, name.replace(ariaState, "aaa:"))) : attr.apply(this, arguments))); }; $.fn.removeAttr = function(name) { return (ariaState.test(name) ? this.each(function() { this.removeAttributeNS(ariaNS, name.replace(ariaState, "")); }) : removeAttr.call(this, name)); }; } //jQuery plugins $.fn.extend({ remove: function() { // Safari has a native remove event which actually removes DOM elements, // so we have to use triggerHandler instead of trigger (#3037). $("*", this).add(this).each(function() { $(this).triggerHandler("remove"); }); return _remove.apply(this, arguments ); }, enableSelection: function() { return this .attr('unselectable', 'off') .css('MozUserSelect', '') .unbind('selectstart.ui'); }, disableSelection: function() { return this .attr('unselectable', 'on') .css('MozUserSelect', 'none') .bind('selectstart.ui', function() { return false; }); }, scrollParent: function() { var scrollParent; if(($.browser.msie && (/(static|relative)/).test(this.css('position'))) || (/absolute/).test(this.css('position'))) { scrollParent = this.parents().filter(function() { return (/(relative|absolute|fixed)/).test($.curCSS(this,'position',1)) && (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } else { scrollParent = this.parents().filter(function() { return (/(auto|scroll)/).test($.curCSS(this,'overflow',1)+$.curCSS(this,'overflow-y',1)+$.curCSS(this,'overflow-x',1)); }).eq(0); } return (/fixed/).test(this.css('position')) || !scrollParent.length ? $(document) : scrollParent; } }); //Additional selectors $.extend($.expr[':'], { data: function(elem, i, match) { return !!$.data(elem, match[3]); }, focusable: function(element) { var nodeName = element.nodeName.toLowerCase(), tabIndex = $.attr(element, 'tabindex'); return (/input|select|textarea|button|object/.test(nodeName) ? !element.disabled : 'a' == nodeName || 'area' == nodeName ? element.href || !isNaN(tabIndex) : !isNaN(tabIndex)) // the element and all of its ancestors must be visible // the browser may report that the area is hidden && !$(element)['area' == nodeName ? 'parents' : 'closest'](':hidden').length; }, tabbable: function(element) { var tabIndex = $.attr(element, 'tabindex'); return (isNaN(tabIndex) || tabIndex >= 0) && $(element).is(':focusable'); } }); // $.widget is a factory to create jQuery plugins // taking some boilerplate code out of the plugin code function getter(namespace, plugin, method, args) { function getMethods(type) { var methods = $[namespace][plugin][type] || []; return (typeof methods == 'string' ? methods.split(/,?\s+/) : methods); } var methods = getMethods('getter'); if (args.length == 1 && typeof args[0] == 'string') { methods = methods.concat(getMethods('getterSetter')); } return ($.inArray(method, methods) != -1); } $.widget = function(name, prototype) { var namespace = name.split(".")[0]; name = name.split(".")[1]; // create plugin method $.fn[name] = function(options) { var isMethodCall = (typeof options == 'string'), args = Array.prototype.slice.call(arguments, 1); // prevent calls to internal methods if (isMethodCall && options.substring(0, 1) == '_') { return this; } // handle getter methods if (isMethodCall && getter(namespace, name, options, args)) { var instance = $.data(this[0], name); return (instance ? instance[options].apply(instance, args) : undefined); } // handle initialization and non-getter methods return this.each(function() { var instance = $.data(this, name); // constructor (!instance && !isMethodCall && $.data(this, name, new $[namespace][name](this, options))._init()); // method call (instance && isMethodCall && $.isFunction(instance[options]) && instance[options].apply(instance, args)); }); }; // create widget constructor $[namespace] = $[namespace] || {}; $[namespace][name] = function(element, options) { var self = this; this.namespace = namespace; this.widgetName = name; this.widgetEventPrefix = $[namespace][name].eventPrefix || name; this.widgetBaseClass = namespace + '-' + name; this.options = $.extend({}, $.widget.defaults, $[namespace][name].defaults, $.metadata && $.metadata.get(element)[name], options); this.element = $(element) .bind('setData.' + name, function(event, key, value) { if (event.target == element) { return self._setData(key, value); } }) .bind('getData.' + name, function(event, key) { if (event.target == element) { return self._getData(key); } }) .bind('remove', function() { return self.destroy(); }); }; // add widget prototype $[namespace][name].prototype = $.extend({}, $.widget.prototype, prototype); // TODO: merge getter and getterSetter properties from widget prototype // and plugin prototype $[namespace][name].getterSetter = 'option'; }; $.widget.prototype = { _init: function() {}, destroy: function() { this.element.removeData(this.widgetName) .removeClass(this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .removeAttr('aria-disabled'); }, option: function(key, value) { var options = key, self = this; if (typeof key == "string") { if (value === undefined) { return this._getData(key); } options = {}; options[key] = value; } $.each(options, function(key, value) { self._setData(key, value); }); }, _getData: function(key) { return this.options[key]; }, _setData: function(key, value) { this.options[key] = value; if (key == 'disabled') { this.element [value ? 'addClass' : 'removeClass']( this.widgetBaseClass + '-disabled' + ' ' + this.namespace + '-state-disabled') .attr("aria-disabled", value); } }, enable: function() { this._setData('disabled', false); }, disable: function() { this._setData('disabled', true); }, _trigger: function(type, event, data) { var callback = this.options[type], eventName = (type == this.widgetEventPrefix ? type : this.widgetEventPrefix + type); event = $.Event(event); event.type = eventName; // copy original event properties over to the new event // this would happen if we could call $.event.fix instead of $.Event // but we don't have a way to force an event to be fixed multiple times if (event.originalEvent) { for (var i = $.event.props.length, prop; i;) { prop = $.event.props[--i]; event[prop] = event.originalEvent[prop]; } } this.element.trigger(event, data); return !($.isFunction(callback) && callback.call(this.element[0], event, data) === false || event.isDefaultPrevented()); } }; $.widget.defaults = { disabled: false }; /** Mouse Interaction Plugin **/ $.ui.mouse = { _mouseInit: function() { var self = this; this.element .bind('mousedown.'+this.widgetName, function(event) { return self._mouseDown(event); }) .bind('click.'+this.widgetName, function(event) { if(self._preventClickEvent) { self._preventClickEvent = false; event.stopImmediatePropagation(); return false; } }); // Prevent text selection in IE if ($.browser.msie) { this._mouseUnselectable = this.element.attr('unselectable'); this.element.attr('unselectable', 'on'); } this.started = false; }, // TODO: make sure destroying one instance of mouse doesn't mess with // other instances of mouse _mouseDestroy: function() { this.element.unbind('.'+this.widgetName); // Restore text selection in IE ($.browser.msie && this.element.attr('unselectable', this._mouseUnselectable)); }, _mouseDown: function(event) { // don't let more than one widget handle mouseStart // TODO: figure out why we have to use originalEvent event.originalEvent = event.originalEvent || {}; if (event.originalEvent.mouseHandled) { return; } // we may have missed mouseup (out of window) (this._mouseStarted && this._mouseUp(event)); this._mouseDownEvent = event; var self = this, btnIsLeft = (event.which == 1), elIsCancel = (typeof this.options.cancel == "string" ? $(event.target).parents().add(event.target).filter(this.options.cancel).length : false); if (!btnIsLeft || elIsCancel || !this._mouseCapture(event)) { return true; } this.mouseDelayMet = !this.options.delay; if (!this.mouseDelayMet) { this._mouseDelayTimer = setTimeout(function() { self.mouseDelayMet = true; }, this.options.delay); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(event) !== false); if (!this._mouseStarted) { event.preventDefault(); return true; } } // these delegates are required to keep context this._mouseMoveDelegate = function(event) { return self._mouseMove(event); }; this._mouseUpDelegate = function(event) { return self._mouseUp(event); }; $(document) .bind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .bind('mouseup.'+this.widgetName, this._mouseUpDelegate); // preventDefault() is used to prevent the selection of text here - // however, in Safari, this causes select boxes not to be selectable // anymore, so this fix is needed ($.browser.safari || event.preventDefault()); event.originalEvent.mouseHandled = true; return true; }, _mouseMove: function(event) { // IE mouseup check - mouseup happened when mouse was out of window if ($.browser.msie && !event.button) { return this._mouseUp(event); } if (this._mouseStarted) { this._mouseDrag(event); return event.preventDefault(); } if (this._mouseDistanceMet(event) && this._mouseDelayMet(event)) { this._mouseStarted = (this._mouseStart(this._mouseDownEvent, event) !== false); (this._mouseStarted ? this._mouseDrag(event) : this._mouseUp(event)); } return !this._mouseStarted; }, _mouseUp: function(event) { $(document) .unbind('mousemove.'+this.widgetName, this._mouseMoveDelegate) .unbind('mouseup.'+this.widgetName, this._mouseUpDelegate); if (this._mouseStarted) { this._mouseStarted = false; this._preventClickEvent = (event.target == this._mouseDownEvent.target); this._mouseStop(event); } return false; }, _mouseDistanceMet: function(event) { return (Math.max( Math.abs(this._mouseDownEvent.pageX - event.pageX), Math.abs(this._mouseDownEvent.pageY - event.pageY) ) >= this.options.distance ); }, _mouseDelayMet: function(event) { return this.mouseDelayMet; }, // These are placeholder methods, to be overriden by extending plugin _mouseStart: function(event) {}, _mouseDrag: function(event) {}, _mouseStop: function(event) {}, _mouseCapture: function(event) { return true; } }; $.ui.mouse.defaults = { cancel: null, distance: 1, delay: 0 }; })(jQuery);
01cms
01cms/branches/1.0/public/common/js/ui.core.js
JavaScript
asf20
13,932
/* * jQuery UI Effects Scale 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Effects/Scale * * Depends: * effects.core.js */ (function($) { $.effects.puff = function(o) { return this.queue(function() { // Create element var el = $(this); // Set options var options = $.extend(true, {}, o.options); var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode var percent = parseInt(o.options.percent,10) || 150; // Set default puff percent options.fade = true; // It's not a puff if it doesn't fade! :) var original = {height: el.height(), width: el.width()}; // Save original // Adjust var factor = percent / 100; el.from = (mode == 'hide') ? original : {height: original.height * factor, width: original.width * factor}; // Animation options.from = el.from; options.percent = (mode == 'hide') ? percent : 100; options.mode = mode; // Animate el.effect('scale', options, o.duration, o.callback); el.dequeue(); }); }; $.effects.scale = function(o) { return this.queue(function() { // Create element var el = $(this); // Set options var options = $.extend(true, {}, o.options); var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode var percent = parseInt(o.options.percent,10) || (parseInt(o.options.percent,10) == 0 ? 0 : (mode == 'hide' ? 0 : 100)); // Set default scaling percent var direction = o.options.direction || 'both'; // Set default axis var origin = o.options.origin; // The origin of the scaling if (mode != 'effect') { // Set default origin and restore for show/hide options.origin = origin || ['middle','center']; options.restore = true; } var original = {height: el.height(), width: el.width()}; // Save original el.from = o.options.from || (mode == 'show' ? {height: 0, width: 0} : original); // Default from state // Adjust var factor = { // Set scaling factor y: direction != 'horizontal' ? (percent / 100) : 1, x: direction != 'vertical' ? (percent / 100) : 1 }; el.to = {height: original.height * factor.y, width: original.width * factor.x}; // Set to state if (o.options.fade) { // Fade option to support puff if (mode == 'show') {el.from.opacity = 0; el.to.opacity = 1;}; if (mode == 'hide') {el.from.opacity = 1; el.to.opacity = 0;}; }; // Animation options.from = el.from; options.to = el.to; options.mode = mode; // Animate el.effect('size', options, o.duration, o.callback); el.dequeue(); }); }; $.effects.size = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left','width','height','overflow','opacity']; var props1 = ['position','top','left','overflow','opacity']; // Always restore var props2 = ['width','height','overflow']; // Copy for children var cProps = ['fontSize']; var vProps = ['borderTopWidth', 'borderBottomWidth', 'paddingTop', 'paddingBottom']; var hProps = ['borderLeftWidth', 'borderRightWidth', 'paddingLeft', 'paddingRight']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'effect'); // Set Mode var restore = o.options.restore || false; // Default restore var scale = o.options.scale || 'both'; // Default scale mode var origin = o.options.origin; // The origin of the sizing var original = {height: el.height(), width: el.width()}; // Save original el.from = o.options.from || original; // Default from state el.to = o.options.to || original; // Default to state // Adjust if (origin) { // Calculate baseline shifts var baseline = $.effects.getBaseline(origin, original); el.from.top = (original.height - el.from.height) * baseline.y; el.from.left = (original.width - el.from.width) * baseline.x; el.to.top = (original.height - el.to.height) * baseline.y; el.to.left = (original.width - el.to.width) * baseline.x; }; var factor = { // Set scaling factor from: {y: el.from.height / original.height, x: el.from.width / original.width}, to: {y: el.to.height / original.height, x: el.to.width / original.width} }; if (scale == 'box' || scale == 'both') { // Scale the css box if (factor.from.y != factor.to.y) { // Vertical props scaling props = props.concat(vProps); el.from = $.effects.setTransition(el, vProps, factor.from.y, el.from); el.to = $.effects.setTransition(el, vProps, factor.to.y, el.to); }; if (factor.from.x != factor.to.x) { // Horizontal props scaling props = props.concat(hProps); el.from = $.effects.setTransition(el, hProps, factor.from.x, el.from); el.to = $.effects.setTransition(el, hProps, factor.to.x, el.to); }; }; if (scale == 'content' || scale == 'both') { // Scale the content if (factor.from.y != factor.to.y) { // Vertical props scaling props = props.concat(cProps); el.from = $.effects.setTransition(el, cProps, factor.from.y, el.from); el.to = $.effects.setTransition(el, cProps, factor.to.y, el.to); }; }; $.effects.save(el, restore ? props : props1); el.show(); // Save & Show $.effects.createWrapper(el); // Create Wrapper el.css('overflow','hidden').css(el.from); // Shift // Animate if (scale == 'content' || scale == 'both') { // Scale the children vProps = vProps.concat(['marginTop','marginBottom']).concat(cProps); // Add margins/font-size hProps = hProps.concat(['marginLeft','marginRight']); // Add margins props2 = props.concat(vProps).concat(hProps); // Concat el.find("*[width]").each(function(){ child = $(this); if (restore) $.effects.save(child, props2); var c_original = {height: child.height(), width: child.width()}; // Save original child.from = {height: c_original.height * factor.from.y, width: c_original.width * factor.from.x}; child.to = {height: c_original.height * factor.to.y, width: c_original.width * factor.to.x}; if (factor.from.y != factor.to.y) { // Vertical props scaling child.from = $.effects.setTransition(child, vProps, factor.from.y, child.from); child.to = $.effects.setTransition(child, vProps, factor.to.y, child.to); }; if (factor.from.x != factor.to.x) { // Horizontal props scaling child.from = $.effects.setTransition(child, hProps, factor.from.x, child.from); child.to = $.effects.setTransition(child, hProps, factor.to.x, child.to); }; child.css(child.from); // Shift children child.animate(child.to, o.duration, o.options.easing, function(){ if (restore) $.effects.restore(child, props2); // Restore children }); // Animate children }); }; // Animate el.animate(el.to, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { if(mode == 'hide') el.hide(); // Hide $.effects.restore(el, restore ? props : props1); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(this, arguments); // Callback el.dequeue(); }}); }); }; })(jQuery);
01cms
01cms/branches/1.0/public/common/js/effects.scale.js
JavaScript
asf20
7,228
/* Chinese initialisation for the jQuery UI date picker plugin. */ /* Written by Cloudream (cloudream@gmail.com). */ jQuery(function($){ $.datepicker.regional['zh-CN'] = { closeText: '关闭', prevText: '&#x3c;上月', nextText: '下月&#x3e;', currentText: '今天', monthNames: ['一月','二月','三月','四月','五月','六月', '七月','八月','九月','十月','十一月','十二月'], monthNamesShort: ['一','二','三','四','五','六', '七','八','九','十','十一','十二'], dayNames: ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'], dayNamesShort: ['周日','周一','周二','周三','周四','周五','周六'], dayNamesMin: ['日','一','二','三','四','五','六'], dateFormat: 'yy-mm-dd', firstDay: 1, isRTL: false}; $.datepicker.setDefaults($.datepicker.regional['zh-CN']); });
01cms
01cms/branches/1.0/public/common/js/ui.datepicker-zh-CN.js
JavaScript
asf20
875
function postDialog() { $(':submit').attr('disabled',true); if($('#autoFrame').length == 0) { $('body').append('<iframe class="hidden" id="autoFrame" name="autoFrame" ></iframe>'); } if($('.ui-dialog').length > 0) { $('.ui-dialog').remove(); } $('<div class="ui-dialog-message"><span class="ui-dialog-loading">&nbsp;</span>正在处理,请稍候...</div>').dialog({ close: function(){$(".ui-dialog").remove();$(".ui-dialog-message").remove();$(':submit').attr('disabled',false);}, title: '提示信息', resizable : false }); } function postResponse(response) { $(".ui-dialog-message").html(response.message); if (response.javascript) { eval(response.javascript); } if (response.goUrl) { redirect(response.goUrl, response.stayTime) } else if (response.stayTime > 0) { window.setTimeout(function(){$(':submit').attr('disabled',false);$(".ui-dialog").hide('slow',function(){$(".ui-dialog").remove();$(".ui-dialog-message").remove();});},response.stayTime * 1000); } } function getDialog(url, goUrl, stayTime) { if(stayTime == undefined) { stayTime = 3; } if($('.ui-dialog').length > 0) { $('.ui-dialog').remove(); } $('<div class="ui-dialog-message"><span class="ui-dialog-loading">&nbsp;</span>正在处理,请稍候...</div>').dialog({ title:'提示信息', resizable : false }); $.ajax({ type : 'get', dataType : 'json', url : url, success : function(response) { $(".ui-dialog-message").html(response.message); if (response.javascript) { eval(response.javascript); } if (response.success && goUrl) { redirect(goUrl, stayTime); } else if (stayTime > 0) { window.setTimeout(function(){$(".ui-dialog").hide('slow');},stayTime*1000); } } }); } function selAll(name) { $("input[name='"+name+"']").attr("checked", true); return false; } function selNone(name) { $("input[name='"+name+"']").attr("checked", false); return false; } function selAnti(name) { $("input[name='"+name+"']").each(function(i){ this.checked=!this.checked; }); return false; } function getSel(name) { var ids = ''; $("input:checked[name='"+name+"']").each(function(i){ ids+=this.value+','; }); return ids.substr(0, ids.length - 1); } function redirect(goUrl, time) { if(time == undefined) { time = 2; } window.setTimeout(function(){window.location.href=goUrl;},time*1000); } $(document).ready(function(){ $(".content table tr,.rowLine") .mouseover(function(){ if($(this).find("input[name='sel[]']").length > 0 && $(this).parents().find("input[name='sel[]']").length > 2) { $(this).removeClass("selected"); $(this).addClass("titleBg"); } }) .mouseout(function(){ if($(this).find("input[name='sel[]']").length > 0 && $(this).parents().find("input[name='sel[]']").length > 2) { if($(this).find("input[name='sel[]']").get(0).checked) { $(this).addClass("selected"); } else { $(this).removeClass("selected"); } $(this).removeClass("titleBg"); } }) });
01cms
01cms/branches/1.0/public/common/js/common.js
JavaScript
asf20
3,168
/* * jQuery UI Progressbar 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Progressbar * * Depends: * ui.core.js */ (function($) { $.widget("ui.progressbar", { _init: function() { this.element .addClass("ui-progressbar" + " ui-widget" + " ui-widget-content" + " ui-corner-all") .attr({ role: "progressbar", "aria-valuemin": this._valueMin(), "aria-valuemax": this._valueMax(), "aria-valuenow": this._value() }); this.valueDiv = $('<div class="ui-progressbar-value ui-widget-header ui-corner-left"></div>').appendTo(this.element); this._refreshValue(); }, destroy: function() { this.element .removeClass("ui-progressbar" + " ui-widget" + " ui-widget-content" + " ui-corner-all") .removeAttr("role") .removeAttr("aria-valuemin") .removeAttr("aria-valuemax") .removeAttr("aria-valuenow") .removeData("progressbar") .unbind(".progressbar"); this.valueDiv.remove(); $.widget.prototype.destroy.apply(this, arguments); }, value: function(newValue) { if (newValue === undefined) { return this._value(); } this._setData('value', newValue); return this; }, _setData: function(key, value) { switch (key) { case 'value': this.options.value = value; this._refreshValue(); this._trigger('change', null, {}); break; } $.widget.prototype._setData.apply(this, arguments); }, _value: function() { var val = this.options.value; if (val < this._valueMin()) val = this._valueMin(); if (val > this._valueMax()) val = this._valueMax(); return val; }, _valueMin: function() { var valueMin = 0; return valueMin; }, _valueMax: function() { var valueMax = 100; return valueMax; }, _refreshValue: function() { var value = this.value(); this.valueDiv[value == this._valueMax() ? 'addClass' : 'removeClass']("ui-corner-right"); this.valueDiv.width(value + '%'); this.element.attr("aria-valuenow", value); } }); $.extend($.ui.progressbar, { version: "1.7.2", defaults: { value: 0 } }); })(jQuery);
01cms
01cms/branches/1.0/public/common/js/ui.progressbar.js
JavaScript
asf20
2,209
/* * jQuery UI Slider 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Slider * * Depends: * ui.core.js */ (function($) { $.widget("ui.slider", $.extend({}, $.ui.mouse, { _init: function() { var self = this, o = this.options; this._keySliding = false; this._handleIndex = null; this._detectOrientation(); this._mouseInit(); this.element .addClass("ui-slider" + " ui-slider-" + this.orientation + " ui-widget" + " ui-widget-content" + " ui-corner-all"); this.range = $([]); if (o.range) { if (o.range === true) { this.range = $('<div></div>'); if (!o.values) o.values = [this._valueMin(), this._valueMin()]; if (o.values.length && o.values.length != 2) { o.values = [o.values[0], o.values[0]]; } } else { this.range = $('<div></div>'); } this.range .appendTo(this.element) .addClass("ui-slider-range"); if (o.range == "min" || o.range == "max") { this.range.addClass("ui-slider-range-" + o.range); } // note: this isn't the most fittingly semantic framework class for this element, // but worked best visually with a variety of themes this.range.addClass("ui-widget-header"); } if ($(".ui-slider-handle", this.element).length == 0) $('<a href="#"></a>') .appendTo(this.element) .addClass("ui-slider-handle"); if (o.values && o.values.length) { while ($(".ui-slider-handle", this.element).length < o.values.length) $('<a href="#"></a>') .appendTo(this.element) .addClass("ui-slider-handle"); } this.handles = $(".ui-slider-handle", this.element) .addClass("ui-state-default" + " ui-corner-all"); this.handle = this.handles.eq(0); this.handles.add(this.range).filter("a") .click(function(event) { event.preventDefault(); }) .hover(function() { if (!o.disabled) { $(this).addClass('ui-state-hover'); } }, function() { $(this).removeClass('ui-state-hover'); }) .focus(function() { if (!o.disabled) { $(".ui-slider .ui-state-focus").removeClass('ui-state-focus'); $(this).addClass('ui-state-focus'); } else { $(this).blur(); } }) .blur(function() { $(this).removeClass('ui-state-focus'); }); this.handles.each(function(i) { $(this).data("index.ui-slider-handle", i); }); this.handles.keydown(function(event) { var ret = true; var index = $(this).data("index.ui-slider-handle"); if (self.options.disabled) return; switch (event.keyCode) { case $.ui.keyCode.HOME: case $.ui.keyCode.END: case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: ret = false; if (!self._keySliding) { self._keySliding = true; $(this).addClass("ui-state-active"); self._start(event, index); } break; } var curVal, newVal, step = self._step(); if (self.options.values && self.options.values.length) { curVal = newVal = self.values(index); } else { curVal = newVal = self.value(); } switch (event.keyCode) { case $.ui.keyCode.HOME: newVal = self._valueMin(); break; case $.ui.keyCode.END: newVal = self._valueMax(); break; case $.ui.keyCode.UP: case $.ui.keyCode.RIGHT: if(curVal == self._valueMax()) return; newVal = curVal + step; break; case $.ui.keyCode.DOWN: case $.ui.keyCode.LEFT: if(curVal == self._valueMin()) return; newVal = curVal - step; break; } self._slide(event, index, newVal); return ret; }).keyup(function(event) { var index = $(this).data("index.ui-slider-handle"); if (self._keySliding) { self._stop(event, index); self._change(event, index); self._keySliding = false; $(this).removeClass("ui-state-active"); } }); this._refreshValue(); }, destroy: function() { this.handles.remove(); this.range.remove(); this.element .removeClass("ui-slider" + " ui-slider-horizontal" + " ui-slider-vertical" + " ui-slider-disabled" + " ui-widget" + " ui-widget-content" + " ui-corner-all") .removeData("slider") .unbind(".slider"); this._mouseDestroy(); }, _mouseCapture: function(event) { var o = this.options; if (o.disabled) return false; this.elementSize = { width: this.element.outerWidth(), height: this.element.outerHeight() }; this.elementOffset = this.element.offset(); var position = { x: event.pageX, y: event.pageY }; var normValue = this._normValueFromMouse(position); var distance = this._valueMax() - this._valueMin() + 1, closestHandle; var self = this, index; this.handles.each(function(i) { var thisDistance = Math.abs(normValue - self.values(i)); if (distance > thisDistance) { distance = thisDistance; closestHandle = $(this); index = i; } }); // workaround for bug #3736 (if both handles of a range are at 0, // the first is always used as the one with least distance, // and moving it is obviously prevented by preventing negative ranges) if(o.range == true && this.values(1) == o.min) { closestHandle = $(this.handles[++index]); } this._start(event, index); self._handleIndex = index; closestHandle .addClass("ui-state-active") .focus(); var offset = closestHandle.offset(); var mouseOverHandle = !$(event.target).parents().andSelf().is('.ui-slider-handle'); this._clickOffset = mouseOverHandle ? { left: 0, top: 0 } : { left: event.pageX - offset.left - (closestHandle.width() / 2), top: event.pageY - offset.top - (closestHandle.height() / 2) - (parseInt(closestHandle.css('borderTopWidth'),10) || 0) - (parseInt(closestHandle.css('borderBottomWidth'),10) || 0) + (parseInt(closestHandle.css('marginTop'),10) || 0) }; normValue = this._normValueFromMouse(position); this._slide(event, index, normValue); return true; }, _mouseStart: function(event) { return true; }, _mouseDrag: function(event) { var position = { x: event.pageX, y: event.pageY }; var normValue = this._normValueFromMouse(position); this._slide(event, this._handleIndex, normValue); return false; }, _mouseStop: function(event) { this.handles.removeClass("ui-state-active"); this._stop(event, this._handleIndex); this._change(event, this._handleIndex); this._handleIndex = null; this._clickOffset = null; return false; }, _detectOrientation: function() { this.orientation = this.options.orientation == 'vertical' ? 'vertical' : 'horizontal'; }, _normValueFromMouse: function(position) { var pixelTotal, pixelMouse; if ('horizontal' == this.orientation) { pixelTotal = this.elementSize.width; pixelMouse = position.x - this.elementOffset.left - (this._clickOffset ? this._clickOffset.left : 0); } else { pixelTotal = this.elementSize.height; pixelMouse = position.y - this.elementOffset.top - (this._clickOffset ? this._clickOffset.top : 0); } var percentMouse = (pixelMouse / pixelTotal); if (percentMouse > 1) percentMouse = 1; if (percentMouse < 0) percentMouse = 0; if ('vertical' == this.orientation) percentMouse = 1 - percentMouse; var valueTotal = this._valueMax() - this._valueMin(), valueMouse = percentMouse * valueTotal, valueMouseModStep = valueMouse % this.options.step, normValue = this._valueMin() + valueMouse - valueMouseModStep; if (valueMouseModStep > (this.options.step / 2)) normValue += this.options.step; // Since JavaScript has problems with large floats, round // the final value to 5 digits after the decimal point (see #4124) return parseFloat(normValue.toFixed(5)); }, _start: function(event, index) { var uiHash = { handle: this.handles[index], value: this.value() }; if (this.options.values && this.options.values.length) { uiHash.value = this.values(index); uiHash.values = this.values(); } this._trigger("start", event, uiHash); }, _slide: function(event, index, newVal) { var handle = this.handles[index]; if (this.options.values && this.options.values.length) { var otherVal = this.values(index ? 0 : 1); if ((this.options.values.length == 2 && this.options.range === true) && ((index == 0 && newVal > otherVal) || (index == 1 && newVal < otherVal))){ newVal = otherVal; } if (newVal != this.values(index)) { var newValues = this.values(); newValues[index] = newVal; // A slide can be canceled by returning false from the slide callback var allowed = this._trigger("slide", event, { handle: this.handles[index], value: newVal, values: newValues }); var otherVal = this.values(index ? 0 : 1); if (allowed !== false) { this.values(index, newVal, ( event.type == 'mousedown' && this.options.animate ), true); } } } else { if (newVal != this.value()) { // A slide can be canceled by returning false from the slide callback var allowed = this._trigger("slide", event, { handle: this.handles[index], value: newVal }); if (allowed !== false) { this._setData('value', newVal, ( event.type == 'mousedown' && this.options.animate )); } } } }, _stop: function(event, index) { var uiHash = { handle: this.handles[index], value: this.value() }; if (this.options.values && this.options.values.length) { uiHash.value = this.values(index); uiHash.values = this.values(); } this._trigger("stop", event, uiHash); }, _change: function(event, index) { var uiHash = { handle: this.handles[index], value: this.value() }; if (this.options.values && this.options.values.length) { uiHash.value = this.values(index); uiHash.values = this.values(); } this._trigger("change", event, uiHash); }, value: function(newValue) { if (arguments.length) { this._setData("value", newValue); this._change(null, 0); } return this._value(); }, values: function(index, newValue, animated, noPropagation) { if (arguments.length > 1) { this.options.values[index] = newValue; this._refreshValue(animated); if(!noPropagation) this._change(null, index); } if (arguments.length) { if (this.options.values && this.options.values.length) { return this._values(index); } else { return this.value(); } } else { return this._values(); } }, _setData: function(key, value, animated) { $.widget.prototype._setData.apply(this, arguments); switch (key) { case 'disabled': if (value) { this.handles.filter(".ui-state-focus").blur(); this.handles.removeClass("ui-state-hover"); this.handles.attr("disabled", "disabled"); } else { this.handles.removeAttr("disabled"); } case 'orientation': this._detectOrientation(); this.element .removeClass("ui-slider-horizontal ui-slider-vertical") .addClass("ui-slider-" + this.orientation); this._refreshValue(animated); break; case 'value': this._refreshValue(animated); break; } }, _step: function() { var step = this.options.step; return step; }, _value: function() { var val = this.options.value; if (val < this._valueMin()) val = this._valueMin(); if (val > this._valueMax()) val = this._valueMax(); return val; }, _values: function(index) { if (arguments.length) { var val = this.options.values[index]; if (val < this._valueMin()) val = this._valueMin(); if (val > this._valueMax()) val = this._valueMax(); return val; } else { return this.options.values; } }, _valueMin: function() { var valueMin = this.options.min; return valueMin; }, _valueMax: function() { var valueMax = this.options.max; return valueMax; }, _refreshValue: function(animate) { var oRange = this.options.range, o = this.options, self = this; if (this.options.values && this.options.values.length) { var vp0, vp1; this.handles.each(function(i, j) { var valPercent = (self.values(i) - self._valueMin()) / (self._valueMax() - self._valueMin()) * 100; var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; $(this).stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); if (self.options.range === true) { if (self.orientation == 'horizontal') { (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ left: valPercent + '%' }, o.animate); (i == 1) && self.range[animate ? 'animate' : 'css']({ width: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); } else { (i == 0) && self.range.stop(1,1)[animate ? 'animate' : 'css']({ bottom: (valPercent) + '%' }, o.animate); (i == 1) && self.range[animate ? 'animate' : 'css']({ height: (valPercent - lastValPercent) + '%' }, { queue: false, duration: o.animate }); } } lastValPercent = valPercent; }); } else { var value = this.value(), valueMin = this._valueMin(), valueMax = this._valueMax(), valPercent = valueMax != valueMin ? (value - valueMin) / (valueMax - valueMin) * 100 : 0; var _set = {}; _set[self.orientation == 'horizontal' ? 'left' : 'bottom'] = valPercent + '%'; this.handle.stop(1,1)[animate ? 'animate' : 'css'](_set, o.animate); (oRange == "min") && (this.orientation == "horizontal") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ width: valPercent + '%' }, o.animate); (oRange == "max") && (this.orientation == "horizontal") && this.range[animate ? 'animate' : 'css']({ width: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); (oRange == "min") && (this.orientation == "vertical") && this.range.stop(1,1)[animate ? 'animate' : 'css']({ height: valPercent + '%' }, o.animate); (oRange == "max") && (this.orientation == "vertical") && this.range[animate ? 'animate' : 'css']({ height: (100 - valPercent) + '%' }, { queue: false, duration: o.animate }); } } })); $.extend($.ui.slider, { getter: "value values", version: "1.7.2", eventPrefix: "slide", defaults: { animate: false, delay: 0, distance: 0, max: 100, min: 0, orientation: 'horizontal', range: false, step: 1, value: 0, values: null } }); })(jQuery);
01cms
01cms/branches/1.0/public/common/js/ui.slider.js
JavaScript
asf20
14,938
/* * jQuery UI Effects Fold 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Effects/Fold * * Depends: * effects.core.js */ (function($) { $.effects.fold = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode var size = o.options.size || 15; // Default fold size var horizFirst = !(!o.options.horizFirst); // Ensure a boolean value var duration = o.duration ? o.duration / 2 : $.fx.speeds._default / 2; // Adjust $.effects.save(el, props); el.show(); // Save & Show var wrapper = $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper var widthFirst = ((mode == 'show') != horizFirst); var ref = widthFirst ? ['width', 'height'] : ['height', 'width']; var distance = widthFirst ? [wrapper.width(), wrapper.height()] : [wrapper.height(), wrapper.width()]; var percent = /([0-9]+)%/.exec(size); if(percent) size = parseInt(percent[1],10) / 100 * distance[mode == 'hide' ? 0 : 1]; if(mode == 'show') wrapper.css(horizFirst ? {height: 0, width: size} : {height: size, width: 0}); // Shift // Animation var animation1 = {}, animation2 = {}; animation1[ref[0]] = mode == 'show' ? distance[0] : size; animation2[ref[1]] = mode == 'show' ? distance[1] : 0; // Animate wrapper.animate(animation1, duration, o.options.easing) .animate(animation2, duration, o.options.easing, function() { if(mode == 'hide') el.hide(); // Hide $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(el[0], arguments); // Callback el.dequeue(); }); }); }; })(jQuery);
01cms
01cms/branches/1.0/public/common/js/effects.fold.js
JavaScript
asf20
1,872
/* * jQuery UI Selectable 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Selectables * * Depends: * ui.core.js */ (function($) { $.widget("ui.selectable", $.extend({}, $.ui.mouse, { _init: function() { var self = this; this.element.addClass("ui-selectable"); this.dragged = false; // cache selectee children based on filter var selectees; this.refresh = function() { selectees = $(self.options.filter, self.element[0]); selectees.each(function() { var $this = $(this); var pos = $this.offset(); $.data(this, "selectable-item", { element: this, $element: $this, left: pos.left, top: pos.top, right: pos.left + $this.outerWidth(), bottom: pos.top + $this.outerHeight(), startselected: false, selected: $this.hasClass('ui-selected'), selecting: $this.hasClass('ui-selecting'), unselecting: $this.hasClass('ui-unselecting') }); }); }; this.refresh(); this.selectees = selectees.addClass("ui-selectee"); this._mouseInit(); this.helper = $(document.createElement('div')) .css({border:'1px dotted black'}) .addClass("ui-selectable-helper"); }, destroy: function() { this.element .removeClass("ui-selectable ui-selectable-disabled") .removeData("selectable") .unbind(".selectable"); this._mouseDestroy(); }, _mouseStart: function(event) { var self = this; this.opos = [event.pageX, event.pageY]; if (this.options.disabled) return; var options = this.options; this.selectees = $(options.filter, this.element[0]); this._trigger("start", event); $(options.appendTo).append(this.helper); // position helper (lasso) this.helper.css({ "z-index": 100, "position": "absolute", "left": event.clientX, "top": event.clientY, "width": 0, "height": 0 }); if (options.autoRefresh) { this.refresh(); } this.selectees.filter('.ui-selected').each(function() { var selectee = $.data(this, "selectable-item"); selectee.startselected = true; if (!event.metaKey) { selectee.$element.removeClass('ui-selected'); selectee.selected = false; selectee.$element.addClass('ui-unselecting'); selectee.unselecting = true; // selectable UNSELECTING callback self._trigger("unselecting", event, { unselecting: selectee.element }); } }); $(event.target).parents().andSelf().each(function() { var selectee = $.data(this, "selectable-item"); if (selectee) { selectee.$element.removeClass("ui-unselecting").addClass('ui-selecting'); selectee.unselecting = false; selectee.selecting = true; selectee.selected = true; // selectable SELECTING callback self._trigger("selecting", event, { selecting: selectee.element }); return false; } }); }, _mouseDrag: function(event) { var self = this; this.dragged = true; if (this.options.disabled) return; var options = this.options; var x1 = this.opos[0], y1 = this.opos[1], x2 = event.pageX, y2 = event.pageY; if (x1 > x2) { var tmp = x2; x2 = x1; x1 = tmp; } if (y1 > y2) { var tmp = y2; y2 = y1; y1 = tmp; } this.helper.css({left: x1, top: y1, width: x2-x1, height: y2-y1}); this.selectees.each(function() { var selectee = $.data(this, "selectable-item"); //prevent helper from being selected if appendTo: selectable if (!selectee || selectee.element == self.element[0]) return; var hit = false; if (options.tolerance == 'touch') { hit = ( !(selectee.left > x2 || selectee.right < x1 || selectee.top > y2 || selectee.bottom < y1) ); } else if (options.tolerance == 'fit') { hit = (selectee.left > x1 && selectee.right < x2 && selectee.top > y1 && selectee.bottom < y2); } if (hit) { // SELECT if (selectee.selected) { selectee.$element.removeClass('ui-selected'); selectee.selected = false; } if (selectee.unselecting) { selectee.$element.removeClass('ui-unselecting'); selectee.unselecting = false; } if (!selectee.selecting) { selectee.$element.addClass('ui-selecting'); selectee.selecting = true; // selectable SELECTING callback self._trigger("selecting", event, { selecting: selectee.element }); } } else { // UNSELECT if (selectee.selecting) { if (event.metaKey && selectee.startselected) { selectee.$element.removeClass('ui-selecting'); selectee.selecting = false; selectee.$element.addClass('ui-selected'); selectee.selected = true; } else { selectee.$element.removeClass('ui-selecting'); selectee.selecting = false; if (selectee.startselected) { selectee.$element.addClass('ui-unselecting'); selectee.unselecting = true; } // selectable UNSELECTING callback self._trigger("unselecting", event, { unselecting: selectee.element }); } } if (selectee.selected) { if (!event.metaKey && !selectee.startselected) { selectee.$element.removeClass('ui-selected'); selectee.selected = false; selectee.$element.addClass('ui-unselecting'); selectee.unselecting = true; // selectable UNSELECTING callback self._trigger("unselecting", event, { unselecting: selectee.element }); } } } }); return false; }, _mouseStop: function(event) { var self = this; this.dragged = false; var options = this.options; $('.ui-unselecting', this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass('ui-unselecting'); selectee.unselecting = false; selectee.startselected = false; self._trigger("unselected", event, { unselected: selectee.element }); }); $('.ui-selecting', this.element[0]).each(function() { var selectee = $.data(this, "selectable-item"); selectee.$element.removeClass('ui-selecting').addClass('ui-selected'); selectee.selecting = false; selectee.selected = true; selectee.startselected = true; self._trigger("selected", event, { selected: selectee.element }); }); this._trigger("stop", event); this.helper.remove(); return false; } })); $.extend($.ui.selectable, { version: "1.7.2", defaults: { appendTo: 'body', autoRefresh: true, cancel: ":input,option", delay: 0, distance: 0, filter: '*', tolerance: 'touch' } }); })(jQuery);
01cms
01cms/branches/1.0/public/common/js/ui.selectable.js
JavaScript
asf20
6,803
/* * jQuery UI Effects Slide 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Effects/Slide * * Depends: * effects.core.js */ (function($) { $.effects.slide = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode var direction = o.options.direction || 'left'; // Default Direction // Adjust $.effects.save(el, props); el.show(); // Save & Show $.effects.createWrapper(el).css({overflow:'hidden'}); // Create Wrapper var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left'; var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg'; var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) : el.outerWidth({margin:true})); if (mode == 'show') el.css(ref, motion == 'pos' ? -distance : distance); // Shift // Animation var animation = {}; animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance; // Animate el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { if(mode == 'hide') el.hide(); // Hide $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(this, arguments); // Callback el.dequeue(); }}); }); }; })(jQuery);
01cms
01cms/branches/1.0/public/common/js/effects.slide.js
JavaScript
asf20
1,589
/* * jQuery UI Accordion 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Accordion * * Depends: * ui.core.js */ (function($) { $.widget("ui.accordion", { _init: function() { var o = this.options, self = this; this.running = 0; // if the user set the alwaysOpen option on init // then we need to set the collapsible option // if they set both on init, collapsible will take priority if (o.collapsible == $.ui.accordion.defaults.collapsible && o.alwaysOpen != $.ui.accordion.defaults.alwaysOpen) { o.collapsible = !o.alwaysOpen; } if ( o.navigation ) { var current = this.element.find("a").filter(o.navigationFilter); if ( current.length ) { if ( current.filter(o.header).length ) { this.active = current; } else { this.active = current.parent().parent().prev(); current.addClass("ui-accordion-content-active"); } } } this.element.addClass("ui-accordion ui-widget ui-helper-reset"); // in lack of child-selectors in CSS we need to mark top-LIs in a UL-accordion for some IE-fix if (this.element[0].nodeName == "UL") { this.element.children("li").addClass("ui-accordion-li-fix"); } this.headers = this.element.find(o.header).addClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all") .bind("mouseenter.accordion", function(){ $(this).addClass('ui-state-hover'); }) .bind("mouseleave.accordion", function(){ $(this).removeClass('ui-state-hover'); }) .bind("focus.accordion", function(){ $(this).addClass('ui-state-focus'); }) .bind("blur.accordion", function(){ $(this).removeClass('ui-state-focus'); }); this.headers .next() .addClass("ui-accordion-content ui-helper-reset ui-widget-content ui-corner-bottom"); this.active = this._findActive(this.active || o.active).toggleClass("ui-state-default").toggleClass("ui-state-active").toggleClass("ui-corner-all").toggleClass("ui-corner-top"); this.active.next().addClass('ui-accordion-content-active'); //Append icon elements $("<span/>").addClass("ui-icon " + o.icons.header).prependTo(this.headers); this.active.find(".ui-icon").toggleClass(o.icons.header).toggleClass(o.icons.headerSelected); // IE7-/Win - Extra vertical space in lists fixed if ($.browser.msie) { this.element.find('a').css('zoom', '1'); } this.resize(); //ARIA this.element.attr('role','tablist'); this.headers .attr('role','tab') .bind('keydown', function(event) { return self._keydown(event); }) .next() .attr('role','tabpanel'); this.headers .not(this.active || "") .attr('aria-expanded','false') .attr("tabIndex", "-1") .next() .hide(); // make sure at least one header is in the tab order if (!this.active.length) { this.headers.eq(0).attr('tabIndex','0'); } else { this.active .attr('aria-expanded','true') .attr('tabIndex', '0'); } // only need links in taborder for Safari if (!$.browser.safari) this.headers.find('a').attr('tabIndex','-1'); if (o.event) { this.headers.bind((o.event) + ".accordion", function(event) { return self._clickHandler.call(self, event, this); }); } }, destroy: function() { var o = this.options; this.element .removeClass("ui-accordion ui-widget ui-helper-reset") .removeAttr("role") .unbind('.accordion') .removeData('accordion'); this.headers .unbind(".accordion") .removeClass("ui-accordion-header ui-helper-reset ui-state-default ui-corner-all ui-state-active ui-corner-top") .removeAttr("role").removeAttr("aria-expanded").removeAttr("tabindex"); this.headers.find("a").removeAttr("tabindex"); this.headers.children(".ui-icon").remove(); var contents = this.headers.next().css("display", "").removeAttr("role").removeClass("ui-helper-reset ui-widget-content ui-corner-bottom ui-accordion-content ui-accordion-content-active"); if (o.autoHeight || o.fillHeight) { contents.css("height", ""); } }, _setData: function(key, value) { if(key == 'alwaysOpen') { key = 'collapsible'; value = !value; } $.widget.prototype._setData.apply(this, arguments); }, _keydown: function(event) { var o = this.options, keyCode = $.ui.keyCode; if (o.disabled || event.altKey || event.ctrlKey) return; var length = this.headers.length; var currentIndex = this.headers.index(event.target); var toFocus = false; switch(event.keyCode) { case keyCode.RIGHT: case keyCode.DOWN: toFocus = this.headers[(currentIndex + 1) % length]; break; case keyCode.LEFT: case keyCode.UP: toFocus = this.headers[(currentIndex - 1 + length) % length]; break; case keyCode.SPACE: case keyCode.ENTER: return this._clickHandler({ target: event.target }, event.target); } if (toFocus) { $(event.target).attr('tabIndex','-1'); $(toFocus).attr('tabIndex','0'); toFocus.focus(); return false; } return true; }, resize: function() { var o = this.options, maxHeight; if (o.fillSpace) { if($.browser.msie) { var defOverflow = this.element.parent().css('overflow'); this.element.parent().css('overflow', 'hidden'); } maxHeight = this.element.parent().height(); if($.browser.msie) { this.element.parent().css('overflow', defOverflow); } this.headers.each(function() { maxHeight -= $(this).outerHeight(); }); var maxPadding = 0; this.headers.next().each(function() { maxPadding = Math.max(maxPadding, $(this).innerHeight() - $(this).height()); }).height(Math.max(0, maxHeight - maxPadding)) .css('overflow', 'auto'); } else if ( o.autoHeight ) { maxHeight = 0; this.headers.next().each(function() { maxHeight = Math.max(maxHeight, $(this).outerHeight()); }).height(maxHeight); } }, activate: function(index) { // call clickHandler with custom event var active = this._findActive(index)[0]; this._clickHandler({ target: active }, active); }, _findActive: function(selector) { return selector ? typeof selector == "number" ? this.headers.filter(":eq(" + selector + ")") : this.headers.not(this.headers.not(selector)) : selector === false ? $([]) : this.headers.filter(":eq(0)"); }, _clickHandler: function(event, target) { var o = this.options; if (o.disabled) return false; // called only when using activate(false) to close all parts programmatically if (!event.target && o.collapsible) { this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all") .find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header); this.active.next().addClass('ui-accordion-content-active'); var toHide = this.active.next(), data = { options: o, newHeader: $([]), oldHeader: o.active, newContent: $([]), oldContent: toHide }, toShow = (this.active = $([])); this._toggle(toShow, toHide, data); return false; } // get the click target var clicked = $(event.currentTarget || target); var clickedIsActive = clicked[0] == this.active[0]; // if animations are still active, or the active header is the target, ignore click if (this.running || (!o.collapsible && clickedIsActive)) { return false; } // switch classes this.active.removeClass("ui-state-active ui-corner-top").addClass("ui-state-default ui-corner-all") .find(".ui-icon").removeClass(o.icons.headerSelected).addClass(o.icons.header); this.active.next().addClass('ui-accordion-content-active'); if (!clickedIsActive) { clicked.removeClass("ui-state-default ui-corner-all").addClass("ui-state-active ui-corner-top") .find(".ui-icon").removeClass(o.icons.header).addClass(o.icons.headerSelected); clicked.next().addClass('ui-accordion-content-active'); } // find elements to show and hide var toShow = clicked.next(), toHide = this.active.next(), data = { options: o, newHeader: clickedIsActive && o.collapsible ? $([]) : clicked, oldHeader: this.active, newContent: clickedIsActive && o.collapsible ? $([]) : toShow.find('> *'), oldContent: toHide.find('> *') }, down = this.headers.index( this.active[0] ) > this.headers.index( clicked[0] ); this.active = clickedIsActive ? $([]) : clicked; this._toggle(toShow, toHide, data, clickedIsActive, down); return false; }, _toggle: function(toShow, toHide, data, clickedIsActive, down) { var o = this.options, self = this; this.toShow = toShow; this.toHide = toHide; this.data = data; var complete = function() { if(!self) return; return self._completed.apply(self, arguments); }; // trigger changestart event this._trigger("changestart", null, this.data); // count elements to animate this.running = toHide.size() === 0 ? toShow.size() : toHide.size(); if (o.animated) { var animOptions = {}; if ( o.collapsible && clickedIsActive ) { animOptions = { toShow: $([]), toHide: toHide, complete: complete, down: down, autoHeight: o.autoHeight || o.fillSpace }; } else { animOptions = { toShow: toShow, toHide: toHide, complete: complete, down: down, autoHeight: o.autoHeight || o.fillSpace }; } if (!o.proxied) { o.proxied = o.animated; } if (!o.proxiedDuration) { o.proxiedDuration = o.duration; } o.animated = $.isFunction(o.proxied) ? o.proxied(animOptions) : o.proxied; o.duration = $.isFunction(o.proxiedDuration) ? o.proxiedDuration(animOptions) : o.proxiedDuration; var animations = $.ui.accordion.animations, duration = o.duration, easing = o.animated; if (!animations[easing]) { animations[easing] = function(options) { this.slide(options, { easing: easing, duration: duration || 700 }); }; } animations[easing](animOptions); } else { if (o.collapsible && clickedIsActive) { toShow.toggle(); } else { toHide.hide(); toShow.show(); } complete(true); } toHide.prev().attr('aria-expanded','false').attr("tabIndex", "-1").blur(); toShow.prev().attr('aria-expanded','true').attr("tabIndex", "0").focus(); }, _completed: function(cancel) { var o = this.options; this.running = cancel ? 0 : --this.running; if (this.running) return; if (o.clearStyle) { this.toShow.add(this.toHide).css({ height: "", overflow: "" }); } this._trigger('change', null, this.data); } }); $.extend($.ui.accordion, { version: "1.7.2", defaults: { active: null, alwaysOpen: true, //deprecated, use collapsible animated: 'slide', autoHeight: true, clearStyle: false, collapsible: false, event: "click", fillSpace: false, header: "> li > :first-child,> :not(li):even", icons: { header: "ui-icon-triangle-1-e", headerSelected: "ui-icon-triangle-1-s" }, navigation: false, navigationFilter: function() { return this.href.toLowerCase() == location.href.toLowerCase(); } }, animations: { slide: function(options, additions) { options = $.extend({ easing: "swing", duration: 300 }, options, additions); if ( !options.toHide.size() ) { options.toShow.animate({height: "show"}, options); return; } if ( !options.toShow.size() ) { options.toHide.animate({height: "hide"}, options); return; } var overflow = options.toShow.css('overflow'), percentDone, showProps = {}, hideProps = {}, fxAttrs = [ "height", "paddingTop", "paddingBottom" ], originalWidth; // fix width before calculating height of hidden element var s = options.toShow; originalWidth = s[0].style.width; s.width( parseInt(s.parent().width(),10) - parseInt(s.css("paddingLeft"),10) - parseInt(s.css("paddingRight"),10) - (parseInt(s.css("borderLeftWidth"),10) || 0) - (parseInt(s.css("borderRightWidth"),10) || 0) ); $.each(fxAttrs, function(i, prop) { hideProps[prop] = 'hide'; var parts = ('' + $.css(options.toShow[0], prop)).match(/^([\d+-.]+)(.*)$/); showProps[prop] = { value: parts[1], unit: parts[2] || 'px' }; }); options.toShow.css({ height: 0, overflow: 'hidden' }).show(); options.toHide.filter(":hidden").each(options.complete).end().filter(":visible").animate(hideProps,{ step: function(now, settings) { // only calculate the percent when animating height // IE gets very inconsistent results when animating elements // with small values, which is common for padding if (settings.prop == 'height') { percentDone = (settings.now - settings.start) / (settings.end - settings.start); } options.toShow[0].style[settings.prop] = (percentDone * showProps[settings.prop].value) + showProps[settings.prop].unit; }, duration: options.duration, easing: options.easing, complete: function() { if ( !options.autoHeight ) { options.toShow.css("height", ""); } options.toShow.css("width", originalWidth); options.toShow.css({overflow: overflow}); options.complete(); } }); }, bounceslide: function(options) { this.slide(options, { easing: options.down ? "easeOutBounce" : "swing", duration: options.down ? 1000 : 200 }); }, easeslide: function(options) { this.slide(options, { easing: "easeinout", duration: 700 }); } } }); })(jQuery);
01cms
01cms/branches/1.0/public/common/js/ui.accordion.js
JavaScript
asf20
13,945
/** * window 1.0 * * Copyright (c) 2009 www.01mvc.com * * http://www.01mvc.com * * Depends: * ui.core.js * ui.draggable.js * ui.resizable.js * ui.dialog.js */ $.fn.window = function(options){ var defaults = { defaultMsg: '<span class="dialogLoading">&nbsp;</span>正在处理,请稍候...', sendUrl: "", goUrl : "", style : "padding:15px; line-height:20px; font-size:13px; text-align:center;", dataClass : "posted", type : "post", dataType : "json", stayTime : 2, buttons : '', height : 'auto', width : 300, maxHeight : '', maxWidth : '', minHeight : '', minWidth : '', title : "提示信息", beforeclose : '', resizable : true, open : '', focus : '', position : 'center', dragStart : '', drag : '', dragStop : '', resizeStart : '', resize : '', resizeStop : '', close : function() {if($(":submit").length > 0)$(":submit").get(0).disabled = false;}, msgClass : 'dialog-message'+$(".ui-dialog").length }; var options = $.extend(defaults, options); var msgClass = options.msgClass; if(options.type == "post" && options.sendUrl != '') { $(this).submit(function(){ $(":submit").get(0).disabled = true; $('<div class="'+msgClass+'" style="'+options.style+'">'+options.defaultMsg+'</div>').dialog({ buttons : options.buttons, height : options.height, width : options.width, maxHeight : options.maxHeight, maxWidth : options.maxWidth, minHeight : options.minHeight, minWidth : options.minWidth, title : options.title, beforeclose : options.beforeclose, resizable : options.resizable, open : options.open, focus : options.focus, position : options.position, dragStart : options.dragStart, drag : options.drag, dragStop : options.dragStop, resizeStart : options.resizeStart, buttons: options.buttons, close : options.close }); $("."+options.dataClass).each(function(){ if(options.data == '') { and = ''; } else { and = '&'; } var value = ''; if(this.type == 'checkbox' || this.type == 'radio') { if(this.checked) { options.data += and + this.name + '=' + this.value; } } else { options.data += and + this.name + '=' + this.value; } }); $.ajax( { type : options.type, dataType : options.dataType, data : options.data, url : options.sendUrl, success : function(response) { $("."+msgClass).html(response.message); if (response.success && options.goUrl != '') { window.setTimeout(function(){ window.location.href = options.goUrl;} ,options.stayTime * 1000); } else { window.setTimeout(function(){$(".ui-dialog:has(."+msgClass+")").hide('slow');$(":submit").get(0).disabled = false;},options.stayTime*1000); } if (response.js != '') { eval(response.js); } } }); return false; }); } else { $('<div class="'+msgClass+'" style="padding:15px; font-size:13px">'+options.defaultMsg+'</div>').dialog({ buttons : options.buttons, height : options.height, width : options.width, maxHeight : options.maxHeight, maxWidth : options.maxWidth, minHeight : options.minHeight, minWidth : options.minWidth, title : options.title, beforeclose : options.beforeclose, resizable : options.resizable, open : options.open, focus : options.focus, position : options.position, dragStart : options.dragStart, drag : options.drag, dragStop : options.dragStop, resizeStart : options.resizeStart, buttons: options.buttons, close : options.close }); if(options.sendUrl != '') { $.ajax( { type : 'get', dataType : options.dataType, data : options.data, url : options.sendUrl, success : function(response) { $("."+msgClass).html(response.message); if (response.success && options.goUrl != '') { window.setTimeout(function(){ window.location.href = options.goUrl;} ,options.stayTime * 1000); } else if(options.stayTime > 0) { window.setTimeout(function(){$(".ui-dialog:has(."+msgClass+")").hide('slow');},options.stayTime*1000); } if (response.js != '') { eval(response.js); } } }); } return false; } };
01cms
01cms/branches/1.0/public/common/js/jquery.window.js
JavaScript
asf20
4,599
/* * jQuery UI Dialog 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Dialog * * Depends: * ui.core.js * ui.draggable.js * ui.resizable.js */ (function($) { var setDataSwitch = { dragStart: "start.draggable", drag: "drag.draggable", dragStop: "stop.draggable", maxHeight: "maxHeight.resizable", minHeight: "minHeight.resizable", maxWidth: "maxWidth.resizable", minWidth: "minWidth.resizable", resizeStart: "start.resizable", resize: "drag.resizable", resizeStop: "stop.resizable" }, uiDialogClasses = 'ui-dialog ' + 'ui-widget ' + 'ui-widget-content ' + 'ui-corner-all '; $.widget("ui.dialog", { _init: function() { this.originalTitle = this.element.attr('title'); var self = this, options = this.options, title = options.title || this.originalTitle || '&nbsp;', titleId = $.ui.dialog.getTitleId(this.element), uiDialog = (this.uiDialog = $('<div/>')) .appendTo(document.body) .hide() .addClass(uiDialogClasses + options.dialogClass) .css({ position: 'absolute', overflow: 'hidden', zIndex: options.zIndex }) // setting tabIndex makes the div focusable // setting outline to 0 prevents a border on focus in Mozilla .attr('tabIndex', -1).css('outline', 0).keydown(function(event) { (options.closeOnEscape && event.keyCode && event.keyCode == $.ui.keyCode.ESCAPE && self.close(event)); }) .attr({ role: 'dialog', 'aria-labelledby': titleId }) .mousedown(function(event) { self.moveToTop(false, event); }), uiDialogContent = this.element .show() .removeAttr('title') .addClass( 'ui-dialog-content ' + 'ui-widget-content') .appendTo(uiDialog), uiDialogTitlebar = (this.uiDialogTitlebar = $('<div></div>')) .addClass( 'ui-dialog-titlebar ' + 'ui-widget-header ' + 'ui-corner-all ' + 'ui-helper-clearfix' ) .prependTo(uiDialog), uiDialogTitlebarClose = $('<a href="#"/>') .addClass( 'ui-dialog-titlebar-close ' + 'ui-corner-all' ) .attr('role', 'button') .hover( function() { uiDialogTitlebarClose.addClass('ui-state-hover'); }, function() { uiDialogTitlebarClose.removeClass('ui-state-hover'); } ) .focus(function() { uiDialogTitlebarClose.addClass('ui-state-focus'); }) .blur(function() { uiDialogTitlebarClose.removeClass('ui-state-focus'); }) .mousedown(function(ev) { ev.stopPropagation(); }) .click(function(event) { self.close(event); return false; }) .appendTo(uiDialogTitlebar), uiDialogTitlebarCloseText = (this.uiDialogTitlebarCloseText = $('<span/>')) .addClass( 'ui-icon ' + 'ui-icon-closethick' ) .text(options.closeText) .appendTo(uiDialogTitlebarClose), uiDialogTitle = $('<span/>') .addClass('ui-dialog-title') .attr('id', titleId) .html(title) .prependTo(uiDialogTitlebar); uiDialogTitlebar.find("*").add(uiDialogTitlebar).disableSelection(); (options.draggable && $.fn.draggable && this._makeDraggable()); (options.resizable && $.fn.resizable && this._makeResizable()); this._createButtons(options.buttons); this._isOpen = false; (options.bgiframe && $.fn.bgiframe && uiDialog.bgiframe()); (options.autoOpen && this.open()); }, destroy: function() { (this.overlay && this.overlay.destroy()); this.uiDialog.hide(); this.element .unbind('.dialog') .removeData('dialog') .removeClass('ui-dialog-content ui-widget-content') .hide().appendTo('body'); this.uiDialog.remove(); (this.originalTitle && this.element.attr('title', this.originalTitle)); }, close: function(event) { var self = this; if (false === self._trigger('beforeclose', event)) { return; } (self.overlay && self.overlay.destroy()); self.uiDialog.unbind('keypress.ui-dialog'); (self.options.hide ? self.uiDialog.hide(self.options.hide, function() { self._trigger('close', event); }) : self.uiDialog.hide() && self._trigger('close', event)); $.ui.dialog.overlay.resize(); self._isOpen = false; // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) if (self.options.modal) { var maxZ = 0; $('.ui-dialog').each(function() { if (this != self.uiDialog[0]) { maxZ = Math.max(maxZ, $(this).css('z-index')); } }); $.ui.dialog.maxZ = maxZ; } }, isOpen: function() { return this._isOpen; }, // the force parameter allows us to move modal dialogs to their correct // position on open moveToTop: function(force, event) { if ((this.options.modal && !force) || (!this.options.stack && !this.options.modal)) { return this._trigger('focus', event); } if (this.options.zIndex > $.ui.dialog.maxZ) { $.ui.dialog.maxZ = this.options.zIndex; } (this.overlay && this.overlay.$el.css('z-index', $.ui.dialog.overlay.maxZ = ++$.ui.dialog.maxZ)); //Save and then restore scroll since Opera 9.5+ resets when parent z-Index is changed. // http://ui.jquery.com/bugs/ticket/3193 var saveScroll = { scrollTop: this.element.attr('scrollTop'), scrollLeft: this.element.attr('scrollLeft') }; this.uiDialog.css('z-index', ++$.ui.dialog.maxZ); this.element.attr(saveScroll); this._trigger('focus', event); }, open: function() { if (this._isOpen) { return; } var options = this.options, uiDialog = this.uiDialog; this.overlay = options.modal ? new $.ui.dialog.overlay(this) : null; (uiDialog.next().length && uiDialog.appendTo('body')); this._size(); this._position(options.position); uiDialog.show(options.show); this.moveToTop(true); // prevent tabbing out of modal dialogs (options.modal && uiDialog.bind('keypress.ui-dialog', function(event) { if (event.keyCode != $.ui.keyCode.TAB) { return; } var tabbables = $(':tabbable', this), first = tabbables.filter(':first')[0], last = tabbables.filter(':last')[0]; if (event.target == last && !event.shiftKey) { setTimeout(function() { first.focus(); }, 1); } else if (event.target == first && event.shiftKey) { setTimeout(function() { last.focus(); }, 1); } })); // set focus to the first tabbable element in the content area or the first button // if there are no tabbable elements, set focus on the dialog itself $([]) .add(uiDialog.find('.ui-dialog-content :tabbable:first')) .add(uiDialog.find('.ui-dialog-buttonpane :tabbable:first')) .add(uiDialog) .filter(':first') .focus(); this._trigger('open'); this._isOpen = true; }, _createButtons: function(buttons) { var self = this, hasButtons = false, uiDialogButtonPane = $('<div></div>') .addClass( 'ui-dialog-buttonpane ' + 'ui-widget-content ' + 'ui-helper-clearfix' ); // if we already have a button pane, remove it this.uiDialog.find('.ui-dialog-buttonpane').remove(); (typeof buttons == 'object' && buttons !== null && $.each(buttons, function() { return !(hasButtons = true); })); if (hasButtons) { $.each(buttons, function(name, fn) { $('<button type="button"></button>') .addClass( 'ui-state-default ' + 'ui-corner-all' ) .text(name) .click(function() { fn.apply(self.element[0], arguments); }) .hover( function() { $(this).addClass('ui-state-hover'); }, function() { $(this).removeClass('ui-state-hover'); } ) .focus(function() { $(this).addClass('ui-state-focus'); }) .blur(function() { $(this).removeClass('ui-state-focus'); }) .appendTo(uiDialogButtonPane); }); uiDialogButtonPane.appendTo(this.uiDialog); } }, _makeDraggable: function() { var self = this, options = this.options, heightBeforeDrag; this.uiDialog.draggable({ cancel: '.ui-dialog-content', handle: '.ui-dialog-titlebar', containment: 'document', start: function() { heightBeforeDrag = options.height; $(this).height($(this).height()).addClass("ui-dialog-dragging"); (options.dragStart && options.dragStart.apply(self.element[0], arguments)); }, drag: function() { (options.drag && options.drag.apply(self.element[0], arguments)); }, stop: function() { $(this).removeClass("ui-dialog-dragging").height(heightBeforeDrag); (options.dragStop && options.dragStop.apply(self.element[0], arguments)); $.ui.dialog.overlay.resize(); } }); }, _makeResizable: function(handles) { handles = (handles === undefined ? this.options.resizable : handles); var self = this, options = this.options, resizeHandles = typeof handles == 'string' ? handles : 'n,e,s,w,se,sw,ne,nw'; this.uiDialog.resizable({ cancel: '.ui-dialog-content', alsoResize: this.element, maxWidth: options.maxWidth, maxHeight: options.maxHeight, minWidth: options.minWidth, minHeight: options.minHeight, start: function() { $(this).addClass("ui-dialog-resizing"); (options.resizeStart && options.resizeStart.apply(self.element[0], arguments)); }, resize: function() { (options.resize && options.resize.apply(self.element[0], arguments)); }, handles: resizeHandles, stop: function() { $(this).removeClass("ui-dialog-resizing"); options.height = $(this).height(); options.width = $(this).width(); (options.resizeStop && options.resizeStop.apply(self.element[0], arguments)); $.ui.dialog.overlay.resize(); } }) .find('.ui-resizable-se').addClass('ui-icon ui-icon-grip-diagonal-se'); }, _position: function(pos) { var wnd = $(window), doc = $(document), pTop = doc.scrollTop(), pLeft = doc.scrollLeft(), minTop = pTop; if ($.inArray(pos, ['center','top','right','bottom','left']) >= 0) { pos = [ pos == 'right' || pos == 'left' ? pos : 'center', pos == 'top' || pos == 'bottom' ? pos : 'middle' ]; } if (pos.constructor != Array) { pos = ['center', 'middle']; } if (pos[0].constructor == Number) { pLeft += pos[0]; } else { switch (pos[0]) { case 'left': pLeft += 0; break; case 'right': pLeft += wnd.width() - this.uiDialog.outerWidth(); break; default: case 'center': pLeft += (wnd.width() - this.uiDialog.outerWidth()) / 2; } } if (pos[1].constructor == Number) { pTop += pos[1]; } else { switch (pos[1]) { case 'top': pTop += 0; break; case 'bottom': pTop += wnd.height() - this.uiDialog.outerHeight(); break; default: case 'middle': pTop += (wnd.height() - this.uiDialog.outerHeight()) / 2; } } // prevent the dialog from being too high (make sure the titlebar // is accessible) pTop = Math.max(pTop, minTop); this.uiDialog.css({top: pTop, left: pLeft}); }, _setData: function(key, value){ (setDataSwitch[key] && this.uiDialog.data(setDataSwitch[key], value)); switch (key) { case "buttons": this._createButtons(value); break; case "closeText": this.uiDialogTitlebarCloseText.text(value); break; case "dialogClass": this.uiDialog .removeClass(this.options.dialogClass) .addClass(uiDialogClasses + value); break; case "draggable": (value ? this._makeDraggable() : this.uiDialog.draggable('destroy')); break; case "height": this.uiDialog.height(value); break; case "position": this._position(value); break; case "resizable": var uiDialog = this.uiDialog, isResizable = this.uiDialog.is(':data(resizable)'); // currently resizable, becoming non-resizable (isResizable && !value && uiDialog.resizable('destroy')); // currently resizable, changing handles (isResizable && typeof value == 'string' && uiDialog.resizable('option', 'handles', value)); // currently non-resizable, becoming resizable (isResizable || this._makeResizable(value)); break; case "title": $(".ui-dialog-title", this.uiDialogTitlebar).html(value || '&nbsp;'); break; case "width": this.uiDialog.width(value); break; } $.widget.prototype._setData.apply(this, arguments); }, _size: function() { /* If the user has resized the dialog, the .ui-dialog and .ui-dialog-content * divs will both have width and height set, so we need to reset them */ var options = this.options; // reset content sizing this.element.css({ height: 0, minHeight: 0, width: 'auto' }); // reset wrapper sizing // determine the height of all the non-content elements var nonContentHeight = this.uiDialog.css({ height: 'auto', width: options.width }) .height(); this.element .css({ minHeight: Math.max(options.minHeight - nonContentHeight, 0), height: options.height == 'auto' ? 'auto' : Math.max(options.height - nonContentHeight, 0) }); } }); $.extend($.ui.dialog, { version: "1.7.2", defaults: { autoOpen: true, bgiframe: false, buttons: {}, closeOnEscape: true, closeText: 'close', dialogClass: '', draggable: true, hide: null, height: 'auto', maxHeight: false, maxWidth: false, minHeight: 50, minWidth: 150, modal: false, position: 'center', resizable: true, show: null, stack: true, title: '', width: 300, zIndex: 1000 }, getter: 'isOpen', uuid: 0, maxZ: 0, getTitleId: function($el) { return 'ui-dialog-title-' + ($el.attr('id') || ++this.uuid); }, overlay: function(dialog) { this.$el = $.ui.dialog.overlay.create(dialog); } }); $.extend($.ui.dialog.overlay, { instances: [], maxZ: 0, events: $.map('focus,mousedown,mouseup,keydown,keypress,click'.split(','), function(event) { return event + '.dialog-overlay'; }).join(' '), create: function(dialog) { if (this.instances.length === 0) { // prevent use of anchors and inputs // we use a setTimeout in case the overlay is created from an // event that we're going to be cancelling (see #2804) setTimeout(function() { // handle $(el).dialog().dialog('close') (see #4065) if ($.ui.dialog.overlay.instances.length) { $(document).bind($.ui.dialog.overlay.events, function(event) { var dialogZ = $(event.target).parents('.ui-dialog').css('zIndex') || 0; return (dialogZ > $.ui.dialog.overlay.maxZ); }); } }, 1); // allow closing by pressing the escape key $(document).bind('keydown.dialog-overlay', function(event) { (dialog.options.closeOnEscape && event.keyCode && event.keyCode == $.ui.keyCode.ESCAPE && dialog.close(event)); }); // handle window resize $(window).bind('resize.dialog-overlay', $.ui.dialog.overlay.resize); } var $el = $('<div></div>').appendTo(document.body) .addClass('ui-widget-overlay').css({ width: this.width(), height: this.height() }); (dialog.options.bgiframe && $.fn.bgiframe && $el.bgiframe()); this.instances.push($el); return $el; }, destroy: function($el) { this.instances.splice($.inArray(this.instances, $el), 1); if (this.instances.length === 0) { $([document, window]).unbind('.dialog-overlay'); } $el.remove(); // adjust the maxZ to allow other modal dialogs to continue to work (see #4309) var maxZ = 0; $.each(this.instances, function() { maxZ = Math.max(maxZ, this.css('z-index')); }); this.maxZ = maxZ; }, height: function() { // handle IE 6 if ($.browser.msie && $.browser.version < 7) { var scrollHeight = Math.max( document.documentElement.scrollHeight, document.body.scrollHeight ); var offsetHeight = Math.max( document.documentElement.offsetHeight, document.body.offsetHeight ); if (scrollHeight < offsetHeight) { return $(window).height() + 'px'; } else { return scrollHeight + 'px'; } // handle "good" browsers } else { return $(document).height() + 'px'; } }, width: function() { // handle IE 6 if ($.browser.msie && $.browser.version < 7) { var scrollWidth = Math.max( document.documentElement.scrollWidth, document.body.scrollWidth ); var offsetWidth = Math.max( document.documentElement.offsetWidth, document.body.offsetWidth ); if (scrollWidth < offsetWidth) { return $(window).width() + 'px'; } else { return scrollWidth + 'px'; } // handle "good" browsers } else { return $(document).width() + 'px'; } }, resize: function() { /* If the dialog is draggable and the user drags it past the * right edge of the window, the document becomes wider so we * need to stretch the overlay. If the user then drags the * dialog back to the left, the document will become narrower, * so we need to shrink the overlay to the appropriate size. * This is handled by shrinking the overlay before setting it * to the full document size. */ var $overlays = $([]); $.each($.ui.dialog.overlay.instances, function() { $overlays = $overlays.add(this); }); $overlays.css({ width: 0, height: 0 }).css({ width: $.ui.dialog.overlay.width(), height: $.ui.dialog.overlay.height() }); } }); $.extend($.ui.dialog.overlay.prototype, { destroy: function() { $.ui.dialog.overlay.destroy(this.$el); } }); })(jQuery);
01cms
01cms/branches/1.0/public/common/js/ui.dialog.js
JavaScript
asf20
18,060
/* * jQuery UI Effects 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Effects/ */ ;jQuery.effects || (function($) { $.effects = { version: "1.7.2", // Saves a set of properties in a data storage save: function(element, set) { for(var i=0; i < set.length; i++) { if(set[i] !== null) element.data("ec.storage."+set[i], element[0].style[set[i]]); } }, // Restores a set of previously saved properties from a data storage restore: function(element, set) { for(var i=0; i < set.length; i++) { if(set[i] !== null) element.css(set[i], element.data("ec.storage."+set[i])); } }, setMode: function(el, mode) { if (mode == 'toggle') mode = el.is(':hidden') ? 'show' : 'hide'; // Set for toggle return mode; }, getBaseline: function(origin, original) { // Translates a [top,left] array into a baseline value // this should be a little more flexible in the future to handle a string & hash var y, x; switch (origin[0]) { case 'top': y = 0; break; case 'middle': y = 0.5; break; case 'bottom': y = 1; break; default: y = origin[0] / original.height; }; switch (origin[1]) { case 'left': x = 0; break; case 'center': x = 0.5; break; case 'right': x = 1; break; default: x = origin[1] / original.width; }; return {x: x, y: y}; }, // Wraps the element around a wrapper that copies position properties createWrapper: function(element) { //if the element is already wrapped, return it if (element.parent().is('.ui-effects-wrapper')) return element.parent(); //Cache width,height and float properties of the element, and create a wrapper around it var props = { width: element.outerWidth(true), height: element.outerHeight(true), 'float': element.css('float') }; element.wrap('<div class="ui-effects-wrapper" style="font-size:100%;background:transparent;border:none;margin:0;padding:0"></div>'); var wrapper = element.parent(); //Transfer the positioning of the element to the wrapper if (element.css('position') == 'static') { wrapper.css({ position: 'relative' }); element.css({ position: 'relative'} ); } else { var top = element.css('top'); if(isNaN(parseInt(top,10))) top = 'auto'; var left = element.css('left'); if(isNaN(parseInt(left,10))) left = 'auto'; wrapper.css({ position: element.css('position'), top: top, left: left, zIndex: element.css('z-index') }).show(); element.css({position: 'relative', top: 0, left: 0 }); } wrapper.css(props); return wrapper; }, removeWrapper: function(element) { if (element.parent().is('.ui-effects-wrapper')) return element.parent().replaceWith(element); return element; }, setTransition: function(element, list, factor, value) { value = value || {}; $.each(list, function(i, x){ unit = element.cssUnit(x); if (unit[0] > 0) value[x] = unit[0] * factor + unit[1]; }); return value; }, //Base function to animate from one class to another in a seamless transition animateClass: function(value, duration, easing, callback) { var cb = (typeof easing == "function" ? easing : (callback ? callback : null)); var ea = (typeof easing == "string" ? easing : null); return this.each(function() { var offset = {}; var that = $(this); var oldStyleAttr = that.attr("style") || ''; if(typeof oldStyleAttr == 'object') oldStyleAttr = oldStyleAttr["cssText"]; /* Stupidly in IE, style is a object.. */ if(value.toggle) { that.hasClass(value.toggle) ? value.remove = value.toggle : value.add = value.toggle; } //Let's get a style offset var oldStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle)); if(value.add) that.addClass(value.add); if(value.remove) that.removeClass(value.remove); var newStyle = $.extend({}, (document.defaultView ? document.defaultView.getComputedStyle(this,null) : this.currentStyle)); if(value.add) that.removeClass(value.add); if(value.remove) that.addClass(value.remove); // The main function to form the object for animation for(var n in newStyle) { if( typeof newStyle[n] != "function" && newStyle[n] /* No functions and null properties */ && n.indexOf("Moz") == -1 && n.indexOf("length") == -1 /* No mozilla spezific render properties. */ && newStyle[n] != oldStyle[n] /* Only values that have changed are used for the animation */ && (n.match(/color/i) || (!n.match(/color/i) && !isNaN(parseInt(newStyle[n],10)))) /* Only things that can be parsed to integers or colors */ && (oldStyle.position != "static" || (oldStyle.position == "static" && !n.match(/left|top|bottom|right/))) /* No need for positions when dealing with static positions */ ) offset[n] = newStyle[n]; } that.animate(offset, duration, ea, function() { // Animate the newly constructed offset object // Change style attribute back to original. For stupid IE, we need to clear the damn object. if(typeof $(this).attr("style") == 'object') { $(this).attr("style")["cssText"] = ""; $(this).attr("style")["cssText"] = oldStyleAttr; } else $(this).attr("style", oldStyleAttr); if(value.add) $(this).addClass(value.add); if(value.remove) $(this).removeClass(value.remove); if(cb) cb.apply(this, arguments); }); }); } }; function _normalizeArguments(a, m) { var o = a[1] && a[1].constructor == Object ? a[1] : {}; if(m) o.mode = m; var speed = a[1] && a[1].constructor != Object ? a[1] : (o.duration ? o.duration : a[2]); //either comes from options.duration or the secon/third argument speed = $.fx.off ? 0 : typeof speed === "number" ? speed : $.fx.speeds[speed] || $.fx.speeds._default; var callback = o.callback || ( $.isFunction(a[1]) && a[1] ) || ( $.isFunction(a[2]) && a[2] ) || ( $.isFunction(a[3]) && a[3] ); return [a[0], o, speed, callback]; } //Extend the methods of jQuery $.fn.extend({ //Save old methods _show: $.fn.show, _hide: $.fn.hide, __toggle: $.fn.toggle, _addClass: $.fn.addClass, _removeClass: $.fn.removeClass, _toggleClass: $.fn.toggleClass, // New effect methods effect: function(fx, options, speed, callback) { return $.effects[fx] ? $.effects[fx].call(this, {method: fx, options: options || {}, duration: speed, callback: callback }) : null; }, show: function() { if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0]))) return this._show.apply(this, arguments); else { return this.effect.apply(this, _normalizeArguments(arguments, 'show')); } }, hide: function() { if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0]))) return this._hide.apply(this, arguments); else { return this.effect.apply(this, _normalizeArguments(arguments, 'hide')); } }, toggle: function(){ if(!arguments[0] || (arguments[0].constructor == Number || (/(slow|normal|fast)/).test(arguments[0])) || ($.isFunction(arguments[0]) || typeof arguments[0] == 'boolean')) { return this.__toggle.apply(this, arguments); } else { return this.effect.apply(this, _normalizeArguments(arguments, 'toggle')); } }, addClass: function(classNames, speed, easing, callback) { return speed ? $.effects.animateClass.apply(this, [{ add: classNames },speed,easing,callback]) : this._addClass(classNames); }, removeClass: function(classNames,speed,easing,callback) { return speed ? $.effects.animateClass.apply(this, [{ remove: classNames },speed,easing,callback]) : this._removeClass(classNames); }, toggleClass: function(classNames,speed,easing,callback) { return ( (typeof speed !== "boolean") && speed ) ? $.effects.animateClass.apply(this, [{ toggle: classNames },speed,easing,callback]) : this._toggleClass(classNames, speed); }, morph: function(remove,add,speed,easing,callback) { return $.effects.animateClass.apply(this, [{ add: add, remove: remove },speed,easing,callback]); }, switchClass: function() { return this.morph.apply(this, arguments); }, // helper functions cssUnit: function(key) { var style = this.css(key), val = []; $.each( ['em','px','%','pt'], function(i, unit){ if(style.indexOf(unit) > 0) val = [parseFloat(style), unit]; }); return val; } }); /* * jQuery Color Animations * Copyright 2007 John Resig * Released under the MIT and GPL licenses. */ // We override the animation for all of these color styles $.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){ $.fx.step[attr] = function(fx) { if ( fx.state == 0 ) { fx.start = getColor( fx.elem, attr ); fx.end = getRGB( fx.end ); } fx.elem.style[attr] = "rgb(" + [ Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0],10), 255), 0), Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1],10), 255), 0), Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2],10), 255), 0) ].join(",") + ")"; }; }); // Color Conversion functions from highlightFade // By Blair Mitchelmore // http://jquery.offput.ca/highlightFade/ // Parse strings looking for color tuples [255,255,255] function getRGB(color) { var result; // Check if we're already dealing with an array of colors if ( color && color.constructor == Array && color.length == 3 ) return color; // Look for rgb(num,num,num) if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color)) return [parseInt(result[1],10), parseInt(result[2],10), parseInt(result[3],10)]; // Look for rgb(num%,num%,num%) if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color)) return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55]; // Look for #a0b1c2 if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color)) return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)]; // Look for #fff if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color)) return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)]; // Look for rgba(0, 0, 0, 0) == transparent in Safari 3 if (result = /rgba\(0, 0, 0, 0\)/.exec(color)) return colors['transparent']; // Otherwise, we're most likely dealing with a named color return colors[$.trim(color).toLowerCase()]; } function getColor(elem, attr) { var color; do { color = $.curCSS(elem, attr); // Keep going until we find an element that has color, or we hit the body if ( color != '' && color != 'transparent' || $.nodeName(elem, "body") ) break; attr = "backgroundColor"; } while ( elem = elem.parentNode ); return getRGB(color); }; // Some named colors to work with // From Interface by Stefan Petre // http://interface.eyecon.ro/ var colors = { aqua:[0,255,255], azure:[240,255,255], beige:[245,245,220], black:[0,0,0], blue:[0,0,255], brown:[165,42,42], cyan:[0,255,255], darkblue:[0,0,139], darkcyan:[0,139,139], darkgrey:[169,169,169], darkgreen:[0,100,0], darkkhaki:[189,183,107], darkmagenta:[139,0,139], darkolivegreen:[85,107,47], darkorange:[255,140,0], darkorchid:[153,50,204], darkred:[139,0,0], darksalmon:[233,150,122], darkviolet:[148,0,211], fuchsia:[255,0,255], gold:[255,215,0], green:[0,128,0], indigo:[75,0,130], khaki:[240,230,140], lightblue:[173,216,230], lightcyan:[224,255,255], lightgreen:[144,238,144], lightgrey:[211,211,211], lightpink:[255,182,193], lightyellow:[255,255,224], lime:[0,255,0], magenta:[255,0,255], maroon:[128,0,0], navy:[0,0,128], olive:[128,128,0], orange:[255,165,0], pink:[255,192,203], purple:[128,0,128], violet:[128,0,128], red:[255,0,0], silver:[192,192,192], white:[255,255,255], yellow:[255,255,0], transparent: [255,255,255] }; /* * jQuery Easing v1.3 - http://gsgd.co.uk/sandbox/jquery/easing/ * * Uses the built in easing capabilities added In jQuery 1.1 * to offer multiple easing options * * TERMS OF USE - jQuery Easing * * Open source under the BSD License. * * Copyright 2008 George McGinley Smith * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ // t: current time, b: begInnIng value, c: change In value, d: duration $.easing.jswing = $.easing.swing; $.extend($.easing, { def: 'easeOutQuad', swing: function (x, t, b, c, d) { //alert($.easing.default); return $.easing[$.easing.def](x, t, b, c, d); }, easeInQuad: function (x, t, b, c, d) { return c*(t/=d)*t + b; }, easeOutQuad: function (x, t, b, c, d) { return -c *(t/=d)*(t-2) + b; }, easeInOutQuad: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t + b; return -c/2 * ((--t)*(t-2) - 1) + b; }, easeInCubic: function (x, t, b, c, d) { return c*(t/=d)*t*t + b; }, easeOutCubic: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t + 1) + b; }, easeInOutCubic: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t + b; return c/2*((t-=2)*t*t + 2) + b; }, easeInQuart: function (x, t, b, c, d) { return c*(t/=d)*t*t*t + b; }, easeOutQuart: function (x, t, b, c, d) { return -c * ((t=t/d-1)*t*t*t - 1) + b; }, easeInOutQuart: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t + b; return -c/2 * ((t-=2)*t*t*t - 2) + b; }, easeInQuint: function (x, t, b, c, d) { return c*(t/=d)*t*t*t*t + b; }, easeOutQuint: function (x, t, b, c, d) { return c*((t=t/d-1)*t*t*t*t + 1) + b; }, easeInOutQuint: function (x, t, b, c, d) { if ((t/=d/2) < 1) return c/2*t*t*t*t*t + b; return c/2*((t-=2)*t*t*t*t + 2) + b; }, easeInSine: function (x, t, b, c, d) { return -c * Math.cos(t/d * (Math.PI/2)) + c + b; }, easeOutSine: function (x, t, b, c, d) { return c * Math.sin(t/d * (Math.PI/2)) + b; }, easeInOutSine: function (x, t, b, c, d) { return -c/2 * (Math.cos(Math.PI*t/d) - 1) + b; }, easeInExpo: function (x, t, b, c, d) { return (t==0) ? b : c * Math.pow(2, 10 * (t/d - 1)) + b; }, easeOutExpo: function (x, t, b, c, d) { return (t==d) ? b+c : c * (-Math.pow(2, -10 * t/d) + 1) + b; }, easeInOutExpo: function (x, t, b, c, d) { if (t==0) return b; if (t==d) return b+c; if ((t/=d/2) < 1) return c/2 * Math.pow(2, 10 * (t - 1)) + b; return c/2 * (-Math.pow(2, -10 * --t) + 2) + b; }, easeInCirc: function (x, t, b, c, d) { return -c * (Math.sqrt(1 - (t/=d)*t) - 1) + b; }, easeOutCirc: function (x, t, b, c, d) { return c * Math.sqrt(1 - (t=t/d-1)*t) + b; }, easeInOutCirc: function (x, t, b, c, d) { if ((t/=d/2) < 1) return -c/2 * (Math.sqrt(1 - t*t) - 1) + b; return c/2 * (Math.sqrt(1 - (t-=2)*t) + 1) + b; }, easeInElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return -(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; }, easeOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d)==1) return b+c; if (!p) p=d*.3; if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); return a*Math.pow(2,-10*t) * Math.sin( (t*d-s)*(2*Math.PI)/p ) + c + b; }, easeInOutElastic: function (x, t, b, c, d) { var s=1.70158;var p=0;var a=c; if (t==0) return b; if ((t/=d/2)==2) return b+c; if (!p) p=d*(.3*1.5); if (a < Math.abs(c)) { a=c; var s=p/4; } else var s = p/(2*Math.PI) * Math.asin (c/a); if (t < 1) return -.5*(a*Math.pow(2,10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )) + b; return a*Math.pow(2,-10*(t-=1)) * Math.sin( (t*d-s)*(2*Math.PI)/p )*.5 + c + b; }, easeInBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*(t/=d)*t*((s+1)*t - s) + b; }, easeOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; return c*((t=t/d-1)*t*((s+1)*t + s) + 1) + b; }, easeInOutBack: function (x, t, b, c, d, s) { if (s == undefined) s = 1.70158; if ((t/=d/2) < 1) return c/2*(t*t*(((s*=(1.525))+1)*t - s)) + b; return c/2*((t-=2)*t*(((s*=(1.525))+1)*t + s) + 2) + b; }, easeInBounce: function (x, t, b, c, d) { return c - $.easing.easeOutBounce (x, d-t, 0, c, d) + b; }, easeOutBounce: function (x, t, b, c, d) { if ((t/=d) < (1/2.75)) { return c*(7.5625*t*t) + b; } else if (t < (2/2.75)) { return c*(7.5625*(t-=(1.5/2.75))*t + .75) + b; } else if (t < (2.5/2.75)) { return c*(7.5625*(t-=(2.25/2.75))*t + .9375) + b; } else { return c*(7.5625*(t-=(2.625/2.75))*t + .984375) + b; } }, easeInOutBounce: function (x, t, b, c, d) { if (t < d/2) return $.easing.easeInBounce (x, t*2, 0, c, d) * .5 + b; return $.easing.easeOutBounce (x, t*2-d, 0, c, d) * .5 + c*.5 + b; } }); /* * * TERMS OF USE - EASING EQUATIONS * * Open source under the BSD License. * * Copyright 2001 Robert Penner * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, this list of * conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list * of conditions and the following disclaimer in the documentation and/or other materials * provided with the distribution. * * Neither the name of the author nor the names of contributors may be used to endorse * or promote products derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE * COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE * GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED * OF THE POSSIBILITY OF SUCH DAMAGE. * */ })(jQuery);
01cms
01cms/branches/1.0/public/common/js/effects.core.js
JavaScript
asf20
20,090
/* * jQuery UI Effects Drop 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Effects/Drop * * Depends: * effects.core.js */ (function($) { $.effects.drop = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['position','top','left','opacity']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'hide'); // Set Mode var direction = o.options.direction || 'left'; // Default Direction // Adjust $.effects.save(el, props); el.show(); // Save & Show $.effects.createWrapper(el); // Create Wrapper var ref = (direction == 'up' || direction == 'down') ? 'top' : 'left'; var motion = (direction == 'up' || direction == 'left') ? 'pos' : 'neg'; var distance = o.options.distance || (ref == 'top' ? el.outerHeight({margin:true}) / 2 : el.outerWidth({margin:true}) / 2); if (mode == 'show') el.css('opacity', 0).css(ref, motion == 'pos' ? -distance : distance); // Shift // Animation var animation = {opacity: mode == 'show' ? 1 : 0}; animation[ref] = (mode == 'show' ? (motion == 'pos' ? '+=' : '-=') : (motion == 'pos' ? '-=' : '+=')) + distance; // Animate el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { if(mode == 'hide') el.hide(); // Hide $.effects.restore(el, props); $.effects.removeWrapper(el); // Restore if(o.callback) o.callback.apply(this, arguments); // Callback el.dequeue(); }}); }); }; })(jQuery);
01cms
01cms/branches/1.0/public/common/js/effects.drop.js
JavaScript
asf20
1,628
/* * jQuery UI Effects Highlight 1.7.2 * * Copyright (c) 2009 AUTHORS.txt (http://jqueryui.com/about) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * http://docs.jquery.com/UI/Effects/Highlight * * Depends: * effects.core.js */ (function($) { $.effects.highlight = function(o) { return this.queue(function() { // Create element var el = $(this), props = ['backgroundImage','backgroundColor','opacity']; // Set options var mode = $.effects.setMode(el, o.options.mode || 'show'); // Set Mode var color = o.options.color || "#ffff99"; // Default highlight color var oldColor = el.css("backgroundColor"); // Adjust $.effects.save(el, props); el.show(); // Save & Show el.css({backgroundImage: 'none', backgroundColor: color}); // Shift // Animation var animation = {backgroundColor: oldColor }; if (mode == "hide") animation['opacity'] = 0; // Animate el.animate(animation, { queue: false, duration: o.duration, easing: o.options.easing, complete: function() { if(mode == "hide") el.hide(); $.effects.restore(el, props); if (mode == "show" && $.browser.msie) this.style.removeAttribute('filter'); if(o.callback) o.callback.apply(this, arguments); el.dequeue(); }}); }); }; })(jQuery);
01cms
01cms/branches/1.0/public/common/js/effects.highlight.js
JavaScript
asf20
1,290