/protected/test.txt
Plain Text | 13930 lines | 13545 code | 385 blank | 0 comment | 0 complexity | 29c971761f8a835f00acf162c4fa918b MD5 | raw file
- /*global php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * Yii is a helper class serving common framework functionalities.
- *
- * It encapsulates {@link YiiBase} which provides the actual implementation.
- * By writing your own Yii class, you can customize some functionalities of YiiBase.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: yii.js 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.YiiBase
- */
- var YII_DEBUG = true, YII_TRACE_LEVEL = 3, YII_BEGIN_TIME = new Date().getTime() / 1000, Yii = /** @lends Yii.prototype */{
- /**
- * @property {Array} class map used by the Yii autoloading mechanism.
- * The array keys are the class names and the array values are the corresponding class file paths.
- * @since 1.1.5
- */
- classMap: {},
- _aliases: {},
- _imports: {},
- _includePaths: {},
- _app: null,
- _logger: null,
- /**
- * @property {Array} class map for core Yii classes.
- * NOTE, DO NOT MODIFY THIS ARRAY MANUALLY. IF YOU CHANGE OR ADD SOME CORE CLASSES,
- * PLEASE RUN 'build autoload' COMMAND TO UPDATE THIS ARRAY.
- */
- _coreClasses: {'CApplication':'/base/CApplication.js','CApplicationComponent':'/base/CApplicationComponent.js','CBehavior':'/base/CBehavior.js','CComponent':'/base/CComponent.js','CErrorEvent':'/base/CErrorEvent.js','CErrorHandler':'/base/CErrorHandler.js','CException':'/base/CException.js','CExceptionEvent':'/base/CExceptionEvent.js','CHttpException':'/base/CHttpException.js','CModel':'/base/CModel.js','CModelBehavior':'/base/CModelBehavior.js','CModelEvent':'/base/CModelEvent.js','CModule':'/base/CModule.js','CSecurityManager':'/base/CSecurityManager.js','CStatePersister':'/base/CStatePersister.js','CApcCache':'/caching/CApcCache.js','CCache':'/caching/CCache.js','CDbCache':'/caching/CDbCache.js','CDummyCache':'/caching/CDummyCache.js','CEAcceleratorCache':'/caching/CEAcceleratorCache.js','CFileCache':'/caching/CFileCache.js','CMemCache':'/caching/CMemCache.js','CWinCache':'/caching/CWinCache.js','CXCache':'/caching/CXCache.js','CZendDataCache':'/caching/CZendDataCache.js','CCacheDependency':'/caching/dependencies/CCacheDependency.js','CChainedCacheDependency':'/caching/dependencies/CChainedCacheDependency.js','CDbCacheDependency':'/caching/dependencies/CDbCacheDependency.js','CDirectoryCacheDependency':'/caching/dependencies/CDirectoryCacheDependency.js','CExpressionDependency':'/caching/dependencies/CExpressionDependency.js','CFileCacheDependency':'/caching/dependencies/CFileCacheDependency.js','CGlobalStateCacheDependency':'/caching/dependencies/CGlobalStateCacheDependency.js','CAttributeCollection':'/collections/CAttributeCollection.js','CConfiguration':'/collections/CConfiguration.js','CList':'/collections/CList.js','CListIterator':'/collections/CListIterator.js','CMap':'/collections/CMap.js','CMapIterator':'/collections/CMapIterator.js','CQueue':'/collections/CQueue.js','CQueueIterator':'/collections/CQueueIterator.js','CStack':'/collections/CStack.js','CStackIterator':'/collections/CStackIterator.js','CTypedList':'/collections/CTypedList.js','CTypedMap':'/collections/CTypedMap.js','CConsoleApplication':'/console/CConsoleApplication.js','CConsoleCommand':'/console/CConsoleCommand.js','CConsoleCommandRunner':'/console/CConsoleCommandRunner.js','CHelpCommand':'/console/CHelpCommand.js','CDbCommand':'/db/CDbCommand.js','CDbConnection':'/db/CDbConnection.js','CDbDataReader':'/db/CDbDataReader.js','CDbException':'/db/CDbException.js','CDbMigration':'/db/CDbMigration.js','CDbTransaction':'/db/CDbTransaction.js','CActiveFinder':'/db/ar/CActiveFinder.js','CActiveRecord':'/db/ar/CActiveRecord.js','CActiveRecordBehavior':'/db/ar/CActiveRecordBehavior.js','CDbColumnSchema':'/db/schema/CDbColumnSchema.js','CDbCommandBuilder':'/db/schema/CDbCommandBuilder.js','CDbCriteria':'/db/schema/CDbCriteria.js','CDbExpression':'/db/schema/CDbExpression.js','CDbSchema':'/db/schema/CDbSchema.js','CDbTableSchema':'/db/schema/CDbTableSchema.js','CMssqlColumnSchema':'/db/schema/mssql/CMssqlColumnSchema.js','CMssqlCommandBuilder':'/db/schema/mssql/CMssqlCommandBuilder.js','CMssqlPdoAdapter':'/db/schema/mssql/CMssqlPdoAdapter.js','CMssqlSchema':'/db/schema/mssql/CMssqlSchema.js','CMssqlTableSchema':'/db/schema/mssql/CMssqlTableSchema.js','CMysqlColumnSchema':'/db/schema/mysql/CMysqlColumnSchema.js','CMysqlSchema':'/db/schema/mysql/CMysqlSchema.js','CMysqlTableSchema':'/db/schema/mysql/CMysqlTableSchema.js','COciColumnSchema':'/db/schema/oci/COciColumnSchema.js','COciCommandBuilder':'/db/schema/oci/COciCommandBuilder.js','COciSchema':'/db/schema/oci/COciSchema.js','COciTableSchema':'/db/schema/oci/COciTableSchema.js','CPgsqlColumnSchema':'/db/schema/pgsql/CPgsqlColumnSchema.js','CPgsqlSchema':'/db/schema/pgsql/CPgsqlSchema.js','CPgsqlTableSchema':'/db/schema/pgsql/CPgsqlTableSchema.js','CSqliteColumnSchema':'/db/schema/sqlite/CSqliteColumnSchema.js','CSqliteCommandBuilder':'/db/schema/sqlite/CSqliteCommandBuilder.js','CSqliteSchema':'/db/schema/sqlite/CSqliteSchema.js','CChoiceFormat':'/i18n/CChoiceFormat.js','CDateFormatter':'/i18n/CDateFormatter.js','CDbMessageSource':'/i18n/CDbMessageSource.js','CGettextMessageSource':'/i18n/CGettextMessageSource.js','CLocale':'/i18n/CLocale.js','CMessageSource':'/i18n/CMessageSource.js','CNumberFormatter':'/i18n/CNumberFormatter.js','CPhpMessageSource':'/i18n/CPhpMessageSource.js','CGettextFile':'/i18n/gettext/CGettextFile.js','CGettextMoFile':'/i18n/gettext/CGettextMoFile.js','CGettextPoFile':'/i18n/gettext/CGettextPoFile.js','CDbLogRoute':'/logging/CDbLogRoute.js','CEmailLogRoute':'/logging/CEmailLogRoute.js','CFileLogRoute':'/logging/CFileLogRoute.js','CLogFilter':'/logging/CLogFilter.js','CLogRoute':'/logging/CLogRoute.js','CLogRouter':'/logging/CLogRouter.js','CLogger':'/logging/CLogger.js','CProfileLogRoute':'/logging/CProfileLogRoute.js','CWebLogRoute':'/logging/CWebLogRoute.js','CDateTimeParser':'/utils/CDateTimeParser.js','CFileHelper':'/utils/CFileHelper.js','CFormatter':'/utils/CFormatter.js','CMarkdownParser':'/utils/CMarkdownParser.js','CPropertyValue':'/utils/CPropertyValue.js','CTimestamp':'/utils/CTimestamp.js','CVarDumper':'/utils/CVarDumper.js','CBooleanValidator':'/validators/CBooleanValidator.js','CCaptchaValidator':'/validators/CCaptchaValidator.js','CCompareValidator':'/validators/CCompareValidator.js','CDateValidator':'/validators/CDateValidator.js','CDefaultValueValidator':'/validators/CDefaultValueValidator.js','CEmailValidator':'/validators/CEmailValidator.js','CExistValidator':'/validators/CExistValidator.js','CFileValidator':'/validators/CFileValidator.js','CFilterValidator':'/validators/CFilterValidator.js','CInlineValidator':'/validators/CInlineValidator.js','CNumberValidator':'/validators/CNumberValidator.js','CRangeValidator':'/validators/CRangeValidator.js','CRegularExpressionValidator':'/validators/CRegularExpressionValidator.js','CRequiredValidator':'/validators/CRequiredValidator.js','CSafeValidator':'/validators/CSafeValidator.js','CStringValidator':'/validators/CStringValidator.js','CTypeValidator':'/validators/CTypeValidator.js','CUniqueValidator':'/validators/CUniqueValidator.js','CUnsafeValidator':'/validators/CUnsafeValidator.js','CUrlValidator':'/validators/CUrlValidator.js','CValidator':'/validators/CValidator.js','CActiveDataProvider':'/web/CActiveDataProvider.js','CArrayDataProvider':'/web/CArrayDataProvider.js','CAssetManager':'/web/CAssetManager.js','CBaseController':'/web/CBaseController.js','CCacheHttpSession':'/web/CCacheHttpSession.js','CClientScript':'/web/CClientScript.js','CController':'/web/CController.js','CDataProvider':'/web/CDataProvider.js','CDbHttpSession':'/web/CDbHttpSession.js','CExtController':'/web/CExtController.js','CFormModel':'/web/CFormModel.js','CHttpCookie':'/web/CHttpCookie.js','CHttpRequest':'/web/CHttpRequest.js','CHttpSession':'/web/CHttpSession.js','CHttpSessionIterator':'/web/CHttpSessionIterator.js','COutputEvent':'/web/COutputEvent.js','CPagination':'/web/CPagination.js','CSort':'/web/CSort.js','CSqlDataProvider':'/web/CSqlDataProvider.js','CTheme':'/web/CTheme.js','CThemeManager':'/web/CThemeManager.js','CUploadedFile':'/web/CUploadedFile.js','CUrlManager':'/web/CUrlManager.js','CWebApplication':'/web/CWebApplication.js','CWebModule':'/web/CWebModule.js','CWidgetFactory':'/web/CWidgetFactory.js','CAction':'/web/actions/CAction.js','CInlineAction':'/web/actions/CInlineAction.js','CViewAction':'/web/actions/CViewAction.js','CAccessControlFilter':'/web/auth/CAccessControlFilter.js','CAuthAssignment':'/web/auth/CAuthAssignment.js','CAuthItem':'/web/auth/CAuthItem.js','CAuthManager':'/web/auth/CAuthManager.js','CBaseUserIdentity':'/web/auth/CBaseUserIdentity.js','CDbAuthManager':'/web/auth/CDbAuthManager.js','CPhpAuthManager':'/web/auth/CPhpAuthManager.js','CUserIdentity':'/web/auth/CUserIdentity.js','CWebUser':'/web/auth/CWebUser.js','CFilter':'/web/filters/CFilter.js','CFilterChain':'/web/filters/CFilterChain.js','CInlineFilter':'/web/filters/CInlineFilter.js','CForm':'/web/form/CForm.js','CFormButtonElement':'/web/form/CFormButtonElement.js','CFormElement':'/web/form/CFormElement.js','CFormElementCollection':'/web/form/CFormElementCollection.js','CFormInputElement':'/web/form/CFormInputElement.js','CFormStringElement':'/web/form/CFormStringElement.js','CGoogleApi':'/web/helpers/CGoogleApi.js','CHtml':'/web/helpers/CHtml.js','CJSON':'/web/helpers/CJSON.js','CJavaScript':'/web/helpers/CJavaScript.js','CPradoViewRenderer':'/web/renderers/CPradoViewRenderer.js','CViewRenderer':'/web/renderers/CViewRenderer.js','CWebService':'/web/services/CWebService.js','CWebServiceAction':'/web/services/CWebServiceAction.js','CWsdlGenerator':'/web/services/CWsdlGenerator.js','CActiveForm':'/web/widgets/CActiveForm.js','CAutoComplete':'/web/widgets/CAutoComplete.js','CClipWidget':'/web/widgets/CClipWidget.js','CContentDecorator':'/web/widgets/CContentDecorator.js','CFilterWidget':'/web/widgets/CFilterWidget.js','CFlexWidget':'/web/widgets/CFlexWidget.js','CHtmlPurifier':'/web/widgets/CHtmlPurifier.js','CInputWidget':'/web/widgets/CInputWidget.js','CMarkdown':'/web/widgets/CMarkdown.js','CMaskedTextField':'/web/widgets/CMaskedTextField.js','CMultiFileUpload':'/web/widgets/CMultiFileUpload.js','COutputCache':'/web/widgets/COutputCache.js','COutputProcessor':'/web/widgets/COutputProcessor.js','CStarRating':'/web/widgets/CStarRating.js','CTabView':'/web/widgets/CTabView.js','CTextHighlighter':'/web/widgets/CTextHighlighter.js','CTreeView':'/web/widgets/CTreeView.js','CWidget':'/web/widgets/CWidget.js','CCaptcha':'/web/widgets/captcha/CCaptcha.js','CCaptchaAction':'/web/widgets/captcha/CCaptchaAction.js','CBasePager':'/web/widgets/pagers/CBasePager.js','CLinkPager':'/web/widgets/pagers/CLinkPager.js','CListPager':'/web/widgets/pagers/CListPager.js'},
- /**
- * Augments a class with properties from another class
- * @param {Object} receivingClass The class that should be augmented
- * @param {Object} givingClass The class that donates the properties
- */
- augment: function (receivingClass, givingClass) {
- var methodName;
- for (methodName in givingClass.prototype) {
- if(!receivingClass.prototype[methodName]) {
- receivingClass.prototype[methodName] = givingClass.prototype[methodName];
- }
- }
- },
-
- /**
- * @returns {String} the version of Yii framework
- */
- getVersion: function () {
- return '1.1.8-dev';
- },
- /**
- * Creates a Web application instance.
- * @param {Mixed} config application configuration.
- * If a string, it is treated as the path of the file that contains the configuration;
- * If an array, it is the actual configuration information.
- * Please make sure you specify the {@link CApplication::basePath basePath} property in the configuration,
- * which should point to the directory containing all application logic, template and data.
- * If not, the directory will be defaulted to 'protected'.
- */
- createWebApplication: function (config) {
- if (config === undefined) {
- config = null;
- }
- return Yii.createApplication('CWebApplication',config);
- },
- /**
- * Creates a console application instance.
- * @param {Mixed} config application configuration.
- * If a string, it is treated as the path of the file that contains the configuration;
- * If an array, it is the actual configuration information.
- * Please make sure you specify the {@link CApplication::basePath basePath} property in the configuration,
- * which should point to the directory containing all application logic, template and data.
- * If not, the directory will be defaulted to 'protected'.
- */
- createConsoleApplication: function (config) {
- if (config === undefined) {
- config = null;
- }
- return Yii.createApplication('CConsoleApplication',config);
- },
- /**
- * Creates an application of the specified class.
- * @param {String} classVar the application class name
- * @param {Mixed} config application configuration. This parameter will be passed as the parameter
- * to the constructor of the application class.
- * @returns {Mixed} the application instance
- * @since 1.0.10
- */
- createApplication: function (classVar, config) {
- if (config === undefined) {
- config = null;
- }
-
- return new Yii[classVar](config);
-
- },
- /**
- * Returns the application singleton, null if the singleton has not been created yet.
- * @returns {Yii.CApplication} the application singleton, null if the singleton has not been created yet.
- */
- app: function () {
- return Yii._app;
- },
- /**
- * Stores the application instance in the class static member.
- * This method helps implement a singleton pattern for CApplication.
- * Repeated invocation of this method or the CApplication constructor
- * will cause the throw of an exception.
- * To retrieve the application instance, use {@link app()}.
- * @param {Yii.CApplication} app the application instance. If this is null, the existing
- * application singleton will be removed.
- * @throws {Yii.CException} if multiple application instances are registered.
- */
- setApplication: function (app) {
- var _app;
- if(Yii._app===null || app===null) {
- Yii._app=app;
- }
- else {
- throw new Yii.CException(Yii.t('yii','Yii application can only be created once.'));
- }
- },
- /**
- * @returns {String} the path of the framework
- */
- getFrameworkPath: function () {
- return YII_PATH;
- },
- /**
- * Creates an object and initializes it based on the given configuration.
- *
- * The specified configuration can be either a string or an array.
- * If the former, the string is treated as the object type which can
- * be either the class name or {@link Yii::getPathOfAlias class path alias}.
- * If the latter, the 'class' element is treated as the object type,
- * and the rest name-value pairs in the array are used to initialize
- * the corresponding object properties.
- *
- * Any additional parameters passed to this method will be
- * passed to the constructor of the object being created.
- *
- * NOTE: the array-typed configuration has been supported since version 1.0.1.
- *
- * @param {Mixed} config the configuration. It can be either a string or an array.
- * @returns {Mixed} the created object
- * @throws {Yii.CException} if the configuration does not have a 'class' element.
- */
- createComponent: function (config) {
- var type, n, args, object, classVar, key, value;
-
- if(typeof(config) === 'string') {
- type=config;
- config=[];
- }
- else if(config['class'] !== undefined) {
- type=config['class'];
- delete config['class'];
- }
- else {
- throw new Yii.CException(Yii.t('yii','Object configuration must be an array containing a "class" element.'));
- }
- if(!Yii[type]) {
- type=Yii.imports(type,true);
- }
- if((n=arguments.length)>1) {
- args=arguments;
- if(n===2) {
- object=new Yii[type](args[1]);
- }
- else if(n===3) {
- object=new Yii[type](args[1],args[2]);
- }
- else if(n===4) {
- object=new Yii[type](args[1],args[2],args[3]);
- }
- else if(n===4) {
- object=new Yii[type](args[1],args[2],args[3]);
- }
- else if(n===5) {
- object=new Yii[type](args[1],args[2],args[3],args[4]);
- }
- }
- else {
- object=new Yii[type]();
- }
-
- for (key in config) {
- if (config.hasOwnProperty(key)) {
-
- value = config[key];
- object.set(key,value);
- }
- }
-
- return object;
- },
- /**
- * Imports a class or a directory.
- *
- * Importing a class is like including the corresponding class file.
- * The main difference is that importing a class is much lighter because it only
- * includes the class file when the class is referenced the first time.
- *
- * Importing a directory is equivalent to adding a directory into the PHP include path.
- * If multiple directories are imported, the directories imported later will take
- * precedence in class file searching (i.e., they are added to the front of the PHP include path).
- *
- * Path aliases are used to import a class or directory. For example,
- * <ul>
- * <li><code>application.components.GoogleMap</code>: import the <code>GoogleMap</code> class.</li>
- * <li><code>application.components.*</code>: import the <code>components</code> directory.</li>
- * </ul>
- *
- * The same path alias can be imported multiple times, but only the first time is effective.
- * Importing a directory does not import any of its subdirectories.
- *
- * Starting from version 1.1.5, this method can also be used to import a class in namespace format
- * (available for PHP 5.3 or above only). It is similar to importing a class in path alias format,
- * except that the dot separator is replaced by the backslash separator. For example, importing
- * <code>application\components\GoogleMap</code> is similar to importing <code>application.components.GoogleMap</code>.
- * The difference is that the former class is using qualified name, while the latter unqualified.
- *
- * Note, importing a class in namespace format requires that the namespace is corresponding to
- * a valid path alias if we replace the backslash characters with dot characters.
- * For example, the namespace <code>application\components</code> must correspond to a valid
- * path alias <code>application.components</code>.
- *
- * @param {String} alias path alias to be imported
- * @param {Boolean} forceInclude whether to include the class file immediately. If false, the class file
- * will be included only when the class is being used. This parameter is used only when
- * the path alias refers to a class.
- * @returns {String} the class name or the directory that this alias refers to
- * @throws {Yii.CException} if the alias is invalid
- */
- imports: function (alias, forceInclude) {
- var result, _imports, pos, namespace, path, classFile, classMap, className, isClass, _includePaths;
- if (forceInclude === undefined) {
- forceInclude = true;
- }
- if(Yii._imports[alias] !== undefined) { // previously imported
-
- return Yii._imports[alias];
- }
-
- if(Yii[alias] !== undefined) {
- return (Yii._imports[alias]=alias);
- }
- if ((pos = alias.indexOf("/")) !== -1) {
- className = String(alias.split("/").pop());
-
- if (className.slice(-3) == ".js") {
-
- className = className.slice(0,-3);
- }
-
- if (Yii[className] !== undefined) {
- return (Yii._imports[alias] = className);
- }
- Yii.include(alias,!forceInclude);
- Yii.classMap[className] = alias;
- Yii._imports[alias] = className;
-
- return className;
- }
- if((pos=alias.indexOf('.'))===-1) { // a simple class name
- result = Yii.autoload(alias, !forceInclude);
- if(forceInclude && !result) {
- throw new Yii.CException(Yii.t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
- {'{alias}':alias}));
- }
- Yii._imports[alias]=alias;
- return alias;
- }
- className=String(alias.split(".").pop());
-
- isClass=className!=='*';
- if (!isClass) {
- throw new Yii.CException("YiiJS does not support importing directories");
- }
- if(Yii[className] !== undefined) {
- return (Yii._imports[alias]=className);
- }
-
- else if((path=Yii.getPathOfAlias(alias))!==false) {
- Yii.include(path + ".js",!forceInclude);
- Yii.classMap[className]=path+'.js';
- return className;
- }
- else {
- throw new Yii.CException(Yii.t('yii','Alias "{alias}" is invalid. Make sure it points to an existing directory or file.',
- {'{alias}':alias}));
- }
- },
- /**
- * Translates an alias into a file path.
- * Note, this method does not ensure the existence of the resulting file path.
- * It only checks if the root alias is valid or not.
- * @param {String} alias alias (e.g. system.web.CController)
- * @returns {Mixed} file path corresponding to the alias, false if the alias is invalid.
- */
- getPathOfAlias: function (alias) {
- var _aliases, pos, rootAlias, _app;
- if(Yii._aliases[alias] !== undefined) {
- return Yii._aliases[alias];
- }
- else if((pos=php.strpos(alias,'.'))!==false) {
- rootAlias=alias.slice(0, pos);
- if(Yii._aliases[rootAlias] !== undefined) {
- return (Yii._aliases[alias]=php.rtrim(Yii._aliases[rootAlias]+'/'+php.str_replace('.','/',alias.slice(pos+1)),'*'+'/'));
- }
- else if(Yii._app !== null && Yii._app instanceof Yii.CWebApplication){
- if(Yii._app.findModule(rootAlias)!==null) {
- return Yii.getPathOfAlias(alias);
- }
- }
- }
- return false;
- },
- /**
- * Create a path alias.
- * Note, this method neither checks the existence of the path nor normalizes the path.
- * @param {String} alias alias to the path
- * @param {String} path the path corresponding to the alias. If this is null, the corresponding
- * path alias will be removed.
- */
- setPathOfAlias: function (alias, path) {
- var _aliases;
- if(php.empty(path)) {
- delete Yii._aliases[alias];
- }
- else {
- Yii._aliases[alias]=php.rtrim(path,'\\/');
- }
- },
- /**
- * Class autoload loader.
- * @param {String} className class name
- * @param {Boolean} async Whether to load this class
- * via an asynchronous AJAX request, otherwise a blocking request is used, defaults to false.
- * @returns {Boolean} whether the class has been loaded successfully
- */
- autoload: function (className, async) {
- var _coreClasses, classMap, namespace, path, result;
- if (async === undefined) {
- async = true;
- }
-
- if(Yii._coreClasses[className] !== undefined) {
- if (Yii[className] !== undefined) {
- return true;
- }
-
- result = Yii.include(YII_PATH+Yii._coreClasses[className], async);
- if (!async) {
- return result;
- }
- }
- else if(Yii.classMap[className] !== undefined) {
- if (Yii[className] !== undefined) {
- return true;
- }
- result = Yii.include(Yii.classMap[className], async);
- if (!async) {
- return result;
- }
- }
- else {
- return Yii[className] !== undefined;
- }
- return true;
- },
-
- /**
- * Includes a remote file, this will be evaled!
- * @param {String} url The URL to load the file from
- * @param {Boolean} async Whether to perform an asynchronous request or not, defaults to true.
- * @param {Function} callback The callback to execute after the included file is evaled
- * @returns {Mixed} either the jQuery ajax request if this is async, or
- * if this is a blocking request returns the content or false depending on whether
- * it succeeded or not.
- */
- include: function (url, async, callback) {
- var options = {}, request;
- if (async === undefined) {
- async = true;
- }
- if (callback === undefined) {
- callback = function () {};
- }
- if(Yii._includePaths[url] !== undefined) { // previously imported
- return Yii._includePaths[url];
- }
- options.url = url;
- options.async = async;
- options.cache = false;
- if (async) {
- options.success = function (res) {
- Yii._includePaths[url] = eval(res);
- callback(Yii._includePaths[url]);
- };
- options.error = function () {
- throw new Yii.CHttpException(404, Yii.t("system", "No such file"));
- };
- return jQuery.ajax(options);
- }
- else {
-
- request = jQuery.ajax(options);
- if (request.status > 399) {
- return false;
- }
- Yii._includePaths[url] = eval(request.responseText);
- callback(Yii._includePaths[url]);
- return Yii._includePaths[url];
-
-
- }
- },
-
-
- /**
- * Writes a trace message.
- * This method will only log a message when the application is in debug mode.
- * @param {String} msg message to be logged
- * @param {String} category category of the message
- * @see log
- */
- trace: function (msg, category) {
- if (category === undefined) {
- category = 'application';
- }
- if(YII_DEBUG) {
- Yii.log(msg,Yii.CLogger.prototype.LEVEL_TRACE,category);
- }
- },
- /**
- * Logs a message.
- * Messages logged by this method may be retrieved via {@link CLogger::getLogs}
- * and may be recorded in different media, such as file, email, database, using
- * {@link CLogRouter}.
- * @param {String} msg message to be logged
- * @param {String} level level of the message (e.g. 'trace', 'warning', 'error'). It is case-insensitive.
- * @param {String} category category of the message (e.g. 'system.web'). It is case-insensitive.
- */
- log: function (msg, level, category) {
- var _logger, traces, count, i, limit, trace, cmd;
- if (level === undefined) {
- level = 'info';
- }
- if (category === undefined) {
- category = 'application';
- }
- if(Yii._logger===null) {
- Yii._logger=new Yii.CLogger();
- }
- if(window['console'] !== undefined && YII_DEBUG && YII_TRACE_LEVEL>0 && level!==Yii.CLogger.prototype.LEVEL_PROFILE) {
- cmd = "log";
- if (level === Yii.CLogger.prototype.LEVEL_ERROR) {
- cmd = "error";
- }
- else if (level === Yii.CLogger.prototype.LEVEL_WARNING) {
- cmd = "warn";
- }
- console[cmd](level + "\t" + php.str_pad(category,30," ") + "\t" + msg);
- }
- Yii._logger.log(msg,level,category);
- },
- /**
- * Marks the begin of a code block for profiling.
- * This has to be matched with a call to {@link endProfile()} with the same token.
- * The begin- and end- calls must also be properly nested, e.g.,
- * <pre>
- * Yii.beginProfile('block1');
- * Yii.beginProfile('block2');
- * Yii.endProfile('block2');
- * Yii.endProfile('block1');
- * </pre>
- * The following sequence is not valid:
- * <pre>
- * Yii.beginProfile('block1');
- * Yii.beginProfile('block2');
- * Yii.endProfile('block1');
- * Yii.endProfile('block2');
- * </pre>
- * @param {String} token token for the code block
- * @param {String} category the category of this log message
- * @see endProfile
- */
- beginProfile: function (token, category) {
- if (category === undefined) {
- category = 'application';
- }
- Yii.log('begin:'+token,Yii.CLogger.prototype.LEVEL_PROFILE,category);
- },
- /**
- * Marks the end of a code block for profiling.
- * This has to be matched with a previous call to {@link beginProfile()} with the same token.
- * @param {String} token token for the code block
- * @param {String} category the category of this log message
- * @see beginProfile
- */
- endProfile: function (token, category) {
- if (category === undefined) {
- category = 'application';
- }
- Yii.log('end:'+token,Yii.CLogger.prototype.LEVEL_PROFILE,category);
- },
- /**
- * @returns {Yii.CLogger} message logger
- */
- getLogger: function () {
- var _logger;
- if(Yii._logger!==null) {
- return Yii._logger;
- }
- else {
- return (Yii._logger=new Yii.CLogger);
- }
- },
- /**
- * Returns a string that can be displayed on your Web page showing Powered-by-Yii information
- * @returns {String} a string that can be displayed on your Web page showing Powered-by-Yii information
- */
- powered: function () {
- return 'Powered by <a href="http://www.yiiframework.com/" rel="external">Yii Framework</a>.';
- },
- /**
- * Translates a message to the specified language.
- * Starting from version 1.0.2, this method supports choice format (see {@link CChoiceFormat}),
- * i.e., the message returned will be chosen from a few candidates according to the given
- * number value. This feature is mainly used to solve plural format issue in case
- * a message has different plural forms in some languages.
- * @param {String} category message category. Please use only word letters. Note, category 'yii' is
- * reserved for Yii framework core code use. See {@link CPhpMessageSource} for
- * more interpretation about message category.
- * @param {String} message the original message
- * @param {Array} params parameters to be applied to the message using <code>strtr</code>.
- * Starting from version 1.0.2, the first parameter can be a number without key.
- * And in this case, the method will call {@link CChoiceFormat::format} to choose
- * an appropriate message translation.
- * Starting from version 1.1.6 you can pass parameter for {@link CChoiceFormat::format}
- * or plural forms format without wrapping it with array.
- * @param {String} source which message source application component to use.
- * Defaults to null, meaning using 'coreMessages' for messages belonging to
- * the 'yii' category and using 'messages' for the rest messages.
- * @param {String} language the target language. If null (default), the {@link CApplication::getLanguage application language} will be used.
- * This parameter has been available since version 1.0.3.
- * @returns {String} the translated message
- * @see CMessageSource
- */
- t: function (category, message, params, source, language) {
- var _app, chunks, expressions, n, i;
- if (params === undefined) {
- params = {};
- }
- if (source === undefined) {
- source = null;
- }
- if (language === undefined) {
- language = null;
- }
-
-
- if(Yii._app!==null) {
- if(source===null) {
- source=(category==='yii'||category==='zii')?'coreMessages':'messages';
- }
- if((source=Yii._app.getComponent(source))!==null && source !== undefined) {
- message=source.translate(category,message,language);
- }
- }
-
- if(params==={} || params === []) {
- return message;
- }
-
- if(params[0] !== undefined) {
- // number choice
- if(php.strpos(message,'|')!==false) {
- if(php.strpos(message,'#')===false) {
- chunks=message.split('|');
- expressions=Yii._app.getLocale(language).getPluralRules();
- n=php.min(php.count(chunks),php.count(expressions));
- if(n) {
- for(i=0;i<n;i++) {
- chunks[i]=expressions[i]+'#'+chunks[i];
- }
- message=chunks.join('|');
- }
- }
- message=Yii.CChoiceFormat.format(message,params[0]);
- }
- if(params['{n}'] === undefined) {
- params['{n}']=params[0];
- }
- delete params[0];
- }
- if (params !== {}) {
- return php.strtr(message,params);
- }
- return message;
- },
- /**
- * Registers a new class autoloader.
- * The new autoloader will be placed before {@link autoload} and after
- * any other existing autoloaders.
- * @param {Function} callback a valid PHP callback (function name or array($className,$methodName)).
- * @since 1.0.10
- */
- registerAutoloader: function (callback) {
-
- },
- /**
- * Removes JSDoc comments from a string
- * TODO: move this somewhere else
- * @param {String} str the string to strip
- * @returns {String} the stripped string
- */
- removeComments: function (str) {
-
- var uid = '_' + (new Date()),
- primatives = [],
- primIndex = 0;
-
- return (
- str
- .replace(/(['"])(\\\1|.)+?\1/g, function(match){
- primatives[primIndex] = match;
- return (uid + '') + primIndex++;
- })
- .replace(/([^\/])(\/(?!\*|\/)(\\\/|.)+?\/[gim]{0,3})/g, function(match, $1, $2){
- primatives[primIndex] = $2;
- return $1 + (uid + '') + primIndex++;
- })
- .replace(/\/\/.*?\/?\*.+?(?=\n|\r|$)|\/\*[\s\S]*?\/\/[\s\S]*?\*\//g, '')
- .replace(/\/\/.+?(?=\n|\r|$)|\/\*[\s\S]+?\*\//g, '')
- .replace(RegExp('\\/\\*[\\s\\S]+' + uid + '\\d+', 'g'), '')
- .replace(RegExp(uid + '(\\d+)', 'g'), function(match, n){
- return primatives[n];
- })
- );
- },
- /**
- * Similar to PHP's preg_match_all
- * @param {RegExp} regex The regular expression to match against
- * @param {String} haystack The string to perform the regex on
- * @returns {Array} an array of matches
- */
- matchAll: function (regex, haystack) {
- var matches = [], i, match;
- match = regex.exec(haystack);
-
- while (match !== null) {
- matches.push(match);
- match = regex.exec(haystack);
- }
- return matches;
- },
- /**
- * Extends a class
- */
- extend: function (childClass, parentClass, properties) {
- childClass.prototype = new Yii[parentClass](false);
- childClass.prototype.constructor = childClass;
- if (properties !== undefined) {
- Yii.forEach(properties, function(name, value) {
- childClass.prototype[name] = value;
- });
- }
- },
-
- /**
- * Implements foreach in JavaScript
- * @param {Mixed} itemList a list of items to iterate through
- * @param {Function} callback The callback function, it will recieve 2 parameters, key and value
- * if the callback returns false, the loop will break.
- */
- forEach: function (itemList, callback) {
- var i, limit;
- if (typeof itemList === "function") {
- return Yii.forEach(itemList(), callback);
- }
- if (Object.prototype.toString.call(itemList) === '[object Array]' || itemList instanceof Yii.CList || itemList instanceof Yii.CStack) {
- limit = itemList.length;
- for (i = 0; i < limit; i++) {
- if (i === "forEach") {
- continue;
- }
- else if (callback(i, itemList[i]) === false) {
- break;
- }
- }
- }
- else {
- for (i in itemList) {
- if (itemList.hasOwnProperty(i)) {
- if (i === "forEach") {
- continue;
- }
- else if (callback(i, itemList[i]) === false) {
- break;
- }
- }
- }
- }
- return itemList;
- },
-
- /**
- * Filter an array of items
- */
- filter: function (items, block) {
- var values = [];
- var thisp = arguments[1];
- for (var i = 0; i < items.length; i++)
- if (block.call(thisp, items[i]))
- values.push(items[i]);
- return values;
- }
- };
- /**
- * A shortcut to application properties.
- * Supports virtual getters and setters, e.g:
- * <pre>
- * $app("securityManager.validationKey") === Yii.app().getSecurityManager().getValidationKey();
- * </pre>
- */
- var $app = function(selector, setVal) {
- var stack, parts, i, limit, item, getter, last;
- if (selector === undefined || php.trim(selector).length === 0) {
- return Yii.app();
- }
- parts = selector.split(".");
-
- limit = parts.length;
- last = limit - 1;
- stack = Yii.app();
- for (i = 0; i < limit; i++) {
-
- if (stack instanceof Yii.CComponent) {
- if (setVal !== undefined) {
- return stack.set(parts.join("."),setVal);
- }
- return stack.get(parts.join("."));
- }
- item = parts.shift();
- if (i === last && setVal !== undefined) {
- if (stack[item] !== undefined) {
- stack[item] = setVal;
- return setVal;
- }
- else if (stack.get !== undefined) {
- stack = stack.set.call(stack, item, setVal);
- return setVal;
- }
- else {
- throw new Yii.CException("No such property: " + item);
- }
- }
- else {
- if (stack[item] !== undefined) {
- stack = stack[item];
- }
- else if (stack.get !== undefined) {
- stack = stack.get.call(stack, item);
- }
- else {
- throw new Yii.CException("No such property: " + item);
- }
- }
- }
-
- return stack;
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CComponent is the base class for all components.
- *
- * CComponent implements the protocol of defining, using properties and events.
- *
- * A property is defined by a getter method, and/or a setter method.
- * Properties can be accessed in the way like accessing normal object members.
- * Reading or writing a property will cause the invocation of the corresponding
- * getter or setter method, e.g
- * <pre>
- * a=component.text; // equivalent to $a=$component->getText();
- * component.text='abc'; // equivalent to $component->setText('abc');
- * </pre>
- * The signatures of getter and setter methods are as follows,
- * <pre>
- * // getter, defines a readable property 'text'
- * public function getText() { +++ }
- * // setter, defines a writable property 'text' with $value to be set to the property
- * public function setText(value) { +++ }
- * </pre>
- *
- * An event is defined by the presence of a method whose name starts with 'on'.
- * The event name is the method name. When an event is raised, functions
- * (called event handlers) attached to the event will be invoked automatically.
- *
- * An event can be raised by calling {@link raiseEvent} method, upon which
- * the attached event handlers will be invoked automatically in the order they
- * are attached to the event. Event handlers must have the following signature,
- * <pre>
- * function eventHandler(event) { +++ }
- * </pre>
- * where $event includes parameters associated with the event.
- *
- * To attach an event handler to an event, see {@link attachEventHandler}.
- * You can also use the following syntax:
- * <pre>
- * component.onClick=callback; // or $component->onClick->add($callback);
- * </pre>
- * where $callback refers to a valid PHP callback. Below we show some callback examples:
- * <pre>
- * 'handleOnClick' // handleOnClick() is a global function
- * [object,'handleOnClick'] // using $object->handleOnClick()
- * ['Page','handleOnClick'] // using Page::handleOnClick()
- * </pre>
- *
- * To raise an event, use {@link raiseEvent}. The on-method defining an event is
- * commonly written like the following:
- * <pre>
- * public function onClick(event)
- * {
- * this.raiseEvent('onClick',event);
- * }
- * </pre>
- * where <code>$event</code> is an instance of {@link CEvent} or its child class.
- * One can then raise the event by calling the on-method instead of {@link raiseEvent} directly.
- *
- * Both property names and event names are case-insensitive.
- *
- * Starting from version 1.0.2, CComponent supports behaviors. A behavior is an
- * instance of {@link IBehavior} which is attached to a component. The methods of
- * the behavior can be invoked as if they belong to the component. Multiple behaviors
- * can be attached to the same component.
- *
- * To attach a behavior to a component, call {@link attachBehavior}; and to detach the behavior
- * from the component, call {@link detachBehavior}.
- *
- * A behavior can be temporarily enabled or disabled by calling {@link enableBehavior}
- * or {@link disableBehavior}, respectively. When disabled, the behavior methods cannot
- * be invoked via the component.
- *
- * Starting from version 1.1.0, a behavior's properties (either its public member variables or
- * its properties defined via getters and/or setters) can be accessed through the component it
- * is attached to.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CComponent.php 3066 2011-03-13 14:22:55Z qiang.xue $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- */
- Yii.CComponent = function CComponent() {
- };
- Yii.CComponent.prototype._e = null;
- Yii.CComponent.prototype._m = null;
- /**
- * Gets the class name for this item.
- * Since JavaScript doesn't really support this we
- * abuse function declarations to implement it,
- * for example instead of:
- * <pre>
- * Yii.Blah = function() { ... }
- * </pre>
- * we use:
- * <pre>
- * Yii.Blah = function Blah() { ... }
- * </pre>
- * We can now retrieve the name of the class by inspecting the constructor.
- */
- Yii.CComponent.prototype.getClassName = function() {
- var matches, className;
-
- matches = /function(.*)\((.*)\)/.exec((this).constructor);
- if (matches) {
- return php.trim(matches[1]);
- }
- };
- /**
- * Returns a property value, an event handler list or a behavior based on its name.
- * Do not call this method. This is a PHP magic method that we override
- * to allow using the following syntax to read a property or obtain event handlers:
- * <pre>
- * value=component.propertyName;
- * handlers=component.eventName;
- * </pre>
- * @param {String} name the property name or event name
- * @returns {Mixed} the property value, event handlers attached to the event, or the named behavior (since version 1.0.2)
- * @throws {Yii.CException} if the property or event is not defined
- * @see __set
- */
- Yii.CComponent.prototype.get = function (name) {
- var getter, i, object, nameParts = [], limit;
-
- if (name.indexOf !== undefined && name.indexOf(".") !== -1) {
- nameParts = name.split(".");
- name = nameParts.shift();
- }
- if (this[name] !== undefined) {
- object = this[name];
- if (nameParts.length > 0) {
- if (object instanceof Yii.CComponent) {
- return object.get(nameParts.join("."));
- }
- limit = nameParts.length;
- for (i = 0; i < limit; i++) {
- name = nameParts.shift();
- object = object[name];
- if (nameParts.length === 0) {
- return object;
- }
-
- if (object instanceof Yii.CComponent) {
- return object.get(nameParts.join("."));
- }
- }
- }
- return object;
- }
- getter='get'+php.ucfirst(name);
- if(php.method_exists(this,getter)) {
- object = this[getter]();
- if (nameParts.length > 0) {
- if (object instanceof Yii.CComponent) {
- return object.get(nameParts.join("."));
- }
- limit = nameParts.length;
- for (i = 0; i < limit; i++) {
- name = nameParts.shift();
- object = object[name];
- if (nameParts.length === 0) {
- return object;
- }
-
- if (object instanceof Yii.CComponent) {
- return object.get(nameParts.join("."));
- }
-
- }
- }
- return object;
- }
- else if(php.strncasecmp(name,'on',2)===0 && php.method_exists(this,name)) {
- // duplicating getEventHandlers() here for performance
- name=name.toLowerCase();
- if(this._e[name] === undefined) {
- this._e[name]=new Yii.CList();
- }
- return this._e[name];
- }
- else if(this._m !== null && this._m[name] !== undefined) {
- return this._m[name];
- }
- else if(this._m !== null) {
- for (i in this._m) {
- if (this._m.hasOwnProperty(i)) {
-
- object = this._m[i];
- try {
- if(object.getEnabled() && (php.property_exists(object,name) || object.canGetProperty(name))) {
- if (nameParts.length > 0) {
- return object.get(nameParts.join("."));
- }
- return object.get(name);
- }
- }
- catch (e) {
- console.log(e);
- }
- }
- }
- }
- console.log(this.getClassName() + " : " + name);
- throw new Yii.CException(Yii.t('yii','Property "{class}.{property}" is not defined.',
- {'{class}':this.getClassName(), '{property}':name}));
- };
- /**
- * Sets value of a component property.
- * Do not call this method. This is a PHP magic method that we override
- * to allow using the following syntax to set a property or attach an event handler
- * <pre>
- * this.propertyName=value;
- * this.eventName=callback;
- * </pre>
- * @param {String} name the property name or the event name
- * @param {Mixed} value the property value or callback
- * @throws {Yii.CException} if the property/event is not defined or the property is read only.
- * @see __get
- */
- Yii.CComponent.prototype.set = function (name, value) {
- var setter, i, object, nameParts = [];
- if (name.indexOf(".") !== -1) {
- nameParts = name.split(".");
- name = nameParts.pop();
- return (this.get(nameParts.join("."))[name] = value);
- }
- if (this[name] !== undefined) {
- return (this[name] = value);
- }
-
- setter='set'+php.ucfirst(name);
- if(php.method_exists(this,setter)) {
- return this[setter](value);
- }
- else if(php.strncasecmp(name,'on',2)===0 && php.method_exists(this,name)) {
- // duplicating getEventHandlers() here for performance
- name=name.toLowerCase();
- if(this._e[name] === undefined) {
- this._e[name]=new Yii.CList();
- }
- return this._e[name].add(value);
- }
- else if(this._m !== null) {
- for (i in this._m) {
- if (this._m.hasOwnProperty(i)) {
-
- object = this._m[i];
-
- if(object.getEnabled() && (php.property_exists(object,name) || object.canSetProperty(name))) {
- return (object.set(name,value));
- }
- }
- }
- }
- if(php.method_exists(this,'get'+php.ucfirst(name))) {
- throw new Yii.CException(Yii.t('yii','Property "{class}.{property}" is read only.',
- {'{class}':this.getClassName(), '{property}':name}));
- }
- else {
- throw new Yii.CException(Yii.t('yii','Property "{class}.{property}" is not defined.',
- {'{class}':this.getClassName(), '{property}':name}));
- }
- };
- /**
- * Checks if a property value is null.
- * Do not call this method. This is a PHP magic method that we override
- * to allow using isset() to detect if a component property is set or not.
- * @param {String} name the property name or the event name
- * @since 1.0.1
- */
- Yii.CComponent.prototype.isset = function (name) {
- var getter, i, object, nameParts = [], value;
- if (name.indexOf(".") !== -1) {
- nameParts = name.split(".");
- name = nameParts.pop();
- try {
- value = this.get(nameParts.join("."))[name];
- if (value !== undefined && value !== null) {
- return true;
- }
- return false;
- }
- catch (e) {
- return false;
- }
- }
- if (this[name] !== undefined) {
- return true;
- }
- getter='get'+php.ucfirst(name);
- if(php.method_exists(this,getter)) {
- return (this[getter]()!==null);
- }
- else if(php.strncasecmp(name,'on',2)===0 && php.method_exists(this,name))
- {
- name=name.toLowerCase();
- return this._e !== null && this._e[name] !== undefined && this._e[name].getCount();
- }
- else if(this._m !== null) {
- if(this._m[name] !== undefined) {
- return true;
- }
- for (i in this._m) {
- if (this._m.hasOwnProperty(i)) {
- object = this._m[i];
- if(object.getEnabled() && (php.property_exists(object,name) || object.canGetProperty(name))) {
- return true;
- }
- }
- }
- }
- return false;
- };
- /**
- * Sets a component property to be null.
- * Do not call this method. This is a PHP magic method that we override
- * to allow using unset() to set a component property to be null.
- * @param {String} name the property name or the event name
- * @throws {Yii.CException} if the property is read only.
- * @since 1.0.1
- */
- Yii.CComponent.prototype.unset = function (name) {
- var setter, i, object, nameParts = [];
- if (name.indexOf(".") !== -1) {
- nameParts = name.split(".");
- name = nameParts.pop();
- object = this.get(nameParts.join("."))[name];
- if (object.unset !== undefined) {
- return object.unset(name);
- }
- return (this.get(nameParts.join("."))[name] = null);
- }
- setter='set'+php.ucfirst(name);
- if (this[name] !== undefined) {
- this[name] = null;
- return;
- }
- else if(php.method_exists(this,setter)) {
- this[setter](null);
- }
- else if(php.strncasecmp(name,'on',2)===0 && php.method_exists(this,name)) {
- delete this._e[name.toLowerCase()];
- }
- else if(this._m !== null)
- {
- if(this._m[name] !== undefined) {
- this.detachBehavior(name);
- }
- else
- {
- for (i in this._m) {
- if (this._m.hasOwnProperty(i)) {
- object = this._m[i];
- if(object.getEnabled()) {
- if(php.property_exists(object,name)) {
- return (object[name]=null);
- }
- else if(object.canSetProperty(name)) {
- return object[setter](null);
- }
- }
- }
- }
- }
- }
- else if(php.method_exists(this,'get'+name)) {
- throw new Yii.CException(Yii.t('yii','Property "{class}.{property}" is read only.',
- {'{class}':this.getClassName(), '{property}':name}));
- }
- };
- /**
- * Calls the named method which is not a class method.
- * Do not call this method. This is a PHP magic method that we override
- * to implement the behavior feature.
- * @param {String} name the method name
- * @param {Array} parameters method parameters
- * @returns {Mixed} the method return value
- * @since 1.0.2
- */
- Yii.CComponent.prototype.call = function (name, parameters) {
- var i, object;
- if (this[name] !== undefined) {
- return php.call_user_func_array([this,name],parameters);
- }
- else if(this._m!==null) {
- for (i in this._m) {
- if (this._m.hasOwnProperty(i)) {
- object = this._m[i];
- if(object.getEnabled() && php.method_exists(object,name)) {
- return php.call_user_func_array([object,name],parameters);
- }
- }
- }
- }
-
- throw new Yii.CException(Yii.t('yii','{class} does not have a method named "{name}".',
- {'{class}':this.getClassName(), '{name}':name}));
- };
- /**
- * Returns the named behavior object.
- * The name 'asa' stands for 'as a'.
- * @param {String} behavior the behavior name
- * @returns {IBehavior} the behavior object, or null if the behavior does not exist
- * @since 1.0.2
- */
- Yii.CComponent.prototype.asa = function (behavior) {
- return this._m !== null && this._m[behavior] !== undefined ? this._m[behavior] : null;
- };
- /**
- * Attaches a list of behaviors to the component.
- * Each behavior is indexed by its name and should be an instance of
- * {@link IBehavior}, a string specifying the behavior class, or an
- * array of the following structure:
- * <pre>
- * {
- * 'class':'path.to.BehaviorClass',
- * 'property1':'value1',
- * 'property2':'value2',
- * }
- * </pre>
- * @param {Array} behaviors list of behaviors to be attached to the component
- * @since 1.0.2
- */
- Yii.CComponent.prototype.attachBehaviors = function (behaviors) {
- var name, behavior;
- for (name in behaviors) {
- if (behaviors.hasOwnProperty(name)) {
- behavior = behaviors[name];
- this.attachBehavior(name,behavior);
- }
- }
- };
- /**
- * Detaches all behaviors from the component.
- * @since 1.0.2
- */
- Yii.CComponent.prototype.detachBehaviors = function () {
- var name, behavior;
- if(this._m!==null) {
- for (name in this._m) {
- if (this._m.hasOwnProperty(name)) {
- behavior = this._m[name];
- this.detachBehavior(name);
- }
- }
- this._m=null;
- }
- };
- /**
- * Attaches a behavior to this component.
- * This method will create the behavior object based on the given
- * configuration. After that, the behavior object will be initialized
- * by calling its {@link IBehavior::attach} method.
- * @param {String} name the behavior's name. It should uniquely identify this behavior.
- * @param {Mixed} behavior the behavior configuration. This is passed as the first
- * parameter to {@link YiiBase::createComponent} to create the behavior object.
- * @returns {IBehavior} the behavior object
- * @since 1.0.2
- */
- Yii.CComponent.prototype.attachBehavior = function (name, behavior) {
- if(!(behavior instanceof Yii.CBehavior)) {
- behavior=Yii.createComponent(behavior);
- }
- behavior.setEnabled(true);
- behavior.attach(this);
- if (this._m === null) {
- this._m = {};
- }
- return (this._m[name]=behavior);
- };
- /**
- * Detaches a behavior from the component.
- * The behavior's {@link IBehavior::detach} method will be invoked.
- * @param {String} name the behavior's name. It uniquely identifies the behavior.
- * @returns {IBehavior} the detached behavior. Null if the behavior does not exist.
- * @since 1.0.2
- */
- Yii.CComponent.prototype.detachBehavior = function (name) {
- var behavior;
- if(this._m[name] !== undefined) {
- this._m[name].detach(this);
- behavior=this._m[name];
- delete this._m[name];
- return behavior;
- }
- };
- /**
- * Enables all behaviors attached to this component.
- * @since 1.0.2
- */
- Yii.CComponent.prototype.enableBehaviors = function () {
- var i, behavior;
- if(this._m!==null) {
- for (i in this._m) {
- if (this._m.hasOwnProperty(i)) {
- behavior = this._m[i];
- behavior.setEnabled(true);
- }
- }
- }
- };
- /**
- * Disables all behaviors attached to this component.
- * @since 1.0.2
- */
- Yii.CComponent.prototype.disableBehaviors = function () {
- var i, behavior;
- if(this._m!==null) {
- for (i in this._m) {
- if (this._m.hasOwnProperty(i)) {
- behavior = this._m[i];
- behavior.setEnabled(false);
- }
- }
- }
- };
- /**
- * Enables an attached behavior.
- * A behavior is only effective when it is enabled.
- * A behavior is enabled when first attached.
- * @param {String} name the behavior's name. It uniquely identifies the behavior.
- * @since 1.0.2
- */
- Yii.CComponent.prototype.enableBehavior = function (name) {
- if(this._m !== null && this._m[name] !== undefined) {
- this._m[name].setEnabled(true);
- }
- };
- /**
- * Disables an attached behavior.
- * A behavior is only effective when it is enabled.
- * @param {String} name the behavior's name. It uniquely identifies the behavior.
- * @since 1.0.2
- */
- Yii.CComponent.prototype.disableBehavior = function (name) {
- if(this._m !== null && this._m[name] !== undefined) {
- this._m[name].setEnabled(false);
- }
- };
- /**
- * Determines whether a property is defined.
- * A property is defined if there is a getter or setter method
- * defined in the class. Note, property names are case-insensitive.
- * @param {String} name the property name
- * @returns {Boolean} whether the property is defined
- * @see canGetProperty
- * @see canSetProperty
- */
- Yii.CComponent.prototype.hasProperty = function (name) {
- return this[name] !== undefined || php.method_exists(this,'get'+php.ucfirst(name)) || php.method_exists(this,'set'+php.ucfirst(name));
- };
- /**
- * Determines whether a property can be read.
- * A property can be read if the class has a getter method
- * for the property name. Note, property name is case-insensitive.
- * @param {String} name the property name
- * @returns {Boolean} whether the property can be read
- * @see canSetProperty
- */
- Yii.CComponent.prototype.canGetProperty = function (name) {
- return this[name] !== undefined || php.method_exists(this,'get'+php.ucfirst(name));
- };
- /**
- * Determines whether a property can be set.
- * A property can be written if the class has a setter method
- * for the property name. Note, property name is case-insensitive.
- * @param {String} name the property name
- * @returns {Boolean} whether the property can be written
- * @see canGetProperty
- */
- Yii.CComponent.prototype.canSetProperty = function (name) {
- return this[name] !== undefined || php.method_exists(this,'set'+php.ucfirst(name));
- };
- /**
- * Determines whether an event is defined.
- * An event is defined if the class has a method named like 'onXXX'.
- * Note, event name is case-insensitive.
- * @param {String} name the event name
- * @returns {Boolean} whether an event is defined
- */
- Yii.CComponent.prototype.hasEvent = function (name) {
- return !php.strncasecmp(name,'on',2) && php.method_exists(this,name);
- };
- /**
- * Checks whether the named event has attached handlers.
- * @param {String} name the event name
- * @returns {Boolean} whether an event has been attached one or several handlers
- */
- Yii.CComponent.prototype.hasEventHandler = function (name) {
-
- return this._e !== null && this._e[name] !== undefined && this._e[name].getCount()>0;
- };
- /**
- * Returns the list of attached event handlers for an event.
- * @param {String} name the event name
- * @returns {Yii.CList} list of attached event handlers for the event
- * @throws {Yii.CException} if the event is not defined
- */
- Yii.CComponent.prototype.getEventHandlers = function (name) {
- if(this.hasEvent(name)) {
-
- if (this._e === null) {
- this._e = {};
- }
- if(this._e[name] === undefined) {
- this._e[name]=new Yii.CList();
- }
- return this._e[name];
- }
- else {
- throw new Yii.CException(Yii.t('yii','Event "{class}.{event}" is not defined.',
- {'{class}':this.getClassName(), '{event}':name}));
- }
- };
- /**
- * Attaches an event handler to an event.
- *
- * An event handler must be a valid PHP callback, i.e., a string referring to
- * a global function name, or an array containing two elements with
- * the first element being an object and the second element a method name
- * of the object.
- *
- * An event handler must be defined with the following signature,
- * <pre>
- * function handlerName(event) {}
- * </pre>
- * where $event includes parameters associated with the event.
- *
- * This is a convenient method of attaching a handler to an event.
- * It is equivalent to the following code:
- * <pre>
- * component.getEventHandlers(eventName).add(eventHandler);
- * </pre>
- *
- * Using {@link getEventHandlers}, one can also specify the excution order
- * of multiple handlers attaching to the same event. For example:
- * <pre>
- * component.getEventHandlers(eventName).insertAt(0,eventHandler);
- * </pre>
- * makes the handler to be invoked first.
- *
- * @param {String} name the event name
- * @param {Yii.Callback} handler the event handler
- * @throws {Yii.CException} if the event is not defined
- * @see detachEventHandler
- */
- Yii.CComponent.prototype.attachEventHandler = function (name, handler) {
- this.getEventHandlers(name).add(handler);
- };
- /**
- * Detaches an existing event handler.
- * This method is the opposite of {@link attachEventHandler}.
- * @param {String} name event name
- * @param {Yii.Callback} handler the event handler to be removed
- * @returns {Boolean} if the detachment process is successful
- * @see attachEventHandler
- */
- Yii.CComponent.prototype.detachEventHandler = function (name, handler) {
- if(this.hasEventHandler(name)) {
- return this.getEventHandlers(name).remove(handler)!==false;
- }
- else {
- return false;
- }
- };
- /**
- * Raises an event.
- * This method represents the happening of an event. It invokes
- * all attached handlers for the event.
- * @param {String} name the event name
- * @param {Yii.CEvent} event the event parameter
- * @throws {Yii.CException} if the event is undefined or an event handler is invalid.
- */
- Yii.CComponent.prototype.raiseEvent = function (name, event) {
- var i, handler, object, method, limit;
- if(this._e !== null && this._e[name] !== undefined) {
- limit = this._e[name].length;
- for (i = 0; i < limit; i++) {
- handler = this._e[name][i];
- if(typeof(handler) === 'string') {
- php.call_user_func(handler,event);
- }
- if(Object.prototype.toString.call(handler) === '[object Array]') {
- // an array: 0 - object, 1 - method name
- object = handler[0];
- method = handler[1];
-
- if(typeof(object) === 'string') { // static method call
- php.call_user_func(handler,event);
- }
- else if(php.method_exists(object,method)) {
-
- object[method](event);
- }
- else {
- throw new Yii.CException(Yii.t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
- {'{class}':this.getClassName(), '{event}':name, '{handler}':handler[1]}));
- }
- }
- else if (typeof handler === "function") { // callback function
- php.call_user_func(handler,event);
- }
- else {
- console.log(i);
- console.log(name);
- console.log(handler);
- throw new Yii.CException(Yii.t('yii','Event "{class}.{event}" is attached with an invalid handler "{handler}".',
- {'{class}':this.getClassName(), '{event}':name, '{handler}':handler}));
- }
- // stop further handling if param.handled is set true
- if((event instanceof Yii.CEvent) && event.handled) {
- return;
- }
-
- }
- }
- else if(YII_DEBUG && !this.hasEvent(name)) {
- throw new Yii.CException(Yii.t('yii','Event "{class}.{event}" is not defined.',
- {'{class}':this.getClassName(), '{event}':name}));
- }
- };
- /**
- * Evaluates a PHP expression or callback under the context of this component.
- *
- * Valid PHP callback can be class method name in the form of
- * array(ClassName/Object, MethodName), or anonymous function (only available in PHP 5.3.0 or above).
- *
- * If a PHP callback is used, the corresponding function/method signature should be
- * <pre>
- * function foo(param1, param2, +++, component) { +++ }
- * </pre>
- * where the array elements in the second parameter to this method will be passed
- * to the callback as $param1, $param2, ...; and the last parameter will be the component itself.
- *
- * If a PHP expression is used, the second parameter will be "extracted" into PHP variables
- * that can be directly accessed in the expression. See {@link http://us.php.net/manual/en/function.extract.php PHP extract}
- * for more details. In the expression, the component object can be accessed using $this.
- *
- * @param {Mixed} _expression_ a PHP expression or PHP callback to be evaluated.
- * @param {Array} _data_ additional parameters to be passed to the above expression/callback.
- * @returns {Mixed} the expression result
- * @since 1.1.0
- */
- Yii.CComponent.prototype.evaluateExpression = function (_expression_, _data_) {
- if (_data_ === undefined) {
- _data_ = [];
- }
- if(typeof(_expression_) === 'string')
- {
- php.extract(_data_);
- return eval('return '+_expression_+';');
- }
- else
- {
- _data_.push(this);
- return php.call_user_func_array(_expression_, _data_);
- }
- }/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CApplicationComponent is the base class for application component classes.
- *
- * CApplicationComponent implements the basic methods required by {@link IApplicationComponent}.
- *
- * When developing an application component, try to put application component initialization code in
- * the {@link init()} method instead of the constructor. This has the advantage that
- * the application component can be customized through application configuration.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CApplicationComponent.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CApplicationComponent = function CApplicationComponent() {
- };
- Yii.CApplicationComponent.prototype = new Yii.CComponent();
- Yii.CApplicationComponent.prototype.constructor = Yii.CApplicationComponent;
- /**
- * @var {Array} the behaviors that should be attached to this component.
- * The behaviors will be attached to the component when {@link init} is called.
- * Please refer to {@link CModel::behaviors} on how to specify the value of this property.
- * @since 1.0.2
- */
- Yii.CApplicationComponent.prototype.behaviors = [];
- Yii.CApplicationComponent.prototype._initialized = false;
- /**
- * Initializes the application component.
- * This method is required by {@link IApplicationComponent} and is invoked by application.
- * If you override this method, make sure to call the parent implementation
- * so that the application component can be marked as initialized.
- */
- Yii.CApplicationComponent.prototype.init = function () {
- this.attachBehaviors(this.behaviors);
- this._initialized=true;
- };
- /**
- * Checks if this application component bas been initialized.
- * @returns {Boolean} whether this application component has been initialized (ie, {@link init()} is invoked).
- */
- Yii.CApplicationComponent.prototype.getIsInitialized = function () {
- return this._initialized;
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CException represents a generic exception for all purposes.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CException.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.Exception
- */
- Yii.CException = function CException (message) {
- if (message === false) {
- return;
- }
- this.message = message;
-
- };
- Yii.CException.prototype = new Error();
- Yii.CException.prototype.constructor = Yii.CException;
- /**
- * Gets a basic stack trace
- * @returns {Array} An array of function calls
- */
- Yii.CException.prototype.stacktrace = function () {
- function st2(f) {
- return !f ? [] :
- st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + Array.prototype.slice.call(f.arguments).join(',') + ')']);
- }
- return st2(arguments.callee.caller);
- };
- /**
- * Gets the stack trace as a string
- * @returns {String} the stack trace, latest item first
- */
- Yii.CException.prototype.getTraceAsString = function () {
- return this.stacktrace().reverse().join("\n");
- };
- /**
- * Gets the exception message
- * @returns {String} the message associated with this error
- */
- Yii.CException.prototype.getMessage = function () {
- return this.message;
- }
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CEvent is the base class for all event classes.
- *
- * It encapsulates the parameters associated with an event.
- * The {@link sender} property describes who raises the event.
- * And the {@link handled} property indicates if the event is handled.
- * If an event handler sets {@link handled} to true, those handlers
- * that are not invoked yet will not be invoked anymore.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CComponent.php 3066 2011-03-13 14:22:55Z qiang.xue $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CEvent = function CEvent(sender, params) {
- if (sender !== false) {
- this.construct(sender, params);
- }
- };
- Yii.CEvent.prototype = new Yii.CComponent();
- Yii.CEvent.prototype.constructor = Yii.CEvent;
- /**
- * @var {Object} the sender of this event
- */
- Yii.CEvent.prototype.sender = null;
- /**
- * @var {Boolean} whether the event is handled. Defaults to false.
- * When a handler sets this true, the rest of the uninvoked event handlers will not be invoked anymore.
- */
- Yii.CEvent.prototype.handled = false;
- /**
- * @var {Mixed} additional event parameters.
- * @since 1.1.7
- */
- Yii.CEvent.prototype.params = null;
- /**
- * Constructor.
- * @param {Mixed} sender sender of the event
- * @param {Mixed} params additional parameters for the event
- */
- Yii.CEvent.prototype.construct = function (sender, params) {
- if (sender === undefined) {
- sender = null;
- }
- if (params === undefined) {
- params = null;
- }
- this.sender=sender;
- this.params=params;
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CEnumerable is the base class for all enumerable types.
- *
- * To define an enumerable type, extend CEnumberable and define string constants.
- * Each constant represents an enumerable value.
- * The constant name must be the same as the constant value.
- * For example,
- * <pre>
- * class TextAlign extends Yii.CEnumerable
- * {
- * const Left='Left';
- * const Right='Right';
- * }
- * </pre>
- * Then, one can use the enumerable values such as TextAlign::Left and
- * TextAlign::Right.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CComponent.php 3066 2011-03-13 14:22:55Z qiang.xue $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- */
- Yii.CEnumerable = function CEnumerable () {
- };
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CModule is the base class for module and application classes.
- *
- * CModule mainly manages application components and sub-modules.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CModule.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.base
- * @since 1.0.4
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CModule = function CModule (id, parent, config) {
- if (id !== false) {
- this.models = {};
- this.views = {};
- this.controllers = {};
-
- this.construct(id, parent, config);
- }
- };
- Yii.CModule.prototype = new Yii.CComponent();
- Yii.CModule.prototype.constructor = Yii.CModule;
- /**
- * @var {Array} the IDs of the application components that should be preloaded.
- */
- Yii.CModule.prototype.preload = [];
- /**
- * @var {Array} the behaviors that should be attached to the module.
- * The behaviors will be attached to the module when {@link init} is called.
- * Please refer to {@link CModel::behaviors} on how to specify the value of this property.
- */
- Yii.CModule.prototype.behaviors = {};
- Yii.CModule.prototype._id = null;
- Yii.CModule.prototype._parentModule = null;
- Yii.CModule.prototype._basePath = null;
- Yii.CModule.prototype._modulePath = null;
- Yii.CModule.prototype._params = null;
- Yii.CModule.prototype._modules = {};
- Yii.CModule.prototype._moduleConfig = {};
- Yii.CModule.prototype._components = {};
- Yii.CModule.prototype._componentConfig = {};
- /**
- * jQuery events to delegate for this module.
- * Array should be of the following format:
- * <pre>
- * [
- * ['#selector a.someLink', 'click', function (e) { alert("clicked!")}],
- * ['#selector form', 'submit', function (e) { alert('Submitted!'); e.preventDefault(); }]
- * ]
- * </pre>
- * These events will be bound to their selectors when the module is run
- * @var Array
- */
- Yii.CModule.prototype.delegates = [];
- /**
- * Holds a list of models belonging to this module
- */
- Yii.CModule.prototype.models = {};
- /**
- * Holds a list of views belonging to this module
- */
- Yii.CModule.prototype.views = {};
- /**
- * Holds a list of controllers belonging to this module
- */
- Yii.CModule.prototype.controllers = {};
- /**
- * Constructor.
- * @param {String} id the ID of this module
- * @param {Yii.CModule} parent the parent module (if any)
- * @param {Mixed} config the module configuration. It can be either an array or
- * the path of a PHP file returning the configuration array.
- */
- Yii.CModule.prototype.construct = function (id, parent, config) {
- if (config === undefined) {
- config = {};
- }
- this._id=id;
- this._parentModule=parent;
- // set basePath at early as possible to avoid trouble
-
- if(config.basePath !== undefined) {
- this.setBasePath(config.basePath);
- delete config.basePath;
- }
- Yii.setPathOfAlias(id,this.getBasePath());
- this.preinit();
- this.configure(config);
- this.attachBehaviors(this.behaviors);
- this.preloadComponents();
- this.init();
- };
- /**
- * Getter magic method.
- * This method is overridden to support accessing application components
- * like reading module properties.
- * @param {String} name application component or property name
- * @returns {Mixed} the named property value
- */
- Yii.CModule.prototype.get = function (name) {
- if(this.hasComponent(name)) {
- return this.getComponent(name);
- }
- else {
- return Yii.CComponent.prototype.get.call(this, name);
- }
- };
- /**
- * Checks if a property value is null.
- * This method overrides the parent implementation by checking
- * if the named application component is loaded.
- * @param {String} name the property name or the event name
- * @returns {Boolean} whether the property value is null
- */
- Yii.CModule.prototype.isset = function (name) {
- if(this.hasComponent(name)) {
- return this.getComponent(name)!==null;
- }
- else {
- return Yii.CComponent.prototype.isset.call(this, name);
- }
- };
- /**
- * Returns the module ID.
- * @returns {String} the module ID.
- */
- Yii.CModule.prototype.getId = function () {
- return this._id;
- };
- /**
- * Sets the module ID.
- * @param {String} id the module ID
- */
- Yii.CModule.prototype.setId = function (id) {
- this._id=id;
- };
- /**
- * Returns the root directory of the module.
- * @returns {String} the root directory of the module. Defaults to the directory containing the module class.
- */
- Yii.CModule.prototype.getBasePath = function () {
- var classVar;
- if(this._basePath===null) {
- classVar=new ReflectionClass(php.get_class(this));
- this._basePath=php.dirname(classVar.getFileName());
- }
- return this._basePath;
- };
- /**
- * Sets the root directory of the module.
- * This method can only be invoked at the beginning of the constructor.
- * @param {String} path the root directory of the module.
- */
- Yii.CModule.prototype.setBasePath = function (path) {
- this._basePath=path;
- };
- /**
- * Returns user-defined parameters.
- * @returns {Yii.CAttributeCollection} the list of user-defined parameters
- */
- Yii.CModule.prototype.getParams = function () {
- if(this._params!==null) {
- return this._params;
- }
- else
- {
- this._params=new Yii.CAttributeCollection();
- this._params.caseSensitive=true;
- return this._params;
- }
- };
- /**
- * Sets user-defined parameters.
- * @param {Array} value user-defined parameters. This should be in name-value pairs.
- */
- Yii.CModule.prototype.setParams = function (value) {
- var params, k, v;
- params=this.getParams();
- for (k in value) {
- if (value.hasOwnProperty(k)) {
- v = value[k];
- params.add(k,v);
- }
- }
- };
- /**
- * Returns the directory that contains the application modules.
- * @returns {String} the directory that contains the application modules. Defaults to the 'modules' subdirectory of {@link basePath}.
- */
- Yii.CModule.prototype.getModulePath = function () {
- if(this._modulePath!==null) {
- return this._modulePath;
- }
- else {
- return (this._modulePath=this.getBasePath()+"/"+'modules');
- }
- };
- /**
- * Sets the directory that contains the application modules.
- * @param {String} value the directory that contains the application modules.
- */
- Yii.CModule.prototype.setModulePath = function (value) {
- this._modulePath = value;
-
- };
- /**
- * Sets the aliases that are used in the module.
- * @param {Array} aliases list of aliases to be imported
- */
- Yii.CModule.prototype.setImport = function (aliases) {
- var i, alias;
- for (i in aliases) {
- if (aliases.hasOwnProperty(i)) {
- alias = aliases[i];
- Yii.imports(alias);
- }
- }
- };
- /**
- * Defines the root aliases.
- * @param {Array} mappings list of aliases to be defined. The array keys are root aliases,
- * while the array values are paths or aliases corresponding to the root aliases.
- * For example,
- * <pre>
- * {
- * 'models':'application.models', // an existing alias
- * 'extensions':'application.extensions', // an existing alias
- * 'backend':php.dirname(__FILE__)+'/../backend', // a directory
- * }
- * </pre>
- * @since 1.0.5
- */
- Yii.CModule.prototype.setAliases = function (mappings) {
- var path, alias, name;
- for (name in mappings) {
- if (mappings.hasOwnProperty(name)) {
- alias = mappings[name];
- if((path=Yii.getPathOfAlias(alias))!==false) {
- Yii.setPathOfAlias(name,path);
- }
- else {
- Yii.setPathOfAlias(name,alias);
- }
- }
- }
- };
- /**
- * Returns the parent module.
- * @returns {Yii.CModule} the parent module. Null if this module does not have a parent.
- */
- Yii.CModule.prototype.getParentModule = function () {
- return this._parentModule;
- };
- /**
- * Retrieves the named application module.
- * The module has to be declared in {@link modules}. A new instance will be created
- * when calling this method with the given ID for the first time.
- * @param {String} id application module ID (case-sensitive)
- * @returns {Yii.CModule} the module instance, null if the module is disabled or does not exist.
- */
- Yii.CModule.prototype.getModule = function (id) {
- var config, classVar, module;
- if(this._modules[id] !== undefined) {
- return this._modules[id];
- }
- else if(this._moduleConfig[id] !== undefined) {
- config=this._moduleConfig[id];
- if(config.enabled === undefined || config.enabled) {
- Yii.trace("Loading \"" + id + "\" module",'system.base.CModule');
- classVar=config['class'];
- delete config['class'];
- if(this===Yii.app()) {
- module=Yii.createComponent(classVar,id,null,config);
- }
- else {
- module=Yii.createComponent(classVar,this.getId()+'/'+id,this,config);
- }
- return (this._modules[id]=module);
- }
- }
- };
- /**
- * Returns a value indicating whether the specified module is installed.
- * @param {String} id the module ID
- * @returns {Boolean} whether the specified module is installed.
- * @since 1.1.2
- */
- Yii.CModule.prototype.hasModule = function (id) {
- return this._moduleConfig[id] !== undefined || this._modules[id] !== undefined;
- };
- /**
- * Returns the configuration of the currently installed modules.
- * @returns {Array} the configuration of the currently installed modules (module ID => configuration)
- */
- Yii.CModule.prototype.getModules = function () {
- return this._moduleConfig;
- };
- /**
- * Configures the sub-modules of this module.
- *
- * Call this method to declare sub-modules and configure them with their initial property values.
- * The parameter should be an array of module configurations. Each array element represents a single module,
- * which can be either a string representing the module ID or an ID-configuration pair representing
- * a module with the specified ID and the initial property values.
- *
- * For example, the following array declares two modules:
- * <pre>
- * {
- * 'admin', // a single module ID
- * 'payment':{ // ID-configuration pair
- * 'server':'paymentserver.com',
- * },
- * }
- * </pre>
- *
- * By default, the module class is determined using the expression <code>ucfirst($moduleID).'Module'</code>.
- * And the class file is located under <code>modules/$moduleID</code>.
- * You may override this default by explicitly specifying the 'class' option in the configuration.
- *
- * You may also enable or disable a module by specifying the 'enabled' option in the configuration.
- *
- * @param {Array} modules module configurations.
- */
- Yii.CModule.prototype.setModules = function (modules) {
- var id, module;
- for (id in modules) {
- if (modules.hasOwnProperty(id)) {
- module = modules[id];
- if(php.is_int(id)) {
- id=module;
- module={};
- }
- if(module['class'] === undefined) {
- Yii.setPathOfAlias(id,this.getModulePath()+"/"+id);
- module['class'] = id+'.'+php.ucfirst(id)+'Module';
- }
- if(this._moduleConfig[id] !== undefined) {
- this._moduleConfig[id]=Yii.CMap.mergeArray(this._moduleConfig[id],module);
- }
- else {
- this._moduleConfig[id]=module;
- }
- }
- }
- };
- /**
- * Checks whether the named component exists.
- * @param {String} id application component ID
- * @returns {Boolean} whether the named application component exists (including both loaded and disabled.)
- */
- Yii.CModule.prototype.hasComponent = function (id) {
- return this._components[id] !== undefined || this._componentConfig[id] !== undefined;
- };
- /**
- * Retrieves the named application component.
- * @param {String} id application component ID (case-sensitive)
- * @param {Boolean} createIfNull whether to create the component if it doesn't exist yet. This parameter
- * has been available since version 1.0.6.
- * @returns {CApplicationComponent} the application component instance, null if the application component is disabled or does not exist.
- * @see hasComponent
- */
- Yii.CModule.prototype.getComponent = function (id, createIfNull) {
- var config, component;
- if (createIfNull === undefined) {
- createIfNull = true;
- }
- if(this._components[id] !== undefined) {
- return this._components[id];
- }
- else if(this._componentConfig[id] !== undefined && createIfNull) {
- config=this._componentConfig[id];
- if(config.enabled === undefined || config.enabled) {
- Yii.trace("Loading \"" + id + "\" application component",'system.CModule');
-
- delete config.enabled;
- component=Yii.createComponent(config);
-
- component.init();
- return (this._components[id]=component);
- }
- }
-
- };
- /**
- * Puts a component under the management of the module.
- * The component will be initialized by calling its {@link CApplicationComponent::init() init()}
- * method if it has not done so.
- * @param {String} id component ID
- * @param {CApplicationComponent} component the component to be added to the module.
- * If this parameter is null, it will unload the component from the module.
- */
- Yii.CModule.prototype.setComponent = function (id, component) {
- if(component===null) {
- delete this._components[id];
- }
- else {
- this._components[id]=component;
- if(!component.getIsInitialized()) {
- component.init();
- }
- }
- };
- /**
- * Returns the application components.
- * @param {Boolean} loadedOnly whether to return the loaded components only. If this is set false,
- * then all components specified in the configuration will be returned, whether they are loaded or not.
- * Loaded components will be returned as objects, while unloaded components as configuration arrays.
- * This parameter has been available since version 1.1.3.
- * @returns {Array} the application components (indexed by their IDs)
- */
- Yii.CModule.prototype.getComponents = function (loadedOnly) {
- if (loadedOnly === undefined) {
- loadedOnly = true;
- }
- if(loadedOnly) {
- return this._components;
- }
- else {
- return php.array_merge(this._componentConfig, this._components);
- }
- };
- /**
- * Sets the application components.
- *
- * When a configuration is used to specify a component, it should consist of
- * the component's initial property values (name-value pairs). Additionally,
- * a component can be enabled (default) or disabled by specifying the 'enabled' value
- * in the configuration.
- *
- * If a configuration is specified with an ID that is the same as an existing
- * component or configuration, the existing one will be replaced silently.
- *
- * The following is the configuration for two components:
- * <pre>
- * {
- * 'db':{
- * 'class':'CDbConnection',
- * 'connectionString':'sqlite:path/to/file.db',
- * },
- * 'cache':{
- * 'class':'CDbCache',
- * 'connectionID':'db',
- * 'enabled':!YII_DEBUG, // enable caching in non-debug mode
- * ),
- * }
- * </pre>
- *
- * @param {Array} components application components(id=>component configuration or instances)
- * @param {Boolean} merge whether to merge the new component configuration with the existing one.
- * Defaults to true, meaning the previously registered component configuration of the same ID
- * will be merged with the new configuration. If false, the existing configuration will be replaced completely.
- */
- Yii.CModule.prototype.setComponents = function (components, merge) {
- var component, id;
- if (merge === undefined) {
- merge = true;
- }
- for (id in components) {
- if (components.hasOwnProperty(id)) {
- component = components[id];
- if(component instanceof Yii.CApplicationComponent) {
- this.setComponent(id,component);
- }
- else if(this._componentConfig[id] !== undefined && merge) {
- this._componentConfig[id]=Yii.CMap.prototype.mergeArray(this._componentConfig[id],component);
- }
- else {
- this._componentConfig[id]=component;
- }
- }
- }
- };
- /**
- * Configures the module with the specified configuration.
- * @param {Array} config the configuration array
- */
- Yii.CModule.prototype.configure = function (config) {
- var key, value;
- if(typeof config === 'object') {
- for (key in config) {
- if (config.hasOwnProperty(key)) {
- value = config[key];
- this.set(key,value);
- }
- }
- }
- };
- /**
- * Loads static application components.
- */
- Yii.CModule.prototype.preloadComponents = function () {
- var i, id;
- for (i in this.preload) {
- if (this.preload.hasOwnProperty(i)) {
- id = this.preload[i];
- this.getComponent(id);
- }
- }
- };
- /**
- * Preinitializes the module.
- * This method is called at the beginning of the module constructor.
- * You may override this method to do some customized preinitialization work.
- * Note that at this moment, the module is not configured yet.
- * @see init
- */
- Yii.CModule.prototype.preinit = function () {
- };
- /**
- * Initializes the module.
- * This method is called at the end of the module constructor.
- * Note that at this moment, the module has been configured, the behaviors
- * have been attached and the application components have been registered.
- * @see preinit
- */
- Yii.CModule.prototype.init = function () {
- Yii.forEach(this.delegates, function(i, item) {
- jQuery("body").undelegate(item[0], item[1]).delegate(item[0], item[1], item[2]);
- });
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CList implements an integer-indexed collection class.
- *
- * You can access, append, insert, remove an item by using
- * {@link itemAt}, {@link add}, {@link insertAt}, {@link remove}, and {@link removeAt}.
- * To get the number of the items in the list, use {@link getCount}.
- * CList can also be used like a regular array as follows,
- * <pre>
- * list.push(item); // append at the end
- * list[index]=item; // $index must be between 0 and $list->Count
- * delete list[index]; // remove the item at $index
- * if(list[index] !== undefined) { // if the list has an item at $index
- * for (index in list) // traverse each item in the list
- * n=php.count(list);
- * } // returns the number of items in the list
- * </pre>
- *
- * To extend CList by doing additional operations with each addition or removal
- * operation (e.g. performing type check), override {@link insertAt()}, and {@link removeAt()}.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CList.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.collections
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CList = function CList (data, readOnly) {
- if (data !== false) {
- this.construct(data, readOnly);
- }
-
- };
- Yii.CList.prototype = new Array();
- Yii.CList.prototype.constructor = Yii.CList;
- Yii.augment(Yii.CList, Yii.CComponent);
- /**
- * @var {Boolean} whether this list is read-only
- */
- Yii.CList.prototype._r = false;
- /**
- * Constructor.
- * Initializes the list with an array or an iterable object.
- * @param {Array} data the initial data. Default is null, meaning no initialization.
- * @param {Boolean} readOnly whether the list is read-only
- * @throws {Yii.CException} If data is not null and neither an array nor an iterator.
- */
- Yii.CList.prototype.construct = function (data, readOnly) {
- if (data === undefined) {
- data = null;
- }
- if (readOnly === undefined) {
- readOnly = false;
- }
- if(data!==null) {
- this.copyFrom(data);
- }
- this.setReadOnly(readOnly);
- };
- /**
- * @returns {Boolean} whether this list is read-only or not. Defaults to false.
- */
- Yii.CList.prototype.getReadOnly = function () {
- return this._r;
- };
- /**
- * @param {Boolean} value whether this list is read-only or not
- */
- Yii.CList.prototype.setReadOnly = function (value) {
- this._r=value;
- };
- /**
- * Returns the number of items in the list.
- * @returns {Integer} the number of items in the list
- */
- Yii.CList.prototype.getCount = function () {
- return this.length;
- };
- /**
- * Returns the item at the specified offset.
- * This method is exactly the same as {@link offsetGet}.
- * @param {Integer} index the index of the item
- * @returns {Mixed} the item at the index
- * @throws {Yii.CException} if the index is out of the range
- */
- Yii.CList.prototype.itemAt = function (index) {
- if(this[index] !== undefined) {
- return this[index];
- }
- else {
- throw new Yii.CException(Yii.t('yii','List index "{index}" is out of bound.',
- {'{index}':index}));
- }
- };
- /**
- * Appends an item at the end of the list.
- * @param {Mixed} item new item
- * @returns {Integer} the zero-based index at which the item is added
- */
- Yii.CList.prototype.add = function (item) {
- return this.push(item);
- };
-
- /**
- * Appends an item at the end of the list, fails if the list is read only.
- * @param {Mixed} item new item
- * @returns {Integer} the zero-based index at which the item is added
- */
- Yii.CList.prototype.push = function (item) {
- if (!this._r) {
- return Array.prototype.push.call(this, item);
- }
- else {
- throw new Yii.CException(Yii.t('yii','The list is read only.'));
- }
- };
-
- /**
- * Pops an item off the end of the list, fails if the list is read only.
- * @returns {Mixed} the popped item
- */
- Yii.CList.prototype.pop = function () {
- if (!this._r) {
- return Array.prototype.pop.call(this);
- }
- else {
- throw new Yii.CException(Yii.t('yii','The list is read only.'));
- }
- };
-
- /**
- * Shifts an item off the start of the list, fails if the list is read only.
- * @returns {Mixed} the shifted item
- */
- Yii.CList.prototype.shift = function () {
- if (!this._r) {
- return Array.prototype.shift.call(this);
- }
- else {
- throw new Yii.CException(Yii.t('yii','The list is read only.'));
- }
- };
- /**
- * Inserts an item at the specified position.
- * Original item at the position and the next items
- * will be moved one step towards the end.
- * @param {Integer} index the specified position.
- * @param {Mixed} item new item
- * @throws {Yii.CException} If the index specified exceeds the bound or the list is read-only
- */
- Yii.CList.prototype.insertAt = function (index, item) {
- if(!this._r)
- {
- if(index===this.length) {
- this[this.length + 1]=item;
- }
- else if(index>=0 && index<this.length)
- {
- php.array_splice(this,index,0,[item]);
- }
- else {
- throw new Yii.CException(Yii.t('yii','List index "{index}" is out of bound.',
- {'{index}':index}));
- }
- }
- else {
- throw new Yii.CException(Yii.t('yii','The list is read only.'));
- }
- };
- /**
- * Removes an item from the list.
- * The list will first search for the item.
- * The first item found will be removed from the list.
- * @param {Mixed} item the item to be removed.
- * @returns {Integer} the index at which the item is being removed
- * @throws {Yii.CException} If the item does not exist
- */
- Yii.CList.prototype.remove = function (item) {
- var index;
- if((index=this.indexOf(item))>=0)
- {
- this.removeAt(index);
- return index;
- }
- else {
- return false;
- }
- };
- /**
- * Removes an item at the specified position.
- * @param {Integer} index the index of the item to be removed.
- * @returns {Mixed} the removed item.
- * @throws {Yii.CException} If the index specified exceeds the bound or the list is read-only
- */
- Yii.CList.prototype.removeAt = function (index) {
- var item;
- if(!this._r) {
- if(index>=0 && index<this.length) {
- if(index===this.length) {
- return this.pop();
- }
- else
- {
- item=this[index];
- php.array_splice(this,index,1);
- return item;
- }
- }
- else {
- throw new Yii.CException(Yii.t('yii','List index "{index}" is out of bound.',
- {'{index}':index}));
- }
- }
- else {
- throw new Yii.CException(Yii.t('yii','The list is read only.'));
- }
- };
- /**
- * Removes all items in the list.
- */
- Yii.CList.prototype.clear = function () {
- var i;
- for(i=this.length - 1; i >= 0; --i) {
- this.removeAt(i);
- }
- };
- /**
- * @param {Mixed} item the item
- * @returns {Boolean} whether the list contains the item
- */
- Yii.CList.prototype.contains = function (item) {
- return this.indexOf(item) >= 0;
- };
- /**
- * @returns {Array} the list of items in array
- */
- Yii.CList.prototype.toArray = function () {
- var ret = [], i, limit;
- limit = this.length;
- for (i = 0; i < limit; i++) {
- ret.push(this[i]);
- }
- return ret;
- };
- /**
- * Copies iterable data into the list.
- * Note, existing data in the list will be cleared first.
- * @param {Mixed} data the data to be copied from, must be an array or object implementing Traversable
- * @throws {Yii.CException} If data is neither an array nor a Traversable.
- */
- Yii.CList.prototype.copyFrom = function (data) {
- var i, item, limit;
- if(Object.prototype.toString.call(data) === '[object Array]' || (data instanceof Array)) {
- if(this.length > 0) {
- this.clear();
- }
- if(data instanceof Yii.CList) {
- data=data.toArray();
- }
- for (i = 0, limit = data.length; i < limit; i++) {
- item = data[i];
- this.add(item);
- }
- }
- else if(data!==null) {
- throw new Yii.CException(Yii.t('yii','List data must be an array or an object implementing Traversable.'));
- }
- };
- /**
- * Merges iterable data into the map.
- * New data will be appended to the end of the existing data.
- * @param {Mixed} data the data to be merged with, must be an array or object implementing Traversable
- * @throws {Yii.CException} If data is neither an array nor an iterator.
- */
- Yii.CList.prototype.mergeWith = function (data) {
- var i, item;
- if(Object.prototype.toString.call(data) === '[object Array]' || (data instanceof Array))
- {
- if(data instanceof Yii.CList) {
- data=data.toArray();
- }
- for (i in data) {
- if (data.hasOwnProperty(i)) {
- item = data[i];
- this.add(item);
- }
- }
- }
- else if(data!==null) {
- throw new Yii.CException(Yii.t('yii','List data must be an array or an object implementing Traversable.'));
- }
- };
- /**
- * Provides convenient access to Yii.forEach()
- * @param {Function} callback The callback function, this will receive 2 parameters, key and value
- * @returns {Yii.CList} the list
- */
- Yii.CList.prototype.forEach = function(callback) {
- return Yii.forEach(this,callback);
- };
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CMap implements a collection that takes key-value pairs.
- *
- * You can access, add or remove an item with a key by using
- * {@link itemAt}, {@link add}, and {@link remove}.
- * To get the number of the items in the map, use {@link getCount}.
- * CMap can also be used like a regular array as follows,
- * <pre>
- * map[key]=value; // add a key-value pair
- * delete map[key]; // remove the value with the specified key
- * if(map[key] !== undefined) { // if the map contains the key
- * for (key in map) // traverse the items in the map
- * n=php.count(map);
- * } // returns the number of items in the map
- * </pre>
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CMap.php 3153 2011-04-01 12:50:06Z qiang.xue $
- * @package system.collections
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CMap = function CMap (data, readOnly) {
- if (data !== false) {
- this.construct(data, readOnly);
- }
-
- };
- Yii.CMap.prototype = new Yii.CComponent();
- Yii.CMap.prototype.constructor = Yii.CMap;
- /**
- * Constructor.
- * Initializes the list with an array or an iterable object.
- * @param {Object} data the intial data. Default is null, meaning no initialization.
- * @throws {Yii.CException} If data is not null and neither an array nor an iterator.
- */
- Yii.CMap.prototype.construct = function (data) {
- if (data === undefined) {
- data = null;
- }
-
- if(data!==null) {
- this.copyFrom(data);
- }
- };
- /**
- * Returns the number of items in the map.
- * @returns {Integer} number of items in the map.
- */
- Yii.CMap.prototype.count = function () {
- return this.getCount();
- };
- /**
- * Returns the number of items in the map.
- * @returns {Integer} the number of items in the map
- */
- Yii.CMap.prototype.getCount = function () {
- var total = 0, i;
- for (i in this) {
- if (this.hasOwnProperty(i)) {
- total++;
- }
- }
-
- return total;
- };
- /**
- * @returns {Array} the key list
- */
- Yii.CMap.prototype.getKeys = function () {
- var i, keys = [];
- for (i in this) {
- if (this.hasOwnProperty(i)) {
- keys.push(i);
- }
- }
- return keys;
- };
- /**
- * Returns the item with the specified key.
- * @param {Mixed} key the key
- * @returns {Mixed} the element at the offset, null if no element is found at the offset
- */
- Yii.CMap.prototype.itemAt = function (key) {
- if(this[key] !== undefined) {
- return this[key];
- }
- else {
- return null;
- }
- };
- /**
- * Adds an item into the map.
- * Note, if the specified key already exists, the old value will be overwritten.
- * @param {Mixed} key key
- * @param {Mixed} value value
- * @throws {Yii.CException} if the map is read-only
- */
- Yii.CMap.prototype.add = function (key, value) {
- if (key === null) {
- key = this.count();
- }
- this[key] = value;
- };
- /**
- * Removes an item from the map by its key.
- * @param {Mixed} key the key of the item to be removed
- * @returns {Mixed} the removed value, null if no such key exists.
- * @throws {Yii.CException} if the map is read-only
- */
- Yii.CMap.prototype.remove = function (key) {
- var value;
- if(this[key] !== undefined) {
- value=this[key];
- delete this[key];
- return value;
- }
- };
- /**
- * Removes all items in the map.
- */
- Yii.CMap.prototype.clear = function () {
- var i, keyList, key;
- for (i in this) {
- if (this.hasOwnProperty(i)) {
- this.remove(i);
- }
- }
- };
- /**
- * @param {Mixed} key the key
- * @returns {Boolean} whether the map contains an item with the specified key
- */
- Yii.CMap.prototype.contains = function (key) {
- return this[key] !== undefined;
- };
- /**
- * @returns {Array} the list of items in array
- */
- Yii.CMap.prototype.toArray = function () {
- var i, ret = [];
- for (i in this) {
- if (this.hasOwnProperty(i)) {
- ret.push(this[i]);
- }
- }
- return ret;
- };
- /**
- * @returns {Object} the list of items in object
- */
- Yii.CMap.prototype.toObject = function () {
- var i, ret = {};
- for (i in this) {
- if (this.hasOwnProperty(i)) {
- ret[i] = this[i];
- }
- }
- return ret;
- };
- /**
- * Copies iterable data into the map.
- * Note, existing data in the map will be cleared first.
- * @param {Mixed} data the data to be copied from, must be an array or object implementing Traversable
- * @throws {Yii.CException} If data is neither an array nor an iterator.
- */
- Yii.CMap.prototype.copyFrom = function (data) {
- var key, value;
- if(typeof data === "object") {
- if(this.getCount()>0) {
- this.clear();
- }
- if(data instanceof Yii.CMap) {
- data=data.toObject();
- }
- for (key in data) {
- if (data.hasOwnProperty(key)) {
- value = data[key];
- this.add(key,value);
- }
- }
- }
- else if(data!==null) {
- throw new Yii.CException(Yii.t('yii','Map data must be an array or an object implementing Traversable.'));
- }
- };
- /**
- * Merges iterable data into the map.
- *
- * Existing elements in the map will be overwritten if their keys are the same as those in the source.
- * If the merge is recursive, the following algorithm is performed:
- * <ul>
- * <li>the map data is saved as $a, and the source data is saved as $b;</li>
- * <li>if $a and $b both have an array indxed at the same string key, the arrays will be merged using this algorithm;</li>
- * <li>any integer-indexed elements in $b will be appended to $a and reindxed accordingly;</li>
- * <li>any string-indexed elements in $b will overwrite elements in $a with the same index;</li>
- * </ul>
- *
- * @param {Mixed} data the data to be merged with, must be an array or object implementing Traversable
- * @param {Boolean} recursive whether the merging should be recursive.
- *
- * @throws {Yii.CException} If data is neither an array nor an iterator.
- */
- Yii.CMap.prototype.mergeWith = function (data, recursive) {
- var d, key, value;
- if (recursive === undefined) {
- recursive = true;
- }
- if(typeof data === "object") {
- if(data instanceof Yii.CMap) {
- data=data.toObject();
- }
- else if(data instanceof Yii.CList) {
- data=data.toArray();
- }
- if(recursive) {
- this.mergeArray(this,data);
- }
- else
- {
- for (key in data) {
- if (data.hasOwnProperty(key)) {
- value = data[key];
- this.add(key,value);
- }
- }
- }
- }
- else if(data!==null) {
- throw new Yii.CException(Yii.t('yii','Map data must be an array or an object implementing Traversable.'));
- }
- };
- /**
- * Merges two arrays into one recursively.
- * If each array has an element with the same string key value, the latter
- * will overwrite the former (different from array_merge_recursive).
- * Recursive merging will be conducted if both arrays have an element of array
- * type and are having the same key.
- * For integer-keyed elements, the elements from the latter array will
- * be appended to the former array.
- * @param {Array} a array to be merged to
- * @param {Array} b array to be merged from
- * @returns {Array} the merged array (the original arrays are not changed.)
- * @see mergeWith
- */
- Yii.CMap.prototype.mergeArray = function (a, b) {
- var k, v;
- for (k in b) {
- if (b.hasOwnProperty(k)) {
- v = b[k];
- if((typeof(k) === 'number' && (k % 1 ? false : true))) {
- a[k] !== undefined ? a.push(v) : a[k]=v;
- }
- else if (a[k] !== undefined && typeof a[k] === "object") {
- a[k]=this.mergeArray(a[k],v);
- }
- else {
- a[k]=v;
- }
- }
- }
- return a;
- };
- /**
- * Provides convenient access to Yii.forEach()
- * @param {Function} callback The callback function, this will receive 2 parameters, key and value
- * @returns {Yii.CMap} the map
- */
- Yii.CMap.prototype.forEach = function(callback) {
- return Yii.forEach(this,callback);
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CValidator is the base class for all validators.
- *
- * Child classes must implement the {@link validateAttribute} method.
- *
- * The following properties are defined in CValidator:
- * <ul>
- * <li>{@link attributes}: array, list of attributes to be validated;</li>
- * <li>{@link message}: string, the customized error message. The message
- * may contain placeholders that will be replaced with the actual content.
- * For example, the "{attribute}" placeholder will be replaced with the label
- * of the problematic attribute. Different validators may define additional
- * placeholders.</li>
- * <li>{@link on}: string, in which scenario should the validator be in effect.
- * This is used to match the 'on' parameter supplied when calling {@link CModel::validate}.</li>
- * </ul>
- *
- * When using {@link createValidator} to create a validator, the following aliases
- * are recognized as the corresponding built-in validator classes:
- * <ul>
- * <li>required: {@link CRequiredValidator}</li>
- * <li>filter: {@link CFilterValidator}</li>
- * <li>match: {@link CRegularExpressionValidator}</li>
- * <li>email: {@link CEmailValidator}</li>
- * <li>url: {@link CUrlValidator}</li>
- * <li>unique: {@link CUniqueValidator}</li>
- * <li>compare: {@link CCompareValidator}</li>
- * <li>length: {@link CStringValidator}</li>
- * <li>in: {@link CRangeValidator}</li>
- * <li>numerical: {@link CNumberValidator}</li>
- * <li>captcha: {@link CCaptchaValidator}</li>
- * <li>type: {@link CTypeValidator}</li>
- * <li>file: {@link CFileValidator}</li>
- * <li>default: {@link CDefaultValueValidator}</li>
- * <li>exist: {@link CExistValidator}</li>
- * <li>boolean: {@link CBooleanValidator}</li>
- * <li>date: {@link CDateValidator}</li>
- * <li>safe: {@link CSafeValidator}</li>
- * <li>unsafe: {@link CUnsafeValidator}</li>
- * </ul>
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CValidator.php 3160 2011-04-03 01:08:23Z qiang.xue $
- * @package system.validators
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CValidator = function CValidator() {
- };
- Yii.CValidator.prototype = new Yii.CComponent();
- Yii.CValidator.prototype.constructor = Yii.CValidator;
- /**
- * @var {Object} list of built-in validators (name=>class)
- */
- Yii.CValidator.prototype.builtInValidators = {
- 'required':'Yii.CRequiredValidator',
- 'filter':'Yii.CFilterValidator',
- 'match':'Yii.CRegularExpressionValidator',
- 'email':'Yii.CEmailValidator',
- 'url':'Yii.CUrlValidator',
- 'unique':'Yii.CUniqueValidator',
- 'compare':'Yii.CCompareValidator',
- 'length':'Yii.CStringValidator',
- 'in':'Yii.CRangeValidator',
- 'numerical':'Yii.CNumberValidator',
- 'captcha':'Yii.CCaptchaValidator',
- 'type':'Yii.CTypeValidator',
- 'file':'Yii.CFileValidator',
- 'default':'Yii.CDefaultValueValidator',
- 'exist':'Yii.CExistValidator',
- 'boolean':'Yii.CBooleanValidator',
- 'safe':'Yii.CSafeValidator',
- 'unsafe':'Yii.CUnsafeValidator',
- 'date':'Yii.CDateValidator'
- };
- /**
- * @var {Array} list of attributes to be validated.
- */
- Yii.CValidator.prototype.attributes = null;
- /**
- * @var {String} the user-defined error message. Different validators may define various
- * placeholders in the message that are to be replaced with actual values. All validators
- * recognize "{attribute}" placeholder, which will be replaced with the label of the attribute.
- */
- Yii.CValidator.prototype.message = null;
- /**
- * @var {Boolean} whether this validation rule should be skipped if when there is already a validation
- * error for the current attribute. Defaults to false.
- * @since 1.1.1
- */
- Yii.CValidator.prototype.skipOnError = false;
- /**
- * @var {Array} list of scenarios that the validator should be applied.
- * Each array value refers to a scenario name with the same name as its array key.
- */
- Yii.CValidator.prototype.on = null;
- /**
- * @var {Boolean} whether attributes listed with this validator should be considered safe for massive assignment.
- * Defaults to true.
- * @since 1.1.4
- */
- Yii.CValidator.prototype.safe = true;
- /**
- * @var {Boolean} whether to perform client-side validation. Defaults to true.
- * Please refer to {@link CActiveForm::enableClientValidation} for more details about client-side validation.
- * @since 1.1.7
- */
- Yii.CValidator.prototype.enableClientValidation = true;
- /**
- * Validates a single attribute.
- * This method should be overridden by child classes.
- * @param {Yii.CModel} object the data object being validated
- * @param {String} attribute the name of the attribute to be validated.
- */
- Yii.CValidator.prototype.validateAttribute = function (object, attribute) {
- };
- /**
- * Creates a validator object.
- * @param {String} name the name or class of the validator
- * @param {Yii.CModel} object the data object being validated that may contain the inline validation method
- * @param {Mixed} attributes list of attributes to be validated. This can be either an array of
- * the attribute names or a string of comma-separated attribute names.
- * @param {Array} params initial values to be applied to the validator properties
- * @returns {Yii.CValidator} the validator
- */
- Yii.CValidator.prototype.createValidator = function (name, object, attributes, params) {
- var n, on, validator, builtInValidators, className, value, nameParts, i, limit, classObject;
- if (params === undefined) {
- params = [];
- }
- if(typeof(attributes) === 'string') {
- attributes=attributes.split(/[\s,]+/);
- }
- if(params.on !== undefined) {
- if(Object.prototype.toString.call(params.on) === '[object Array]') {
- on=params.on;
- }
- else {
- on=params.on.split(/[\s,]+/);
- }
- }
- else {
- on=[];
- }
- if (object[name] !== undefined && typeof object[name] === "function") {
- validator=new Yii.CInlineValidator();
- validator.attributes=attributes;
- validator.method=name;
- validator.params=params;
- if(params.skipOnError !== undefined) {
- validator.skipOnError=params.skipOnError;
- }
- }
- else {
- params.attributes = attributes;
- if(this.builtInValidators[name] !== undefined) {
- className = this.builtInValidators[name];
- }
- else {
- className = name;
- }
-
- if (className.slice(0,3) === "Yii") {
-
- validator=new Yii[className.slice(4)]();
-
- }
- else {
- validator = new window[className]();
- }
- for (n in params) {
- if (params.hasOwnProperty(n)) {
- value = params[n];
- validator[n]=value;
- }
- }
-
- }
- validator.on=php.empty(on) ? [] : php.array_combine(on,on);
- return validator;
- };
- /**
- * Validates the specified object.
- * @param {Yii.CModel} object the data object being validated
- * @param {Array} attributes the list of attributes to be validated. Defaults to null,
- * meaning every attribute listed in {@link attributes} will be validated.
- */
- Yii.CValidator.prototype.validate = function (object, attributes) {
- var i, attribute, self = this;
-
- if (attributes === undefined) {
- attributes = null;
- }
- if(Object.prototype.toString.call(attributes) === '[object Array]') {
- attributes=php.array_intersect(this.attributes,attributes);
- }
- else {
- attributes=this.attributes;
- }
-
- Yii.forEach(attributes, function(i,attribute) {
- if(!self.skipOnError || !object.hasErrors(attribute)) {
- self.validateAttribute(object,attribute);
- }
- });
-
- };
- /**
- * Returns the JavaScript needed for performing client-side validation.
- * Do not override this method if the validator does not support client-side validation.
- * Two predefined JavaScript variables can be used:
- * <ul>
- * <li>value: the value to be validated</li>
- * <li>messages: an array used to hold the validation error messages for the value</li>
- * </ul>
- * @param {Yii.CModel} object the data object being validated
- * @param {String} attribute the name of the attribute to be validated.
- * @returns {String} the client-side validation script. Null if the validator does not support client-side validation.
- * @see CActiveForm::enableClientValidation
- * @since 1.1.7
- */
- Yii.CValidator.prototype.clientValidateAttribute = function (object, attribute) {
- };
- /**
- * Returns a value indicating whether the validator applies to the specified scenario.
- * A validator applies to a scenario as long as any of the following conditions is met:
- * <ul>
- * <li>the validator's "on" property is empty</li>
- * <li>the validator's "on" property contains the specified scenario</li>
- * </ul>
- * @param {String} scenario scenario name
- * @returns {Boolean} whether the validator applies to the specified scenario.
- * @since 1.0.2
- */
- Yii.CValidator.prototype.applyTo = function (scenario) {
- return php.empty(this.on) || this.on[scenario] !== undefined;
- };
- /**
- * Adds an error about the specified attribute to the active record.
- * This is a helper method that performs message selection and internationalization.
- * @param {Yii.CModel} object the data object being validated
- * @param {String} attribute the attribute being validated
- * @param {String} message the error message
- * @param {Array} params values for the placeholders in the error message
- */
- Yii.CValidator.prototype.addError = function (object, attribute, message, params) {
- if (params === undefined) {
- params = [];
- }
- params['{attribute}']=object.getAttributeLabel(attribute);
-
- object.addError(attribute,php.strtr(message,params));
- };
- /**
- * Checks if the given value is empty.
- * A value is considered empty if it is null, an empty array, or the trimmed result is an empty string.
- * Note that this method is different from PHP empty(). It will return false when the value is 0.
- * @param {Mixed} value the value to be checked
- * @param {Boolean} trim whether to perform trimming before checking if the string is empty. Defaults to false.
- * @returns {Boolean} whether the value is empty
- * @since 1.0.9
- */
- Yii.CValidator.prototype.isEmpty = function (value, trim) {
- if (trim === undefined) {
- trim = false;
- }
- return value===null || value===[] || value==='' || trim && (/boolean|number|string/).test(typeof value) && php.trim(value)==='';
- }/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CMessageSource is the base class for message translation repository classes.
- *
- * A message source is an application component that provides message internationalization (i18n).
- * It stores messages translated in different languages and provides
- * these translated versions when requested.
- *
- * A concrete class must implement {@link loadMessages} or override {@link translateMessage}.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CMessageSource.php 2798 2011-01-01 19:29:03Z qiang.xue $
- * @package system.i18n
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CApplicationComponent
- */
- Yii.CMessageSource = function CMessageSource () {
-
- };
- Yii.CMessageSource.prototype = new Yii.CApplicationComponent();
- Yii.CMessageSource.prototype.constructor = Yii.CMessageSource;
- /**
- * @var {Boolean} whether to force message translation when the source and target languages are the same.
- * Defaults to false, meaning translation is only performed when source and target languages are different.
- * @since 1.1.4
- */
- Yii.CMessageSource.prototype.forceTranslation = false;
- Yii.CMessageSource.prototype._language = null;
- Yii.CMessageSource.prototype._messages = {};
- /**
- * Loads the message translation for the specified language and category.
- * @param {String} category the message category
- * @param {String} language the target language
- * @returns {Object} the loaded messages
- */
- Yii.CMessageSource.prototype.loadMessages = function (category, language) {
- };
- /**
- * @returns {String} the language that the source messages are written in.
- * Defaults to {@link CApplication::language application language}.
- */
- Yii.CMessageSource.prototype.getLanguage = function () {
- return this._language===null ? Yii.app().sourceLanguage : this._language;
- };
- /**
- * @param {String} language the language that the source messages are written in.
- */
- Yii.CMessageSource.prototype.setLanguage = function (language) {
- this._language=Yii.CLocale.prototype.getCanonicalID(language);
- };
- /**
- * Translates a message to the specified language.
- *
- * Note, if the specified language is the same as
- * the {@link getLanguage source message language}, messages will NOT be translated.
- *
- * If the message is not found in the translations, an {@link onMissingTranslation}
- * event will be raised. Handlers can mark this message or do some
- * default handling. The {@link CMissingTranslationEvent::message}
- * property of the event parameter will be returned.
- *
- * @param {String} category the message category
- * @param {String} message the message to be translated
- * @param {String} language the target language. If null (default), the {@link CApplication::getLanguage application language} will be used.
- * This parameter has been available since version 1.0.3.
- * @returns {String} the translated message (or the original message if translation is not needed)
- */
- Yii.CMessageSource.prototype.translate = function (category, message, language) {
- if (language === undefined) {
- language = null;
- }
- if(language===null) {
- language=Yii.app().getLanguage();
- }
- if(this.forceTranslation || language!==this.getLanguage()) {
- return this.translateMessage(category,message,language);
- }
- else {
- return message;
- }
- };
- /**
- * Translates the specified message.
- * If the message is not found, an {@link onMissingTranslation}
- * event will be raised.
- * @param {String} category the category that the message belongs to
- * @param {String} message the message to be translated
- * @param {String} language the target language
- * @returns {String} the translated message
- */
- Yii.CMessageSource.prototype.translateMessage = function (category, message, language) {
- var key, event;
- key=language+'.'+category;
- if(this._messages[key] === undefined) {
- this._messages[key]=this.loadMessages(category,language);
- }
- if(this._messages[key][message] !== undefined && this._messages[key][message]!=='') {
- return this._messages[key][message];
- }
- else if(this.hasEventHandler('onMissingTranslation'))
- {
- event=new Yii.CMissingTranslationEvent(this,category,message,language);
- this.onMissingTranslation(event);
- return event.message;
- }
- else {
- return message;
- }
- };
- /**
- * Raised when a message cannot be translated.
- * Handlers may log this message or do some default handling.
- * The {@link CMissingTranslationEvent::message} property
- * will be returned by {@link translateMessage}.
- * @param {Yii.CMissingTranslationEvent} event the event parameter
- */
- Yii.CMessageSource.prototype.onMissingTranslation = function (event) {
- this.raiseEvent('onMissingTranslation',event);
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CFilter is the base class for all filters.
- *
- * A filter can be applied before and after an action is executed.
- * It can modify the context that the action is to run or decorate the result that the
- * action generates.
- *
- * Override {@link preFilter()} to specify the filtering logic that should be applied
- * before the action, and {@link postFilter()} for filtering logic after the action.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CFilter.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.web.filters
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CFilter = function CFilter () {
- };
- Yii.CFilter.prototype = new Yii.CComponent();
- Yii.CFilter.prototype.constructor = Yii.CFilter;
- /**
- * Performs the filtering.
- * The default implementation is to invoke {@link preFilter}
- * and {@link postFilter} which are meant to be overridden
- * child classes. If a child class needs to override this method,
- * make sure it calls <code>$filterChain->run()</code>
- * if the action should be executed.
- * @param {Yii.CFilterChain} filterChain the filter chain that the filter is on.
- */
- Yii.CFilter.prototype.filter = function (filterChain) {
- if(this.preFilter(filterChain))
- {
- filterChain.run();
- this.postFilter(filterChain);
- }
- };
- /**
- * Initializes the filter.
- * This method is invoked after the filter properties are initialized
- * and before {@link preFilter} is called.
- * You may override this method to include some initialization logic.
- * @since 1.1.4
- */
- Yii.CFilter.prototype.init = function () {
- };
- /**
- * Performs the pre-action filtering.
- * @param {Yii.CFilterChain} filterChain the filter chain that the filter is on.
- * @returns {Boolean} whether the filtering process should continue and the action
- * should be executed.
- */
- Yii.CFilter.prototype.preFilter = function (filterChain) {
- return true;
- };
- /**
- * Performs the post-action filtering.
- * @param {Yii.CFilterChain} filterChain the filter chain that the filter is on.
- */
- Yii.CFilter.prototype.postFilter = function (filterChain) {
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CViewRenderer is the base class for view renderer classes.
- *
- * A view renderer is an application component that renders views written
- * in a customized syntax.
- *
- * Once installing a view renderer as a 'viewRenderer' application component,
- * the normal view rendering process will be intercepted by the renderer.
- * The renderer will first parse the source view file and then render the
- * the resulting view file.
- *
- * Parsing results are saved as temporary files that may be stored
- * under the application runtime directory or together with the source view file.
- *
- * @originalAuthor Steve Heyns http://customgothic.com/
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CViewRenderer.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.web.renderers
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CApplicationComponent
- */
- Yii.CViewRenderer = function CViewRenderer () {
- };
- Yii.CViewRenderer.prototype = new Yii.CApplicationComponent();
- Yii.CViewRenderer.prototype.constructor = Yii.CViewRenderer;
- /**
- * @var {String} the extension name of the view file. Defaults to '.html'.
- * @since 1.0.9
- */
- Yii.CViewRenderer.prototype.fileExtension = '.html';
- /**
- * Renders a view file.
- * @param {Yii.CBaseController} context the controller or widget who is rendering the view file.
- * @param {String} sourceFile the view file path
- * @param {Mixed} data the data to be passed to the view
- * @param {Boolean} returnVar whether the rendering result should be returned
- * @returns {Mixed} the rendering result, or null if the rendering result is not needed.
- */
- Yii.CViewRenderer.prototype.renderFile = function (context, sourceFile, data, returnVar) {
- var file, viewFile;
-
- viewFile=this.getViewFile(sourceFile);
-
- return context.renderInternal(viewFile,data,returnVar);
- };
- /**
- * Generates the resulting view file path.
- * @param {String} file source view file path
- * @returns {String} resulting view file path
- */
- Yii.CViewRenderer.prototype.getViewFile = function (file) {
- return file;
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CFormElement is the base class for presenting all kinds of form element.
- *
- * CFormElement implements the way to get and set arbitrary attributes.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CFormElement.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.web.form
- * @since 1.1
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CFormElement = function CFormElement (config, parent) {
- if (config !== false) {
- this.construct(config, parent);
- }
- };
- Yii.CFormElement.prototype = new Yii.CComponent();
- Yii.CFormElement.prototype.constructor = Yii.CFormElement;
- /**
- * @var {Array} list of attributes (name=>value) for the HTML element represented by this object.
- */
- Yii.CFormElement.prototype.attributes = {};
- Yii.CFormElement.prototype._parent = null;
- Yii.CFormElement.prototype._visible = null;
- /**
- * Renders this element.
- * @returns {String} the rendering result
- */
- Yii.CFormElement.prototype.render = function () {
- };
- /**
- * Constructor.
- * @param {Mixed} config the configuration for this element.
- * @param {Mixed} parent the direct parent of this element.
- * @see configure
- */
- Yii.CFormElement.prototype.construct = function (config, parent) {
-
- this.configure(config);
- this._parent=parent;
- };
- /**
- * Converts the object to a string.
- * This is a PHP magic method.
- * The default implementation simply calls {@link render} and return
- * the rendering result.
- * @returns {String} the string representation of this object.
- */
- Yii.CFormElement.prototype.toString = function () {
- return this.render();
- };
- /**
- * Returns a property value or an attribute value.
- * Do not call this method. This is a PHP magic method that we override
- * to allow using the following syntax to read a property or attribute:
- * <pre>
- * value=element.propertyName;
- * value=element.attributeName;
- * </pre>
- * @param {String} name the property or attribute name
- * @returns {Mixed} the property or attribute value
- * @throws {Yii.CException} if the property or attribute is not defined
- * @see __set
- */
- Yii.CFormElement.prototype.get = function (name) {
- var getter;
- getter='get'+php.ucfirst(name);
- if(php.method_exists(this,getter)) {
- return this[getter]();
- }
- else if(this.attributes[name] !== undefined) {
- return this.attributes[name];
- }
- else {
- throw new Yii.CException(Yii.t('yii','Property "{class}.{property}" is not defined.',
- {'{class}':this.getClassName(), '{property}':name}));
- }
- };
- /**
- * Sets value of a property or attribute.
- * Do not call this method. This is a PHP magic method that we override
- * to allow using the following syntax to set a property or attribute.
- * <pre>
- * this.propertyName=value;
- * this.attributeName=value;
- * </pre>
- * @param {String} name the property or attribute name
- * @param {Mixed} value the property or attribute value
- * @see __get
- */
- Yii.CFormElement.prototype.set = function (name, value) {
- var setter;
- setter='set'+php.ucfirst(name);
-
- if(php.method_exists(this,setter)) {
- this[setter](value);
- }
- else if (this[name] !== undefined) {
- this[name] = value;
- }
- else {
- this.attributes[name]=value;
- }
- };
- /**
- * Configures this object with property initial values.
- * @param {Mixed} config the configuration for this object. This can be an array
- * representing the property names and their initial values.
- * It can also be a string representing the file name of the PHP script
- * that returns a configuration array.
- */
- Yii.CFormElement.prototype.configure = function (config) {
- var name, value;
-
- for (name in config) {
- if (config.hasOwnProperty(name)) {
- value = config[name];
- this.set(name,value);
- }
- }
- };
- /**
- * Returns a value indicating whether this element is visible and should be rendered.
- * This method will call {@link evaluateVisible} to determine the visibility of this element.
- * @returns {Boolean} whether this element is visible and should be rendered.
- */
- Yii.CFormElement.prototype.getVisible = function () {
- if(this._visible===null) {
- this._visible=this.evaluateVisible();
- }
- return this._visible;
- };
- /**
- * @param {Boolean} value whether this element is visible and should be rendered.
- */
- Yii.CFormElement.prototype.setVisible = function (value) {
- this._visible=value;
- };
- /**
- * @returns {Mixed} the direct parent of this element. This could be either a {@link CForm} object or a {@link CBaseController} object
- * (a controller or a widget).
- */
- Yii.CFormElement.prototype.getParent = function () {
- return this._parent;
- };
- /**
- * Evaluates the visibility of this element.
- * Child classes should override this method to implement the actual algorithm
- * for determining the visibility.
- * @returns {Boolean} whether this element is visible. Defaults to true.
- */
- Yii.CFormElement.prototype.evaluateVisible = function () {
- return true;
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CBaseController is the base class for {@link CController} and {@link CWidget}.
- *
- * It provides the common functionalities shared by controllers who need to render views.
- *
- * CBaseController also implements the support for the following features:
- * <ul>
- * <li>{@link CClipWidget Clips} : a clip is a piece of captured output that can be inserted elsewhere.</li>
- * <li>{@link CWidget Widgets} : a widget is a self-contained sub-controller with its own view and model.</li>
- * <li>{@link COutputCache Fragment cache} : fragment cache selectively caches a portion of the output.</li>
- * </ul>
- *
- * To use a widget in a view, use the following in the view:
- * <pre>
- * this.widget('path.to.widgetClass',{'property1':'value1',+++});
- * </pre>
- * or
- * <pre>
- * this.beginWidget('path.to.widgetClass',{'property1':'value1',+++});
- * // ... display other contents here
- * this.endWidget();
- * </pre>
- *
- * To create a clip, use the following:
- * <pre>
- * this.beginClip('clipID');
- * // ... display the clip contents
- * this.endClip();
- * </pre>
- * Then, in a different view or place, the captured clip can be inserted as:
- * <pre>
- * document.write(this.clips['clipID']);
- * </pre>
- *
- * To use fragment cache, do as follows,
- * <pre>
- * if(this.beginCache('cacheID',{'property1':'value1',+++})
- * {
- * // ... display the content to be cached here
- * this.endCache();
- * }
- * </pre>
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CBaseController.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.web
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CBaseController = function CBaseController() {
- };
- Yii.CBaseController.prototype = new Yii.CComponent();
- Yii.CBaseController.prototype.constructor = Yii.CBaseController;
- Yii.CBaseController.prototype._widgetStack = [];
- /**
- * Returns the view script file according to the specified view name.
- * This method must be implemented by child classes.
- * @param {String} viewName view name
- * @returns {String} the file path for the named view. False if the view cannot be found.
- */
- Yii.CBaseController.prototype.getViewFile = function (viewName) {
- };
- /**
- * Renders a view file.
- *
- * @param {String} viewFile view file path
- * @param {Array} data data to be extracted and made available to the view
- * @param {Function} callback The callback to execute
- * @throws {Yii.CException} if the view file does not exist
- */
- Yii.CBaseController.prototype.renderFile = function (viewFile, data, callback) {
- var renderer;
- if (data === undefined) {
- data = null;
- }
- if((renderer=Yii.app().getViewRenderer())!==undefined && renderer.fileExtension==='.'+(viewFile.split(".").pop())) {
- return renderer.renderFile(this,viewFile,data,callback);
- }
- else {
- return this.renderInternal(viewFile,data,callback);
- }
-
- };
- /**
- * Renders a view file.
- * This method includes the view file as a JavaScript script
- * and captures the display result if required.
- * @param {String} viewFile view file
- * @param {Array} data data to be extracted and made available to the view file
- * @param {Function} callback The callback to execute with the rendering result
- * @returns {String} the rendering result. Null if the rendering result is not required.
- */
- Yii.CBaseController.prototype.renderInternal = function (_viewFile_, _data_, _callback_) {
- var data;
- if (_data_ === undefined) {
- _data_ = null;
- }
-
- return Yii.include(_viewFile_,true, _callback_);
-
- };
- /**
- * Creates a widget and initializes it.
- * This method first creates the specified widget instance.
- * It then configures the widget's properties with the given initial values.
- * At the end it calls {@link CWidget::init} to initialize the widget.
- * Starting from version 1.1, if a {@link CWidgetFactory widget factory} is enabled,
- * this method will use the factory to create the widget, instead.
- * @param {String} className class name (can be in path alias format)
- * @param {Array} properties initial property values
- * @returns {Yii.CWidget} the fully initialized widget instance.
- */
- Yii.CBaseController.prototype.createWidget = function (className, properties) {
- var widget;
- if (properties === undefined) {
- properties = [];
- }
- widget=Yii.app().getWidgetFactory().createWidget(this,className,properties);
-
- widget.init();
- return widget;
- };
- /**
- * Creates a widget and executes it.
- * @param {String} className the widget class name or class in dot syntax (e.g. application.widgets.MyWidget)
- * @param {Array} properties list of initial property values for the widget (Property Name => Property Value)
- * @param {Boolean} captureOutput whether to capture the output of the widget. If true, the method will capture
- * and return the output generated by the widget. If false, the output will be directly sent for display
- * and the widget object will be returned. This parameter is available since version 1.1.2.
- * @returns {Mixed} the widget instance when $captureOutput is false, or the widget output when $captureOutput is true.
- */
- Yii.CBaseController.prototype.widget = function (className, properties, captureOutput) {
- var widget;
- if (properties === undefined) {
- properties = [];
- }
- widget=this.createWidget(className,properties);
- return(widget.run());
-
- };
- /**
- * Creates a widget and executes it.
- * This method is similar to {@link widget()} except that it is expecting
- * a {@link endWidget()} call to end the execution.
- * @param {String} className the widget class name or class in dot syntax (e.g. application.widgets.MyWidget)
- * @param {Array} properties list of initial property values for the widget (Property Name => Property Value)
- * @returns {Yii.CWidget} the widget created to run
- * @see endWidget
- */
- Yii.CBaseController.prototype.beginWidget = function (className, properties) {
- var widget;
- if (properties === undefined) {
- properties = [];
- }
- widget=this.createWidget(className,properties);
-
- this._widgetStack.push(widget);
- return widget;
- };
- /**
- * Ends the execution of the named widget.
- * This method is used together with {@link beginWidget()}.
- * @param {String} id optional tag identifying the method call for debugging purpose.
- * @returns {Yii.CWidget} the widget just ended running
- * @throws {Yii.CException} if an extra endWidget call is made
- * @see beginWidget
- */
- Yii.CBaseController.prototype.endWidget = function (id) {
- var widget;
- if (id === undefined) {
- id = '';
- }
- if((widget=php.array_pop(this._widgetStack))!==null)
- {
- widget.run();
- return widget;
- }
- else {
- throw new Yii.CException(Yii.t('yii','{controller} has an extra endWidget({id}) call in its view.',
- {'{controller}':php.get_class(this),'{id}':id}));
- }
- };
- /**
- * Begins recording a clip.
- * This method is a shortcut to beginning {@link CClipWidget}.
- * @param {String} id the clip ID.
- * @param {Array} properties initial property values for {@link CClipWidget}.
- */
- Yii.CBaseController.prototype.beginClip = function (id, properties) {
- if (properties === undefined) {
- properties = [];
- }
- properties.id=id;
- this.beginWidget('CClipWidget',properties);
- };
- /**
- * Ends recording a clip.
- * This method is an alias to {@link endWidget}.
- */
- Yii.CBaseController.prototype.endClip = function () {
- this.endWidget('CClipWidget');
- };
- /**
- * Begins fragment caching.
- * This method will display cached content if it is availabe.
- * If not, it will start caching and would expect a {@link endCache()}
- * call to end the cache and save the content into cache.
- * A typical usage of fragment caching is as follows,
- * <pre>
- * if(this.beginCache(id))
- * {
- * // ...generate content here
- * this.endCache();
- * }
- * </pre>
- * @param {String} id a unique ID identifying the fragment to be cached.
- * @param {Array} properties initial property values for {@link COutputCache}.
- * @returns {Boolean} whether we need to generate content for caching. False if cached version is available.
- * @see endCache
- */
- Yii.CBaseController.prototype.beginCache = function (id, properties) {
- var cache;
- if (properties === undefined) {
- properties = [];
- }
- properties.id=id;
- cache=this.beginWidget('COutputCache',properties);
- if(cache.getIsContentCached())
- {
- this.endCache();
- return false;
- }
- else {
- return true;
- }
- };
- /**
- * Ends fragment caching.
- * This is an alias to {@link endWidget}.
- * @see beginCache
- */
- Yii.CBaseController.prototype.endCache = function () {
- this.endWidget('COutputCache');
- };
- /**
- * Begins the rendering of content that is to be decorated by the specified view.
- * @param {Mixed} view the name of the view that will be used to decorate the content. The actual view script
- * is resolved via {@link getViewFile}. If this parameter is null (default),
- * the default layout will be used as the decorative view.
- * Note that if the current controller does not belong to
- * any module, the default layout refers to the application's {@link CWebApplication::layout default layout};
- * If the controller belongs to a module, the default layout refers to the module's
- * {@link CWebModule::layout default layout}.
- * @param {Object} data the variables (name=>value) to be extracted and made available in the decorative view.
- * This parameter has been available since version 1.0.4
- * @see beginContent
- * @see CContentDecorator
- */
- Yii.CBaseController.prototype.beginContent = function (view, data) {
- if (view === undefined) {
- view = null;
- }
- if (data === undefined) {
- data = {};
- }
- this.beginWidget('CContentDecorator',{'view':view, 'data':data});
- };
- /**
- * Ends the rendering of content.
- * @see beginContent
- */
- Yii.CBaseController.prototype.endContent = function () {
- this.endWidget('CContentDecorator');
- }/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CWidget is the base class for widgets.
- *
- * A widget is a self-contained component that may generate presentation
- * based on model data. It can be viewed as a micro-controller that embeds
- * into the controller-managed views.
- *
- * Compared with {@link CController controller}, a widget has neither actions nor filters.
- *
- * Usage is described at {@link CBaseController} and {@link CBaseController::widget}.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CWidget.php 3097 2011-03-17 20:01:03Z qiang.xue $
- * @package system.web.widgets
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CBaseController
- */
- Yii.CWidget = function CWidget() {
- };
- Yii.CWidget.prototype = new Yii.CBaseController();
- Yii.CWidget.prototype.constructor = Yii.CWidget;
- /**
- * @var {String} the prefix to the IDs of the {@link actions}.
- * When a widget is declared an action provider in {@link CController::actions},
- * a prefix can be specified to differentiate its action IDs from others.
- * The same prefix should then also be used to configure this property
- * when the widget is used in a view of the controller.
- * @since 1.0.1
- */
- Yii.CWidget.prototype.actionPrefix = null;
- /**
- * @var {Mixed} the name of the skin to be used by this widget. Defaults to 'default'.
- * If this is set as false, no skin will be applied to this widget.
- * @see CWidgetFactory
- * @since 1.1
- */
- Yii.CWidget.prototype.skin = 'default';
- /**
- * @var {Object} view paths for different types of widgets
- */
- Yii.CWidget.prototype._viewPaths = {};
- /**
- * @var {Integer} the counter for generating implicit IDs.
- */
- Yii.CWidget.prototype._counter = 0;
- /**
- * @var {String} id of the widget.
- */
- Yii.CWidget.prototype._id = null;
- /**
- * @var {Yii.CBaseController} owner/creator of this widget. It could be either a widget or a controller.
- */
- Yii.CWidget.prototype._owner = null;
- /**
- * Returns a list of actions that are used by this widget.
- * The structure of this method's return value is similar to
- * that returned by {@link CController::actions}.
- *
- * When a widget uses several actions, you can declare these actions using
- * this method. The widget will then become an action provider, and the actions
- * can be easily imported into a controller.
- *
- * Note, when creating URLs referring to the actions listed in this method,
- * make sure the action IDs are prefixed with {@link actionPrefix}.
- *
- * @see actionPrefix
- * @see CController::actions
- * @since 1.0.1
- */
- Yii.CWidget.prototype.actions = function () {
- return [];
- };
- /**
- * Constructor.
- * @param {Yii.CBaseController} owner owner/creator of this widget. It could be either a widget or a controller.
- */
- Yii.CWidget.prototype.construct = function (owner) {
- if (owner === undefined) {
- owner = null;
- }
- this._owner=owner===null?Yii.app().getController():owner;
- };
- /**
- * Returns the owner/creator of this widget.
- * @returns {Yii.CBaseController} owner/creator of this widget. It could be either a widget or a controller.
- */
- Yii.CWidget.prototype.getOwner = function () {
- return this._owner;
- };
- /**
- * Returns the ID of the widget or generates a new one if requested.
- * @param {Boolean} autoGenerate whether to generate an ID if it is not set previously
- * @returns {String} id of the widget.
- */
- Yii.CWidget.prototype.getId = function (autoGenerate) {
- var _counter;
- if (autoGenerate === undefined) {
- autoGenerate = true;
- }
- if(this._id!==null) {
- return this._id;
- }
- else if(autoGenerate) {
- return (this._id='yw'+Yii.CWidget.prototype._counter++);
- }
- };
- /**
- * Sets the ID of the widget.
- * @param {String} value id of the widget.
- */
- Yii.CWidget.prototype.setId = function (value) {
- this._id=value;
- };
- /**
- * Returns the controller that this widget belongs to.
- * @returns {Yii.CController} the controller that this widget belongs to.
- */
- Yii.CWidget.prototype.getController = function () {
- if(this._owner instanceof Yii.CController) {
- return this._owner;
- }
- else {
- return Yii.app().getController();
- }
- };
- /**
- * Initializes the widget.
- * This method is called by {@link CBaseController::createWidget}
- * and {@link CBaseController::beginWidget} after the widget's
- * properties have been initialized.
- */
- Yii.CWidget.prototype.init = function () {
- };
- /**
- * Executes the widget.
- * This method is called by {@link CBaseController::endWidget}.
- */
- Yii.CWidget.prototype.run = function () {
- };
- /**
- * Returns the directory containing the view files for this widget.
- * The default implementation returns the 'views' subdirectory of the directory containing the widget class file.
- * If $checkTheme is set true, the directory "ThemeID/views/ClassName" will be returned when it exists.
- * @param {Boolean} checkTheme whether to check if the theme contains a view path for the widget.
- * @returns {String} the directory containing the view files for this widget.
- */
- Yii.CWidget.prototype.getViewPath = function (checkTheme) {
- var className, _viewPaths, theme, path, viewFolder, pathParts;
- if (checkTheme === undefined) {
- checkTheme = false;
- }
- className=php.get_class(this);
- if(Yii.CWidget.prototype._viewPaths[className] !== undefined) {
- return Yii.CWidget.prototype._viewPaths[className];
- }
- else
- {
- if(checkTheme && (theme=Yii.app().getTheme())!==null) {
- path=theme.getViewPath()+"/";
- path+=className;
- return (Yii.CWidget.prototype._viewPaths[className]=path);
- }
-
- viewFolder = php.rtrim(Yii.app().getBasePath(),"/") + '/views/widgets/';
- return (Yii.CWidget.prototype._viewPaths[className]=viewFolder + className);
- }
- };
- /**
- * Looks for the view script file according to the view name.
- * This method will look for the view under the widget's {@link getViewPath viewPath}.
- * The view script file is named as "ViewName.php". A localized view file
- * may be returned if internationalization is needed. See {@link CApplication::findLocalizedFile}
- * for more details.
- * Since version 1.0.2, the view name can also refer to a path alias
- * if it contains dot characters.
- * @param {String} viewName name of the view (without file extension)
- * @returns {String} the view file path. False if the view file does not exist
- * @see CApplication::findLocalizedFile
- */
- Yii.CWidget.prototype.getViewFile = function (viewName) {
- var renderer, extension, viewFile;
- if((renderer=Yii.app().getViewRenderer())!==undefined) {
- extension=renderer.fileExtension;
- }
- else {
- extension='.js';
- }
- if(php.strpos(viewName,'.')) { // a path alias
- viewFile=Yii.getPathOfAlias(viewName);
- }
- else {
- viewFile=this.getViewPath(true)+'/'+viewName;
- return Yii.app().findLocalizedFile(viewFile+extension);
-
- }
- if(is_file(viewFile+extension)) {
- return Yii.app().findLocalizedFile(viewFile+extension);
- }
- else if(extension!=='.js' && is_file(viewFile+'.js')) {
- return Yii.app().findLocalizedFile(viewFile+'.js');
- }
- else {
- return false;
- }
- };
- /**
- * Renders a view.
- *
- * The named view refers to a PHP script (resolved via {@link getViewFile})
- * that is included by this method. If $data is an associative array,
- * it will be extracted as PHP variables and made available to the script.
- *
- * @param {String} view name of the view to be rendered. See {@link getViewFile} for details
- * about how the view script is resolved.
- * @param {Array} data data to be extracted into PHP variables and made available to the view script
- * @param {Boolean} returnVar whether the rendering result should be returned instead of being displayed to end users
- * @returns {String} the rendering result. Null if the rendering result is not required.
- * @throws {Yii.CException} if the view does not exist
- * @see getViewFile
- */
- Yii.CWidget.prototype.render = function (view, data, returnVar) {
- var viewFile;
- if (data === undefined) {
- data = null;
- }
- if (returnVar === undefined) {
- returnVar = false;
- }
- if((viewFile=this.getViewFile(view))!==false) {
- return this.renderFile(viewFile,data,returnVar);
- }
- else {
- throw new Yii.CException(Yii.t('yii','{widget} cannot find the view "{view}".',
- {'{widget}':php.get_class(this), '{view}':view}));
- }
- }/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CLogRoute is the base class for all log route classes.
- *
- * A log route object retrieves log messages from a logger and sends it
- * somewhere, such as files, emails.
- * The messages being retrieved may be filtered first before being sent
- * to the destination. The filters include log level filter and log category filter.
- *
- * To specify level filter, set {@link levels} property,
- * which takes a string of comma-separated desired level names (e.g. 'Error, Debug').
- * To specify category filter, set {@link categories} property,
- * which takes a string of comma-separated desired category names (e.g. 'System.Web, System.IO').
- *
- * Level filter and category filter are combinational, i.e., only messages
- * satisfying both filter conditions will they be returned.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CLogRoute.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.logging
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CLogRoute = function CLogRoute () {
- };
- Yii.CLogRoute.prototype = new Yii.CComponent();
- Yii.CLogRoute.prototype.constructor = Yii.CLogRoute;
- /**
- * @var {Boolean} whether to enable this log route. Defaults to true.
- * @since 1.0.7
- */
- Yii.CLogRoute.prototype.enabled = true;
- /**
- * @var {String} list of levels separated by comma or space. Defaults to empty, meaning all levels.
- */
- Yii.CLogRoute.prototype.levels = '';
- /**
- * @var {String} list of categories separated by comma or space. Defaults to empty, meaning all categories.
- */
- Yii.CLogRoute.prototype.categories = '';
- /**
- * @var {Mixed} the additional filter (eg {@link CLogFilter}) that can be applied to the log messages.
- * The value of this property will be passed to {@link Yii::createComponent} to create
- * a log filter object. As a result, this can be either a string representing the
- * filter class name or an array representing the filter configuration.
- * In general, the log filter class should be {@link CLogFilter} or a child class of it.
- * Defaults to null, meaning no filter will be used.
- * @since 1.0.6
- */
- Yii.CLogRoute.prototype.filter = null;
- /**
- * @var {Array} the logs that are collected so far by this log route.
- * @since 1.1.0
- */
- Yii.CLogRoute.prototype.logs = null;
- /**
- * Initializes the route.
- * This method is invoked after the route is created by the route manager.
- */
- Yii.CLogRoute.prototype.init = function () {
- };
- /**
- * Formats a log message given different fields.
- * @param {String} message message content
- * @param {Integer} level message level
- * @param {String} category message category
- * @param {Integer} time timestamp
- * @returns {String} formatted message
- */
- Yii.CLogRoute.prototype.formatLogMessage = function (message, level, category, time) {
- return php.date('Y/m/d H:i:s',time)+" [" + level + "] [" + category + "] " + message + "\n";
- };
- /**
- * Retrieves filtered log messages from logger for further processing.
- * @param {Yii.CLogger} logger logger instance
- * @param {Boolean} processLogs whether to process the logs after they are collected from the logger
- */
- Yii.CLogRoute.prototype.collectLogs = function (logger, processLogs) {
- var logs;
-
- if (processLogs === undefined) {
- processLogs = false;
- }
-
- logs=logger.getLogs(this.levels,this.categories);
- this.logs=php.empty(this.logs) ? logs : php.array_merge(this.logs,logs);
- if(processLogs && !php.empty(this.logs)) {
- if(this.filter!==null) {
- Yii.createComponent(this.filter).filter(this.logs);
- }
- this.processLogs(this.logs);
- }
- };
- /**
- * Processes log messages and sends them to specific destination.
- * Derived child classes must implement this method.
- * @param {Array} logs list of messages. Each array elements represents one message
- * with the following structure:
- * array(
- * [0] => message (string)
- * [1] => level (string)
- * [2] => category (string)
- * [3] => timestamp (float, obtained by microtime(true));
- */
- Yii.CLogRoute.prototype.processLogs = function (logs) {
- };/*global Yii, php, $, jQuery, console, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CWebLogRoute shows the log content in Web page.
- *
- * The log content can appear either at the end of the current Web page
- * or in FireBug console window (if {@link showInFireBug} is set true).
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CWebLogRoute.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.logging
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CLogRoute
- */
- Yii.CWebLogRoute = function CWebLogRoute () {
- };
- Yii.CWebLogRoute.prototype = new Yii.CLogRoute();
- Yii.CWebLogRoute.prototype.constructor = Yii.CWebLogRoute;
- /**
- * @var {Boolean} whether the log should be displayed in FireBug instead of browser window. Defaults to false.
- */
- Yii.CWebLogRoute.prototype.showInFireBug = false;
- /**
- * @var {Boolean} whether the log should be ignored in FireBug for ajax calls. Defaults to true.
- * This option should be used carefully, because an ajax call returns all output as a result data.
- * For example if the ajax call expects a json type result any output from the logger will cause ajax call to fail.
- */
- Yii.CWebLogRoute.prototype.ignoreAjaxInFireBug = true;
- /**
- * Displays the log messages.
- * @param {Array} logs list of log messages
- */
- Yii.CWebLogRoute.prototype.processLogs = function (logs) {
- var logView = [], i, limit, log;
- limit = logs.length;
- for (i = 0; i < limit; i++) {
- log = logs[i];
- logView.push({
- 'time': php.date('H:i:s.',log[3]) + php.sprintf('%06d',Number((log[3]-Number(log[3]))*1000000)),
- 'level': log[1],
- 'category': log[2],
- 'message': log[0]
- });
- }
- if (this.showInFireBug) {
- if (console.group !== undefined) {
- console.group("Application Log");
- }
- Yii.forEach(logView, function (index, log) {
- var func;
- if (log[1] === Yii.CLogger.prototype.LEVEL_WARNING) {
- func = "warn";
- }
- else if (log[2] === Yii.CLogger.prototype.LEVEL_ERROR) {
- func = "error";
- }
- else {
- func = "log";
- }
- if (console[func] === undefined) {
- func = "log";
- }
- console[func]("[" + log.time + "] [" + log.level + "] [" + log.category + "] " + log.message);
- });
- if (console.group !== undefined) {
- console.groupEnd();
- }
- }
- else {
- this.render('log',logView);
- }
- };
- /**
- * Renders the view.
- * @param {String} view the view name (file name without extension). The file is assumed to be located under framework/data/views.
- * @param {Array} data data to be passed to the view
- */
- Yii.CWebLogRoute.prototype.render = function (view, data) {
- var app, isAjax, viewFile;
-
- app=Yii.app();
- isAjax=app.getRequest().getIsAjaxRequest();
- if(this.showInFireBug) {
- if(isAjax && this.ignoreAjaxInFireBug) {
- return;
- }
- view+='-firebug';
- }
- else if(!(app instanceof Yii.CWebApplication) || isAjax) {
- return;
- }
- viewFile='system.views.'+view;
- jQuery("body").append(Yii.CController.prototype.renderPartial(viewFile, {data: data},true));
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CView is a base class for views
- *
- * @package system.web
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CView = function CView (config) {
- if (config !== false) {
- this.template = null;
- this.construct(config);
- }
- };
- Yii.CView.prototype = new Yii.CComponent();
- Yii.CView.prototype.constructor = Yii.CView;
- /**
- * Holds a list of registered views
- */
- Yii.CView.prototype._views = {};
-
- /**
- * Holds a list of cached templates
- * @var Object
- */
- Yii.CView.prototype._templates = {};
- /**
- * The content of the template that should be used to render this view
- * @var String
- */
- Yii.CView.prototype.template = null;
-
- /**
- * The URL of the template to use for this view.
- * @var String
- */
- Yii.CView.prototype.templateURL = null;
-
- /**
- * The layout view to use when rendering, if none specified
- * the default layout will be used.
- * @var Yii.CView
- */
- Yii.CView.prototype.layout = null;
-
- /**
- * jQuery events to delegate for this view.
- * Array should be of the following format:
- * <pre>
- * [
- * ['#selector a.someLink', 'click', function (e) { alert("clicked!")}],
- * ['#selector form', 'submit', function (e) { alert('Submitted!'); e.preventDefault(); }]
- * ]
- * </pre>
- * These events will be bound to their selectors when the view is rendered
- * @var Array
- */
- Yii.CView.prototype.delegates = [];
- /**
- * Registers a view that can be rendered later
- * @param {String} alias The alias for this view so it can be retrieved later
- * @param {Object} config An object that will be used as a configuration for a new CView
- */
- Yii.CView.prototype.registerView = function (alias, config) {
- var url;
- if (alias.indexOf("/") === -1) {
- url = Yii.getPathOfAlias(alias) + ".js";
- }
- else {
- url = alias;
- }
- Yii.CView.prototype._views[url] = config;
- };
-
- /**
- * Loads a particular view and executes the callback
- * @param {String} alias The alias of the view to load
- * @param {Function} callback The callback to execute, it will receive the loaded view as first parameter
- */
- Yii.CView.prototype.load = function (alias, callback) {
- var config, view, className, url;
- if (alias.indexOf("/") === -1) {
- url = Yii.getPathOfAlias(alias) + ".js";
- }
- else {
- url = alias;
- }
- config = Yii.CView.prototype._views[url];
-
- if (config === undefined) {
- // load the view
-
- Yii.include(url, true, function() {
- config = Yii.CView.prototype._views[url];
-
- if (config === undefined) {
- throw new Yii.CHttpException(404, "No such view: " + url);
- }
- if (config['class'] === undefined) {
- className = "CView";
- }
- else {
- className = config['class'];
- delete config['class'];
- }
- return callback(new Yii[className](config));
- });
- }
- else {
- if (config['class'] === undefined) {
- className = "CView";
- }
- else {
- className = config['class'];
- delete config['class'];
- }
- return callback(new Yii[className](config));
- }
- }
-
- /**
- * Constructs the view and applies the given configuration
- */
- Yii.CView.prototype.construct = function (config) {
- var self = this;
- if (config === undefined) {
- return;
- }
- Yii.forEach(config, function (key, value) {
- self[key] = value;
- });
- }
- /**
- * Renders the view wrapped in the layout
- * @param {Function} callback The function to execute after the view has been rendered
- */
- Yii.CView.prototype.render = function (callback) {
- var func, self = this;
- if (this.layout === null) {
- this.renderPartial(callback);
- }
- else {
- this.load(this.layout, function(layout) {
- func = function(html) {
- layout.content = html;
- layout.render(callback);
- }
- self.renderPartial(func);
- });
-
- }
- };
-
- /**
- * Renders the view
- * @param {Function} callback The function to execute after the view has been rendered
- */
- Yii.CView.prototype.renderPartial = function (callback) {
- var elements = {}, dependencies = [], stack = [], self = this, output = "", func;
- Yii.forEach(this, function(name, value) {
- if (name.slice(0,1) !== "_") {
- elements[name] = value;
- if (value instanceof Yii.CView) {
- dependencies.push(name);
- }
- }
- });
- Yii.forEach(this.delegates, function(i, item) {
- jQuery("body").undelegate(item[0], item[1]).delegate(item[0], item[1], item[2]);
- });
- func = function() {
- self.getTemplate(function(template) {
- callback(Mustache.to_html(template, self), self);
-
- });
- }
- if (dependencies.length > 0) {
- // can only call this callback when the others have completed.
- stack.push(func);
- Yii.forEach(dependencies, function(i, name) {
- stack.push(function() {
- self[name].renderPartial(function(output, parent) {
- self[name] = output;
- stack.pop()();
- });
- });
-
- });
- return stack.pop()();
- }
- else {
- func();
- }
- };
-
-
- /**
- * Gets the contents of the template
- * @param {Function} callback The function to execute after retrieving the template contents
- * @returns {String} the template contents
- */
- Yii.CView.prototype.getTemplate = function (callback) {
- var self = this, url;
-
- if (this.template === null) {
- url = this.templateURL;
- if (url.indexOf("/") === -1 && url.indexOf(".") !== -1) {
- url = Yii.getPathOfAlias(url) + ".tpl";
- }
- if (this._templates[url] !== undefined) {
- this.template = this._templates[url];
- callback(this.template, this);
- }
- else {
- jQuery.ajax(url, {
- success: function(data) {
- self._templates[url] = data;
- self.template = data;
- callback(self.template, self);
- },
- error: function (xhr) {
- self._template = "ERROR: " + xhr.responseText;
- callback(self.template, self);
- }
-
- });
- }
- }
- else {
- callback(this.template, this);
- }
- return this.template;
- };
-
- /**
- * Sets the contents of the template
- * @param {String} value The template contents
- */
- Yii.CView.prototype.setTemplate = function (value) {
- this.template = value;
- }
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CApplication is the base class for all application classes.
- *
- * An application serves as the global context that the user request
- * is being processed. It manages a set of application components that
- * provide specific functionalities to the whole application.
- *
- * The core application components provided by CApplication are the following:
- * <ul>
- * <li>{@link getErrorHandler errorHandler}: handles JavaScript errors and
- * uncaught exceptions. This application component is dynamically loaded when needed.</li>
- * <li>{@link getSecurityManager securityManager}: provides security-related
- * services, such as hashing, encryption. This application component is dynamically
- * loaded when needed.</li>
- * <li>{@link getStatePersister statePersister}: provides global state
- * persistence method. This application component is dynamically loaded when needed.</li>
- * <li>{@link getCache cache}: provides caching feature. This application component is
- * disabled by default.</li>
- * <li>{@link getMessages messages}: provides the message source for translating
- * application messages. This application component is dynamically loaded when needed.</li>
- * <li>{@link getCoreMessages coreMessages}: provides the message source for translating
- * Yii framework messages. This application component is dynamically loaded when needed.</li>
- * </ul>
- *
- * CApplication will undergo the following lifecycles when processing a user request:
- * <ol>
- * <li>load application configuration;</li>
- * <li>set up class autoloader and error handling;</li>
- * <li>load static application components;</li>
- * <li>{@link onBeginRequest}: preprocess the user request;</li>
- * <li>{@link processRequest}: process the user request;</li>
- * <li>{@link onEndRequest}: postprocess the user request;</li>
- * </ol>
- *
- * Starting from lifecycle 3, if a JavaScript error or an uncaught exception occurs,
- * the application will switch to its error handling logic and jump to step 6 afterwards.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CApplication.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.base
- * @since 1.0
- *
- * @property string $basePath Returns the root path of the application.
- * @property CCache $cache Returns the cache component.
- * @property CPhpMessageSource $coreMessages Returns the core message translations.
- * @property CDateFormatter $dateFormatter Returns the locale-dependent date formatter.
- * @property CDbConnection $db Returns the database connection component.
- * @property CErrorHandler $errorHandler Returns the error handler component.
- * @property string $extensionPath Returns the root directory that holds all third-party extensions.
- * @property string $id Returns the unique identifier for the application.
- * @property string $language Returns the language that the user is using and the application should be targeted to.
- * @property CLocale $locale Returns the locale instance.
- * @property string $localeDataPath Returns the directory that contains the locale data.
- * @property CMessageSource $messages Returns the application message translations component.
- * @property CNumberFormatter $numberFormatter The locale-dependent number formatter.
- * @property CHttpRequest $request Returns the request component.
- * @property string $runtimePath Returns the directory that stores runtime files.
- * @property CSecurityManager $securityManager Returns the security manager component.
- * @property CStatePersister $statePersister Returns the state persister component.
- * @property string $timeZone Returns the time zone used by this application.
- * @property CUrlManager $urlManager Returns the URL manager component.
- * @author Charles Pick
- * @class
- * @extends Yii.CModule
- */
- Yii.CApplication = function CApplication (config) {
- if (config !== false) {
- this.construct(config);
- }
- };
- Yii.CApplication.prototype = new Yii.CModule(false);
- Yii.CApplication.prototype.constructor = Yii.CApplication;
- /**
- * @var {String} the application name. Defaults to 'My Application'.
- */
- Yii.CApplication.prototype.name = 'My Application';
- /**
- * @var {String} the charset currently used for the application. Defaults to 'UTF-8'.
- */
- Yii.CApplication.prototype.charset = 'UTF-8';
- /**
- * @var {String} the language that the application is written in. This mainly refers to
- * the language that the messages and view files are in. Defaults to 'en_us' (US English).
- */
- Yii.CApplication.prototype.sourceLanguage = 'en_us';
- Yii.CApplication.prototype._id = null;
- Yii.CApplication.prototype._basePath = null;
- Yii.CApplication.prototype._runtimePath = null;
- Yii.CApplication.prototype._extensionPath = null;
- Yii.CApplication.prototype._globalState = null;
- Yii.CApplication.prototype._stateChanged = null;
- Yii.CApplication.prototype._ended = false;
- Yii.CApplication.prototype._language = null;
- Yii.CApplication.prototype._timezone = null;
- /**
- * Processes the request.
- * This is the place where the actual request processing work is done.
- * Derived classes should override this method.
- */
- Yii.CApplication.prototype.processRequest = function () {
- };
- /**
- * Constructor.
- * @param {Mixed} config application configuration.
- * If a string, it is treated as the path of the file that contains the configuration;
- * If an array, it is the actual configuration information.
- * Please make sure you specify the {@link getBasePath basePath} property in the configuration,
- * which should point to the directory containing all application logic, template and data.
- * If not, the directory will be defaulted to 'protected'.
- */
- Yii.CApplication.prototype.construct = function (config) {
- if (config === undefined) {
- config = {};
- }
- Yii.setApplication(this);
-
- // set basePath at early as possible to avoid trouble
-
- if(config.basePath !== undefined) {
- this.setBasePath(config.basePath);
- delete config.basePath;
- }
- else {
- this.setBasePath('protected');
- }
- Yii.setPathOfAlias('application',this.getBasePath());
- Yii.setPathOfAlias('webroot',location.protocol + "//" + location.hostname + "/");
- Yii.setPathOfAlias('ext',this.getBasePath()+'/'+'extensions');
- this.preinit();
-
- this.initSystemHandlers();
- this.registerCoreComponents();
- this.configure(config);
- this.attachBehaviors(this.behaviors);
- this.preloadComponents();
- this.init();
- };
- /**
- * Runs the application.
- * This method loads static application components. Derived classes usually overrides this
- * method to do more application-specific tasks.
- * Remember to call the parent implementation so that static application components are loaded.
- */
- Yii.CApplication.prototype.run = function () {
- try {
- if(this.hasEventHandler('onBeginRequest')) {
- this.onBeginRequest(new Yii.CEvent(this));
- }
- Yii.beginProfile("Request");
- this.processRequest();
- Yii.endProfile("Request");
- if(this.hasEventHandler('onEndRequest')) {
- this.onEndRequest(new Yii.CEvent(this));
- }
- }
- catch (e) {
- if (e instanceof TypeError) {
- this.displayError("TypeError",e);
- }
- else if (e instanceof Yii.CException) {
- this.displayException(e);
- }
- else {
- this.displayError("Error",e);
- }
- }
- };
- /**
- * Terminates the application.
- * This method replaces JavaScript's exit() function by calling
- * {@link onEndRequest} before exiting.
- * @param {Integer} status exit status (value 0 means normal exit while other values mean abnormal exit).
- * @param {Boolean} exit whether to exit the current request. This parameter has been available since version 1.1.5.
- * It defaults to true, meaning the JavaScript's exit() function will be called at the end of this method.
- */
- Yii.CApplication.prototype.end = function (status, exit) {
- if (status === undefined) {
- status = 0;
- }
- if (exit === undefined) {
- exit = true;
- }
- if(this.hasEventHandler('onEndRequest')) {
- this.onEndRequest(new Yii.CEvent(this));
- }
- if(exit) {
- exit(status);
- }
- };
- /**
- * Raised right BEFORE the application processes the request.
- * @param {Yii.CEvent} event the event parameter
- */
- Yii.CApplication.prototype.onBeginRequest = function (event) {
- this.raiseEvent('onBeginRequest',event);
- };
- /**
- * Raised right AFTER the application processes the request.
- * @param {Yii.CEvent} event the event parameter
- */
- Yii.CApplication.prototype.onEndRequest = function (event) {
- if(!this._ended) {
- this._ended=true;
- this.raiseEvent('onEndRequest',event);
- }
- };
- /**
- * Returns the unique identifier for the application.
- * @returns {String} the unique identifier for the application.
- */
- Yii.CApplication.prototype.getId = function () {
- if(this._id!==null) {
- return this._id;
- }
- else {
- return (this._id=php.sprintf('%x',php.crc32(this.getBasePath()+this.name)));
- }
- };
- /**
- * Sets the unique identifier for the application.
- * @param {String} id the unique identifier for the application.
- */
- Yii.CApplication.prototype.setId = function (id) {
- this._id=id;
- };
- /**
- * Returns the root path of the application.
- * @returns {String} the root directory of the application. Defaults to 'protected'.
- */
- Yii.CApplication.prototype.getBasePath = function () {
- return this._basePath;
- };
- /**
- * Sets the root directory of the application.
- * This method can only be invoked at the begin of the constructor.
- * @param {String} path the root directory of the application.
- */
- Yii.CApplication.prototype.setBasePath = function (path) {
- this._basePath = path;
- };
- /**
- * Returns the directory that stores runtime files.
- * @returns {String} the directory that stores runtime files. Defaults to 'protected/runtime'.
- */
- Yii.CApplication.prototype.getRuntimePath = function () {
- if(this._runtimePath!==null) {
- return this._runtimePath;
- }
- else
- {
- this.setRuntimePath(this.getBasePath()+"/runtime");
- return this._runtimePath;
- }
- };
- /**
- * Sets the directory that stores runtime files.
- * @param {String} path the directory that stores runtime files.
- */
- Yii.CApplication.prototype.setRuntimePath = function (path) {
- this._runtimePath= path;
- };
- /**
- * Returns the root directory that holds all third-party extensions.
- * @returns {String} the directory that contains all extensions. Defaults to the 'extensions' directory under 'protected'.
- */
- Yii.CApplication.prototype.getExtensionPath = function () {
- return Yii.getPathOfAlias('ext');
- };
- /**
- * Sets the root directory that holds all third-party extensions.
- * @param {String} path the directory that contains all third-party extensions.
- */
- Yii.CApplication.prototype.setExtensionPath = function (path) {
- Yii.setPathOfAlias('ext',path);
- };
- /**
- * Returns the language that the user is using and the application should be targeted to.
- * @returns {String} the language that the user is using and the application should be targeted to.
- * Defaults to the {@link sourceLanguage source language}.
- */
- Yii.CApplication.prototype.getLanguage = function () {
- return this._language===null ? this.sourceLanguage : this._language;
- };
- /**
- * Specifies which language the application is targeted to.
- *
- * This is the language that the application displays to end users.
- * If set null, it uses the {@link sourceLanguage source language}.
- *
- * Unless your application needs to support multiple languages, you should always
- * set this language to null to maximize the application's performance.
- * @param {String} language the user language (e.g. 'en_US', 'zh_CN').
- * If it is null, the {@link sourceLanguage} will be used.
- */
- Yii.CApplication.prototype.setLanguage = function (language) {
- this._language=language;
- };
- /**
- * Returns the time zone used by this application.
- * @returns {String} the time zone used by this application.
- * @see http://php.net/manual/en/function.date-default-timezone-get.php
- * @since 1.0.9
- */
- Yii.CApplication.prototype.getTimeZone = function () {
- if (this._timezone === null) {
- this._timezone = jzTimezoneDetector.determine_timezone().timezone.olson_tz;
- }
- return this._timezone;
- };
- /**
- * Sets the time zone used by this application.
- * This is a simple wrapper of JavaScript function date_default_timezone_set().
- * @param {String} value the time zone used by this application.
- * @see http://php.net/manual/en/function.date-default-timezone-set.php
- * @since 1.0.9
- */
- Yii.CApplication.prototype.setTimeZone = function (value) {
- this._timezone = value;
- };
- /**
- * Returns the localized version of a specified file.
- *
- * The searching is based on the specified language code. In particular,
- * a file with the same name will be looked for under the subdirectory
- * named as the locale ID. For example, given the file "path/to/view.php"
- * and locale ID "zh_cn", the localized file will be looked for as
- * "path/to/zh_cn/view.php". If the file is not found, the original file
- * will be returned.
- *
- * For consistency, it is recommended that the locale ID is given
- * in lower case and in the format of LanguageID_RegionID (e.g. "en_us").
- *
- * @param {String} srcFile the original file
- * @param {String} srcLanguage the language that the original file is in. If null, the application {@link sourceLanguage source language} is used.
- * @param {String} language the desired language that the file should be localized to. If null, the {@link getLanguage application language} will be used.
- * @returns {String} the matching localized file. The original file is returned if no localized version is found
- * or if source language is the same as the desired language.
- */
- Yii.CApplication.prototype.findLocalizedFile = function (srcFile, srcLanguage, language) {
- var desiredFile;
- if (srcLanguage === undefined) {
- srcLanguage = null;
- }
- if (language === undefined) {
- language = null;
- }
- if(srcLanguage===null) {
- srcLanguage=this.sourceLanguage;
- }
- if(language===null) {
- language=this.getLanguage();
- }
- if(language===srcLanguage) {
- return srcFile;
- }
-
- // TODO: fix this and determine how to deal with localized files
- return srcFile;
- //desiredFile=php.dirname(srcFile)+DIRECTORY_SEPARATOR+language+DIRECTORY_SEPARATOR+php.basename(srcFile);
- //return is_file(desiredFile) ? desiredFile : srcFile;
- };
- /**
- * Returns the locale instance.
- * @param {String} localeID the locale ID (e.g. en_US). If null, the {@link getLanguage application language ID} will be used.
- * @returns {Yii.CLocale} the locale instance
- */
- Yii.CApplication.prototype.getLocale = function (localeID) {
- if (localeID === undefined) {
- localeID = null;
- }
- return Yii.CLocale.getInstance(localeID===null?this.getLanguage():localeID);
- };
- /**
- * Returns the directory that contains the locale data.
- * @returns {String} the directory that contains the locale data. It defaults to 'framework/i18n/data'.
- * @since 1.1.0
- */
- Yii.CApplication.prototype.getLocaleDataPath = function () {
- var dataPath;
- return Yii.CLocale.dataPath===null ? Yii.getPathOfAlias('system.i18n.data') : Yii.CLocale.dataPath;
- };
- /**
- * Sets the directory that contains the locale data.
- * @param {String} value the directory that contains the locale data.
- * @since 1.1.0
- */
- Yii.CApplication.prototype.setLocaleDataPath = function (value) {
- var dataPath;
- Yii.CLocale.dataPath=value;
- };
- /**
- * @returns {Yii.CNumberFormatter} the locale-dependent number formatter.
- * The current {@link getLocale application locale} will be used.
- */
- Yii.CApplication.prototype.getNumberFormatter = function () {
- return this.getLocale().getNumberFormatter();
- };
- /**
- * Returns the locale-dependent date formatter.
- * @returns {Yii.CDateFormatter} the locale-dependent date formatter.
- * The current {@link getLocale application locale} will be used.
- */
- Yii.CApplication.prototype.getDateFormatter = function () {
- return this.getLocale().getDateFormatter();
- };
- /**
- * Returns the database connection component.
- * @returns {Yii.CDbConnection} the database connection
- */
- Yii.CApplication.prototype.getDb = function () {
- return this.getComponent('db');
- };
- /**
- * Returns the error handler component.
- * @returns {Yii.CErrorHandler} the error handler application component.
- */
- Yii.CApplication.prototype.getErrorHandler = function () {
- return this.getComponent('errorHandler');
- };
- /**
- * Returns the security manager component.
- * @returns {Yii.CSecurityManager} the security manager application component.
- */
- Yii.CApplication.prototype.getSecurityManager = function () {
- return this.getComponent('securityManager');
- };
- /**
- * Returns the state persister component.
- * @returns {Yii.CStatePersister} the state persister application component.
- */
- Yii.CApplication.prototype.getStatePersister = function () {
- return this.getComponent('statePersister');
- };
- /**
- * Returns the cache component.
- * @returns {Yii.CCache} the cache application component. Null if the component is not enabled.
- */
- Yii.CApplication.prototype.getCache = function () {
- return this.getComponent('cache');
- };
- /**
- * Returns the core message translations component.
- * @returns {Yii.CPhpMessageSource} the core message translations
- */
- Yii.CApplication.prototype.getCoreMessages = function () {
- return this.getComponent('coreMessages');
- };
- /**
- * Returns the application message translations component.
- * @returns {Yii.CMessageSource} the application message translations
- */
- Yii.CApplication.prototype.getMessages = function () {
- return this.getComponent('messages');
- };
- /**
- * Returns the request component.
- * @returns {Yii.CHttpRequest} the request component
- */
- Yii.CApplication.prototype.getRequest = function () {
- return this.getComponent('request');
- };
- /**
- * Returns the URL manager component.
- * @returns {Yii.CUrlManager} the URL manager component
- */
- Yii.CApplication.prototype.getUrlManager = function () {
- return this.getComponent('urlManager');
- };
- /**
- * Returns a global value.
- *
- * A global value is one that is persistent across users sessions and requests.
- * @param {String} key the name of the value to be returned
- * @param {Mixed} defaultValue the default value. If the named global value is not found, this will be returned instead.
- * @returns {Mixed} the named global value
- * @see setGlobalState
- */
- Yii.CApplication.prototype.getGlobalState = function (key, defaultValue) {
- if (defaultValue === undefined) {
- defaultValue = null;
- }
- if(this._globalState===null) {
-
- this.loadGlobalState();
- }
- if(this._globalState[key] !== undefined) {
- return this._globalState[key];
- }
- else {
- return defaultValue;
- }
- };
- /**
- * Sets a global value.
- *
- * A global value is one that is persistent across users sessions and requests.
- * Make sure that the value is serializable and unserializable.
- * @param {String} key the name of the value to be saved
- * @param {Mixed} value the global value to be saved. It must be serializable.
- * @param {Mixed} defaultValue the default value. If the named global value is the same as this value, it will be cleared from the current storage.
- * @see getGlobalState
- */
- Yii.CApplication.prototype.setGlobalState = function (key, value, defaultValue) {
- var changed;
- if (defaultValue === undefined) {
- defaultValue = null;
- }
- if(this._globalState===null) {
- this.loadGlobalState();
- }
- changed=this._stateChanged;
- if(value===defaultValue) {
- if(this._globalState[key] !== undefined) {
- delete this._globalState[key];
- this._stateChanged=true;
- }
- }
- else if(this._globalState[key] === undefined || this._globalState[key]!==value) {
- this._globalState[key]=value;
- this._stateChanged=true;
- }
- if(this._stateChanged!==changed) {
- this.saveGlobalState();
- }
- };
- /**
- * Clears a global value.
- *
- * The value cleared will no longer be available in this request and the following requests.
- * @param {String} key the name of the value to be cleared
- */
- Yii.CApplication.prototype.clearGlobalState = function (key) {
- this.setGlobalState(key,true,true);
- };
- /**
- * Loads the global state data from persistent storage.
- * @see getStatePersister
- * @throws {Yii.CException} if the state persister is not available
- */
- Yii.CApplication.prototype.loadGlobalState = function () {
- var persister;
- persister=this.getStatePersister();
- if((this._globalState=persister.load())===null) {
- this._globalState={};
- }
- this._stateChanged=false;
- };
- /**
- * Saves the global state data into persistent storage.
- * @see getStatePersister
- * @throws {Yii.CException} if the state persister is not available
- */
- Yii.CApplication.prototype.saveGlobalState = function () {
- if(this._stateChanged) {
- this._stateChanged=false;
- this.getStatePersister().save(this._globalState);
- }
- };
- /**
- * Handles uncaught JavaScript exceptions.
- *
- * This method is implemented as a JavaScript exception handler. It requires
- * that constant YII_ENABLE_EXCEPTION_HANDLER be defined true.
- *
- * This method will first raise an {@link onException} event.
- * If the exception is not handled by any event handler, it will call
- * {@link getErrorHandler errorHandler} to process the exception.
- *
- * The application will be terminated by this method.
- *
- * @param {Exception} exception exception that is not caught
- */
- Yii.CApplication.prototype.handleException = function (exception) {
- var category, message, event, handler, msg;
- // disable error capturing to avoid recursive errors
-
- category='exception.'+php.get_class(exception);
- if(exception instanceof Yii.CHttpException) {
- category+='.'+exception.statusCode;
- }
- message=exception.message;
-
- Yii.log(message,Yii.CLogger.LEVEL_ERROR,category);
- try
- {
- event=new Yii.CExceptionEvent(this,exception);
- this.onException(event);
- if(!event.handled) {
- // try an error handler
- if((handler=this.getErrorHandler())!==null) {
- handler.handle(event);
- }
- else {
- this.displayException(exception);
- }
- }
- }
- catch(e) {
- this.displayException(e);
- }
- try
- {
- this.end(1);
- return;
- }
- catch(e) {
- // use the most primitive way to log error
- msg = php.get_class(e)+': '+e.message+"\n";
- msg += e.getTraceAsString()+"\n";
- msg += "Previous exception:\n";
- msg += php.get_class(exception)+': '+exception.message+"\n";
- msg += exception.getTraceAsString()+"\n";
- console.log(msg);
- return;
- }
- };
- /**
- * Handles JavaScript execution errors such as warnings, notices.
- *
- * This method is implemented as a JavaScript error handler. It requires
- * that constant YII_ENABLE_ERROR_HANDLER be defined true.
- *
- * This method will first raise an {@link onError} event.
- * If the error is not handled by any event handler, it will call
- * {@link getErrorHandler errorHandler} to process the error.
- *
- * The application will be terminated by this method.
- *
- * @param {Integer} code the level of the error raised
- * @param {String} message the error message
- * @param {String} file the filename that the error was raised in
- * @param {Integer} line the line number the error was raised at
- */
- Yii.CApplication.prototype.handleError = function (code, message, file, line) {
- var log = "", trace, t, i, event, handler, msg;
- if(code) {
- log="message (" + file + ":" + line + ")\nStack trace:\n";
- trace=Yii.CException.prototype.stacktrace();
- // skip the first 3 stacks as they do not tell the error position
- if(php.count(trace)>3) {
- trace=php.array_slice(trace,3);
- }
- for (i in trace) {
- if (trace.hasOwnProperty(i)) {
- t = trace[i];
- if(t.file === undefined) {
- t.file='unknown';
- }
- if(t.line === undefined) {
- t.line=0;
- }
- if(t['function'] === undefined) {
- t['function']='unknown';
- }
- log+="#i " + t.file + "(" + t.line + "): ";
- if(t.object !== undefined && (!t.object instanceof Array && t.object !== null && typeof(t.object) === 'object')) {
- log+=php.get_class(t.object)+'.';
- }
- log+= t['function'] + "()\n";
- }
- }
- Yii.log(log, Yii.CLogger.prototype.LEVEL_ERROR, "js");
- try {
- event = new Yii.CErrorEvent(this, code, message, file, line);
- this.onError(event);
- if (!event.handled) {
- // try an error handler
- handler = this.getErrorHandler();
- if (handler !== null) {
- handler.handle(event);
- }
- else {
- this.displayError(code, message, file, line);
- }
- }
- }
- catch (e) {
- this.displayException(e);
- }
-
- try {
- this.end(1);
- }
- catch(e) {
- // use the most primitive way to log error
- msg = php.get_class(e)+': '+e.message+"\n";
- msg += e.getTraceAsString()+"\n";
- msg += "Previous error:\n";
- msg += log + "\n";
- console.log(msg);
- return;
- }
- }
- };
- /**
- * Raised when an uncaught JavaScript exception occurs.
- *
- * An event handler can set the {@link CExceptionEvent::handled handled}
- * property of the event parameter to be true to indicate no further error
- * handling is needed. Otherwise, the {@link getErrorHandler errorHandler}
- * application component will continue processing the error.
- *
- * @param {Yii.CExceptionEvent} event event parameter
- */
- Yii.CApplication.prototype.onException = function (event) {
- this.raiseEvent('onException',event);
- };
- /**
- * Raised when a JavaScript execution error occurs.
- *
- * An event handler can set the {@link CErrorEvent::handled handled}
- * property of the event parameter to be true to indicate no further error
- * handling is needed. Otherwise, the {@link getErrorHandler errorHandler}
- * application component will continue processing the error.
- *
- * @param {Yii.CErrorEvent} event event parameter
- */
- Yii.CApplication.prototype.onError = function (event) {
- this.raiseEvent('onError',event);
- };
- /**
- * Displays the captured JavaScript error.
- * This method displays the error in HTML when there is
- * no active error handler.
- * @param {Integer} code error code
- * @param {String} message error message
- * @param {String} file error file
- * @param {String} line error line
- */
- Yii.CApplication.prototype.displayError = function (code, message, file, line) {
- var trace, t, i;
- if(YII_DEBUG) {
- document.write("<h1>JavaScript Error [" + code + "]</h1>\n");
- document.write("<p>" + message + "(" + file + ":" + line + ")</p>\n");
- document.write('<table class="yiiLog" width="100%" cellpadding="2" style="border-spacing:1px;font:11px Verdana, Arial, Helvetica, sans-serif;background:#EEEEEE;color:#666666;">');
- document.write('<tr style="background-color:#ccc;">');
- document.write("<th style='width:120px'>Timestamp</th>");
- document.write("<th>Level</th>");
- document.write("<th>Category</th>");
- document.write("<th>Message</th>");
- document.write("</tr>");
- Yii.forEach(Yii._logger.getLogs(), function (i, log) {
- document.write("<tr><td>" + php.date('H:i:s.',log[3]) + php.sprintf('%06d',Number((log[3]-Number(log[3]))*1000000)) + "</td><td>" + log[1] + "</td><td>" + log[2] + "</td><td>" + log[0] + "</td></tr>");
- });
- document.write("</table>");
- document.write("<h2>Stack Trace</h2>");
- document.write('<pre>');
- trace=Yii.CException.prototype.stacktrace();
- // skip the first 3 stacks as they do not tell the error position
- if(php.count(trace)>3) {
- trace=php.array_slice(trace,3);
- }
- for (i in trace) {
- if (trace.hasOwnProperty(i)) {
- document.write(trace[i] + "\n");
- }
- }
- document.write("</pre>");
- }
- else {
- document.write("<h1>JavaScript Error [" + code + "]</h1>\n");
- document.write("<p>" + message + "</p>\n");
- }
- };
- /**
- * Displays the uncaught JavaScript exception.
- * This method displays the exception in HTML when there is
- * no active error handler.
- * @param {Exception} exception the uncaught exception
- */
- Yii.CApplication.prototype.displayException = function (exception) {
- if(YII_DEBUG) {
- document.write('<h1>'+php.get_class(exception)+"</h1>\n");
- document.write('<p>'+exception.getMessage()+'</p>');
- document.write('<pre>'+exception.getTraceAsString()+'</pre>');
- }
- else
- {
- document.write('<h1>'+php.get_class(exception)+"</h1>\n");
- document.write('<p>'+exception.getMessage()+'</p>');
- }
- };
- /**
- * Initializes the class autoloader and error handlers.
- */
- Yii.CApplication.prototype.initSystemHandlers = function () {
- return;
- window.onerror = function (err, loc) {
- Yii.app().displayError("",err);
- return false;
- };
- };
- /**
- * Registers the core application components.
- * @see setComponents
- */
- Yii.CApplication.prototype.registerCoreComponents = function () {
- var components;
- components={
- 'coreMessages':{
- 'class':'CJavaScriptMessageSource',
- 'language':'en_us',
- 'basePath':YII_PATH + '/messages'
- },
- 'db':{
- 'class':'CDbConnection'
- },
- 'messages':{
- 'class':'CJavaScriptMessageSource'
- },
- 'errorHandler':{
- 'class':'CErrorHandler'
- },
- 'securityManager':{
- 'class':'CSecurityManager'
- },
- 'statePersister':{
- 'class':'CStatePersister'
- },
- 'urlManager':{
- 'class':'CUrlManager'
- },
- 'request':{
- 'class':'CHttpRequest'
- },
- 'format':{
- 'class':'CFormatter'
- }
- };
- this.setComponents(components);
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CBehavior is a convenient base class for behavior classes.
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CBehavior.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.base
- * @since 1.0.2
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CBehavior = function CBehavior() {
- };
- Yii.CBehavior.prototype = new Yii.CComponent();
- Yii.CBehavior.prototype.constructor = Yii.CBehavior;
- Yii.CBehavior.prototype._enabled = null;
- Yii.CBehavior.prototype._owner = null;
- /**
- * Declares events and the corresponding event handler methods.
- * The events are defined by the {@link owner} component, while the handler
- * methods by the behavior class. The handlers will be attached to the corresponding
- * events when the behavior is attached to the {@link owner} component; and they
- * will be detached from the events when the behavior is detached from the component.
- * @returns {Object} events (keys) and the corresponding event handler methods (values).
- */
- Yii.CBehavior.prototype.events = function () {
- return {};
- };
- /**
- * Attaches the behavior object to the component.
- * The default implementation will set the {@link owner} property
- * and attach event handlers as declared in {@link events}.
- * Make sure you call the parent implementation if you override this method.
- * @param {Yii.CComponent} owner the component that this behavior is to be attached to.
- */
- Yii.CBehavior.prototype.attach = function (owner) {
- var eventHandler, event, handler;
- this._owner=owner;
- eventHandler = this.events();
- for (event in eventHandler) {
- if (eventHandler.hasOwnProperty(event)) {
- handler = eventHandler[event];
- owner.attachEventHandler(event,[this,handler]);
- }
- }
- };
- /**
- * Detaches the behavior object from the component.
- * The default implementation will unset the {@link owner} property
- * and detach event handlers declared in {@link events}.
- * Make sure you call the parent implementation if you override this method.
- * @param {Yii.CComponent} owner the component that this behavior is to be detached from.
- */
- Yii.CBehavior.prototype.detach = function (owner) {
- var eventHandler, event, handler;
- eventHandler = this.events();
- for (event in eventHandler) {
- if (eventHandler.hasOwnProperty(event)) {
- handler = eventHandler[event];
- owner.detachEventHandler(event,[this,handler]);
- }
- }
- this._owner=null;
- };
- /**
- * @returns {Yii.CComponent} the owner component that this behavior is attached to.
- */
- Yii.CBehavior.prototype.getOwner = function () {
- return this._owner;
- };
- /**
- * @returns {Boolean} whether this behavior is enabled
- */
- Yii.CBehavior.prototype.getEnabled = function () {
- return this._enabled;
- };
- /**
- * @param {Boolean} value whether this behavior is enabled
- */
- Yii.CBehavior.prototype.setEnabled = function (value) {
- var eventHandler, event, handler, eventHandlerList;
- if(this._enabled!=value && this._owner) {
- if(value) {
- eventHandler = this.events();
- for (event in eventHandler) {
- if (eventHandler.hasOwnProperty(event)) {
- handler = eventHandler[event];
- this._owner.attachEventHandler(event,[this,handler]);
- }
- }
- }
- else {
- eventHandlerList = this.events();
- for (event in eventHandlerList) {
- if (eventHandlerList.hasOwnProperty(event)) {
- handler = eventHandlerList[event];
- this._owner.detachEventHandler(event,[this,handler]);
- }
- }
- }
- }
- this._enabled=value;
- }/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CErrorEvent represents the parameter for the {@link CApplication::onError onError} event.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CErrorEvent.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CEvent
- */
- Yii.CErrorEvent = function CErrorEvent () {
- };
- Yii.CErrorEvent.prototype = new Yii.CEvent();
- Yii.CErrorEvent.prototype.constructor = Yii.CErrorEvent;
- /**
- * @var {String} error code
- */
- Yii.CErrorEvent.prototype.code = null;
- /**
- * @var {String} error message
- */
- Yii.CErrorEvent.prototype.message = null;
- /**
- * @var {String} error message
- */
- Yii.CErrorEvent.prototype.file = null;
- /**
- * @var {String} error file
- */
- Yii.CErrorEvent.prototype.line = null;
- /**
- * Constructor.
- * @param {Mixed} sender sender of the event
- * @param {String} code error code
- * @param {String} message error message
- * @param {String} file error file
- * @param {Integer} line error line
- */
- Yii.CErrorEvent.prototype.construct = function (sender, code, message, file, line) {
- this.code=code;
- this.message=message;
- this.file=file;
- this.line=line;
- parent.__construct(sender);
- }/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CExceptionEvent represents the parameter for the {@link CApplication::onException onException} event.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CExceptionEvent.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CEvent
- */
- Yii.CExceptionEvent = function CExceptionEvent (sender, exception) {
- this.construct(sender, exception);
- };
- Yii.CExceptionEvent.prototype = new Yii.CEvent();
- Yii.CExceptionEvent.prototype.constructor = Yii.CExceptionEvent;
- /**
- * @var {Yii.CException} the exception that this event is about.
- */
- Yii.CExceptionEvent.prototype.exception = null;
- /**
- * Constructor.
- * @param {Mixed} sender sender of the event
- * @param {Yii.CException} exception the exception
- */
- Yii.CExceptionEvent.prototype.construct = function (sender, exception) {
- this.exception=exception;
- Yii.CEvent.prototype.construct.call(this, sender);
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CHttpException represents an exception caused by invalid operations of end-users.
- *
- * The HTTP error code can be obtained via {@link statusCode}.
- * Error handlers may use this status code to decide how to format the error page.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CHttpException.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CException
- */
- Yii.CHttpException = function CHttpException (status, message, code) {
-
- this.construct(status, message, code);
- };
- Yii.CHttpException.prototype = new Yii.CException(false);
- Yii.CHttpException.prototype.constructor = Yii.CHttpException;
- /**
- * @var {Integer} HTTP status code, such as 403, 404, 500, etc.
- */
- Yii.CHttpException.prototype.statusCode = null;
- /**
- * Constructor.
- * @param {Integer} status HTTP status code, such as 404, 500, etc.
- * @param {String} message error message
- * @param {Integer} code error code
- */
- Yii.CHttpException.prototype.construct = function (status, message, code) {
- if (message === undefined) {
- message = null;
- }
- if (code === undefined) {
- code = 0;
- }
- this.statusCode=status;
-
- Yii.CException.call(this, message, code);
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CModel is the base class providing the common features needed by data model objects.
- *
- * CModel defines the basic framework for data models that need to be validated.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CModel.php 3087 2011-03-15 02:08:53Z qiang.xue $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CModel = function CModel () {
- };
- Yii.CModel.prototype = new Yii.CComponent();
- Yii.CModel.prototype.constructor = Yii.CModel;
- Yii.CModel.prototype._errors = {};
- Yii.CModel.prototype._validators = null;
- Yii.CModel.prototype._scenario = '';
- /**
- * Returns the list of attribute names of the model.
- * @returns {Array} list of attribute names.
- * @since 1.0.1
- */
- Yii.CModel.prototype.attributeNames = function () {
-
- };
- /**
- * Returns the validation rules for attributes.
- *
- * This method should be overridden to declare validation rules.
- * Each rule is an object with the following structure:
- * <pre>
- * {
- * attributes: 'attribute list',
- * validator: 'validator name',
- * on: 'scenario name', ...validation parameters...
- * }
- * </pre>
- * where
- * <ul>
- * <li>attributes: specifies the attributes (separated by commas) to be validated;</li>
- * <li>validator: specifies the validator to be used. It can be the name of a model class
- * method, the name of a built-in validator, or a validator class.
- * A validation method must have the following signature:
- * <pre>
- * // params refers to validation parameters given in the rule
- * function validatorName(attribute, params)
- * </pre>
- * A built-in validator refers to one of the validators declared in {@link Yii.CValidator.builtInValidators}.
- * And a validator class is a class extending {@link Yii.CValidator}.</li>
- * <li>on: this specifies the scenarios when the validation rule should be performed.
- * Separate different scenarios with commas. If this option is not set, the rule
- * will be applied in any scenario. Please see {@link Yii.CModel.scenario} for more details about this option.</li>
- * <li>additional parameters are used to initialize the corresponding validator properties.
- * Please refer to individal validator class API for possible properties.</li>
- * </ul>
- *
- * The following are some examples:
- * <pre>
- * [
- * {
- * attributes: 'username',
- * validator: 'required'
- * },
- * {
- * attributes: 'username',
- * validator: 'length',
- * min: 3,
- * max: 12
- * },
- * {
- * attributes: 'password',
- * validator: 'compare',
- * compareAttribute: 'password2',
- * on: 'register'
- * },
- * {
- * attributes: 'password',
- * validator: 'authenticate',
- * on: 'login'
- * }
- * ];
- * </pre>
- *
- * @returns {Array} validation rules to be applied when {@link validate()} is called.
- * @see scenario
- */
- Yii.CModel.prototype.rules = function () {
- return [];
- };
- /**
- * Returns a list of behaviors that this model should behave as.
- * The return value should be an array of behavior configurations indexed by
- * behavior names. Each behavior configuration can be either a string specifying
- * the behavior class or an array of the following structure:
- * <pre>
- * 'behaviorName':{
- * 'class':'path.to.BehaviorClass',
- * 'property1':'value1',
- * 'property2':'value2',
- * }
- * </pre>
- *
- * Note, the behavior classes must implement {@link IBehavior} or extend from
- * {@link CBehavior}. Behaviors declared in this method will be attached
- * to the model when it is instantiated.
- *
- * For more details about behaviors, see {@link CComponent}.
- * @returns {Object} the behavior configurations (behavior name=>behavior configuration)
- * @since 1.0.2
- */
- Yii.CModel.prototype.behaviors = function () {
- return {};
- };
- /**
- * Returns the attribute labels.
- * Attribute labels are mainly used in error messages of validation.
- * By default an attribute label is generated using {@link generateAttributeLabel}.
- * This method allows you to explicitly specify attribute labels.
- *
- * Note, in order to inherit labels defined in the parent class, a child class needs to
- * merge the parent labels with child labels using functions like array_merge().
- *
- * @returns {Object} attribute labels (name=>label)
- * @see generateAttributeLabel
- */
- Yii.CModel.prototype.attributeLabels = function () {
- return {};
- };
- /**
- * Performs the validation.
- *
- * This method executes the validation rules as declared in {@link rules}.
- * Only the rules applicable to the current {@link scenario} will be executed.
- * A rule is considered applicable to a scenario if its 'on' option is not set
- * or contains the scenario.
- *
- * Errors found during the validation can be retrieved via {@link getErrors}.
- *
- * @param {Array} attributes list of attributes that should be validated. Defaults to null,
- * meaning any attribute listed in the applicable validation rules should be
- * validated. If this parameter is given as a list of attributes, only
- * the listed attributes will be validated.
- * @param {Boolean} clearErrors whether to call {@link clearErrors} before performing validation
- * @returns {Boolean} whether the validation is successful without any error.
- * @see beforeValidate
- * @see afterValidate
- */
- Yii.CModel.prototype.validate = function (attributes, clearErrors) {
- var i, limit, validatorList, validator;
- if (attributes === undefined) {
- attributes = null;
- }
- if (clearErrors === undefined) {
- clearErrors = true;
- }
- if (clearErrors) {
- this.clearErrors();
- }
- if(this.beforeValidate()) {
- validatorList = this.getValidators();
-
- limit = validatorList.length;
- for (i = 0; i < limit; i++) {
- validator = validatorList[i];
- validator.validate(this,attributes);
- }
-
- this.afterValidate();
- return !this.hasErrors();
- }
- else {
- return false;
- }
- };
- /**
- * This method is invoked after a model instance is created by new operator.
- * The default implementation raises the {@link onAfterConstruct} event.
- * You may override this method to do postprocessing after model creation.
- * Make sure you call the parent implementation so that the event is raised properly.
- */
- Yii.CModel.prototype.afterConstruct = function () {
- if(this.hasEventHandler('onAfterConstruct')) {
- this.onAfterConstruct(new Yii.CEvent(this));
- }
- };
- /**
- * This method is invoked before validation starts.
- * The default implementation calls {@link onBeforeValidate} to raise an event.
- * You may override this method to do preliminary checks before validation.
- * Make sure the parent implementation is invoked so that the event can be raised.
- * @returns {Boolean} whether validation should be executed. Defaults to true.
- * If false is returned, the validation will stop and the model is considered invalid.
- */
- Yii.CModel.prototype.beforeValidate = function () {
- var event;
-
- event=new Yii.CModelEvent(this);
-
- this.onBeforeValidate(event);
- return event.isValid;
- };
- /**
- * This method is invoked after validation ends.
- * The default implementation calls {@link onAfterValidate} to raise an event.
- * You may override this method to do postprocessing after validation.
- * Make sure the parent implementation is invoked so that the event can be raised.
- */
- Yii.CModel.prototype.afterValidate = function () {
- this.onAfterValidate(new Yii.CEvent(this));
- };
- /**
- * This event is raised after the model instance is created by new operator.
- * @param {Yii.CEvent} event the event parameter
- * @since 1.0.2
- */
- Yii.CModel.prototype.onAfterConstruct = function (event) {
- this.raiseEvent('onAfterConstruct',event);
- };
- /**
- * This event is raised before the validation is performed.
- * @param {Yii.CModelEvent} event the event parameter
- * @since 1.0.2
- */
- Yii.CModel.prototype.onBeforeValidate = function (event) {
- this.raiseEvent('onBeforeValidate',event);
- };
- /**
- * This event is raised after the validation is performed.
- * @param {Yii.CEvent} event the event parameter
- * @since 1.0.2
- */
- Yii.CModel.prototype.onAfterValidate = function (event) {
- this.raiseEvent('onAfterValidate',event);
- };
- /**
- * Returns all the validators declared in the model.
- * This method differs from {@link getValidators} in that the latter
- * would only return the validators applicable to the current {@link scenario}.
- * Also, since this method return a {@link CList} object, you may
- * manipulate it by inserting or removing validators (useful in behaviors).
- * For example, <code>$model->validatorList->add($newValidator)</code>.
- * The change made to the {@link CList} object will persist and reflect
- * in the result of the next call of {@link getValidators}.
- * @returns {Yii.CList} all the validators declared in the model.
- * @since 1.1.2
- */
- Yii.CModel.prototype.getValidatorList = function () {
- if(this._validators===null) {
- this._validators=this.createValidators();
- }
- return this._validators;
- };
- /**
- * Returns the validators applicable to the current {@link scenario}.
- * @param {String} attribute the name of the attribute whose validators should be returned.
- * If this is null, the validators for ALL attributes in the model will be returned.
- * @returns {Array} the validators applicable to the current {@link scenario}.
- * @since 1.0.1
- */
- Yii.CModel.prototype.getValidators = function (attribute) {
- var validators, scenario, i, limit, validator;
- if (attribute === undefined) {
- attribute = null;
- }
- if(this._validators===null) {
- this._validators=this.createValidators();
- }
- validators=[];
- scenario=this.getScenario();
- limit = this._validators.length;
- for (i = 0; i < limit; i++) {
- validator = this._validators[i];
- if(validator.applyTo(scenario)) {
- if(attribute===null || php.in_array(attribute,validator.attributes,true)) {
- validators.push(validator);
- }
- }
- }
-
- return validators;
- };
- /**
- * Creates validator objects based on the specification in {@link rules}.
- * This method is mainly used internally.
- * @returns {Yii.CList} validators built based on {@link rules()}.
- */
- Yii.CModel.prototype.createValidators = function () {
- var validators, i, ruleList, rule, validator, validatorName = null, attributes = null;
- validators=[];
- ruleList = this.rules();
- for (i in ruleList) {
- if (ruleList.hasOwnProperty(i)) {
- rule = ruleList[i];
- attributes = rule.attributes;
- delete rule.attributes;
- validatorName = rule.validator;
- delete rule.validator;
-
- if(attributes !== undefined && validatorName !== undefined) { // attributes, validator name
-
- validator = new Yii.CValidator();
- validators.push(validator.createValidator(validatorName,this,attributes,rule));
- }
- else {
- throw new Yii.CException(Yii.t('yii','{class} has an invalid validation rule. The rule must specify attributes to be validated and the validator name.',
- {'{class}':php.get_class(this)}));
- }
- }
- }
- return validators;
- };
- /**
- * Returns a value indicating whether the attribute is required.
- * This is determined by checking if the attribute is associated with a
- * {@link CRequiredValidator} validation rule in the current {@link scenario}.
- * @param {String} attribute attribute name
- * @returns {Boolean} whether the attribute is required
- * @since 1.0.2
- */
- Yii.CModel.prototype.isAttributeRequired = function (attribute) {
- var i, validatorList, validator;
- validatorList = this.getValidators(attribute);
- for (i in validatorList) {
- if (validatorList.hasOwnProperty(i)) {
- validator = validatorList[i];
- if(validator instanceof Yii.CRequiredValidator) {
- return true;
- }
- }
- }
- return false;
- };
- /**
- * Returns a value indicating whether the attribute is safe for massive assignments.
- * @param {String} attribute attribute name
- * @returns {Boolean} whether the attribute is safe for massive assignments
- * @since 1.1
- */
- Yii.CModel.prototype.isAttributeSafe = function (attribute) {
- var attributes;
- attributes=this.getSafeAttributeNames();
-
- return php.in_array(attribute,attributes);
- };
- /**
- * Returns the text label for the specified attribute.
- * @param {String} attribute the attribute name
- * @returns {String} the attribute label
- * @see generateAttributeLabel
- * @see attributeLabels
- */
- Yii.CModel.prototype.getAttributeLabel = function (attribute) {
- var labels;
- labels=this.attributeLabels();
- if(labels[attribute] !== undefined) {
- return labels[attribute];
- }
- else {
- return this.generateAttributeLabel(attribute);
- }
- };
- /**
- * Returns a value indicating whether there is any validation error.
- * @param {String} attribute attribute name. Use null to check all attributes.
- * @returns {Boolean} whether there is any error.
- */
- Yii.CModel.prototype.hasErrors = function (attribute) {
- var i;
- if (attribute === undefined) {
- attribute = null;
- }
- if(attribute===null) {
- for (i in this._errors) {
- if (this._errors.hasOwnProperty(i)) {
- return true;
- }
- }
- return false;
- }
- else {
- return this._errors[attribute] !== undefined;
- }
- };
- /**
- * Returns the errors for all attribute or a single attribute.
- * @param {String} attribute attribute name. Use null to retrieve errors for all attributes.
- * @returns {Array} errors for all attributes or the specified attribute. Empty array is returned if no error.
- */
- Yii.CModel.prototype.getErrors = function (attribute) {
- if (attribute === undefined) {
- attribute = null;
- }
- if(attribute===null) {
- return this._errors;
- }
- else {
- return this._errors[attribute] !== undefined ? this._errors[attribute] : [];
- }
- };
- /**
- * Returns the first error of the specified attribute.
- * @param {String} attribute attribute name.
- * @returns {String} the error message. Null is returned if no error.
- * @since 1.0.2
- */
- Yii.CModel.prototype.getError = function (attribute) {
- return this._errors[attribute] !== undefined ? php.reset(this._errors[attribute]) : null;
- };
- /**
- * Adds a new error to the specified attribute.
- * @param {String} attribute attribute name
- * @param {String} error new error message
- */
- Yii.CModel.prototype.addError = function (attribute, error) {
- if (this._errors[attribute] === undefined) {
- this._errors[attribute] = [];
- }
- this._errors[attribute].push(error);
- };
- /**
- * Adds a list of errors.
- * @param {Array} errors a list of errors. The array keys must be attribute names.
- * The array values should be error messages. If an attribute has multiple errors,
- * these errors must be given in terms of an array.
- * You may use the result of {@link getErrors} as the value for this parameter.
- * @since 1.0.5
- */
- Yii.CModel.prototype.addErrors = function (errors) {
- var error, i, attribute, e;
- for (attribute in errors) {
- if (errors.hasOwnProperty(attribute)) {
- error = errors[attribute];
- if(Object.prototype.toString.call(error) === '[object Array]') {
- for (i in error) {
- if (error.hasOwnProperty(i)) {
- e = error[i];
- if (this._errors[attribute] === undefined) {
- this._errors[attribute] = [];
- }
- this._errors[attribute].push(e);
- }
- }
- }
- else {
- if (this._errors[attribute] === undefined) {
- this._errors[attribute] = [];
- }
- this._errors[attribute].push(error);
- }
- }
- }
- };
- /**
- * Removes errors for all attributes or a single attribute.
- * @param {String} attribute attribute name. Use null to remove errors for all attribute.
- */
- Yii.CModel.prototype.clearErrors = function (attribute) {
- if (attribute === undefined) {
- attribute = null;
- }
- if(attribute===null) {
- this._errors={};
- }
- else {
- delete this._errors[attribute];
- }
- };
- /**
- * Generates a user friendly attribute label.
- * This is done by replacing underscores or dashes with blanks and
- * changing the first letter of each word to upper case.
- * For example, 'department_name' or 'DepartmentName' becomes 'Department Name'.
- * @param {String} name the column name
- * @returns {String} the attribute label
- */
- Yii.CModel.prototype.generateAttributeLabel = function (name) {
- return php.trim(name.replace(/([A-Z])/g, ' $1').replace(/_|-|\./g, ' ')).replace(/^./, function (str) {
- return str.toUpperCase();
- }
- );
- };
- /**
- * Returns all attribute values.
- * @param {Array} names list of attributes whose value needs to be returned.
- * Defaults to null, meaning all attributes as listed in {@link attributeNames} will be returned.
- * If it is an array, only the attributes in the array will be returned.
- * @returns {Array} attribute values (name=>value).
- */
- Yii.CModel.prototype.getAttributes = function (names) {
- var values, i, nameList, name, values2, n;
- if (names === undefined) {
- names = null;
- }
- values={};
- nameList = this.attributeNames();
- for (i in nameList) {
- if (nameList.hasOwnProperty(i)) {
- name = nameList[i];
- values[name]=this.name;
- }
- }
- if(Object.prototype.toString.call(names) === '[object Array]') {
- values2=[];
- for (n in names) {
- if (names.hasOwnProperty(n)) {
- name = names[n];
- values2[name] = (values[name] !== undefined ? values[name] : null);
- }
- }
- return values2;
- }
- else {
- return values;
- }
- };
- /**
- * Sets the attribute values in a massive way.
- * @param {Array} values attribute values (name=>value) to be set.
- * @param {Boolean} safeOnly whether the assignments should only be done to the safe attributes.
- * A safe attribute is one that is associated with a validation rule in the current {@link scenario}.
- * @see getSafeAttributeNames
- * @see attributeNames
- */
- Yii.CModel.prototype.setAttributes = function (values, safeOnly) {
- var attributes, name, value;
- if (safeOnly === undefined) {
- safeOnly = true;
- }
- if(!values instanceof Object) {
- return;
- }
- attributes=php.array_flip(safeOnly ? this.getSafeAttributeNames() : this.attributeNames());
- for (name in values) {
- if (values.hasOwnProperty(name)) {
- value = values[name];
- if(attributes[name] !== undefined) {
- this.name=value;
- }
- else if(safeOnly) {
- this.onUnsafeAttribute(name,value);
- }
- }
- }
- };
- /**
- * Unsets the attributes.
- * @param {Array} names list of attributes to be set null. If this parameter is not given,
- * all attributes as specified by {@link attributeNames} will have their values unset.
- * @since 1.1.3
- */
- Yii.CModel.prototype.unsetAttributes = function (names) {
- var i, name;
- if (names === undefined) {
- names = null;
- }
- if(names===null) {
- names=this.attributeNames();
- }
- for (i in names) {
- if (names.hasOwnProperty(i)) {
- name = names[i];
- this.name=null;
- }
- }
- };
- /**
- * This method is invoked when an unsafe attribute is being massively assigned.
- * The default implementation will log a warning message if YII_DEBUG is on.
- * It does nothing otherwise.
- * @param {String} name the unsafe attribute name
- * @param {Mixed} value the attribute value
- * @since 1.1.1
- */
- Yii.CModel.prototype.onUnsafeAttribute = function (name, value) {
- if(YII_DEBUG) {
- Yii.log(Yii.t('yii','Failed to set unsafe attribute "{attribute}".',{'{attribute}':name}),Yii.CLogger.LEVEL_WARNING);
- }
- };
- /**
- * Returns the scenario that this model is used in.
- *
- * Scenario affects how validation is performed and which attributes can
- * be massively assigned.
- *
- * A validation rule will be performed when calling {@link validate()}
- * if its 'on' option is not set or contains the current scenario value.
- *
- * And an attribute can be massively assigned if it is associated with
- * a validation rule for the current scenario. Note that an exception is
- * the {@link CUnsafeValidator unsafe} validator which marks the associated
- * attributes as unsafe and not allowed to be massively assigned.
- *
- * @returns {String} the scenario that this model is in.
- * @since 1.0.4
- */
- Yii.CModel.prototype.getScenario = function () {
- return this._scenario;
- };
- /**
- * Sets the scenario for the model.
- * @param {String} value the scenario that this model is in.
- * @see getScenario
- * @since 1.0.4
- */
- Yii.CModel.prototype.setScenario = function (value) {
- this._scenario=value;
- };
- /**
- * Returns the attribute names that are safe to be massively assigned.
- * A safe attribute is one that is associated with a validation rule in the current {@link scenario}.
- * @returns {Array} safe attribute names
- * @since 1.0.2
- */
- Yii.CModel.prototype.getSafeAttributeNames = function () {
- var attributes, unsafe, i, validatorList, validator, n, name, j, k;
- attributes=[];
- unsafe=[];
- validatorList = this.getValidators();
- for (i in validatorList) {
- if (validatorList.hasOwnProperty(i)) {
- validator = validatorList[i];
- if(!validator.safe) {
- for (n in validator.attributes) {
- if (validator.attributes.hasOwnProperty(n)) {
- name = validator.attributes[n];
- unsafe.push(name);
- }
- }
- }
- else
- {
- for (j in validator.attributes) {
- if (validator.attributes.hasOwnProperty(j)) {
- name = validator.attributes[j];
- attributes[name]=true;
- }
- }
- }
- }
- }
- for (k in unsafe) {
- if (unsafe.hasOwnProperty(k)) {
- name = unsafe[k];
- delete attributes[name];
- }
- }
- return php.array_keys(attributes);
- };
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CModelBehavior is a base class for behaviors that are attached to a model component.
- * The model should extend from {@link CModel} or its child classes.
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CModelBehavior.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.base
- * @since 1.0.2
- * @author Charles Pick
- * @class
- * @extends Yii.CBehavior
- */
- Yii.CModelBehavior = function CModelBehavior() {
- };
- Yii.CModelBehavior.prototype = new Yii.CBehavior();
- Yii.CModelBehavior.prototype.constructor = Yii.CModelBehavior;
- /**
- * Declares events and the corresponding event handler methods.
- * The default implementation returns 'onBeforeValidate' and 'onAfterValidate' events and handlers.
- * If you override this method, make sure you merge the parent result to the return value.
- * @returns {Object} events (keys) and the corresponding event handler methods (values).
- * @see CBehavior::events
- */
- Yii.CModelBehavior.prototype.events = function () {
- return {
- 'onAfterConstruct':'afterConstruct',
- 'onBeforeValidate':'beforeValidate',
- 'onAfterValidate':'afterValidate'
- };
- };
- /**
- * Responds to {@link CModel::onAfterConstruct} event.
- * Overrides this method if you want to handle the corresponding event of the {@link CBehavior::owner owner}.
- * @param {Yii.CEvent} event event parameter
- */
- Yii.CModelBehavior.prototype.afterConstruct = function (event) {
- };
- /**
- * Responds to {@link CModel::onBeforeValidate} event.
- * Overrides this method if you want to handle the corresponding event of the {@link owner}.
- * You may set {@link CModelEvent::isValid} to be false to quit the validation process.
- * @param {Yii.CModelEvent} event event parameter
- */
- Yii.CModelBehavior.prototype.beforeValidate = function (event) {
- };
- /**
- * Responds to {@link CModel::onAfterValidate} event.
- * Overrides this method if you want to handle the corresponding event of the {@link owner}.
- * @param {Yii.CEvent} event event parameter
- */
- Yii.CModelBehavior.prototype.afterValidate = function (event) {
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CModelEvent class.
- *
- * CModelEvent represents the event parameters needed by events raised by a model.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CModelEvent.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CEvent
- */
- Yii.CModelEvent = function CModelEvent () {
- };
- Yii.CModelEvent.prototype = new Yii.CEvent();
- Yii.CModelEvent.prototype.constructor = Yii.CModelEvent;
- /**
- * @var {Boolean} whether the model is in valid status and should continue its normal method execution cycles. Defaults to true.
- * For example, when this event is raised in a {@link CFormModel} object that is executing {@link CModel::beforeValidate},
- * if this property is set false by the event handler, the {@link CModel::validate} method will quit after handling this event.
- * If true, the normal execution cycles will continue, including performing the real validations and calling
- * {@link CModel::afterValidate}.
- */
- Yii.CModelEvent.prototype.isValid = true;
- /**
- * @var {Yii.CDbCrireria} the query criteria that is passed as a parameter to a find method of {@link CActiveRecord}.
- * Note that this property is only used by {@link CActiveRecord::onBeforeFind} event.
- * This property could be null.
- * @since 1.1.5
- */
- Yii.CModelEvent.prototype.criteria = null;/*global Yii, php, sjcl, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CSecurityManager provides private keys, hashing and encryption functions.
- *
- * CSecurityManager is used by Yii components and applications for security-related purpose.
- * For example, it is used in cookie validation feature to prevent cookie data
- * from being tampered.
- *
- * CSecurityManager is mainly used to protect data from being tampered and viewed.
- * It can generate HMAC and encrypt the data. The private key used to generate HMAC
- * is set by {@link setValidationKey ValidationKey}. The key used to encrypt data is
- * specified by {@link setEncryptionKey EncryptionKey}. If the above keys are not
- * explicitly set, random keys will be generated and used.
- *
- * To protected data with HMAC, call {@link hashData()}; and to check if the data
- * is tampered, call {@link validateData()}, which will return the real data if
- * it is not tampered. The algorithm used to generated HMAC is specified by
- * {@link validation}.
- *
- * To encrypt and decrypt data, call {@link encrypt()} and {@link decrypt()}
- * respectively, which uses 3DES encryption algorithm. Note, the PHP Mcrypt
- * extension must be installed and loaded.
- *
- * CSecurityManager is a core application component that can be accessed via
- * {@link CApplication::getSecurityManager()}.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CSecurityManager.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CApplicationComponent
- */
- Yii.CSecurityManager = function CSecurityManager() {
- };
- Yii.CSecurityManager.prototype = new Yii.CApplicationComponent();
- Yii.CSecurityManager.prototype.constructor = Yii.CSecurityManager;
- /**
- * @const
- */
- Yii.CSecurityManager.STATE_VALIDATION_KEY = 'Yii.CSecurityManager.validationkey';
- /**
- * @const
- */
- Yii.CSecurityManager.STATE_ENCRYPTION_KEY = 'Yii.CSecurityManager.encryptionkey';
- /**
- * @var {String} the name of the hashing algorithm to be used by {@link computeHMAC}.
- *
- * Defaults to 'sha1', meaning using SHA1 hash algorithm.
- * @since 1.1.3
- */
- Yii.CSecurityManager.prototype.hashAlgorithm = 'sha1';
-
- Yii.CSecurityManager.prototype._validationKey = null;
- Yii.CSecurityManager.prototype._encryptionKey = null;
- /**
- * @returns {String} a randomly generated private key
- */
- Yii.CSecurityManager.prototype.generateRandomKey = function () {
- return php.sprintf('%08x%08x%08x%08x',php.mt_rand(),php.mt_rand(),php.mt_rand(),php.mt_rand());
- };
- /**
- * @returns {String} the private key used to generate HMAC.
- * If the key is not explicitly set, a random one is generated and returned.
- */
- Yii.CSecurityManager.prototype.getValidationKey = function () {
- var key;
- if(this._validationKey!==null) {
- return this._validationKey;
- }
- else {
- if((key=Yii.app().getGlobalState(this.STATE_VALIDATION_KEY))!==null) {
- this.setValidationKey(key);
- }
- else {
- key=this.generateRandomKey();
- this.setValidationKey(key);
- Yii.app().setGlobalState(this.STATE_VALIDATION_KEY,key);
- }
- return this._validationKey;
- }
- };
- /**
- * @param {String} value the key used to generate HMAC
- * @throws {Yii.CException} if the key is empty
- */
- Yii.CSecurityManager.prototype.setValidationKey = function (value) {
- if(!php.empty(value)) {
- this._validationKey=value;
- }
- else {
- throw new Yii.CException(Yii.t('yii','CSecurityManager.validationKey cannot be empty.'));
- }
- };
- /**
- * @returns {String} the private key used to encrypt/decrypt data.
- * If the key is not explicitly set, a random one is generated and returned.
- */
- Yii.CSecurityManager.prototype.getEncryptionKey = function () {
- var key;
- if(this._encryptionKey!==null) {
- return this._encryptionKey;
- }
- else {
- if((key=Yii.app().getGlobalState(this.STATE_ENCRYPTION_KEY))!==null) {
- this.setEncryptionKey(key);
- }
- else {
- key=this.generateRandomKey();
- this.setEncryptionKey(key);
- Yii.app().setGlobalState(this.STATE_ENCRYPTION_KEY,key);
- }
- return this._encryptionKey;
- }
- };
- /**
- * @param {String} value the key used to encrypt/decrypt data.
- * @throws {Yii.CException} if the key is empty
- */
- Yii.CSecurityManager.prototype.setEncryptionKey = function (value) {
- if(!php.empty(value)) {
- this._encryptionKey=value;
- }
- else {
- throw new Yii.CException(Yii.t('yii','CSecurityManager.encryptionKey cannot be empty.'));
- }
- };
- /**
- * This method has been deprecated since version 1.1.3.
- * Please use {@link hashAlgorithm} instead.
- */
- Yii.CSecurityManager.prototype.getValidation = function () {
- return this.hashAlgorithm;
- };
- /**
- * This method has been deprecated since version 1.1.3.
- * Please use {@link hashAlgorithm} instead.
- * @param {String} value -
- */
- Yii.CSecurityManager.prototype.setValidation = function (value) {
- this.hashAlgorithm=value;
- };
- /**
- * Encrypts data.
- * @param {String} data data to be encrypted.
- * @param {String} key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
- * @returns {String} the encrypted data
- * @throws {Yii.CException} if PHP Mcrypt extension is not loaded
- */
- Yii.CSecurityManager.prototype.encrypt = function (data, key) {
- var module, iv, encrypted;
- if (key === undefined) {
- key = null;
- }
- module=this.openCryptModule();
- key=key===null ? php.md5(this.getEncryptionKey()) : key;
- encrypted = module.encrypt(key, data);
- return encrypted;
- };
- /**
- * Decrypts data
- * @param {String} data data to be decrypted.
- * @param {String} key the decryption key. This defaults to null, meaning using {@link getEncryptionKey EncryptionKey}.
- * @returns {String} the decrypted data
- * @throws {Yii.CException} if PHP Mcrypt extension is not loaded
- */
- Yii.CSecurityManager.prototype.decrypt = function (data, key) {
- var module, ivSize, iv, decrypted;
- if (key === undefined) {
- key = null;
- }
- module=this.openCryptModule();
- key=key===null ? php.md5(this.getEncryptionKey()) : key;
- decrypted = module.decrypt(key, data);
- return decrypted;
- };
- /**
- * Opens the mcrypt module with the configuration specified in {@link cryptAlgorithm}.
- * @returns {Resource} the mycrypt module handle.
- * @since 1.1.3
- */
- Yii.CSecurityManager.prototype.openCryptModule = function () {
- var module;
- if(sjcl !== undefined) {
- return sjcl;
- }
- else {
- throw new Yii.CException(Yii.t('yii','CSecurityManager requires the Stanford Javascript Crypto Library to be loaded in order to use data encryption feature.'));
- }
- };
- /**
- * Prefixes data with an HMAC.
- * @param {String} data data to be hashed.
- * @param {String} key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
- * @returns {String} data prefixed with HMAC
- */
- Yii.CSecurityManager.prototype.hashData = function (data, key) {
- if (key === undefined) {
- key = null;
- }
- return this.computeHMAC(data,key)+data;
- };
- /**
- * Validates if data is tampered.
- * @param {String} data data to be validated. The data must be previously
- * generated using {@link hashData()}.
- * @param {String} key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
- * @returns {String} the real data with HMAC stripped off. False if the data
- * is tampered.
- */
- Yii.CSecurityManager.prototype.validateData = function (data, key) {
- var len, hmac, data2;
- if (key === undefined) {
- key = null;
- }
- len=php.strlen(this.computeHMAC('test'));
-
- if(php.strlen(data)>=len) {
- hmac=data.slice(0, len);
- data2=data.slice(len);
- return hmac===this.computeHMAC(data2,key)?data2:false;
- }
- else {
- return false;
- }
- };
- /**
- * Computes the HMAC for the data with {@link getValidationKey ValidationKey}.
- * @param {String} data data to be generated HMAC
- * @param {String} key the private key to be used for generating HMAC. Defaults to null, meaning using {@link validationKey}.
- * @returns {String} the HMAC for the data
- */
- Yii.CSecurityManager.prototype.computeHMAC = function (data, key) {
- var pack, func, hmac;
- if (key === undefined) {
- key = null;
- }
- if(key===null) {
- key=this.getValidationKey();
- }
- hmac = new sjcl.misc.hmac(key);
- return php.md5(hmac.encrypt(data).join(""));
-
- };
-
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CStatePersister implements a file-based persistent data storage.
- *
- * It can be used to keep data available through multiple requests and sessions.
- *
- * By default, CStatePersister stores data in a file named 'state.bin' that is located
- * under the application {@link CApplication::getRuntimePath runtime path}.
- * You may change the location by setting the {@link stateFile} property.
- *
- * To retrieve the data from CStatePersister, call {@link load()}. To save the data,
- * call {@link save()}.
- *
- * Comparison among state persister, session and cache is as follows:
- * <ul>
- * <li>session: data persisting within a single user session.</li>
- * <li>state persister: data persisting through all requests/sessions (e.g. hit counter).</li>
- * <li>cache: volatile and fast storage. It may be used as storage medium for session or state persister.</li>
- * </ul>
- *
- * Since server resource is often limited, be cautious if you plan to use CStatePersister
- * to store large amount of data. You should also consider using database-based persister
- * to improve the throughput.
- *
- * CStatePersister is a core application component used to store global application state.
- * It may be accessed via {@link CApplication::getStatePersister()}.
- * page state persistent method based on cache.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CStatePersister.php 3165 2011-04-06 08:27:40Z mdomba $
- * @package system.base
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CApplicationComponent
- */
- Yii.CStatePersister = function CStatePersister() {
- };
- Yii.CStatePersister.prototype = new Yii.CApplicationComponent();
- Yii.CStatePersister.prototype.constructor = Yii.CStatePersister;
- /**
- * Initializes the component.
- * This method overrides the parent implementation by making sure the
- * browser supports localStorage
- */
- Yii.CStatePersister.prototype.init = function () {
- Yii.CApplicationComponent.prototype.init.call(this);
-
- try {
- return "localStorage" in window && window.localStorage !== null;
- }
- catch (e) {
- throw new Yii.CException(Yii.t('yii','Unable to access local storage, please ensure that you\'re using a modern browser!'));
- }
- };
- /**
- * Loads state data from persistent storage.
- * @returns {Mixed} state data. Null if no state data available.
- */
- Yii.CStatePersister.prototype.load = function () {
- var state = {}, i, value;
- if(window.localStorage.length !== 0) {
-
- for (i in window.localStorage) {
- if (window.localStorage.hasOwnProperty(i)) {
- try {
- state[i] = Yii.CJSON.decode(window.localStorage[i]);
- }
- catch (e) {
- state[i] = window.localStorage[i];
- }
- }
- }
- return state;
- }
- else {
- return null;
- }
- };
- /**
- * Saves application state in persistent storage.
- * @param {Mixed} state state data (must be serializable).
- */
- Yii.CStatePersister.prototype.save = function (state) {
- var i;
- window.localStorage.clear();
- for(i in state) {
- if (state.hasOwnProperty(i)) {
- window.localStorage[i] = Yii.CJSON.encode(state[i]);
- }
- }
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CCache is the base class for cache classes with different cache storage implementation.
- *
- * A data item can be stored in cache by calling {@link set} and be retrieved back
- * later by {@link get}. In both operations, a key identifying the data item is required.
- * An expiration time and/or a dependency can also be specified when calling {@link set}.
- * If the data item expires or the dependency changes, calling {@link get} will not
- * return back the data item.
- *
- * Note, by definition, cache does not ensure the existence of a value
- * even if it does not expire. Cache is not meant to be a persistent storage.
- *
- * CCache implements the interface {@link ICache} with the following methods:
- * <ul>
- * <li>{@link get} : retrieve the value with a key (if any) from cache</li>
- * <li>{@link set} : store the value with a key into cache</li>
- * <li>{@link add} : store the value only if cache does not have this key</li>
- * <li>{@link delete} : delete the value with the specified key from cache</li>
- * <li>{@link flush} : delete all values from cache</li>
- * </ul>
- *
- * Child classes must implement the following methods:
- * <ul>
- * <li>{@link getValue}</li>
- * <li>{@link setValue}</li>
- * <li>{@link addValue}</li>
- * <li>{@link deleteValue}</li>
- * <li>{@link flush} (optional)</li>
- * </ul>
- *
- * CCache also implements ArrayAccess so that it can be used like an array.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CCache.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.caching
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CApplicationComponent
- */
- Yii.CCache = function CCache () {
- };
- Yii.CCache.prototype = new Yii.CApplicationComponent();
- Yii.CCache.prototype.constructor = Yii.CCache;
- /**
- * @var {String} a string prefixed to every cache key so that it is unique. Defaults to {@link CApplication::getId() application ID}.
- */
- Yii.CCache.prototype.keyPrefix = null;
- /**
- * Initializes the application component.
- * This method overrides the parent implementation by setting default cache key prefix.
- */
- Yii.CCache.prototype.init = function () {
- Yii.CApplicationComponent.prototype.init.call(this);
- if(this.keyPrefix===null) {
- this.keyPrefix=Yii.app().getId();
- }
- };
- /**
- * @param {String} key a key identifying a value to be cached
- * @returns {Sring} a key generated from the provided key which ensures the uniqueness across applications
- */
- Yii.CCache.prototype.generateUniqueKey = function (key) {
- return php.md5(this.keyPrefix+key);
- };
- /**
- * Retrieves a value from cache with a specified key.
- * @param {String} id a key identifying the cached value
- * @returns {Mixed} the value stored in cache, false if the value is not in the cache, expired or the dependency has changed.
- */
- Yii.CCache.prototype.get = function (id) {
- var value, data;
- if((value=this.getValue(this.generateUniqueKey(id)))!==false) {
- data = value;
-
- if (!data) {
- return false;
- }
- if(Object.prototype.toString.call(data) !== '[object Array]') {
- if (data.length > 0) {
- try {
- data = Yii.CJSON.decode(data);
- }
- catch (e) {
- return false;
- }
- }
- else {
- return false;
- }
- }
- if (false && data[1] !== undefined && data[1] !== {}) {
- data[1] = Yii.createComponent(data[1]);
- }
- if(data[1] === null || !(data[1] instanceof Yii.CCacheDependency) || !data[1].getHasChanged()) {
- Yii.trace('Serving "'+id+'" from cache','system.caching.'+this.getClassName());
- return data[0];
- }
- }
- return false;
- };
- /**
- * Retrieves multiple values from cache with the specified keys.
- * Some caches (such as memcache, apc) allow retrieving multiple cached values at one time,
- * which may improve the performance since it reduces the communication cost.
- * In case a cache doesn't support this feature natively, it will be simulated by this method.
- * @param {Array} ids list of keys identifying the cached values
- * @returns {Array} list of cached values corresponding to the specified keys. The array
- * is returned in terms of (key,value) pairs.
- * If a value is not cached or expired, the corresponding array value will be false.
- * @since 1.0.8
- */
- Yii.CCache.prototype.mget = function (ids) {
- var uniqueIDs, results, i, id, values, uniqueID, data;
- uniqueIDs={};
- results={};
- for (i in ids) {
- if (ids.hasOwnProperty(i)) {
- id = ids[i];
- uniqueIDs[id]=this.generateUniqueKey(id);
- results[id]=false;
- }
- }
- values=this.getValues(uniqueIDs);
- for (id in uniqueIDs) {
- if (uniqueIDs.hasOwnProperty(id)) {
- uniqueID = uniqueIDs[id];
- if(values[uniqueID] === undefined) {
- continue;
- }
- data=Yii.CJSON.decode(values[uniqueID]);
- data = value;
- if(Object.prototype.toString.call(data) !== '[object Array]') {
- if (data.length > 0) {
- try {
- data = Yii.CJSON.decode(data);
- }
- catch (e) {
- return false;
- }
- }
- else {
- return false;
- }
- }
- if (data[1] !== undefined && data[1] !== {}) {
- data[1] = Yii.createComponent(data[1]);
- }
- if(!(data[1] instanceof Yii.CCacheDependency) || !data[1].getHasChanged()) {
- Yii.trace('Serving "'+id+'" from cache','system.caching.'+this.getClassName());
- results[id] = data[0];
- }
- }
- }
- return results;
- };
- /**
- * Stores a value identified by a key into cache.
- * If the cache already contains such a key, the existing value and
- * expiration time will be replaced with the new ones.
- *
- * @param {String} id the key identifying the value to be cached
- * @param {Mixed} value the value to be cached
- * @param {Integer} expire the number of seconds in which the cached value will expire. 0 means never expire.
- * @param {ICacheDependency} dependency dependency of the cached item. If the dependency changes, the item is labeled invalid.
- * @returns {Boolean} true if the value is successfully stored into cache, false otherwise
- */
- Yii.CCache.prototype.set = function (id, value, expire, dependency) {
- var data;
- if (expire === undefined) {
- expire = 0;
- }
- if (dependency === undefined) {
- dependency = null;
- }
- Yii.trace('Saving "'+id+'" to cache','system.caching.'+this.getClassName());
- if(dependency!==null) {
- dependency.evaluateDependency();
- }
- data=[value,dependency];
- return this.setValue(this.generateUniqueKey(id),Yii.CJSON.encode(data),expire);
- };
- /**
- * Stores a value identified by a key into cache if the cache does not contain this key.
- * Nothing will be done if the cache already contains the key.
- * @param {String} id the key identifying the value to be cached
- * @param {Mixed} value the value to be cached
- * @param {Integer} expire the number of seconds in which the cached value will expire. 0 means never expire.
- * @param {ICacheDependency} dependency dependency of the cached item. If the dependency changes, the item is labeled invalid.
- * @returns {Boolean} true if the value is successfully stored into cache, false otherwise
- */
- Yii.CCache.prototype.add = function (id, value, expire, dependency) {
- var data;
- if (expire === undefined) {
- expire = 0;
- }
- if (dependency === undefined) {
- dependency = null;
- }
- Yii.trace('Adding "'+id+'" to cache','system.caching.'+this.getClassName());
- if(dependency!==null) {
- dependency.evaluateDependency();
- }
- data=[value,dependency];
- return this.addValue(this.generateUniqueKey(id),Yii.CJSON.encode(data),expire);
- };
- /**
- * Deletes a value with the specified key from cache
- * @param {String} id the key of the value to be deleted
- * @returns {Boolean} if no error happens during deletion
- */
- Yii.CCache.prototype.remove = function (id) {
- Yii.trace('Deleting "'+id+'" from cache','system.caching.'+this.getClassName());
- return this.deleteValue(this.generateUniqueKey(id));
- };
- /**
- * Deletes all values from cache.
- * Be careful of performing this operation if the cache is shared by multiple applications.
- * @returns {Boolean} whether the flush operation was successful.
- */
- Yii.CCache.prototype.flush = function () {
- Yii.trace('Flushing cache','system.caching.'+this.getClassName());
- return this.flushValues();
- };
- /**
- * Retrieves a value from cache with a specified key.
- * This method should be implemented by child classes to retrieve the data
- * from specific cache storage. The uniqueness and dependency are handled
- * in {@link get()} already. So only the implementation of data retrieval
- * is needed.
- * @param {String} key a unique key identifying the cached value
- * @returns {String} the value stored in cache, false if the value is not in the cache or expired.
- * @throws {Yii.CException} if this method is not overridden by child classes
- */
- Yii.CCache.prototype.getValue = function (key) {
- throw new Yii.CException(Yii.t('yii','{className} does not support get() functionality.',
- {'{className}':this.getClassName()}));
- };
- /**
- * Retrieves multiple values from cache with the specified keys.
- * The default implementation simply calls {@link getValue} multiple
- * times to retrieve the cached values one by one.
- * If the underlying cache storage supports multiget, this method should
- * be overridden to exploit that feature.
- * @param {Array} keys a list of keys identifying the cached values
- * @returns {Object} a list of cached values indexed by the keys
- * @since 1.0.8
- */
- Yii.CCache.prototype.getValues = function (keys) {
- var results, i, key;
- results={};
- for (i in keys) {
- if (keys.hasOwnProperty(i)) {
- key = keys[i];
- results[key]=this.getValue(key);
- }
- }
- return results;
- };
- /**
- * Stores a value identified by a key in cache.
- * This method should be implemented by child classes to store the data
- * in specific cache storage. The uniqueness and dependency are handled
- * in {@link set()} already. So only the implementation of data storage
- * is needed.
- *
- * @param {String} key the key identifying the value to be cached
- * @param {String} value the value to be cached
- * @param {Integer} expire the number of seconds in which the cached value will expire. 0 means never expire.
- * @returns {Boolean} true if the value is successfully stored into cache, false otherwise
- * @throws {Yii.CException} if this method is not overridden by child classes
- */
- Yii.CCache.prototype.setValue = function (key, value, expire) {
- throw new Yii.CException(Yii.t('yii','{className} does not support set() functionality.',
- {'{className}':this.getClassName()}));
- };
- /**
- * Stores a value identified by a key into cache if the cache does not contain this key.
- * This method should be implemented by child classes to store the data
- * in specific cache storage. The uniqueness and dependency are handled
- * in {@link add()} already. So only the implementation of data storage
- * is needed.
- *
- * @param {String} key the key identifying the value to be cached
- * @param {String} value the value to be cached
- * @param {Integer} expire the number of seconds in which the cached value will expire. 0 means never expire.
- * @returns {Boolean} true if the value is successfully stored into cache, false otherwise
- * @throws {Yii.CException} if this method is not overridden by child classes
- */
- Yii.CCache.prototype.addValue = function (key, value, expire) {
- throw new Yii.CException(Yii.t('yii','{className} does not support add() functionality.',
- {'{className}':this.getClassName()}));
- };
- /**
- * Deletes a value with the specified key from cache
- * This method should be implemented by child classes to delete the data from actual cache storage.
- * @param {String} key the key of the value to be deleted
- * @returns {Boolean} if no error happens during deletion
- * @throws {Yii.CException} if this method is not overridden by child classes
- */
- Yii.CCache.prototype.deleteValue = function (key) {
- throw new Yii.CException(Yii.t('yii','{className} does not support delete() functionality.',
- {'{className}':this.getClassName()}));
- };
- /**
- * Deletes all values from cache.
- * Child classes may implement this method to realize the flush operation.
- * @returns {Boolean} whether the flush operation was successful.
- * @throws {Yii.CException} if this method is not overridden by child classes
- * @since 1.1.5
- */
- Yii.CCache.prototype.flushValues = function () {
- throw new Yii.CException(Yii.t('yii','{className} does not support flushValues() functionality.',
- {'{className}':this.getClassName()}));
- };
- /**
- * Returns whether there is a cache entry with a specified key.
- * This method is required by the interface ArrayAccess.
- * @param {String} id a key identifying the cached value
- * @returns {Boolean}
- */
- Yii.CCache.prototype.offsetExists = function (id) {
- return this.get(id)!==false;
- };
- /**
- * Retrieves the value from cache with a specified key.
- * This method is required by the interface ArrayAccess.
- * @param {String} id a key identifying the cached value
- * @returns {Mixed} the value stored in cache, false if the value is not in the cache or expired.
- */
- Yii.CCache.prototype.offsetGet = function (id) {
- return this.get(id);
- };
- /**
- * Stores the value identified by a key into cache.
- * If the cache already contains such a key, the existing value will be
- * replaced with the new ones. To add expiration and dependencies, use the set() method.
- * This method is required by the interface ArrayAccess.
- * @param {String} id the key identifying the value to be cached
- * @param {Mixed} value the value to be cached
- */
- Yii.CCache.prototype.offsetSet = function (id, value) {
- this.set(id, value);
- };
- /**
- * Deletes the value with the specified key from cache
- * This method is required by the interface ArrayAccess.
- * @param {String} id the key of the value to be deleted
- * @returns {Boolean} if no error happens during deletion
- */
- Yii.CCache.prototype.offsetUnset = function (id) {
- this.remove(id);
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CLocalCache implements a cache application component based on localStorage
- * @package system.caching
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CCache
- */
- Yii.CLocalCache = function CLocalCache () {
- };
- Yii.CLocalCache.prototype = new Yii.CCache();
- Yii.CLocalCache.prototype.constructor = Yii.CLocalCache;
- /**
- * Retrieves a value from cache with a specified key.
- * This is the implementation of the method declared in the parent class.
- * @param {String} key a unique key identifying the cached value
- * @returns {String} the value stored in cache, false if the value is not in the cache or expired.
- */
- Yii.CLocalCache.prototype.getValue = function (key) {
- var raw, item, expiry, now;
- raw = localStorage.getItem(key);
- if (raw === null) {
- return false;
- }
- try {
- item = Yii.CJSON.decode(raw);
- now = php.time();
- expiry = item.shift();
- if (expiry !== 0 && expiry < now) {
- localStorage.removeItem(key);
- return false;
- }
- return item.shift();
- }
- catch (e) {
- return raw;
- }
- };
- /**
- * Stores a value identified by a key in cache.
- * This is the implementation of the method declared in the parent class.
- *
- * @param {String} key the key identifying the value to be cached
- * @param {String} value the value to be cached
- * @param {Integer} expire the number of seconds in which the cached value will expire. 0 means never expire.
- * @returns {Boolean} true if the value is successfully stored into cache, false otherwise
- */
- Yii.CLocalCache.prototype.setValue = function (key, value, expire) {
- if(expire>0) {
- expire+=php.time();
- }
- else {
- expire=0;
- }
-
- return localStorage.setItem(key, Yii.CJSON.encode([expire,value]));
-
- };
- /**
- * Stores a value identified by a key into cache if the cache does not contain this key.
- * This is the implementation of the method declared in the parent class.
- *
- * @param {String} key the key identifying the value to be cached
- * @param {String} value the value to be cached
- * @param {Integer} expire the number of seconds in which the cached value will expire. 0 means never expire.
- * @returns {Boolean} true if the value is successfully stored into cache, false otherwise
- */
- Yii.CLocalCache.prototype.addValue = function (key, value, expire) {
- if(expire>0) {
- expire+=php.time();
- }
- else {
- expire=0;
- }
- // TODO: expiry!
- return localStorage.setItem(key, value);
- };
- /**
- * Deletes a value with the specified key from cache
- * This is the implementation of the method declared in the parent class.
- * @param {String} key the key of the value to be deleted
- * @returns {Boolean} if no error happens during deletion
- */
- Yii.CLocalCache.prototype.remove = function (key) {
- return localStorage.removeItem(key);
- };
- /**
- * Deletes all values from cache.
- * This is the implementation of the method declared in the parent class.
- * @returns {Boolean} whether the flush operation was successful.
- * @since 1.1.5
- */
- Yii.CLocalCache.prototype.flushValues = function () {
- return localStorage.clear();
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CSessionCache implements a cache application component based on sessionStorage
- * @package system.caching
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CCache
- */
- Yii.CSessionCache = function CSessionCache () {
- };
- Yii.CSessionCache.prototype = new Yii.CCache();
- Yii.CSessionCache.prototype.constructor = Yii.CSessionCache;
- /**
- * Retrieves a value from cache with a specified key.
- * This is the implementation of the method declared in the parent class.
- * @param {String} key a unique key identifying the cached value
- * @returns {String} the value stored in cache, false if the value is not in the cache or expired.
- */
- Yii.CSessionCache.prototype.getValue = function (key) {
- var raw, item, expiry, now;
- raw = sessionStorage.getItem(key);
- if (raw === null) {
- return false;
- }
- try {
- item = Yii.CJSON.decode(raw);
- now = php.time();
- expiry = item.shift();
- if (expiry !== 0 && expiry < now) {
- sessionStorage.removeItem(key);
- return false;
- }
- return item.shift();
- }
- catch (e) {
- return raw;
- }
- };
- /**
- * Stores a value identified by a key in cache.
- * This is the implementation of the method declared in the parent class.
- *
- * @param {String} key the key identifying the value to be cached
- * @param {String} value the value to be cached
- * @param {Integer} expire the number of seconds in which the cached value will expire. 0 means never expire.
- * @returns {Boolean} true if the value is successfully stored into cache, false otherwise
- */
- Yii.CSessionCache.prototype.setValue = function (key, value, expire) {
- if(expire>0) {
- expire+=php.time();
- }
- else {
- expire=0;
- }
-
- return sessionStorage.setItem(key, Yii.CJSON.encode([expire,value]));
-
- };
- /**
- * Stores a value identified by a key into cache if the cache does not contain this key.
- * This is the implementation of the method declared in the parent class.
- *
- * @param {String} key the key identifying the value to be cached
- * @param {String} value the value to be cached
- * @param {Integer} expire the number of seconds in which the cached value will expire. 0 means never expire.
- * @returns {Boolean} true if the value is successfully stored into cache, false otherwise
- */
- Yii.CSessionCache.prototype.addValue = function (key, value, expire) {
- if(expire>0) {
- expire+=php.time();
- }
- else {
- expire=0;
- }
- // TODO: expiry!
- return sessionStorage.setItem(key, value);
- };
- /**
- * Deletes a value with the specified key from cache
- * This is the implementation of the method declared in the parent class.
- * @param {String} key the key of the value to be deleted
- * @returns {Boolean} if no error happens during deletion
- */
- Yii.CSessionCache.prototype.remove = function (key) {
- return sessionStorage.removeItem(key);
- };
- /**
- * Deletes all values from cache.
- * This is the implementation of the method declared in the parent class.
- * @returns {Boolean} whether the flush operation was successful.
- * @since 1.1.5
- */
- Yii.CSessionCache.prototype.flushValues = function () {
- return sessionStorage.clear();
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CAttributeCollection implements a collection for storing attribute names and values.
- *
- * Besides all functionalities provided by {@link CMap}, CAttributeCollection
- * allows you to get and set attribute values like getting and setting
- * properties. For example, the following usages are all valid for a
- * CAttributeCollection object:
- * <pre>
- * collection.text='text'; // same as: $collection->add('text','text');
- * document.write(collection.text); // same as: echo $collection->itemAt('text');
- * </pre>
- *
- * The case sensitivity of attribute names can be toggled by setting the
- * {@link caseSensitive} property of the collection.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CAttributeCollection.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.collections
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CMap
- */
- Yii.CAttributeCollection = function CAttributeCollection(data, readOnly) {
- this.construct(data, readOnly);
-
- };
- Yii.CAttributeCollection.prototype = new Yii.CMap();
- Yii.CAttributeCollection.prototype.constructor = Yii.CAttributeCollection;
- /**
- * @var {Boolean} whether the keys are case-sensitive. Defaults to false.
- */
- Yii.CAttributeCollection.prototype.caseSensitive = false;
- /**
- * Returns a property value or an event handler list by property or event name.
- * This method overrides the parent implementation by returning
- * a key value if the key exists in the collection.
- * @param {String} name the property name or the event name
- * @returns {Mixed} the property value or the event handler list
- * @throws {Yii.CException} if the property/event is not defined.
- */
- Yii.CAttributeCollection.prototype.get = function (name) {
- if(this.contains(name)) {
- return this.itemAt(name);
- }
- else {
- return Yii.CMap.prototype.get.call(this, name);
- }
- };
- /**
- * Sets value of a component property.
- * This method overrides the parent implementation by adding a new key value
- * to the collection.
- * @param {String} name the property name or event name
- * @param {Mixed} value the property value or event handler
- * @throws {Yii.CException} If the property is not defined or read-only.
- */
- Yii.CAttributeCollection.prototype.set = function (name, value) {
- this.add(name,value);
- };
- /**
- * Checks if a property value is null.
- * This method overrides the parent implementation by checking
- * if the key exists in the collection and contains a non-null value.
- * @param {String} name the property name or the event name
- * @returns {Boolean} whether the property value is null
- * @since 1.0.1
- */
- Yii.CAttributeCollection.prototype.isset = function (name) {
- if(this.contains(name)) {
- return this.itemAt(name)!==null;
- }
- else {
- return Yii.CMap.prototype.isset.call(this, name);
- }
- };
- /**
- * Sets a component property to be null.
- * This method overrides the parent implementation by clearing
- * the specified key value.
- * @param {String} name the property name or the event name
- * @since 1.0.1
- */
- Yii.CAttributeCollection.prototype.unset = function (name) {
- this.remove(name);
- };
- /**
- * Returns the item with the specified key.
- * This overrides the parent implementation by converting the key to lower case first if {@link caseSensitive} is false.
- * @param {Mixed} key the key
- * @returns {Mixed} the element at the offset, null if no element is found at the offset
- */
- Yii.CAttributeCollection.prototype.itemAt = function (key) {
- if(this.caseSensitive) {
- return Yii.CMap.prototype.itemAt.call(this,key);
- }
- else {
- return Yii.CMap.prototype.itemAt.call(this,key.toLowerCase());
- }
- };
- /**
- * Adds an item into the map.
- * This overrides the parent implementation by converting the key to lower case first if {@link caseSensitive} is false.
- * @param {Mixed} key key
- * @param {Mixed} value value
- */
- Yii.CAttributeCollection.prototype.add = function (key, value) {
- if(this.caseSensitive) {
- Yii.CMap.prototype.add.call(this, key,value);
- }
- else {
- Yii.CMap.prototype.add.call(this, key.toLowerCase(),value);
- }
- };
- /**
- * Removes an item from the map by its key.
- * This overrides the parent implementation by converting the key to lower case first if {@link caseSensitive} is false.
- * @param {Mixed} key the key of the item to be removed
- * @returns {Mixed} the removed value, null if no such key exists.
- */
- Yii.CAttributeCollection.prototype.remove = function (key) {
- if(this.caseSensitive) {
- return Yii.CMap.prototype.remove.call(this, key);
- }
- else {
- return Yii.CMap.prototype.remove.call(this, key.toLowerCase());
- }
- };
- /**
- * Returns whether the specified is in the map.
- * This overrides the parent implementation by converting the key to lower case first if {@link caseSensitive} is false.
- * @param {Mixed} key the key
- * @returns {Boolean} whether the map contains an item with the specified key
- */
- Yii.CAttributeCollection.prototype.contains = function (key) {
- if(this.caseSensitive) {
- return Yii.CMap.prototype.contains.call(this, key);
- }
- else {
- return Yii.CMap.prototype.contains.call(this, key.toLowerCase());
- }
- };
- /**
- * Determines whether a property is defined.
- * This method overrides parent implementation by returning true
- * if the collection contains the named key.
- * @param {String} name the property name
- * @returns {Boolean} whether the property is defined
- */
- Yii.CAttributeCollection.prototype.hasProperty = function (name) {
- return this.contains(name) || Yii.CMap.prototype.hasProperty.call(this, name);
- };
- /**
- * Determines whether a property can be read.
- * This method overrides parent implementation by returning true
- * if the collection contains the named key.
- * @param {String} name the property name
- * @returns {Boolean} whether the property can be read
- */
- Yii.CAttributeCollection.prototype.canGetProperty = function (name) {
- return this.contains(name) || Yii.CMap.prototype.canGetProperty.call(this, name);
- };
- /**
- * Determines whether a property can be set.
- * This method overrides parent implementation by always returning true
- * because you can always add a new value to the collection.
- * @param {String} name the property name
- * @returns {Boolean} true
- */
- Yii.CAttributeCollection.prototype.canSetProperty = function (name) {
- return true;
- }/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CConfiguration represents an array-based configuration.
- *
- * It can be used to initialize an object's properties.
- *
- * The configuration data may be obtained from a PHP script. For example,
- * <pre>
- * return {
- * 'name':'My Application',
- * 'defaultController':'index',
- * };
- * </pre>
- * Use the following code to load the above configuration data:
- * <pre>
- * config=new Yii.CConfiguration('path/to/config.php');
- * </pre>
- *
- * To apply the configuration to an object, call {@link applyTo()}.
- * Each (key,value) pair in the configuration data is applied
- * to the object like: $object->$key=$value.
- *
- * Since CConfiguration extends from {@link CMap}, it can be
- * used like an associative array. See {@link CMap} for more details.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CConfiguration.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.collections
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CMap
- */
- Yii.CConfiguration = function CConfiguration (data, readOnly) {
- this.construct(data, readOnly);
-
- };
- Yii.CConfiguration.prototype = new Yii.CMap();
- Yii.CConfiguration.prototype.constructor = Yii.CConfiguration;
- /**
- * Saves the configuration into a JSON string.
- * The string is a valid JSON expression representing the configuration data as an object.
- * @returns {String} the JSON representation of the configuration
- */
- Yii.CConfiguration.prototype.saveAsString = function () {
- return Yii.CJSON.encode(this.toObject());
- };
- /**
- * Applies the configuration to an object.
- * Each (key,value) pair in the configuration data is applied
- * to the object like: $object->$key=$value.
- * @param {Object} object object to be applied with this configuration
- */
- Yii.CConfiguration.prototype.applyTo = function (object) {
- var keyValue, key, value;
- keyValue = this.toObject();
- for (key in keyValue) {
- if (keyValue.hasOwnProperty(key)) {
- value = keyValue[key];
- object[key] = value;
- }
- }
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CQueue implements a queue.
- *
- * The typical queue operations are implemented, which include
- * {@link enqueue()}, {@link dequeue()} and {@link peek()}. In addition,
- * {@link contains()} can be used to check if an item is contained
- * in the queue. To obtain the number of the items in the queue,
- * check the {@link getCount Count} property.
- *
- * Items in the queue may be traversed using foreach as follows,
- * <pre>
- * for (i in queue) +++
- * </pre>
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CQueue.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.collections
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CQueue = function CQueue(data) {
- this.readOnly = false;
- this.construct(data);
-
- };
- Yii.CQueue.prototype = new Yii.CList();
- Yii.CQueue.prototype.constructor = Yii.CQueue;
- /**
- * Constructor.
- * Initializes the queue with an array or an iterable object.
- * @param {Array} data the intial data. Default is null, meaning no initialization.
- * @throws {Yii.CException} If data is not null and neither an array nor an iterator.
- */
- Yii.CQueue.prototype.construct = function (data) {
- if (data === undefined) {
- data = null;
- }
- if(data!==null) {
- this.copyFrom(data);
- }
- };
- /**
- * @param {Mixed} item the item
- * @returns {Boolean} whether the queue contains the item
- */
- Yii.CQueue.prototype.contains = function (item) {
- var i, limit = this.length;
- for (i = 0; i < limit; i++) {
- if (item === this[i]) {
- return true;
- }
- }
- return false;
- };
- /**
- * Returns the item at the top of the queue.
- * @returns {Mixed} item at the top of the queue
- * @throws {Yii.CException} if the queue is empty
- */
- Yii.CQueue.prototype.peek = function () {
- if(this.length===0) {
- throw new Yii.CException(Yii.t('yii','The queue is empty.'));
- }
- else {
- return this[0];
- }
- };
- /**
- * Removes and returns the object at the beginning of the queue.
- * @returns {Mixed} the item at the beginning of the queue
- * @throws {Yii.CException} if the queue is empty
- */
- Yii.CQueue.prototype.dequeue = function () {
- if(this.length===0) {
- throw new Yii.CException(Yii.t('yii','The queue is empty.'));
- }
- else {
- return this.shift();
- }
- };
- /**
- * Adds an object to the end of the queue.
- * @param {Mixed} item the item to be appended into the queue
- */
- Yii.CQueue.prototype.enqueue = function (item) {
- this.push(item);
- };
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CStack implements a stack.
- *
- * The typical stack operations are implemented, which include
- * {@link push()}, {@link pop()} and {@link peek()}. In addition,
- * {@link contains()} can be used to check if an item is contained
- * in the stack. To obtain the number of the items in the stack,
- * check the {@link getCount Count} property.
- *
- * Items in the stack may be traversed using foreach as follows,
- * <pre>
- * for (i in stack) +++
- * </pre>
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CStack.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.collections
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CStack = function CStack (data) {
- this.construct(data);
- };
- Yii.CStack.prototype = new Array();
- Yii.CStack.prototype.constructor = Yii.CStack;
- Yii.augment(Yii.CStack, Yii.CComponent);
- /**
- * Constructor.
- * Initializes the stack with an array or an iterable object.
- * @param {Array} data the initial data. Default is null, meaning no initialization.
- * @throws {Yii.CException} If data is not null and neither an array nor an iterator.
- */
- Yii.CStack.prototype.construct = function (data) {
- if (data === undefined) {
- data = null;
- }
- if(data!==null) {
- this.copyFrom(data);
- }
- };
- /**
- * @returns {Array} the list of items in stack
- */
- Yii.CStack.prototype.toArray = function () {
- var ret = [], i, limit;
- limit = this.length;
- for (i = 0; i < limit; i++) {
- ret.push(this[i]);
- }
- return ret;
- };
- /**
- * Copies iterable data into the stack.
- * Note, existing data in the list will be cleared first.
- * @param {Mixed} data the data to be copied from, must be an array or object implementing Traversable
- * @throws {Yii.CException} If data is neither an array nor a Traversable.
- */
- Yii.CStack.prototype.copyFrom = function (data) {
- var i, item;
- if(Object.prototype.toString.call(data) === '[object Array]' || (data instanceof Array))
- {
- this.clear();
- for (i in data)
- {
- if (data.hasOwnProperty(i)) {
- item = data[i];
- this.push(item);
- }
- }
- }
- else if(data!==null) {
- throw new Yii.CException(Yii.t('yii','Stack data must be an array or an object implementing Traversable.'));
- }
- };
- /**
- * Removes all items in the stack.
- */
- Yii.CStack.prototype.clear = function () {
- var i, limit;
- limit = this.length;
- for(i = 0; i < limit; i++) {
- delete this[i];
- }
- };
- /**
- * @param {Mixed} item the item
- * @returns {Boolean} whether the stack contains the item
- */
- Yii.CStack.prototype.contains = function (item) {
- var i, limit = this.length;
- for (i = 0; i < limit; i++) {
- if (item === this[i]) {
- return true;
- }
- }
- return false;
- };
- /**
- * Returns the item at the top of the stack.
- * Unlike {@link pop()}, this method does not remove the item from the stack.
- * @returns {Mixed} item at the top of the stack
- * @throws {Yii.CException} if the stack is empty
- */
- Yii.CStack.prototype.peek = function () {
- if(this.length) {
- return this[this.length - 1];
- }
- else {
- throw new Yii.CException(Yii.t('yii','The stack is empty.'));
- }
- };
- /**
- * Pops up the item at the top of the stack.
- * @returns {Mixed} the item at the top of the stack
- * @throws {Yii.CException} if the stack is empty
- */
- Yii.CStack.prototype.pop = function () {
- if(this.length) {
- return Array.prototype.pop.call(this);
- }
- else {
- throw new Yii.CException(Yii.t('yii','The stack is empty.'));
- }
- };
- /**
- * Returns the number of items in the stack.
- * @returns {Integer} the number of items in the stack
- */
- Yii.CStack.prototype.getCount = function () {
- return this.length;
- };
- /**
- * Returns the number of items in the stack.
- * This method is required by Countable interface.
- * @returns {Integer} number of items in the stack.
- */
- Yii.CStack.prototype.count = function () {
- return this.length;
- };
- /**
- * Provides convenient access to Yii.forEach()
- * @param {Function} callback The callback function, this will receive 2 parameters, key and value
- * @returns {Yii.CStack} the stack
- */
- Yii.CStack.prototype.forEach = function(callback) {
- return Yii.forEach(this,callback);
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CTypedList represents a list whose items are of the certain type.
- *
- * CTypedList extends {@link CList} by making sure that the elements to be
- * added to the list is of certain class type.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CTypedList.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.collections
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CList
- */
- Yii.CTypedList = function CTypedList (type) {
- this.construct(type);
- };
- Yii.CTypedList.prototype = new Yii.CList();
- Yii.CTypedList.prototype.constructor = Yii.CTypedList;
- Yii.CTypedList.prototype._type = null;
- /**
- * Constructor.
- * @param {String} type class type
- */
- Yii.CTypedList.prototype.construct = function (type) {
- this._type=type;
- };
- /**
- * Inserts an item at the specified position.
- * This method overrides the parent implementation by
- * checking the item to be inserted is of certain type.
- * @param {Integer} index the specified position.
- * @param {Mixed} item new item
- * @throws {Yii.CException} If the index specified exceeds the bound,
- * the list is read-only or the element is not of the expected type.
- */
- Yii.CTypedList.prototype.insertAt = function (index, item) {
- if(item instanceof this._type) {
- Yii.CList.prototype.insertAt.call(this,index,item);
- }
- else {
- throw new Yii.CException(Yii.t('yii','CTypedList<{type}> can only hold objects of {type} class.',
- {'{type}':this._type}));
- }
- };
- /**
- * Pushes an item on to the end of the list
- * @param {Mixed} the item to add
- * @returns {Integer} the number of items in the list
- */
- Yii.CTypedList.prototype.push = function (item) {
- if(item instanceof this._type) {
- return Yii.CList.prototype.push.call(this,item);
- }
- else {
- throw new Yii.CException(Yii.t('yii','CTypedList<{type}> can only hold objects of {type} class.',
- {'{type}':this._type}));
- }
- };
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CTypedMap represents a map whose items are of the certain type.
- *
- * CTypedMap extends {@link CMap} by making sure that the elements to be
- * added to the list is of certain class type.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CTypedMap.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.collections
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CMap
- */
- Yii.CTypedMap = function CTypedMap (type) {
- this.construct(type);
- };
- Yii.CTypedMap.prototype = new Yii.CMap();
- Yii.CTypedMap.prototype.constructor = Yii.CTypedMap;
- Yii.CTypedMap.prototype._type = null;
- /**
- * Constructor.
- * @param {String} type class type
- */
- Yii.CTypedMap.prototype.construct = function (type) {
- this._type=type;
- };
- /**
- * Adds an item into the map.
- * This method overrides the parent implementation by
- * checking the item to be inserted is of certain type.
- * @param {Integer} index the specified position.
- * @param {Mixed} item new item
- * @throws {Yii.CException} If the index specified exceeds the bound,
- * the map is read-only or the element is not of the expected type.
- */
- Yii.CTypedMap.prototype.add = function (index, item) {
- if(item instanceof this._type) {
- Yii.CMap.prototype.add.call(this, index,item);
- }
- else {
- throw new Yii.CException(Yii.t('yii','CTypedMap<{type}> can only hold objects of {type} class.',
- {'{type}':this._type}));
- }
- };var YII_PATH = "/js/test/";
- var appConfig = {
- 'basePath': "/js/app",
- 'name': "EbayStore",
- 'preload': ["log"],
- 'params': {
- 'version': 0.1
- },
- 'components': {
- 'db': {
- 'connectionString': 'sqlite:host=localhost;dbname=ebaystore',
- 'enableParamLogging': true,
- 'enableProfiling': true,
- 'initSQLs': [
-
- ]
- },
- 'viewRenderer' : {
- 'class': 'CMustacheViewRenderer'
- },
- 'request': {
- 'enableCsrfValidation': true,
- 'enableCookieValidation': true
- },
- 'log': {
- 'class': 'CLogRouter',
- 'routes': [
- {
- 'class': 'CProfileLogRoute',
- 'showInFireBug': false
- },
- {
- 'class': 'CWebLogRoute',
- 'showInFireBug': false
- }
- ]
- },
- 'cache': {
- 'class': 'CSessionCache'
- },
- 'urlManager': {
- 'urlFormat': 'path',
- 'showScriptName': false,
- 'urlSuffix': '.html',
- 'useStrictParsing': false,
- 'rules': [
- {
- 'pattern': '/',
- 'route': '/site/index',
- 'urlSuffix': ''
- },
- {
- 'pattern': 'contactus',
- 'route': '/site/contact'
- },
- {
- 'pattern': '<controller:\\w+>s',
- 'route': '<controller>/index'
- },
- {
- 'pattern': '<controller:\\w+>s/<id:\\d+>',
- 'route': '<controller>/view'
- },
- {
- 'pattern': '<controller:\\w+>s/<action:\\w+>/<id:\\d+>',
- 'route': '<controller>/<action>'
- },
- {
- 'pattern': '<controller:\\w+>s/<action:\\w+>',
- 'route': '<controller>/<action>'
- }
- ]
- }
- }
- };
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * A base class for data sources.
- * @package system.ds
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CActiveDataSource = function CActiveDataSource () {
-
- };
- Yii.CActiveDataSource.prototype = new Yii.CComponent();
- Yii.CActiveDataSource.prototype.constructor = Yii.CActiveDataSource;
-
- /**
- * Gets data from the data source and executes the callback when data arrives.
- * Child classes must override this method!
- * @param {Function} callback The callback function to execute, this will recieve the
- * data as its first parameter and the data source as its second parameter.
- *
- */
- Yii.CActiveDataSource.prototype.getData = function (callback) {
-
- };
-
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CAsyncRecord is the base class for classes representing relational data loaded from a remote data source.
- *
- * It implements the active record design pattern, a popular Object-Relational Mapping (ORM) technique.
- *
- * @package system.ds
- * @since 1.0
- *
- * @property array $attributes
- * @author Charles Pick
- * @class
- * @extends Yii.CModel
- */
- Yii.CAsyncRecord = function CAsyncRecord (scenario, callback) {
- if (scenario !== false) {
- return this.construct(scenario, callback);
- }
- };
- Yii.CAsyncRecord.prototype = new Yii.CModel(false);
- Yii.CAsyncRecord.prototype.constructor = Yii.CAsyncRecord;
- /**
- * @const
- */
- Yii.CAsyncRecord.prototype.BELONGS_TO = 'CBelongsToRelation';
- /**
- * @const
- */
- Yii.CAsyncRecord.prototype.HAS_ONE = 'CHasOneRelation';
- /**
- * @const
- */
- Yii.CAsyncRecord.prototype.HAS_MANY = 'CHasManyRelation';
- /**
- * @const
- */
- Yii.CAsyncRecord.prototype.MANY_MANY = 'CManyManyRelation';
- /**
- * @const
- */
- Yii.CAsyncRecord.prototype.STAT = 'CStatRelation';
- /**
- * @var {Yii.CActiveDataSource} the default data source for all active records
- * @see getDbConnection
- */
- Yii.CAsyncRecord.prototype._ds = null;
- /**
- * Whether or not to wrap the posted data in an object or not.
- * If this is set to true, data will be wrapped in an object with the same name as
- * this model. If set to a string, the string value will be used to wrap. If false
- * no wrapping will be applied.
- * Defaults to false.
- * @var Mixed
- */
- Yii.CAsyncRecord.prototype.wrapData = false;
- Yii.CAsyncRecord.prototype._models = {};
- Yii.CAsyncRecord.prototype._new = false;
- Yii.CAsyncRecord.prototype._attributes = {};
- Yii.CAsyncRecord.prototype._related = {};
- Yii.CAsyncRecord.prototype._c = null;
- Yii.CAsyncRecord.prototype._pk = null;
- Yii.CAsyncRecord.prototype._alias = 't';
- /**
- * Constructor.
- * @param {String} scenario scenario name. See {@link CModel::scenario} for more details about this parameter.
- */
- Yii.CAsyncRecord.prototype.construct = function (scenario) {
- if (scenario === undefined) {
- scenario = 'insert';
- }
- if(scenario===null) { // internally used by populateRecord() and model()
- return;
- }
- this._attributes = {};
- this._ds = this.dataStoreDefaults();
- this.setScenario(scenario);
- this.setIsNewRecord(true);
- this._attributes=this.attributeDefaults();
- this.init();
- this.attachBehaviors(this.behaviors());
- this.afterConstruct();
- };
-
- /**
- * Initializes this model.
- * This method is invoked when an AR instance is newly created and has
- * its {@link scenario} set.
- * You may override this method to provide code that is needed to initialize the model (e.g. setting
- * initial property values.)
- * @since 1.0.8
- */
- Yii.CAsyncRecord.prototype.init = function () {
- };
- /**
- * Returns a list of attribute names and their default values.
- * Child classes should override this!
- * @returns {Object} attributeName: value
- */
- Yii.CAsyncRecord.prototype.attributeDefaults = function () {
- return {};
- };
- /**
- * Sets the parameters about query caching.
- * This is a shortcut method to {@link CDbConnection::cache()}.
- * It changes the query caching parameter of the {@link dbConnection} instance.
- * @param {Integer} duration the number of seconds that query results may remain valid in cache.
- * If this is 0, the caching will be disabled.
- * @param {Yii.CCacheDependency} dependency the dependency that will be used when saving the query results into cache.
- * @param {Integer} queryCount number of SQL queries that need to be cached after calling this method. Defaults to 1,
- * meaning that the next SQL query will be cached.
- * @returns {Yii.CAsyncRecord} the active record instance itself.
- * @since 1.1.7
- */
- Yii.CAsyncRecord.prototype.cache = function (duration, dependency, queryCount) {
- if (dependency === undefined) {
- dependency = null;
- }
- if (queryCount === undefined) {
- queryCount = 1;
- }
- this.getDataSource().cache(duration, dependency, queryCount);
- return this;
- };
-
- /**
- * Getter magic method.
- * This method is overridden so that RR attributes can be accessed like properties.
- * @param {String} name property name
- * @returns {Mixed} property value
- * @see getAttribute
- */
- Yii.CAsyncRecord.prototype.get = function (name) {
- var getter, i, object, nameParts = [], limit;
- if (name.indexOf(".") !== -1) {
- nameParts = name.split(".");
- name = nameParts.shift();
- }
- if (this[name] !== undefined) {
- object = this[name];
- }
- else if (this._attributes[name] !== undefined) {
- object = this._attributes[name];
- }
- else if (this._related[name] !== undefined) {
- object = this._related[name];
- }
- if (object !== undefined) {
- if (nameParts.length > 0) {
- if (object instanceof Yii.CComponent) {
- return object.get(nameParts.join("."));
- }
- limit = nameParts.length;
- for (i = 0; i < limit; i++) {
- name = nameParts.shift();
- object = object[name];
- if (nameParts.length === 0) {
- return object;
- }
-
- if (object instanceof Yii.CComponent) {
- return object.get(nameParts.join("."));
- }
- }
- }
- return object;
- }
- else {
- if (nameParts.length > 0) {
- return Yii.CModel.prototype.get.call(this, php.array_merge([name],nameParts).join("."));
- }
- return Yii.CModel.prototype.get.call(this,name);
- }
- };
- /**
- * Setter magic method.
- * This method is overridden so that RR attributes can be accessed like properties.
- * @param {String} name property name
- * @param {Mixed} value property value
- */
- Yii.CAsyncRecord.prototype.set = function (name, value) {
- var nameParts = [];
- if (name.indexOf(".") !== -1) {
- nameParts = name.split(".");
- name = nameParts.pop();
- nameParts = nameParts.join(".");
- return (this.get(nameParts)[name] = value);
- }
- else if(this.setAttribute(name,value)===false) {
- if(this.relations[name] !== undefined) {
- this._related[name]=value;
- }
- else {
- Yii.CModel.prototype.set.call(this, name,value);
- }
- }
- };
- /**
- * Gets the data source for this model.
- * @returns {Yii.CActiveDataSource} The data source that this model interacts with
- */
- Yii.CAsyncRecord.prototype.getDataSource = function () {
- if (this._ds !== null) {
- if (this._ds instanceof Yii.CActiveDataSource) {
- return this._ds;
- }
- this._ds = Yii.createComponent(this._ds);
- }
- return this._ds;
- };
-
- /**
- * Sets the data source for this model
- * @param {Yii.CActiveDataSource} value The data source to use with this model
- */
- Yii.CAsyncRecord.prototype.setDataSource = function (value) {
- var className;
- if (!(value instanceof Yii.CActiveDataSource)) {
- if (value['class'] !== undefined) {
- className = value['class'];
- delete value['class'];
- }
- else {
- className = 'CActiveDataSource';
- }
-
- value = Yii.createComponent(className, value);
- }
- this._ds = value;
- }
-
- /**
- * Checks whether this AR has the named attribute
- * @param {String} name attribute name
- * @returns {Boolean} whether this AR has the named attribute (table column).
- */
- Yii.CAsyncRecord.prototype.hasAttribute = function (name) {
- return this.get(name) !== undefined;
- };
- /**
- * Returns the named attribute value.
- * If this is a new record and the attribute is not set before,
- * the default column value will be returned.
- * If this record is the result of a query and the attribute is not loaded,
- * null will be returned.
- * You may also use $this->AttributeName to obtain the attribute value.
- * @param {String} name the attribute name
- * @returns {Mixed} the attribute value. Null if the attribute is not set or does not exist.
- * @see hasAttribute
- */
- Yii.CAsyncRecord.prototype.getAttribute = function (name) {
- if(this[name] !== undefined) {
- return this[name];
- }
- else if(this._attributes[name] !== undefined) {
- return this._attributes[name];
- }
- };
- /**
- * Returns all column attribute values.
- * Note, related objects are not returned.
- * @param {Mixed} names names of attributes whose value needs to be returned.
- * If this is true (default), then all attribute values will be returned, including
- * those that are not loaded from DB (null will be returned for those attributes).
- * If this is null, all attributes except those that are not loaded from DB will be returned.
- * @returns {Array} attribute values indexed by attribute names.
- */
- Yii.CAsyncRecord.prototype.getAttributes = function (names) {
- var attributes, nameColumn, name, attrs, i, column;
- if (names === undefined) {
- names = true;
- }
- attributes=this._attributes;
-
- if(Object.prototype.toString.call(names) === '[object Array]') {
- attrs=[];
- for (i in names) {
- if (names.hasOwnProperty(i)) {
- name = names[i];
- if(this[name] !== undefined) {
- attrs[name]=this.name;
- }
- else {
- attrs[name]=attributes[name] !== undefined?attributes[name]:null;
- }
- }
- }
- return attrs;
- }
- else {
- return attributes;
- }
- };
- /**
- * Sets the named attribute value.
- * You may also use $this->AttributeName to set the attribute value.
- * @param {String} name the attribute name
- * @param {Mixed} value the attribute value.
- * @returns {Boolean} whether the attribute exists and the assignment is conducted successfully
- * @see hasAttribute
- */
- Yii.CAsyncRecord.prototype.setAttribute = function (name, value) {
- if(this[name] !== undefined) {
- this[name]=value;
- }
- else if(this._attributes[name] !== undefined) {
- this._attributes[name]=value;
- }
- else {
- return false;
- }
- return true;
- };
-
- /**
- * Returns if the current record is new.
- * @returns {Boolean} whether the record is new and should be inserted when calling {@link save}.
- * This property is automatically set in constructor and {@link populateRecord}.
- * Defaults to false, but it will be set to true if the instance is created using
- * the new operator.
- */
- Yii.CAsyncRecord.prototype.getIsNewRecord = function () {
- return this._new;
- };
- /**
- * Sets if the record is new.
- * @param {Boolean} value whether the record is new and should be inserted when calling {@link save}.
- * @see getIsNewRecord
- */
- Yii.CAsyncRecord.prototype.setIsNewRecord = function (value) {
- this._new=value;
- };
- /**
- * This event is raised before the record is saved.
- * By setting {@link CModelEvent::isValid} to be false, the normal {@link save()} process will be stopped.
- * @param {Yii.CModelEvent} event the event parameter
- * @since 1.0.2
- */
- Yii.CAsyncRecord.prototype.onBeforeSave = function (event) {
- this.raiseEvent('onBeforeSave',event);
- };
- /**
- * This event is raised after the record is saved.
- * @param {Yii.CEvent} event the event parameter
- * @since 1.0.2
- */
- Yii.CAsyncRecord.prototype.onAfterSave = function (event) {
- this.raiseEvent('onAfterSave',event);
- };
- /**
- * This event is raised before the record is deleted.
- * By setting {@link CModelEvent::isValid} to be false, the normal {@link delete()} process will be stopped.
- * @param {Yii.CModelEvent} event the event parameter
- * @since 1.0.2
- */
- Yii.CAsyncRecord.prototype.onBeforeDelete = function (event) {
- this.raiseEvent('onBeforeDelete',event);
- };
- /**
- * This event is raised after the record is deleted.
- * @param {Yii.CEvent} event the event parameter
- * @since 1.0.2
- */
- Yii.CAsyncRecord.prototype.onAfterDelete = function (event) {
- this.raiseEvent('onAfterDelete',event);
- };
- /**
- * This event is raised before an AR finder performs a find call.
- * In this event, the {@link CModelEvent::criteria} property contains the query criteria
- * passed as parameters to those find methods. If you want to access
- * the query criteria specified in scopes, please use {@link getDbCriteria()}.
- * You can modify either criteria to customize them based on needs.
- * @param {Yii.CModelEvent} event the event parameter
- * @see beforeFind
- * @since 1.0.9
- */
- Yii.CAsyncRecord.prototype.onBeforeFind = function (event) {
- this.raiseEvent('onBeforeFind',event);
- };
- /**
- * This event is raised after the record is instantiated by a find method.
- * @param {Yii.CEvent} event the event parameter
- * @since 1.0.2
- */
- Yii.CAsyncRecord.prototype.onAfterFind = function (event) {
- this.raiseEvent('onAfterFind',event);
- };
- /**
- * This method is invoked before saving a record (after validation, if any).
- * The default implementation raises the {@link onBeforeSave} event.
- * You may override this method to do any preparation work for record saving.
- * Use {@link isNewRecord} to determine whether the saving is
- * for inserting or updating record.
- * Make sure you call the parent implementation so that the event is raised properly.
- * @returns {Boolean} whether the saving should be executed. Defaults to true.
- */
- Yii.CAsyncRecord.prototype.beforeSave = function () {
- var event;
- if(this.hasEventHandler('onBeforeSave')) {
- event=new Yii.CModelEvent(this);
- this.onBeforeSave(event);
- return event.isValid;
- }
- else {
- return true;
- }
- };
- /**
- * This method is invoked after saving a record successfully.
- * The default implementation raises the {@link onAfterSave} event.
- * You may override this method to do postprocessing after record saving.
- * Make sure you call the parent implementation so that the event is raised properly.
- */
- Yii.CAsyncRecord.prototype.afterSave = function () {
- if(this.hasEventHandler('onAfterSave')) {
- this.onAfterSave(new Yii.CEvent(this));
- }
- };
- /**
- * This method is invoked before deleting a record.
- * The default implementation raises the {@link onBeforeDelete} event.
- * You may override this method to do any preparation work for record deletion.
- * Make sure you call the parent implementation so that the event is raised properly.
- * @returns {Boolean} whether the record should be deleted. Defaults to true.
- */
- Yii.CAsyncRecord.prototype.beforeDelete = function () {
- var event;
- if(this.hasEventHandler('onBeforeDelete')) {
- event=new Yii.CModelEvent(this);
- this.onBeforeDelete(event);
- return event.isValid;
- }
- else {
- return true;
- }
- };
- /**
- * This method is invoked after deleting a record.
- * The default implementation raises the {@link onAfterDelete} event.
- * You may override this method to do postprocessing after the record is deleted.
- * Make sure you call the parent implementation so that the event is raised properly.
- */
- Yii.CAsyncRecord.prototype.afterDelete = function () {
- if(this.hasEventHandler('onAfterDelete')) {
- this.onAfterDelete(new Yii.CEvent(this));
- }
- };
- /**
- * This method is invoked before an AR finder executes a find call.
- * The find calls include {@link find}, {@link findAll}, {@link findByPk},
- * {@link findAllByPk}, {@link findByAttributes} and {@link findAllByAttributes}.
- * The default implementation raises the {@link onBeforeFind} event.
- * If you override this method, make sure you call the parent implementation
- * so that the event is raised properly.
- *
- * Starting from version 1.1.5, this method may be called with a hidden {@link CDbCriteria}
- * parameter which represents the current query criteria as passed to a find method of AR.
- *
- * @since 1.0.9
- */
- Yii.CAsyncRecord.prototype.beforeFind = function () {
- var event;
- if(this.hasEventHandler('onBeforeFind')) {
- event=new Yii.CModelEvent(this);
- // for backward compatibility
- event.criteria=arguments.length>0 ? arguments[0] : null;
- this.onBeforeFind(event);
- }
- };
- /**
- * This method is invoked after each record is instantiated by a find method.
- * The default implementation raises the {@link onAfterFind} event.
- * You may override this method to do postprocessing after each newly found record is instantiated.
- * Make sure you call the parent implementation so that the event is raised properly.
- */
- Yii.CAsyncRecord.prototype.afterFind = function () {
- if(this.hasEventHandler('onAfterFind')) {
- this.onAfterFind(new Yii.CEvent(this));
- }
- };
- /**
- * Calls {@link beforeFind}.
- * This method is internally used.
- * @since 1.0.11
- */
- Yii.CAsyncRecord.prototype.beforeFindInternal = function () {
- this.beforeFind();
- };
- /**
- * Calls {@link afterFind}.
- * This method is internally used.
- * @since 1.0.3
- */
- Yii.CAsyncRecord.prototype.afterFindInternal = function () {
- this.afterFind();
- };
-
-
- /**
- * Adds an item to the data source based on this remote record attributes.
- * Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
- * After the record is inserted to data source successfully, its {@link isNewRecord} property will be set false,
- * and its {@link scenario} property will be set to be 'update'.
- * @param {Array} attributes list of attributes that need to be saved. Defaults to null,
- * meaning all attributes that are loaded from DS will be saved.
- * @param {Function} callback The callback that will be executed after the insert succeeds
- * @returns {Mixed} The data source request
- * @throws {Yii.CException} if the record is not new
- */
- Yii.CAsyncRecord.prototype.create = function (attributes, callback) {
- var builder, table, command, primaryKey, i, pk, self = this, func, postData;
- if (attributes === undefined) {
- attributes = null;
- }
- if(!this.getIsNewRecord()) {
- throw new Yii.CDbException(Yii.t('yii','The remote record cannot be created because it is not new.'));
- }
- if(this.beforeSave()) {
- Yii.trace(this.getClassName()+'.create()','system.ds.CAsyncRecord');
- func = function (data, dataSource) {
- var model;
- model = self.populateRecord(data);
- model.afterSave();
- model.setIsNewRecord(false);
- model.setScenario('update');
- callback(model, dataSource);
- };
- if (this.wrapData === true) {
- postData = {};
- postData[this.getClassName()] = this.getAttributes(attributes);
- }
- else if (this.wrapData) {
- postData = {};
- postData[this.wrapData] = this.getAttributes(attributes);
- }
- else {
- postData = this.getAttributes(attributes);
- }
- return this.getDataSource().create(postData, func);
- }
- return false;
- };
- /**
- * Updates the row represented by this remote record.
- * All loaded attributes will be saved to the database.
- * Note, validation is not performed in this method. You may call {@link validate} to perform the validation.
- * @param {Array} attributes list of attributes that need to be saved. Defaults to null,
- * meaning all attributes that are loaded from DB will be saved.
- * @param {Function} callback The callback that will be executed after the update succeeds
- * @returns {Mixed} The data source request
- * @throws {Yii.CException} if the record is new
- */
- Yii.CAsyncRecord.prototype.update = function (attributes, callback) {
- var self = this, func, postData;
- if (attributes === undefined) {
- attributes = null;
- }
- if(this.getIsNewRecord()) {
- throw new Yii.CDbException(Yii.t('yii','The remote record cannot be updated because it is new.'));
- }
-
- if(this.beforeSave()) {
- Yii.trace(this.getClassName()+'.update()','system.ds.CAsyncRecord');
- func = function (data, dataSource) {
- var model;
- model = self.populateRecord(data);
- model.afterSave();
- model.setIsNewRecord(false);
- model.setScenario('update');
- callback(model, dataSource);
- };
- if (this.wrapData === true) {
- postData = {};
- postData[this.getClassName()] = this.getAttributes(attributes);
- }
- else if (this.wrapData) {
- postData = {};
- postData[this.wrapData] = this.getAttributes(attributes);
- }
- else {
- postData = this.getAttributes(attributes);
- }
-
- return this.getDataSource().update(postData, func);
- }
- else {
- return false;
- }
- };
- /**
- * Saves a selected list of attributes.
- * Unlike {@link save}, this method only saves the specified attributes
- * of an existing row dataset and does NOT call either {@link beforeSave} or {@link afterSave}.
- * Also note that this method does neither attribute filtering nor validation.
- * So do not use this method with untrusted data (such as user posted data).
- * @param {Array} attributes attributes to be updated. Each element represents an attribute name
- * or an attribute value indexed by its name. If the latter, the record's
- * attribute will be changed accordingly before saving.
- * @param {Function} callback The callback that will be executed after the insert succeeds
- * @returns {Mixed} The data source request
- * @throws {Yii.CException} if the record is new or any database error
- */
- Yii.CAsyncRecord.prototype.saveAttributes = function (attributes, callback) {
- var values, name, value;
- if(!this.getIsNewRecord()) {
- Yii.trace(this.getClassName()+'.saveAttributes()','system.ds.CAsyncRecord');
- values={};
- for (name in attributes) {
- if (attributes.hasOwnProperty(name)) {
- value = attributes[name];
- if((typeof(name) === 'number' && (name % 1 ? false : true))) {
- values[value]=this[value];
- }
- else {
- values[name]=this[name]=value;
- }
- }
- }
- Yii.trace(this.getClassName()+'.update()','system.ds.CAsyncRecord');
- return this.getDataSource().update(values, callback);
- }
- else {
- throw new Yii.CDbException(Yii.t('yii','The active record cannot be updated because it is new.'));
- }
- };
- /**
- * Saves the current record.
- *
- * The record is created if its {@link isNewRecord}
- * property is true (usually the case when the record is created using the 'new'
- * operator). Otherwise, it will be used to update the corresponding item in the data source
- * (usually the case if the record is obtained using one of those 'find' methods.)
- *
- * Validation will be performed before saving the record. If the validation fails,
- * the record will not be saved. You can call {@link getErrors()} to retrieve the
- * validation errors.
- *
- * If the record is saved via insertion, its {@link isNewRecord} property will be
- * set false, and its {@link scenario} property will be set to be 'update'.
- * And if its primary key is auto-incremental and is not set before insertion,
- * the primary key will be populated with the automatically generated key value.
- * @param {Function} callback The callback function that will be executed after the save
- * @param {Boolean} runValidation whether to perform validation before saving the record.
- * If the validation fails, the record will not be saved to database.
- * @param {Array} attributes list of attributes that need to be saved. Defaults to null,
- * meaning all attributes that are loaded from DB will be saved.
- * @returns {Mixed} the response from the data source
- */
- Yii.CAsyncRecord.prototype.save = function (callback, runValidation, attributes) {
- if (runValidation === undefined) {
- runValidation = true;
- }
- if (attributes === undefined) {
- attributes = null;
- }
- if(!runValidation || this.validate(attributes)) {
-
- return this.getIsNewRecord() ? this.create(attributes, callback) : this.update(attributes, callback);
- }
- else {
- return false;
- }
- };
-
- /**
- * Creates a remote record with the given attributes.
- * This method is internally used by the find methods.
- * @param {Array} attributes attribute values (column name=>column value)
- * @param {Boolean} callAfterFind whether to call {@link afterFind} after the record is populated.
- * This parameter is added in version 1.0.3.
- * @returns {Yii.CAsyncRecord} the newly created active record. The class of the object is the same as the model class.
- * Null is returned if the input data is false.
- */
- Yii.CAsyncRecord.prototype.populateRecord = function (attributes, callAfterFind) {
- var record, md, name, value;
- if (callAfterFind === undefined) {
- callAfterFind = true;
- }
- if(attributes!==false) {
- record=this.instantiate(attributes);
- record.setIsNewRecord(false);
- record.setScenario('update');
- record.init();
-
- for (name in attributes) {
- if (attributes.hasOwnProperty(name)) {
- value = attributes[name];
- if(record[name] !== undefined) {
- record[name]=value;
- }
- else if(record._attributes[name] !== undefined) {
- record._attributes[name]=value;
- }
- }
- }
- record._pk=record.getPrimaryKey();
- record.attachBehaviors(record.behaviors());
- if(callAfterFind) {
- record.afterFind();
- }
- return record;
- }
- else {
- return null;
- }
- };
- /**
- * Creates a list of active records based on the input data.
- * This method is internally used by the find methods.
- * @param {Array} data list of attribute values for the active records.
- * @param {Boolean} callAfterFind whether to call {@link afterFind} after each record is populated.
- * This parameter is added in version 1.0.3.
- * @param {String} index the name of the attribute whose value will be used as indexes of the query result array.
- * If null, it means the array will be indexed by zero-based integers.
- * @returns {Array} list of active records.
- */
- Yii.CAsyncRecord.prototype.populateRecords = function (data, callAfterFind, index) {
- var records, i, limit, record, attributes;
- if (callAfterFind === undefined) {
- callAfterFind = true;
- }
- if (index === undefined) {
- index = null;
- }
- records=[];
- limit = data.length;
- for (i = 0; i < limit; i++) {
- attributes = data[i];
- if((record=this.populateRecord(attributes,callAfterFind))!==null) {
- if(index===null) {
- records.push(record);
- }
- else {
- records[record[index]]=record;
- }
- }
- }
- return records;
- };
- /**
- * Creates an active record instance.
- * This method is called by {@link populateRecord} and {@link populateRecords}.
- * You may override this method if the instance being created
- * depends the attributes that are to be populated to the record.
- * For example, by creating a record based on the value of a column,
- * you may implement the so-called single-table inheritance mapping.
- * @param {Object} attributes list of attribute values for the active records.
- * @returns {Yii.CAsyncRecord} the active record
- * @since 1.0.2
- */
- Yii.CAsyncRecord.prototype.instantiate = function (attributes) {
- var classVar, model;
- classVar=this.getClassName();
- model=new Yii[classVar]();
- return model;
- };
-
- /**
- * Returns the primary key value.
- * @returns {Mixed} the primary key value. An array (column name=>column value) is returned if the primary key is composite.
- * If primary key is not defined, null will be returned.
- */
- Yii.CAsyncRecord.prototype.getPrimaryKey = function () {
- var table, values,name,pk,self = this;
- pk = this.primaryKey();
-
- if(typeof(pk) === 'string') {
-
- return this.get(pk);
- }
- else if(Object.prototype.toString.call(pk) === '[object Array]') {
- values={};
- Yii.forEach(pk, function (i, name) {
- values[name] = self.get(name);
- });
- return values;
- }
- else {
- return null;
- }
- };
- /**
- * Sets the primary key value.
- * After calling this method, the old primary key value can be obtained from {@link oldPrimaryKey}.
- * @param {Mixed} value the new primary key value. If the primary key is composite, the new value
- * should be provided as an array (column name=>column value).
- * @since 1.1.0
- */
- Yii.CAsyncRecord.prototype.setPrimaryKey = function (value) {
- var table, values,name,pk,self = this;
- pk = this.primaryKey();
- if(typeof(pk) === 'string') {
- this.set(pk, value);
- }
- else if(Object.prototype.toString.call(pk) === '[object Array]') {
- values={};
- Yii.forEach(pk, function (i, name) {
- self[name] = value[i];
- });
-
- }
-
- };
- /**
- * Performs a query, this is mainly used internally by the find / findAll methods
- * @param {Function} callback The callback function to execute when data arrives
- * @param {Object} criteria The criteria that will be sent to the server
- * @param {Boolean} all whether to return all data or not
- */
- Yii.CAsyncRecord.prototype.query = function (callback, criteria, all) {
- var command, finder, func, self = this;
- if (all === undefined) {
- all = false;
- }
- this.beforeFind();
- func = function(data, dataSource) {
- if (all) {
- return callback(self.populateRecords(data, true), dataSource);
- }
- else {
- return callback(self.populateRecord(data.shift(), true), dataSource);
- }
- };
- return this.getDataSource().search(criteria,func);
- };
-
-
- /**
- * Finds a single remote record with the specified condition.
- * @param {Function} callback The callback function that will recieve the results
- * @param {Mixed} criteria query criteria.
- * @returns {Yii.CAsyncRecord} the record found. Null if no record is found.
- */
- Yii.CAsyncRecord.prototype.find = function (callback, criteria) {
-
- Yii.trace(this.getClassName()+'.find()','system.ds.CAsyncRecord');
-
- return this.query(callback, criteria);
- };
- /**
- * Finds all remote records satisfying the specified condition.
- * See {@link find()} for detailed explanation about $condition and $params.
- * @param {Function} callback The callback function that will recieve the results
- * @param {Mixed} criteria query criteria.
- * @returns {Array} list of active records satisfying the specified condition. An empty array is returned if none is found.
- */
- Yii.CAsyncRecord.prototype.findAll = function (callback, criteria) {
- Yii.trace(this.getClassName()+'.findAll()','system.ds.CAsyncRecord');
- return this.query(callback, criteria,true);
-
- };
- /**
- * Finds a remote active record with the specified primary key.
- * See {@link find()} for detailed explanation about $condition and $params.
- * @param {Function} callback The callback function that will recieve the results
- * @param {Mixed} pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
- * @returns {Yii.CAsyncRecord} the record found. Null if none is found.
- */
- Yii.CAsyncRecord.prototype.findByPk = function (callback, pk, criteria) {
- var postData;
- if (criteria === undefined) {
- criteria = {};
- }
- criteria[this.primaryKey()] = pk;
- if (this.wrapData === true) {
- postData = {};
- postData[this.getClassName()] = criteria;
- }
- else if (this.wrapData) {
- postData = {};
- postData[this.wrapData] = criteria;
- }
- else {
- postData = criteria;
- }
- Yii.trace(this.getClassName()+'.findByPk()','system.ds.CAsyncRecord');
-
-
- return this.query(callback, postData);
- };
- /**
- * Finds all active records with the specified primary keys.
- * See {@link find()} for detailed explanation about $condition and $params.
- * @param {Function} callback The callback function that will recieve the results
- * @param {Mixed} pk primary key value(s). Use array for multiple primary keys. For composite key, each key value must be an array (column name=>column value).
- * @param {Mixed} condition query condition or criteria.
- * @param {Object} params parameters to be bound to an SQL statement.
- * @returns {Array} the records found. An empty array is returned if none is found.
- */
- Yii.CAsyncRecord.prototype.findAllByPk = function (callback, pk, criteria) {
- var postData;
- if (criteria === undefined) {
- criteria = {};
- }
- criteria[this.primaryKey()] = pk;
- if (this.wrapData === true) {
- postData = {};
- postData[this.getClassName()] = criteria;
- }
- else if (this.wrapData) {
- postData = {};
- postData[this.wrapData] = criteria;
- }
- else {
- postData = criteria;
- }
- Yii.trace(this.getClassName()+'.findAllByPk()','system.ds.CAsyncRecord');
- return this.query(callback, postData,true);
- };
- /**
- * Finds a single active record that has the specified attribute values.
- * See {@link find()} for detailed explanation about $condition and $params.
- * @param {Function} callback The callback function that will recieve the results
- * @param {Object} attributes list of attribute values (indexed by attribute names) that the active records should match.
- * Since version 1.0.8, an attribute value can be an array which will be used to generate an IN condition.
- * @returns {Yii.CAsyncRecord} the record found. Null if none is found.
- */
- Yii.CAsyncRecord.prototype.findByAttributes = function (callback, attributes) {
- var postData;
- Yii.trace(this.getClassName()+'.findByAttributes()','system.ds.CAsyncRecord');
-
- if (this.wrapData === true) {
- postData = {};
- postData[this.getClassName()] = attributes;
- }
- else if (this.wrapData) {
- postData = {};
- postData[this.wrapData] = attributes;
- }
- else {
- postData = attributes;
- }
- return this.query(callback, postData);
- };
- /**
- * Finds all active records that have the specified attribute values.
- * See {@link find()} for detailed explanation about $condition and $params.
- * @param {Function} callback The callback function that will recieve the results
- * @param {Array} attributes list of attribute values (indexed by attribute names) that the active records should match.
- * Since version 1.0.8, an attribute value can be an array which will be used to generate an IN condition.
- * @returns {Array} the records found. An empty array is returned if none is found.
- */
- Yii.CAsyncRecord.prototype.findAllByAttributes = function (callback, attributes) {
- var postData;
- Yii.trace(this.getClassName()+'.findAllByAttributes()','system.ds.CAsyncRecord');
- if (this.wrapData === true) {
- postData = {};
- postData[this.getClassName()] = attributes;
- }
- else if (this.wrapData) {
- postData = {};
- postData[this.wrapData] = attributes;
- }
- else {
- postData = attributes;
- }
- return this.query(callback, postData, true);
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CAsyncRecordBehavior is the base class for behaviors that can be attached to {@link CAsyncRecord}.
- * Compared with {@link CModelBehavior}, CAsyncRecordBehavior attaches to more events
- * that are only defined by {@link CAsyncRecord}.
- *
- * @package system.ds
- * @since 1.0.2
- * @author Charles Pick
- * @class
- * @extends Yii.CModelBehavior
- */
- Yii.CAsyncRecordBehavior = function CAsyncRecordBehavior () {
- };
- Yii.CAsyncRecordBehavior.prototype = new Yii.CModelBehavior();
- Yii.CAsyncRecordBehavior.prototype.constructor = Yii.CAsyncRecordBehavior;
- /**
- * Declares events and the corresponding event handler methods.
- * If you override this method, make sure you merge the parent result to the return value.
- * @returns {Array} events (array keys) and the corresponding event handler methods (array values).
- * @see CBehavior::events
- */
- Yii.CAsyncRecordBehavior.prototype.events = function () {
- return php.array_merge(parent.events(), {
- 'onBeforeSave':'beforeSave',
- 'onAfterSave':'afterSave',
- 'onBeforeDelete':'beforeDelete',
- 'onAfterDelete':'afterDelete',
- 'onBeforeFind':'beforeFind',
- 'onAfterFind':'afterFind'
- });
- };
- /**
- * Responds to {@link CAsyncRecord::onBeforeSave} event.
- * Overrides this method if you want to handle the corresponding event of the {@link CBehavior::owner owner}.
- * You may set {@link CModelEvent::isValid} to be false to quit the saving process.
- * @param {Yii.CModelEvent} event event parameter
- */
- Yii.CAsyncRecordBehavior.prototype.beforeSave = function (event) {
- };
- /**
- * Responds to {@link CAsyncRecord::onAfterSave} event.
- * Overrides this method if you want to handle the corresponding event of the {@link CBehavior::owner owner}.
- * @param {Yii.CModelEvent} event event parameter
- */
- Yii.CAsyncRecordBehavior.prototype.afterSave = function (event) {
- };
- /**
- * Responds to {@link CAsyncRecord::onBeforeDelete} event.
- * Overrides this method if you want to handle the corresponding event of the {@link CBehavior::owner owner}.
- * You may set {@link CModelEvent::isValid} to be false to quit the deletion process.
- * @param {Yii.CEvent} event event parameter
- */
- Yii.CAsyncRecordBehavior.prototype.beforeDelete = function (event) {
- };
- /**
- * Responds to {@link CAsyncRecord::onAfterDelete} event.
- * Overrides this method if you want to handle the corresponding event of the {@link CBehavior::owner owner}.
- * @param {Yii.CEvent} event event parameter
- */
- Yii.CAsyncRecordBehavior.prototype.afterDelete = function (event) {
- };
- /**
- * Responds to {@link CAsyncRecord::onBeforeFind} event.
- * Overrides this method if you want to handle the corresponding event of the {@link CBehavior::owner owner}.
- * @param {Yii.CEvent} event event parameter
- * @since 1.0.9
- */
- Yii.CAsyncRecordBehavior.prototype.beforeFind = function (event) {
- };
- /**
- * Responds to {@link CAsyncRecord::onAfterFind} event.
- * Overrides this method if you want to handle the corresponding event of the {@link CBehavior::owner owner}.
- * @param {Yii.CEvent} event event parameter
- */
- Yii.CAsyncRecordBehavior.prototype.afterFind = function (event) {
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * A class for retrieving data from JSON data sources
- * @package system.ds
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CActiveDataSource
- */
- Yii.CJSONDataSource = function CJSONDataSource (construct) {
- if (construct !== false) {
- this.ajaxOptions = {};
- this.cacheDuration = null;
- this.cacheDependency = null;
- this.cacheKey = null;
- }
- };
- Yii.CJSONDataSource.prototype = new Yii.CActiveDataSource();
- Yii.CJSONDataSource.prototype.constructor = Yii.CJSONDataSource;
- Yii.CJSONDataSource.prototype.cacheDependency = null;
- Yii.CJSONDataSource.prototype.cacheDuration = null;
- Yii.CJSONDataSource.prototype._cacheKey = null;
-
- Yii.CJSONDataSource.prototype.cache = function (duration, dependency) {
- this.cacheDuration = duration;
- this.cacheDependency = dependency;
- };
- /**
- * Gets the cache key
- */
- Yii.CJSONDataSource.prototype.getCacheKey = function() {
- if (this._cacheKey === null) {
- this._cacheKey = Yii.CJSON.encode(this.ajaxOptions);
- }
- return this._cacheKey;
- };
- /**
- * Whether to use JSONP or not, defaults to false meaning use AJAX for requests.
- * @var Boolean
- */
- Yii.CJSONDataSource.prototype.useJSONP = false;
-
- /**
- * Options to pass to the ajax request.
- * @var Object
- */
- Yii.CJSONDataSource.prototype.ajaxOptions = {};
- /**
- * A list of actions and their respective URLs. has the format:
- * {
- * 'list': 'http://example.com/products/list.json',
- * 'search': ['product/search', {'format': 'json'}],
- * 'create': ['product/create', {'format': 'json'}],
- * 'update': ['product/update', {'format': 'json'}]
- * }
- * @see Yii.CHtml.normalizeUrl
- * @var Object
- */
- Yii.CJSONDataSource.prototype.routes = {};
- /**
- * Makes the request and executes the callback when data arrives.
- * @param {Function} callback The callback function to execute, this will recieve the
- * data as its first parameter and the data source as its second parameter.
- * @returns {jQuery.ajaxRequest} The ajax request
- */
- Yii.CJSONDataSource.prototype.makeRequest = function (callback) {
- var options, source = this, result;
- if (this.ajaxOptions.type === undefined) {
- this.ajaxOptions.type = "GET";
- }
- this.ajaxOptions.success = function (data) {
- if (source.cacheDuration !== null && source.ajaxOptions.type.toLowerCase() === "get") {
- Yii.app().getCache().set(source.getCacheKey(), data, source.cacheDuration);
- }
- callback(data, source);
- };
- if (source.ajaxOptions.type.toLowerCase() === "get" && source.cacheDuration !== null && (result = Yii.app().getCache().get(source.getCacheKey())) !== false) {
- return callback(result, source);
- }
-
- return Yii.app().ajax.makeRequest(this.ajaxOptions);
- };
-
- /**
- * Gets a list of items from the data source
- * @param {Function} callback the callback function to execute, this will
- * receive the response from the server as its first parameter and the data source
- * as the second parameter
- * @returns {jQuery.ajaxRequest} The ajax request
- */
- Yii.CJSONDataSource.prototype.list = function (callback) {
-
- this.ajaxOptions.url = this.routes.list;
- return this.makeRequest(callback);
- };
-
- /**
- * Searches for items from the data source.
- * @param {Object} criteria The search criteria, field:'search query'
- * @param {Function} callback the callback function to execute, this will
- * receive the response from the server as its first parameter and the data source
- * as the second parameter
- * @returns {jQuery.ajaxRequest} The ajax request
- */
- Yii.CJSONDataSource.prototype.search = function (criteria, callback) {
- this.ajaxOptions.data = criteria;
- this.ajaxOptions.url = this.routes.search;
- return this.makeRequest(callback);
- };
-
- /**
- * Creates a new item.
- * @param {Object} data The data to post to the server
- * @param {Function} callback the callback function to execute, this will
- * receive the response from the server as its first parameter and the data source
- * as the second parameter
- * @returns {jQuery.ajaxRequest} The ajax request
- */
- Yii.CJSONDataSource.prototype.create = function (data, callback) {
- this.ajaxOptions.data = data;
- if (this.ajaxOptions.type === undefined || this.ajaxOptions.type.toLowerCase() === "get") {
- this.ajaxOptions.type = "post";
- }
- this.ajaxOptions.url = this.routes.create;
- return this.makeRequest(callback);
- };
-
- /**
- * Updates an item
- * @param {Object} data The data to post to the server
- * @param {Function} callback the callback function to execute, this will
- * receive the response from the server as its first parameter and the data source
- * as the second parameter
- * @returns {jQuery.ajaxRequest} The ajax request
- */
- Yii.CJSONDataSource.prototype.update = function (data, callback) {
- this.ajaxOptions.data = data;
- if (this.ajaxOptions.type === undefined || this.ajaxOptions.type.toLowerCase() === "get") {
- this.ajaxOptions.type = "post";
- }
- this.ajaxOptions.url = this.routes.update;
- return this.makeRequest(callback);
- };
-
- /**
- * Deletes an item
- * @param {Object} data The data to post to the server
- * @param {Function} callback the callback function to execute, this will
- * receive the response from the server as its first parameter and the data source
- * as the second parameter
- * @returns {jQuery.ajaxRequest} The ajax request
- */
- Yii.CJSONDataSource.prototype.remove = function (data, callback) {
- this.ajaxOptions.data = data;
- if (this.ajaxOptions.type === undefined || this.ajaxOptions.type.toLowerCase() === "get") {
- this.ajaxOptions.type = "post";
- }
- this.ajaxOptions.url = this.routes.remove;
- return this.makeRequest(callback);
- };
-
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CChoiceFormat is a helper that chooses an appropriate message based on the specified number value.
- * The candidate messages are given as a string in the following format:
- * <pre>
- * 'expr1#message1|expr2#message2|expr3#message3'
- * </pre>
- * where each expression should be a valid PHP expression with 'n' as the only variable.
- * For example, 'n==1' and 'n%10==2 && n>10' are both valid expressions.
- * The variable 'n' will take the given number value, and if an expression evaluates true,
- * the corresponding message will be returned.
- *
- * For example, given the candidate messages 'n==1#one|n==2#two|n>2#others' and
- * the number value 2, the resulting message will be 'two'.
- *
- * For expressions like 'n==1', we can also use a shortcut '1'. So the above example
- * candidate messages can be simplified as '1#one|2#two|n>2#others'.
- *
- * In case the given number doesn't select any message, the last candidate message
- * will be returned.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CChoiceFormat.php 2899 2011-01-20 21:10:03Z alexander.makarow $
- * @package system.i18n
- * @since 1.0.2
- * @author Charles Pick
- * @class
- */
- Yii.CChoiceFormat = function CChoiceFormat () {
- };
- /**
- * Formats a message according to the specified number value.
- * @param {String} messages the candidate messages in the format of 'expr1#message1|expr2#message2|expr3#message3'.
- * See {@link CChoiceFormat} for more details.
- * @param {Mixed} number the number value
- * @returns {String} the selected message
- */
- Yii.CChoiceFormat.prototype.format = function (messages, number) {
- var n, matches, i, expression, message, match;
- matches = (messages + "|").match(/\s*([^#]*)\s*#([^\|]*)\|/g);
- if (matches !== null) {
- n = matches.length;
- }
- else {
- return messages;
- }
- if(n===0) {
- return messages;
- }
- for(i=0;i<n;++i) {
- match = matches[i].match(/\s*([^#]*)\s*#([^\|]*)\|/);
- expression=match[0];
- message=match[1];
- if(expression===String(Number(expression))) {
- if(expression==number) {
- return message;
- }
- }
- else if(this.evaluate(expression,number)) {
- return message;
- }
- }
- return message; // return the last choice
- };
- /**
- * Evaluates a PHP expression with the given number value.
- * @param {String} expression the PHP expression
- * @param {Mixed} n the number value
- * @returns {Boolean} the expression result
- */
- Yii.CChoiceFormat.prototype.evaluate = function (expression, n) {
- return eval(expression);
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CDateFormatter provides date/time localization functionalities.
- *
- * CDateFormatter allows you to format dates and times in a locale-sensitive manner.
- * Patterns are interpreted in the locale that the CDateFormatter instance
- * is associated with. For example, month names and weekday names may vary
- * under different locales, which yields different formatting results.
- * The patterns that CDateFormatter recognizes are as defined in
- * {@link http://www.unicode.org/reports/tr35/#Date_Format_Patterns CLDR}.
- *
- * CDateFormatter supports predefined patterns as well as customized ones:
- * <ul>
- * <li>The method {@link formatDateTime()} formats date or time or both using
- * predefined patterns which include 'full', 'long', 'medium' (default) and 'short'.</li>
- * <li>The method {@link format()} formats datetime using the specified pattern.
- * See {@link http://www.unicode.org/reports/tr35/#Date_Format_Patterns} for
- * details about the recognized pattern characters.</li>
- * </ul>
- *
- * @originalAuthor Wei Zhuo <weizhuo[at]gmail[dot]com>
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CDateFormatter.php 2798 2011-01-01 19:29:03Z qiang.xue $
- * @package system.i18n
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CDateFormatter = function CDateFormatter (locale) {
- if (locale !== false) {
- this.construct(false);
- }
- };
- Yii.CDateFormatter.prototype = new Yii.CComponent();
- Yii.CDateFormatter.prototype.constructor = Yii.CDateFormatter;
- /**
- * @var {Array} pattern characters mapping to the corresponding translator methods
- */
- Yii.CDateFormatter.prototype._formatters = {'G':'formatEra','y':'formatYear','M':'formatMonth','L':'formatMonth','d':'formatDay','h':'formatHour12','H':'formatHour24','m':'formatMinutes','s':'formatSeconds','E':'formatDayInWeek','c':'formatDayInWeek','e':'formatDayInWeek','D':'formatDayInYear','F':'formatDayInMonth','w':'formatWeekInYear','W':'formatWeekInMonth','a':'formatPeriod','k':'formatHourInDay','K':'formatHourInPeriod','z':'formatTimeZone','Z':'formatTimeZone','v':'formatTimeZone'};
- Yii.CDateFormatter.prototype._locale = null;
- Yii.CDateFormatter.prototype._formats = [];
- /**
- * Constructor.
- * @param {Mixed} locale locale ID (string) or CLocale instance
- */
- Yii.CDateFormatter.prototype.construct = function (locale) {
- if(typeof(locale) === 'string') {
- this._locale=Yii.CLocale.getInstance(locale);
- }
- else {
- this._locale=locale;
- }
- };
- /**
- * Formats a date according to a customized pattern.
- * @param {String} pattern the pattern (See {@link http://www.unicode.org/reports/tr35/#Date_Format_Patterns})
- * @param {Mixed} time UNIX timestamp or a string in strtotime format
- * @returns {String} formatted date time.
- */
- Yii.CDateFormatter.prototype.format = function (pattern, time) {
- var date, tokens, i, token;
- if(typeof(time) === 'string')
- {
- if(php.ctype_digit(time)) {
- time=Number(time);
- }
- else {
- time=php.strtotime(time);
- }
- }
- date=Yii.CTimestamp.getdate(time,false,false);
- tokens=this.parseFormat(pattern);
- for (i in tokens) {
- if (tokens.hasOwnProperty(i)) {
-
- if(Object.prototype.toString.call(tokens[i]) === '[object Array]') {
- // a callback: method name, sub-pattern
- tokens[i]=this[tokens[i][0]](tokens[i][1],date);
- }
- }
- }
- return tokens.join('');
- };
- /**
- * Formats a date according to a predefined pattern.
- * The predefined pattern is determined based on the date pattern width and time pattern width.
- * @param {Mixed} timestamp UNIX timestamp or a string in strtotime format
- * @param {String} dateWidth width of the date pattern. It can be 'full', 'long', 'medium' and 'short'.
- * If null, it means the date portion will NOT appear in the formatting result
- * @param {String} timeWidth width of the time pattern. It can be 'full', 'long', 'medium' and 'short'.
- * If null, it means the time portion will NOT appear in the formatting result
- * @returns {String} formatted date time.
- */
- Yii.CDateFormatter.prototype.formatDateTime = function (timestamp, dateWidth, timeWidth) {
- var date, time, dateTimePattern;
- if (dateWidth === undefined) {
- dateWidth = 'medium';
- }
- if (timeWidth === undefined) {
- timeWidth = 'medium';
- }
- if(!php.empty(dateWidth)) {
- date=this.format(this._locale.getDateFormat(dateWidth),timestamp);
- }
- if(!php.empty(timeWidth)) {
- time=this.format(this._locale.getTimeFormat(timeWidth),timestamp);
- }
- if(date !== undefined && time !== undefined) {
- dateTimePattern=this._locale.getDateTimeFormat();
- return php.strtr(dateTimePattern,{'{0}':time,'{1}':date});
- }
- else if(date !== undefined) {
- return date;
- }
- else if(time !== undefined) {
- return time;
- }
- };
- /**
- * Parses the datetime format pattern.
- * @param {String} pattern the pattern to be parsed
- * @returns {Array} tokenized parsing result
- */
- Yii.CDateFormatter.prototype.parseFormat = function (pattern) {
- var tokens, n, isLiteral, literal, i, c, j, p, _formatters;
-
- if(this._formats[pattern] !== undefined) {
- return this._formats[pattern];
- }
- tokens=[];
- n=php.strlen(pattern);
- isLiteral=false;
- literal='';
- for(i=0;i<n;++i) {
- c=pattern[i];
- if(c==="'") {
- if(i<n-1 && pattern[i+1]==="'"){
- tokens.push("'");
- i++;
- }
- else if(isLiteral){
- tokens.push(literal);
- literal='';
- isLiteral=false;
- }
- else{
- isLiteral=true;
- literal='';
- }
- }
- else if(isLiteral) {
- literal+=c;
- }
- else {
- for(j=i+1;j<n;++j) {
- if(pattern[j]!==c) {
- break;
- }
- }
- p=php.str_repeat(c,j-i);
- if(this._formatters[c] !== undefined) {
- tokens.push([this._formatters[c],p]);
- }
- else {
- tokens.push(p);
- }
- i=j-1;
- }
- }
- if(literal!=='') {
- tokens.push(literal);
- }
- return (this._formats[pattern]=tokens);
- };
- /**
- * Get the year.
- * "yy" will return the last two digits of year.
- * "y...y" will pad the year with 0 in the front, e.g. "yyyyy" will generate "02008" for year 2008.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {String} formatted year
- */
- Yii.CDateFormatter.prototype.formatYear = function (pattern, date) {
- var year;
- year=date.year;
- if(pattern==='yy') {
- return php.str_pad(year%100,2,'0','STR_PAD_LEFT');
- }
- else {
- return php.str_pad(year,php.strlen(pattern),'0','STR_PAD_LEFT');
- }
- };
- /**
- * Get the month.
- * "M" will return integer 1 through 12;
- * "MM" will return two digits month number with necessary zero padding, e.g. 05;
- * "MMM" will return the abrreviated month name, e.g. "Jan";
- * "MMMM" will return the full month name, e.g. "January";
- * "MMMMM" will return the narrow month name, e.g. "J";
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {String} month name
- */
- Yii.CDateFormatter.prototype.formatMonth = function (pattern, date) {
- var month;
- month=date.mon;
- switch(pattern) {
- case 'M':
- return month;
- case 'MM':
- return php.str_pad(month,2,'0','STR_PAD_LEFT');
- case 'MMM':
- return this._locale.getMonthName(month,'abbreviated');
- case 'MMMM':
- return this._locale.getMonthName(month,'wide');
- case 'MMMMM':
- return this._locale.getMonthName(month,'narrow');
- case 'L':
- return month;
- case 'LL':
- return php.str_pad(month,2,'0','STR_PAD_LEFT');
- case 'LLL':
- return this._locale.getMonthName(month,'abbreviated', true);
- case 'LLLL':
- return this._locale.getMonthName(month,'wide', true);
- case 'LLLLL':
- return this._locale.getMonthName(month,'narrow', true);
- default:
- throw new Yii.CException(Yii.t('yii','The pattern for month must be "M", "MM", "MMM", "MMMM", "L", "LL", "LLL" or "LLLL".'));
- }
- };
- /**
- * Get the day of the month.
- * "d" for non-padding, "dd" will always return 2 digits day numbers, e.g. 05.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {String} day of the month
- */
- Yii.CDateFormatter.prototype.formatDay = function (pattern, date) {
- var day;
- day=date.mday;
- if(pattern==='d') {
- return day;
- }
- else if(pattern==='dd') {
- return php.str_pad(day,2,'0','STR_PAD_LEFT');
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for day of the month must be "d" or "dd".'));
- }
- };
- /**
- * Get the day in the year, e.g. [1-366]
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {Integer} hours in AM/PM format.
- */
- Yii.CDateFormatter.prototype.formatDayInYear = function (pattern, date) {
- var day, n;
- day=date.yday;
- if((n=php.strlen(pattern))<=3) {
- return php.str_pad(day,n,'0','STR_PAD_LEFT');
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for day in year must be "D", "DD" or "DDD".'));
- }
- };
- /**
- * Get day of week in the month, e.g. 2nd Wed in July.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {Integer} day in month
- * @see http://www.unicode.org/reports/tr35/#Date_Format_Patterns
- */
- Yii.CDateFormatter.prototype.formatDayInMonth = function (pattern, date) {
- if(pattern==='F') {
- return Number((date.mday+6)/7);
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for day in month must be "F".'));
- }
- };
- /**
- * Get the day of the week.
- * "E", "EE", "EEE" will return abbreviated week day name, e.g. "Tues";
- * "EEEE" will return full week day name;
- * "EEEEE" will return the narrow week day name, e.g. "T";
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {String} day of the week.
- * @see http://www.unicode.org/reports/tr35/#Date_Format_Patterns
- */
- Yii.CDateFormatter.prototype.formatDayInWeek = function (pattern, date) {
- var day;
- day=date.wday;
- switch(pattern) {
- case 'E':
- case 'EE':
- case 'EEE':
- case 'eee':
- return this._locale.getWeekDayName(day,'abbreviated');
- case 'EEEE':
- case 'eeee':
- return this._locale.getWeekDayName(day,'wide');
- case 'EEEEE':
- case 'eeeee':
- return this._locale.getWeekDayName(day,'narrow');
- case 'e':
- case 'ee':
- case 'c':
- return day ? day : 7;
- case 'ccc':
- return this._locale.getWeekDayName(day,'abbreviated',true);
- case 'cccc':
- return this._locale.getWeekDayName(day,'wide',true);
- case 'ccccc':
- return this._locale.getWeekDayName(day,'narrow',true);
- default:
- throw new Yii.CException(Yii.t('yii','The pattern for day of the week must be "E", "EE", "EEE", "EEEE", "EEEEE", "e", "ee", "eee", "eeee", "eeeee", "c", "cccc" or "ccccc".'));
- }
- };
- /**
- * Get the AM/PM designator, 12 noon is PM, 12 midnight is AM.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {String} AM or PM designator
- */
- Yii.CDateFormatter.prototype.formatPeriod = function (pattern, date) {
- if(pattern==='a') {
- if(php.intval(date.hours/12)) {
- return this._locale.getPMName();
- }
- else {
- return this._locale.getAMName();
- }
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for AM/PM marker must be "a".'));
- }
- };
- /**
- * Get the hours in 24 hour format, i.e. [0-23].
- * "H" for non-padding, "HH" will always return 2 characters.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {String} hours in 24 hour format.
- */
- Yii.CDateFormatter.prototype.formatHour24 = function (pattern, date) {
- var hour;
- hour=date.hours;
- if(pattern==='H') {
- return hour;
- }
- else if(pattern==='HH') {
- return php.str_pad(hour,2,'0','STR_PAD_LEFT');
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for 24 hour format must be "H" or "HH".'));
- }
- };
- /**
- * Get the hours in 12 hour format, i.e., [1-12]
- * "h" for non-padding, "hh" will always return 2 characters.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {String} hours in 12 hour format.
- */
- Yii.CDateFormatter.prototype.formatHour12 = function (pattern, date) {
- var hour;
- hour=date.hours;
- hour=(hour==12|hour===0)?12:(hour)%12;
- if(pattern==='h') {
- return hour;
- }
- else if(pattern==='hh') {
- return php.str_pad(hour,2,'0','STR_PAD_LEFT');
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for 12 hour format must be "h" or "hh".'));
- }
- };
- /**
- * Get the hours [1-24].
- * 'k' for non-padding, and 'kk' with 2 characters padding.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {Integer} hours [1-24]
- */
- Yii.CDateFormatter.prototype.formatHourInDay = function (pattern, date) {
- var hour;
- hour=date.hours==0?24:date.hours;
- if(pattern==='k') {
- return hour;
- }
- else if(pattern==='kk') {
- return php.str_pad(hour,2,'0','STR_PAD_LEFT');
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for hour in day must be "k" or "kk".'));
- }
- };
- /**
- * Get the hours in AM/PM format, e.g [0-11]
- * "K" for non-padding, "KK" will always return 2 characters.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {Integer} hours in AM/PM format.
- */
- Yii.CDateFormatter.prototype.formatHourInPeriod = function (pattern, date) {
- var hour;
- hour=date.hours%12;
- if(pattern==='K') {
- return hour;
- }
- else if(pattern==='KK') {
- return php.str_pad(hour,2,'0','STR_PAD_LEFT');
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for hour in AM/PM must be "K" or "KK".'));
- }
- };
- /**
- * Get the minutes.
- * "m" for non-padding, "mm" will always return 2 characters.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {String} minutes.
- */
- Yii.CDateFormatter.prototype.formatMinutes = function (pattern, date) {
- var minutes;
- minutes=date.minutes;
- if(pattern==='m') {
- return minutes;
- }
- else if(pattern==='mm') {
- return php.str_pad(minutes,2,'0','STR_PAD_LEFT');
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for minutes must be "m" or "mm".'));
- }
- };
- /**
- * Get the seconds.
- * "s" for non-padding, "ss" will always return 2 characters.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {String} seconds
- */
- Yii.CDateFormatter.prototype.formatSeconds = function (pattern, date) {
- var seconds;
- seconds=date.seconds;
- if(pattern==='s') {
- return seconds;
- }
- else if(pattern==='ss') {
- return php.str_pad(seconds,2,'0','STR_PAD_LEFT');
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for seconds must be "s" or "ss".'));
- }
- };
- /**
- * Get the week in the year.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {Integer} week in year
- */
- Yii.CDateFormatter.prototype.formatWeekInYear = function (pattern, date) {
- if(pattern==='w') {
- return php.date('W',php.mktime(0,0,0,date.mon,date.mday,date.year));
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for week in year must be "w".'));
- }
- };
- /**
- * Get week in the month.
- * @param {Array} pattern result of {@link CTimestamp::getdate}.
- * @param {String} date a pattern.
- * @returns {Integer} week in month
- */
- Yii.CDateFormatter.prototype.formatWeekInMonth = function (pattern, date) {
- if(pattern==='W') {
- return php.date('W',php.mktime(0,0,0,date.mon, date.mday,date.year))-php.date('W', php.mktime(0,0,0,date.mon,1,date.year))+1;
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for week in month must be "W".'));
- }
- };
- /**
- * Get the timezone of the server machine.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {String} time zone
- * @todo How to get the timezone for a different region?
- */
- Yii.CDateFormatter.prototype.formatTimeZone = function (pattern, date) {
- if(pattern[0]==='z' || pattern[0]==='v') {
- return php.date('T', php.mktime(date.hours, date.minutes, date.seconds, date.mon, date.mday, date.year));
- }
- else if(pattern[0]==='Z') {
- return php.date('O', php.mktime(date.hours, date.minutes, date.seconds, date.mon, date.mday, date.year));
- }
- else {
- throw new Yii.CException(Yii.t('yii','The pattern for time zone must be "z" or "v".'));
- }
- };
- /**
- * Get the era. i.e. in gregorian, year > 0 is AD, else BC.
- * @param {String} pattern a pattern.
- * @param {Array} date result of {@link CTimestamp::getdate}.
- * @returns {String} era
- * @todo How to support multiple Eras?, e.g. Japanese.
- */
- Yii.CDateFormatter.prototype.formatEra = function (pattern, date) {
- var era;
- era=date.year>0 ? 1 : 0;
- switch(pattern)
- {
- case 'G':
- case 'GG':
- case 'GGG':
- return this._locale.getEraName(era,'abbreviated');
- case 'GGGG':
- return this._locale.getEraName(era,'wide');
- case 'GGGGG':
- return this._locale.getEraName(era,'narrow');
- default:
- throw new Yii.CException(Yii.t('yii','The pattern for era must be "G", "GG", "GGG", "GGGG" or "GGGGG".'));
- }
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CJavaScriptMessageSource represents a message source that stores translated messages in JavaScript scripts.
- *
- * CJavaScriptMessageSource uses JavaScript files and arrays to keep message translations.
- * <ul>
- * <li>All translations are saved under the {@link basePath} directory.</li>
- * <li>Translations in one language are kept as JavaScript files under an individual subdirectory
- * whose name is the same as the language ID. Each JavaScript file contains messages
- * belonging to the same category, and the file name is the same as the category name.</li>
- * <li>Within a JavaScript file, an object of (source, translation) pairs is returned.
- * For example:
- * <pre>
- * ({
- * 'original message 1' : 'translated message 1',
- * 'original message 2' : 'translated message 2'
- * });
- * </pre>
- * </li>
- * </ul>
- * When {@link cachingDuration} is set as a positive number, message translations will be cached.
- *
- * Starting from version 1.0.10, messages for an extension class (e.g. a widget, a module) can be specially managed and used.
- * In particular, if a message belongs to an extension whose class name is Xyz, then the message category
- * can be specified in the format of 'Xyz.categoryName'. And the corresponding message file
- * is assumed to be 'BasePath/messages/LanguageID/categoryName.php', where 'BasePath' refers to
- * the directory that contains the extension class file. When using Yii.t() to translate an extension message,
- * the category name should be set as 'Xyz.categoryName'.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CJavaScriptMessageSource.php 2798 2011-01-01 19:29:03Z qiang.xue $
- * @package system.i18n
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CMessageSource
- */
- Yii.CJavaScriptMessageSource = function CJavaScriptMessageSource () {
- };
- Yii.CJavaScriptMessageSource.prototype = new Yii.CMessageSource(false);
- Yii.CJavaScriptMessageSource.prototype.constructor = Yii.CJavaScriptMessageSource;
- /**
- * @const
- */
- Yii.CJavaScriptMessageSource.CACHE_KEY_PREFIX = 'Yii.CJavaScriptMessageSource.';
- /**
- * @var {Integer} the time in seconds that the messages can remain valid in cache.
- * Defaults to 0, meaning the caching is disabled.
- */
- Yii.CJavaScriptMessageSource.prototype.cachingDuration = 0;
- /**
- * @var {String} the ID of the cache application component that is used to cache the messages.
- * Defaults to 'cache' which refers to the primary cache application component.
- * Set this property to false if you want to disable caching the messages.
- * @since 1.0.10
- */
- Yii.CJavaScriptMessageSource.prototype.cacheID = 'cache';
- /**
- * @var {String} the base path for all translated messages. Defaults to null, meaning
- * the "messages" subdirectory of the application directory (e.g. "protected/messages").
- */
- Yii.CJavaScriptMessageSource.prototype.basePath = null;
- Yii.CJavaScriptMessageSource.prototype._files = {};
- /**
- * Initializes the application component.
- * This method overrides the parent implementation by preprocessing
- * the user request data.
- */
- Yii.CJavaScriptMessageSource.prototype.init = function () {
- Yii.CMessageSource.prototype.init.call(this);
- if(this.basePath===null) {
- this.basePath=Yii.getPathOfAlias('application.messages');
- }
- };
- /**
- * Determines the message file name based on the given category and language.
- * If the category name contains a dot, it will be split into the module class name and the category name.
- * In this case, the message file will be assumed to be located within the 'messages' subdirectory of
- * the directory containing the module class file.
- * Otherwise, the message file is assumed to be under the {@link basePath}.
- * @param {String} category category name
- * @param {String} language language ID
- * @returns {String} the message file path
- * @since 1.0.10
- */
- Yii.CJavaScriptMessageSource.prototype.getMessageFile = function (category, language) {
- var pos, moduleClass, moduleCategory, classVar;
- if (this._files[category] === undefined) {
- this._files[category] = {};
- }
- if(this._files[category][language] === undefined) {
-
- if((pos=php.strpos(category,'.'))!==false) {
- moduleClass=category.slice(0, pos);
- moduleCategory=category.slice(pos+1);
- this._files[category][language]=Yii.getPathOfAlias(moduleClass + ".messages." + moduleCategory) + ".js";
- }
- else {
- this._files[category][language]=this.basePath+'/'+language+'/'+category+'.js';
- }
- }
- return this._files[category][language];
- };
- /**
- * Loads the message translation for the specified language and category.
- * @param {String} category the message category
- * @param {String} language the target language
- * @returns {Object} the loaded messages
- */
- Yii.CJavaScriptMessageSource.prototype.loadMessages = function (category, language) {
- var messageFile, cache, key, data, messages, dependency;
- messageFile=this.getMessageFile(category,language);
- if(this.cachingDuration>0 && this.cacheID!==false && (cache=Yii.app().getComponent(this.cacheID))!==null) {
- key=this.Yii.CACHE_KEY_PREFIX + messageFile;
- if((data=cache.get(key))!==false) {
- if (!data instanceof "Object") {
- data = Yii.CJSON.decode(data);
- }
- return data;
- }
- }
- try {
- data = Yii.include(messageFile, false);
- if (data === false) {
- return {};
- }
- if (this.cachingDuration > 0 && this.cacheID !== false && (cache=Yii.app().getComponent(this.cacheID))!==null) {
- key=this.Yii.CACHE_KEY_PREFIX + messageFile;
- cache.set(key, data, this.cachingDuration);
- }
- return data;
- }
- catch (e) {
- return {};
- }
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CLocale represents the data relevant to a locale.
- *
- * The data includes the number formatting information and date formatting information.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CLocale.php 2844 2011-01-13 01:29:55Z alexander.makarow $
- * @package system.i18n
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CLocale = function CLocale (id) {
-
- if (id !== false) {
- this.construct(id);
- }
- };
- Yii.CLocale._locales = null;
- Yii.CLocale.prototype = new Yii.CComponent();
- Yii.CLocale.prototype.constructor = Yii.CLocale;
- /**
- * @var {String} the directory that contains the locale data. If this property is not set,
- * the locale data will be loaded from 'framework/i18n/data'.
- * @since 1.1.0
- */
- Yii.CLocale.prototype.dataPath = null;
- Yii.CLocale.prototype._id = null;
- Yii.CLocale.prototype._data = null;
- Yii.CLocale.prototype._dateFormatter = null;
- Yii.CLocale.prototype._numberFormatter = null;
- /**
- * Returns the instance of the specified locale.
- * Since the constructor of CLocale is protected, you can only use
- * this method to obtain an instance of the specified locale.
- * @param {String} id the locale ID (e.g. en_US)
- * @returns {Yii.CLocale} the locale instance
- */
- Yii.CLocale.getInstance = function (id) {
-
- if(this._locales === null) {
- this._locales = {};
- }
- if(this._locales[id] !== undefined) {
- return this._locales[id];
- }
- else {
- return (this._locales[id]=new Yii.CLocale(id));
- }
- };
- /**
- * @returns {Array} IDs of the locales which the framework can recognize
- */
- Yii.CLocale.prototype.getLocaleIDs = function () {
- var locales;
- locales=["aa","aa_dj","aa_er","aa_et","af","af_na","af_za","ak","ak_gh","am","am_et","ar","ar_ae","ar_bh","ar_dz","ar_eg","ar_iq","ar_jo","ar_kw","ar_lb","ar_ly","ar_ma","ar_om","ar_qa","ar_sa","ar_sd","ar_sy","ar_tn","ar_ye","as","as_in","asa","asa_tz","az","az_arab","az_arab_ir","az_az","az_cyrl","az_cyrl_az","az_ir","az_latn","az_latn_az","be","be_by","bem","bem_zm","bez","bez_tz","bg","bg_bg","bm","bm_ml","bn","bn_bd","bn_in","bo","bo_cn","bo_in","br","br_fr","brx","brx_in","bs","bs_ba","byn","byn_er","ca","ca_es","cch","cch_ng","cgg","cgg_ug","chr","chr_us","cs","cs_cz","cy","cy_gb","da","da_dk","dav","dav_ke","de","de_at","de_be","de_ch","de_de","de_li","de_lu","dv","dv_mv","dz","dz_bt","ebu","ebu_ke","ee","ee_gh","ee_tg","el","el_cy","el_gr","el_polyton","en","en_as","en_au","en_be","en_bw","en_bz","en_ca","en_dsrt","en_dsrt_us","en_gb","en_gu","en_hk","en_ie","en_in","en_jm","en_mh","en_mp","en_mt","en_mu","en_na","en_nz","en_ph","en_pk","en_sg","en_shaw","en_tt","en_um","en_us","en_us_posix","en_vi","en_za","en_zw","en_zz","eo","es","es_419","es_ar","es_bo","es_cl","es_co","es_cr","es_do","es_ec","es_es","es_gq","es_gt","es_hn","es_mx","es_ni","es_pa","es_pe","es_pr","es_py","es_sv","es_us","es_uy","es_ve","et","et_ee","eu","eu_es","fa","fa_af","fa_ir","ff","ff_sn","fi","fi_fi","fil","fil_ph","fo","fo_fo","fr","fr_be","fr_bf","fr_bi","fr_bj","fr_bl","fr_ca","fr_cd","fr_cf","fr_cg","fr_ch","fr_ci","fr_cm","fr_dj","fr_fr","fr_ga","fr_gn","fr_gp","fr_gq","fr_km","fr_lu","fr_mc","fr_mf","fr_mg","fr_ml","fr_mq","fr_ne","fr_re","fr_rw","fr_sn","fr_td","fr_tg","fur","fur_it","ga","ga_ie","gaa","gaa_gh","gez","gez_er","gez_et","gl","gl_es","gsw","gsw_ch","gu","gu_in","guz","guz_ke","gv","gv_gb","ha","ha_arab","ha_arab_ng","ha_arab_sd","ha_gh","ha_latn","ha_latn_gh","ha_latn_ne","ha_latn_ng","ha_ne","ha_ng","ha_sd","haw","haw_us","he","he_il","hi","hi_in","hr","hr_hr","hu","hu_hu","hy","hy_am","ia","id","id_id","ig","ig_ng","ii","ii_cn","in","is","is_is","it","it_ch","it_it","iu","iw","ja","ja_jp","jmc","jmc_tz","ka","ka_ge","kab","kab_dz","kaj","kaj_ng","kam","kam_ke","kcg","kcg_ng","kde","kde_tz","kea","kea_cv","kfo","kfo_ci","khq","khq_ml","ki","ki_ke","kk","kk_cyrl","kk_cyrl_kz","kk_kz","kl","kl_gl","kln","kln_ke","km","km_kh","kn","kn_in","ko","ko_kr","kok","kok_in","kpe","kpe_gn","kpe_lr","ksb","ksb_tz","ksh","ksh_de","ku","ku_arab","ku_arab_iq","ku_arab_ir","ku_iq","ku_ir","ku_latn","ku_latn_sy","ku_latn_tr","ku_sy","ku_tr","kw","kw_gb","ky","ky_kg","lag","lag_tz","lg","lg_ug","ln","ln_cd","ln_cg","lo","lo_la","lt","lt_lt","luo","luo_ke","luy","luy_ke","lv","lv_lv","mas","mas_ke","mas_tz","mer","mer_ke","mfe","mfe_mu","mg","mg_mg","mi","mi_nz","mk","mk_mk","ml","ml_in","mn","mn_cn","mn_cyrl","mn_cyrl_mn","mn_mn","mn_mong","mn_mong_cn","mo","mr","mr_in","ms","ms_bn","ms_my","mt","mt_mt","my","my_mm","naq","naq_na","nb","nb_no","nd","nd_zw","nds","nds_de","ne","ne_in","ne_np","nl","nl_be","nl_nl","nn","nn_no","no","nr","nr_za","nso","nso_za","ny","ny_mw","nyn","nyn_ug","oc","oc_fr","om","om_et","om_ke","or","or_in","pa","pa_arab","pa_arab_pk","pa_guru","pa_guru_in","pa_in","pa_pk","pl","pl_pl","ps","ps_af","pt","pt_ao","pt_br","pt_gw","pt_mz","pt_pt","rm","rm_ch","ro","ro_md","ro_ro","rof","rof_tz","root","ru","ru_md","ru_ru","ru_ua","rw","rw_rw","rwk","rwk_tz","sa","sa_in","saq","saq_ke","se","se_fi","se_no","seh","seh_mz","ses","ses_ml","sg","sg_cf","sh","sh_ba","sh_cs","sh_yu","shi","shi_latn","shi_latn_ma","shi_ma","shi_tfng","shi_tfng_ma","si","si_lk","sid","sid_et","sk","sk_sk","sl","sl_si","sn","sn_zw","so","so_dj","so_et","so_ke","so_so","sq","sq_al","sr","sr_ba","sr_cs","sr_cyrl","sr_cyrl_ba","sr_cyrl_cs","sr_cyrl_me","sr_cyrl_rs","sr_cyrl_yu","sr_latn","sr_latn_ba","sr_latn_cs","sr_latn_me","sr_latn_rs","sr_latn_yu","sr_me","sr_rs","sr_yu","ss","ss_sz","ss_za","ssy","ssy_er","st","st_ls","st_za","sv","sv_fi","sv_se","sw","sw_ke","sw_tz","syr","syr_sy","ta","ta_in","ta_lk","te","te_in","teo","teo_ke","teo_ug","tg","tg_cyrl","tg_cyrl_tj","tg_tj","th","th_th","ti","ti_er","ti_et","tig","tig_er","tl","tl_ph","tn","tn_za","to","to_to","tr","tr_tr","trv","trv_tw","ts","ts_za","tt","tt_ru","tzm","tzm_latn","tzm_latn_ma","tzm_ma","ug","ug_arab","ug_arab_cn","ug_cn","uk","uk_ua","ur","ur_in","ur_pk","uz","uz_af","uz_arab","uz_arab_af","uz_cyrl","uz_cyrl_uz","uz_latn","uz_latn_uz","uz_uz","ve","ve_za","vi","vi_vn","vun","vun_tz","wal","wal_et","wo","wo_latn","wo_latn_sn","wo_sn","xh","xh_za","xog","xog_ug","yo","yo_ng","zh","zh_cn","zh_hans","zh_hans_cn","zh_hans_hk","zh_hans_mo","zh_hans_sg","zh_hant","zh_hant_hk","zh_hant_mo","zh_hant_tw","zh_hk","zh_mo","zh_sg","zh_tw","zu","zu_za"];
-
- return locales;
- };
- /**
- * Constructor.
- * Since the constructor is protected, please use {@link getInstance}
- * to obtain an instance of the specified locale.
- * @param {String} id the locale ID (e.g. en_US)
- */
- Yii.CLocale.prototype.construct = function (id) {
- var dataPath, dataFile;
- this._id=this.getCanonicalID(id);
- dataPath=this.dataPath===null ? YII_PATH + '/i18n/data' : this.dataPath;
- dataFile=dataPath+"/"+this._id+'.js';
- this._data= Yii.include(dataFile,false);
-
- };
- /**
- * Converts a locale ID to its canonical form.
- * In canonical form, a locale ID consists of only underscores and lower-case letters.
- * @param {String} id the locale ID to be converted
- * @returns {String} the locale ID in canonical form
- */
- Yii.CLocale.prototype.getCanonicalID = function (id) {
- return php.str_replace('-','_',id).toLowerCase();
- };
- /**
- * @returns {String} the locale ID (in canonical form)
- */
- Yii.CLocale.prototype.getId = function () {
- return this._id;
- };
- /**
- * @returns {Yii.CNumberFormatter} the number formatter for this locale
- */
- Yii.CLocale.prototype.getNumberFormatter = function () {
- if(this._numberFormatter===null) {
- this._numberFormatter=new Yii.CNumberFormatter(this);
- }
- return this._numberFormatter;
- };
- /**
- * @returns {Yii.CDateFormatter} the date formatter for this locale
- */
- Yii.CLocale.prototype.getDateFormatter = function () {
- if(this._dateFormatter===null) {
- this._dateFormatter=new Yii.CDateFormatter(this);
- }
- return this._dateFormatter;
- };
- /**
- * @param {String} currency 3-letter ISO 4217 code. For example, the code "USD" represents the US Dollar and "EUR" represents the Euro currency.
- * @returns {String} the localized currency symbol. Null if the symbol does not exist.
- */
- Yii.CLocale.prototype.getCurrencySymbol = function (currency) {
- return this._data.currencySymbols[currency] !== undefined ? this._data.currencySymbols[currency] : null;
- };
- /**
- * @param {String} name symbol name
- * @returns {String} symbol
- */
- Yii.CLocale.prototype.getNumberSymbol = function (name) {
- return this._data.numberSymbols[name] !== undefined ? this._data.numberSymbols[name] : null;
- };
- /**
- * @returns {String} the decimal format
- */
- Yii.CLocale.prototype.getDecimalFormat = function () {
- return this._data.decimalFormat;
- };
- /**
- * @returns {String} the currency format
- */
- Yii.CLocale.prototype.getCurrencyFormat = function () {
- return this._data.currencyFormat;
- };
- /**
- * @returns {String} the percent format
- */
- Yii.CLocale.prototype.getPercentFormat = function () {
- return this._data.percentFormat;
- };
- /**
- * @returns {String} the scientific format
- */
- Yii.CLocale.prototype.getScientificFormat = function () {
- return this._data.scientificFormat;
- };
- /**
- * @param {Integer} month month (1-12)
- * @param {String} width month name width. It can be 'wide', 'abbreviated' or 'narrow'.
- * @param {Boolean} standAlone whether the month name should be returned in stand-alone format
- * @returns {String} the month name
- */
- Yii.CLocale.prototype.getMonthName = function (month, width, standAlone) {
- if (width === undefined) {
- width = 'wide';
- }
- if (standAlone === undefined) {
- standAlone = false;
- }
- if(standAlone) {
- return this._data.monthNamesSA[width][month] !== undefined ? this._data.monthNamesSA[width][month] : this._data.monthNames[width][month];
- }
- else {
- return this._data.monthNames[width][month] !== undefined ? this._data.monthNames[width][month] : this._data.monthNamesSA[width][month];
- }
- };
- /**
- * Returns the month names in the specified width.
- * @param {String} width month name width. It can be 'wide', 'abbreviated' or 'narrow'.
- * @param {Boolean} standAlone whether the month names should be returned in stand-alone format
- * @returns {Array} month names indexed by month values (1-12)
- * @since 1.0.9
- */
- Yii.CLocale.prototype.getMonthNames = function (width, standAlone) {
- if (width === undefined) {
- width = 'wide';
- }
- if (standAlone === undefined) {
- standAlone = false;
- }
- if(standAlone) {
- return this._data.monthNamesSA[width] !== undefined ? this._data.monthNamesSA[width] : this._data.monthNames[width];
- }
- else {
- return this._data.monthNames[width] !== undefined ? this._data.monthNames[width] : this._data.monthNamesSA[width];
- }
- };
- /**
- * @param {Integer} day weekday (0-6, 0 means Sunday)
- * @param {String} width weekday name width. It can be 'wide', 'abbreviated' or 'narrow'.
- * @param {Boolean} standAlone whether the week day name should be returned in stand-alone format
- * @returns {String} the weekday name
- */
- Yii.CLocale.prototype.getWeekDayName = function (day, width, standAlone) {
- if (width === undefined) {
- width = 'wide';
- }
- if (standAlone === undefined) {
- standAlone = false;
- }
- if(standAlone) {
- return this._data.weekDayNamesSA[width][day] !== undefined ? this._data.weekDayNamesSA[width][day] : this._data.weekDayNames[width][day];
- }
- else {
- return this._data.weekDayNames[width][day] !== undefined ? this._data.weekDayNames[width][day] : this._data.weekDayNamesSA[width][day];
- }
- };
- /**
- * Returns the week day names in the specified width.
- * @param {String} width weekday name width. It can be 'wide', 'abbreviated' or 'narrow'.
- * @param {Boolean} standAlone whether the week day name should be returned in stand-alone format
- * @returns {Array} the weekday names indexed by weekday values (0-6, 0 means Sunday, 1 Monday, etc.)
- * @since 1.0.9
- */
- Yii.CLocale.prototype.getWeekDayNames = function (width, standAlone) {
- if (width === undefined) {
- width = 'wide';
- }
- if (standAlone === undefined) {
- standAlone = false;
- }
- if(standAlone) {
- return this._data.weekDayNamesSA[width] !== undefined ? this._data.weekDayNamesSA[width] : this._data.weekDayNames[width];
- }
- else {
- return this._data.weekDayNames[width] !== undefined ? this._data.weekDayNames[width] : this._data.weekDayNamesSA[width];
- }
- };
- /**
- * @param {Integer} era era (0,1)
- * @param {String} width era name width. It can be 'wide', 'abbreviated' or 'narrow'.
- * @returns {String} the era name
- */
- Yii.CLocale.prototype.getEraName = function (era, width) {
- if (width === undefined) {
- width = 'wide';
- }
- return this._data.eraNames[width][era];
- };
- /**
- * @returns {String} the AM name
- */
- Yii.CLocale.prototype.getAMName = function () {
- return this._data.amName;
- };
- /**
- * @returns {String} the PM name
- */
- Yii.CLocale.prototype.getPMName = function () {
- return this._data.pmName;
- };
- /**
- * @param {String} width date format width. It can be 'full', 'long', 'medium' or 'short'.
- * @returns {String} date format
- */
- Yii.CLocale.prototype.getDateFormat = function (width) {
- if (width === undefined) {
- width = 'medium';
- }
- return this._data.dateFormats[width];
- };
- /**
- * @param {String} width time format width. It can be 'full', 'long', 'medium' or 'short'.
- * @returns {String} date format
- */
- Yii.CLocale.prototype.getTimeFormat = function (width) {
- if (width === undefined) {
- width = 'medium';
- }
- return this._data.timeFormats[width];
- };
- /**
- * @returns {String} datetime format, i.e., the order of date and time.
- */
- Yii.CLocale.prototype.getDateTimeFormat = function () {
- return this._data.dateTimeFormat;
- };
- /**
- * @returns {String} the character orientation, which is either 'ltr' (left-to-right) or 'rtl' (right-to-left)
- * @since 1.1.2
- */
- Yii.CLocale.prototype.getOrientation = function () {
- return this._data.orientation !== undefined ? this._data.orientation : 'ltr';
- };
- /**
- * @returns {Array} plural forms expressions
- */
- Yii.CLocale.prototype.getPluralRules = function () {
- return this._data.pluralRules !== undefined ? this._data.pluralRules : [];
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CMissingTranslationEvent represents the parameter for the {@link CMessageSource::onMissingTranslation onMissingTranslation} event.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CMessageSource.php 2798 2011-01-01 19:29:03Z qiang.xue $
- * @package system.i18n
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CEvent
- */
- Yii.CMissingTranslationEvent = function CMissingTranslationEvent (sender, params) {
- if (sender !== false) {
- this.construct(sender, params);
- }
- };
- Yii.CMissingTranslationEvent.prototype = new Yii.CEvent(false);
- Yii.CMissingTranslationEvent.prototype.constructor = Yii.CMissingTranslationEvent;
- /**
- * @var {String} the message to be translated
- */
- Yii.CMissingTranslationEvent.prototype.message = null;
- /**
- * @var {String} the category that the message belongs to
- */
- Yii.CMissingTranslationEvent.prototype.category = null;
- /**
- * @var {String} the ID of the language that the message is to be translated to
- */
- Yii.CMissingTranslationEvent.prototype.language = null;
- /**
- * Constructor.
- * @param {Mixed} sender sender of this event
- * @param {String} category the category that the message belongs to
- * @param {String} message the message to be translated
- * @param {String} language the ID of the language that the message is to be translated to
- */
- Yii.CMissingTranslationEvent.prototype.construct = function (sender, category, message, language) {
- Yii.CEvent.prototype.construct.call(this, sender);
- this.message=message;
- this.category=category;
- this.language=language;
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CLogFilter preprocesses the logged messages before they are handled by a log route.
- *
- * CLogFilter is meant to be used by a log route to preprocess the logged messages
- * before they are handled by the route. The default implementation of CLogFilter
- * prepends additional context information to the logged messages. In particular,
- * by setting {@link logVars}, predefined PHP variables such as
- * $_SERVER, $_POST, etc. can be saved as a log message, which may help identify/debug
- * issues encountered.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CLogFilter.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.logging
- * @since 1.0.6
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CLogFilter = function CLogFilter () {
- };
- Yii.CLogFilter.prototype = new Yii.CComponent();
- Yii.CLogFilter.prototype.constructor = Yii.CLogFilter;
- /**
- * @var {Boolean} whether to prefix each log message with the current user session ID.
- * Defaults to false.
- */
- Yii.CLogFilter.prototype.prefixSession = false;
- /**
- * @var {Boolean} whether to prefix each log message with the current user
- * {@link CWebUser::name name} and {@link CWebUser::id ID}. Defaults to false.
- */
- Yii.CLogFilter.prototype.prefixUser = false;
- /**
- * @var {Boolean} whether to log the current user name and ID. Defaults to true.
- */
- Yii.CLogFilter.prototype.logUser = true;
- /**
- * @var {Array} list of the predefined variables that should be logged.
- * Note that a variable must be globally accessible. Otherwise it won't be logged.
- */
- Yii.CLogFilter.prototype.logVars = [];
- /**
- * Filters the given log messages.
- * This is the main method of CLogFilter. It processes the log messages
- * by adding context information, etc.
- * @param {Array} logs the log messages
- */
- Yii.CLogFilter.prototype.filter = function (logs) {
- var message;
- if (!php.empty(logs)) {
- if((message=this.getContext())!=='') {
- php.array_unshift(logs,[message,Yii.CLogger.LEVEL_INFO,'application',YII_BEGIN_TIME]);
- }
- this.format(logs);
- }
- return logs;
- };
- /**
- * Formats the log messages.
- * The default implementation will prefix each message with session ID
- * if {@link prefixSession} is set true. It may also prefix each message
- * with the current user's name and ID if {@link prefixUser} is true.
- * @param {Array} logs the log messages
- */
- Yii.CLogFilter.prototype.format = function (logs) {
- var prefix, id, user, i, log;
- prefix='';
- if(this.prefixSession && (id=document.cookie.match(/PHPSESSID=[^;]+/))!==null) {
- prefix+="[" + id + "]";
- }
- if(this.prefixUser && (user=Yii.app().getComponent('user',false))!==null) {
- prefix+='['+user.getName()+']['+user.getId()+']';
- }
- if(prefix!=='') {
- for (i in logs) {
- if (logs.hasOwnProperty(i)) {
- logs[i][0]=prefix+' '+logs[i][0];
- }
- }
- }
- };
- /**
- * Generates the context information to be logged.
- * The default implementation will dump user information, system variables, etc.
- * @returns {String} the context information. If an empty string, it means no context information.
- */
- Yii.CLogFilter.prototype.getContext = function () {
- var context, user, i, name;
- context=[];
- if(this.logUser && (user=Yii.app().getComponent('user',false))!==null) {
- context.push('User: '+user.getName()+' (ID: '+user.getId()+')');
- }
- for (i in this.logVars) {
- if (this.logVars.hasOwnProperty(i)) {
- name = this.logVars[i];
- if(window[name] !== undefined) {
- context.push(name + " = " + window[name]);
- }
- }
- }
- return context.join("\n\n");
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CLogRouter manages log routes that record log messages in different media.
- *
- * For example, a file log route {@link CFileLogRoute} records log messages
- * in log files. An email log route {@link CEmailLogRoute} sends log messages
- * to specific email addresses. See {@link CLogRoute} for more details about
- * different log routes.
- *
- * Log routes may be configured in application configuration like following:
- * <pre>
- * {
- * 'preload':{'log'}, // preload log component when app starts
- * 'components':{
- * 'log':{
- * 'class':'CLogRouter',
- * 'routes':{
- * {
- * 'class':'CFileLogRoute',
- * 'levels':'trace, info',
- * 'categories':'system.*',
- * },
- * {
- * 'class':'CEmailLogRoute',
- * 'levels':'error, warning',
- * 'email':'admin@example.com',
- * },
- * ),
- * ),
- * ),
- * }
- * </pre>
- *
- * You can specify multiple routes with different filtering conditions and different
- * targets, even if the routes are of the same type.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CLogRouter.php 3066 2011-03-13 14:22:55Z qiang.xue $
- * @package system.logging
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CApplicationComponent
- */
- Yii.CLogRouter = function CLogRouter () {
- };
- Yii.CLogRouter.prototype = new Yii.CApplicationComponent();
- Yii.CLogRouter.prototype.constructor = Yii.CLogRouter;
- Yii.CLogRouter.prototype._routes = [];
- /**
- * Initializes this application component.
- * This method is required by the IApplicationComponent interface.
- */
- Yii.CLogRouter.prototype.init = function () {
- var route, name;
- Yii.CApplicationComponent.prototype.init();
- for (name in this._routes) {
- if (this._routes.hasOwnProperty(name)) {
- route = this._routes[name];
- route=Yii.createComponent(route);
- route.init();
- this._routes[name]=route;
- }
- }
- Yii.getLogger().attachEventHandler('onFlush',[this,'collectLogs']);
- Yii.app().attachEventHandler('onEndRequest',[this,'processLogs']);
-
- };
- /**
- * @returns {Array} the currently initialized routes
- */
- Yii.CLogRouter.prototype.getRoutes = function () {
- return new Yii.CMap(this._routes);
- };
- /**
- * @param {Array} config list of route configurations. Each array element represents
- * the configuration for a single route and has the following array structure:
- * <ul>
- * <li>class: specifies the class name or alias for the route class.</li>
- * <li>name-value pairs: configure the initial property values of the route.</li>
- * </ul>
- */
- Yii.CLogRouter.prototype.setRoutes = function (config) {
- var name, route;
- for (name in config) {
- if (config.hasOwnProperty(name)) {
- route = config[name];
- this._routes[name]=route;
- }
- }
-
- };
- /**
- * Collects log messages from a logger.
- * This method is an event handler to the {@link CLogger::onFlush} event.
- * @param {Yii.CEvent} event event parameter
- */
- Yii.CLogRouter.prototype.collectLogs = function (event) {
- var logger, dumpLogs, i, route;
- logger=Yii.getLogger();
- dumpLogs=event.params.dumpLogs !== undefined && event.params.dumpLogs;
- for (i in this._routes) {
- if (this._routes.hasOwnProperty(i)) {
- route = this._routes[i];
- if(route.enabled) {
- route.collectLogs(logger,dumpLogs);
- }
- }
- }
- };
- /**
- * Collects and processes log messages from a logger.
- * This method is an event handler to the {@link CApplication::onEndRequest} event.
- * @param {Yii.CEvent} event event parameter
- * @since 1.1.0
- */
- Yii.CLogRouter.prototype.processLogs = function (event) {
- var logger, i, route;
- logger=Yii.getLogger();
-
- for (i in this._routes) {
- if (this._routes.hasOwnProperty(i)) {
- route = this._routes[i];
-
- if(route.enabled) {
-
- route.collectLogs(logger,true);
-
- }
- }
- }
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CLogger records log messages in memory.
- *
- * CLogger implements the methods to retrieve the messages with
- * various filter conditions, including log levels and log categories.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CLogger.php 3137 2011-03-28 11:08:06Z mdomba $
- * @package system.logging
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CComponent
- */
- Yii.CLogger = function() {
- };
- Yii.CLogger.prototype = new Yii.CComponent();
- Yii.CLogger.prototype.constructor = Yii.CLogger;
- /**
- * @const
- */
- Yii.CLogger.prototype.LEVEL_TRACE = 'trace';
- /**
- * @const
- */
- Yii.CLogger.prototype.LEVEL_WARNING = 'warning';
- /**
- * @const
- */
- Yii.CLogger.prototype.LEVEL_ERROR = 'error';
- /**
- * @const
- */
- Yii.CLogger.prototype.LEVEL_INFO = 'info';
- /**
- * @const
- */
- Yii.CLogger.prototype.LEVEL_PROFILE = 'profile';
- /**
- * @var {Integer} how many messages should be logged before they are flushed to destinations.
- * Defaults to 10,000, meaning for every 10,000 messages, the {@link flush} method will be
- * automatically invoked once. If this is 0, it means messages will never be flushed automatically.
- * @since 1.1.0
- */
- Yii.CLogger.prototype.autoFlush = 10000;
- /**
- * @var {Array} log messages
- */
- Yii.CLogger.prototype._logs = [];
- /**
- * @var {Integer} number of log messages
- */
- Yii.CLogger.prototype._logCount = 0;
- /**
- * @var {Array} log levels for filtering (used when filtering)
- */
- Yii.CLogger.prototype._levels = null;
- /**
- * @var {Array} log categories for filtering (used when filtering)
- */
- Yii.CLogger.prototype._categories = null;
- /**
- * @var {Array} the profiling results (category, token => time in seconds)
- * @since 1.0.6
- */
- Yii.CLogger.prototype._timings = null;
- /**
- * Logs a message.
- * Messages logged by this method may be retrieved back via {@link getLogs}.
- * @param {String} message message to be logged
- * @param {String} level level of the message (e.g. 'Trace', 'Warning', 'Error'). It is case-insensitive.
- * @param {String} category category of the message (e.g. 'system.web'). It is case-insensitive.
- * @see getLogs
- */
- Yii.CLogger.prototype.log = function (message, level, category) {
- if (level === undefined) {
- level = 'info';
- }
- if (category === undefined) {
- category = 'application';
- }
- this._logs.push([message,level,category,php.microtime(true)]);
- this._logCount++;
- if(this.autoFlush>0 && this._logCount>=this.autoFlush) {
- this.flush();
- }
- };
- /**
- * Retrieves log messages.
- *
- * Messages may be filtered by log levels and/or categories.
- * A level filter is specified by a list of levels separated by comma or space
- * (e.g. 'trace, error'). A category filter is similar to level filter
- * (e.g. 'system, system.web'). A difference is that in category filter
- * you can use pattern like 'system.*' to indicate all categories starting
- * with 'system'.
- *
- * If you do not specify level filter, it will bring back logs at all levels.
- * The same applies to category filter.
- *
- * Level filter and category filter are combinational, i.e., only messages
- * satisfying both filter conditions will be returned.
- *
- * @param {String} levels level filter
- * @param {String} categories category filter
- * @returns {Array} list of messages. Each array elements represents one message
- * with the following structure:
- * array(
- * [0] => message (string)
- * [1] => level (string)
- * [2] => category (string)
- * [3] => timestamp (float, obtained by microtime(true));
- */
- Yii.CLogger.prototype.getLogs = function (levels, categories) {
- var ret, self;
- if (levels === undefined) {
- levels = '';
- this._levels = [];
- }
- else {
- this._levels=levels.toLowerCase().split(/[\s,]+/);
- }
- if (categories === undefined) {
- categories = '';
- this._categories = [];
- }
- else {
- this._categories=categories.toLowerCase().split(/[\s,]+/);
- }
-
-
- self = this;
- if(php.empty(levels) && php.empty(categories)) {
- return this._logs;
- }
- else if(php.empty(levels)) {
-
- return Yii.filter(this._logs,function(value, k, arr) {
- var matched = false, cat = value[2].toLowerCase(), c;
- Yii.forEach(self._categories, function(i, category) {
- if(cat===category || ((c=php.rtrim(category,'.*'))!==category && php.strpos(cat,c)===0)) {
- matched = true;
- return false;
- }
- });
- return matched ? value : false;
- });
-
- }
- else if(php.empty(categories)) {
- return Yii.filter(this._logs,function(value, k, arr) {
- var matched = false, matchLevel = value[1].toLowerCase();
- Yii.forEach(self._levels, function(i, level) {
- if (level === matchLevel) {
- matched = true;
- return false;
- }
- });
- return matched ? value : false;
- });
- }
- else {
- return Yii.filter(Yii.filter(this._logs,function(value, k, arr) {
- var matched = false, cat = value[2].toLowerCase(), c;
- Yii.forEach(self._categories, function(i, category) {
- if(cat===category || ((c=php.rtrim(category,'.*'))!==category && php.strpos(cat,c)===0)) {
- matched = true;
- return false;
- }
- });
- return matched ? value : false;
- }), function(value, k, arr) {
- var matched = false, matchLevel = value[1].toLowerCase();
- Yii.forEach(self._levels, function(i, level) {
- if (level === matchLevel) {
- matched = true;
- return false;
- }
- });
- return matched ? value : false;
- });
-
- }
- };
- /**
- * Filter function used by {@link getLogs}
- * @param {Array} value element to be filtered
- * @returns {Array} valid log, false if not.
- */
- Yii.CLogger.prototype.filterByCategory = function (value) {
- var i, cat, category, c;
- for (i in this._categories) {
- if (this._categories.hasOwnProperty(i)) {
- category = this._categories[i];
- cat=value[2].toLowerCase();
- if(cat===category || ((c=php.rtrim(category,'.*'))!==category && php.strpos(cat,c)===0)) {
- return value;
- }
- }
- }
- return false;
- };
- /**
- * Filter function used by {@link getLogs}
- * @param {Array} value element to be filtered
- * @returns {Array} valid log, false if not.
- */
- Yii.CLogger.prototype.filterByLevel = function (value) {
- var matched = false, matchLevel = value[1].toLowerCase();
-
- Yii.forEach(this._levels, function(i, level) {
- console.log(level);
- if (level === matchLevel) {
- matched = true;
- return false;
- }
- });
- return matched ? value : false;
- };
- /**
- * Returns the total time for serving the current request.
- * This method calculates the difference between now and the timestamp
- * defined by constant YII_BEGIN_TIME.
- * To estimate the execution time more accurately, the constant should
- * be defined as early as possible (best at the beginning of the entry script.)
- * @returns {Float} the total time for serving the current request.
- */
- Yii.CLogger.prototype.getExecutionTime = function () {
- return php.microtime(true)-YII_BEGIN_TIME;
- };
- /**
- * Not Available in JavaScript, always returns 0
- * @returns {Integer} memory usage of the application (in bytes).
- */
- Yii.CLogger.prototype.getMemoryUsage = function () {
- return 0;
- };
- /**
- * Returns the profiling results.
- * The results may be filtered by token and/or category.
- * If no filter is specified, the returned results would be an array with each element
- * being array($token,$category,$time).
- * If a filter is specified, the results would be an array of timings.
- * @param {String} token token filter. Defaults to null, meaning not filtered by token.
- * @param {String} category category filter. Defaults to null, meaning not filtered by category.
- * @param {Boolean} refresh whether to refresh the internal timing calculations. If false,
- * only the first time calling this method will the timings be calculated internally.
- * @returns {Array} the profiling results.
- * @since 1.0.6
- */
- Yii.CLogger.prototype.getProfilingResults = function (token, category, refresh) {
- var results, i, timing;
- if (token === undefined) {
- token = null;
- }
- if (category === undefined) {
- category = null;
- }
- if (refresh === undefined) {
- refresh = false;
- }
- if(this._timings===null || refresh) {
- this.calculateTimings();
- }
- if(token===null && category===null) {
- return this._timings;
- }
- results=[];
- for (i in this._timings) {
- if (this._timings.hasOwnProperty(i)) {
- timing = this._timings[i];
- if((category===null || timing[1]===category) && (token===null || timing[0]===token)) {
- results.push(timing[2]);
- }
- }
- }
- return results;
- };
- Yii.CLogger.prototype.calculateTimings = function () {
- var stack, i, log, message, level, category, timestamp, token, last, delta, now;
- this._timings=[];
- stack=[];
- for (i in this._logs) {
- if (this._logs.hasOwnProperty(i)) {
- log = this._logs[i];
- if(log[1]!==Yii.CLogger.prototype.LEVEL_PROFILE) {
- continue;
- }
- message = log[0];
- level = log[1];
- category = log[2];
- timestamp = log[3];
- if(!php.strncasecmp(message,'begin:',6)) {
- log[0]=message.slice(6);
- stack.push(log);
- }
- else if(!php.strncasecmp(message,'end:',4)) {
- token=message.slice(4);
- if((last=php.array_pop(stack))!==null && last[0]===token) {
- delta=log[3]-last[3];
- this._timings.push([message,category,delta]);
- }
- else {
- throw new Yii.CException(Yii.t('yii','CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.',
- {'{token}':token}));
- }
- }
- }
- }
- now=php.microtime(true);
- while((last=php.array_pop(stack))!==null) {
- delta=now-last[3];
- this._timings.push([last[0],last[2],delta]);
- }
- };
- /**
- * Removes all recorded messages from the memory.
- * This method will raise an {@link onFlush} event.
- * The attached event handlers can process the log messages before they are removed.
- * @param {Boolean} dumpLogs whether to process the logs
- * @since 1.1.0
- */
- Yii.CLogger.prototype.flush = function (dumpLogs) {
- if (dumpLogs === undefined) {
- dumpLogs = false;
- }
- this.onFlush(new Yii.CEvent(this, {'dumpLogs':dumpLogs}));
- this._logs=[];
- this._logCount=0;
- };
- /**
- * Raises an <code>onFlush</code> event.
- * @param {Yii.CEvent} event the event parameter
- * @since 1.1.0
- */
- Yii.CLogger.prototype.onFlush = function (event) {
- this.raiseEvent('onFlush', event);
- }/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CProfileLogRoute displays the profiling results in Web page.
- *
- * The profiling is done by calling {@link YiiBase::beginProfile()} and {@link YiiBase::endProfile()},
- * which marks the begin and end of a code block.
- *
- * CProfileLogRoute supports two types of report by setting the {@link setReport report} property:
- * <ul>
- * <li>summary: list the execution time of every marked code block</li>
- * <li>callstack: list the mark code blocks in a hierarchical view reflecting their calling sequence.</li>
- * </ul>
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CProfileLogRoute.php 3001 2011-02-24 16:42:44Z alexander.makarow $
- * @package system.logging
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CWebLogRoute
- */
- Yii.CProfileLogRoute = function CProfileLogRoute () {
- };
- Yii.CProfileLogRoute.prototype = new Yii.CWebLogRoute();
- Yii.CProfileLogRoute.prototype.constructor = Yii.CProfileLogRoute;
- /**
- * @var {Boolean} whether to aggregate results according to profiling tokens.
- * If false, the results will be aggregated by categories.
- * Defaults to true. Note that this property only affects the summary report
- * that is enabled when {@link report} is 'summary'.
- * @since 1.0.6
- */
- Yii.CProfileLogRoute.prototype.groupByToken = true;
- /**
- * @var {String} type of profiling report to display
- */
- Yii.CProfileLogRoute.prototype._report = 'summary';
- /**
- * Initializes the route.
- * This method is invoked after the route is created by the route manager.
- */
- Yii.CProfileLogRoute.prototype.init = function () {
-
- this.levels=Yii.CLogger.prototype.LEVEL_PROFILE;
- };
- /**
- * @returns {String} the type of the profiling report to display. Defaults to 'summary'.
- */
- Yii.CProfileLogRoute.prototype.getReport = function () {
- return this._report;
- };
- /**
- * @param {String} value the type of the profiling report to display. Valid values include 'summary' and 'callstack'.
- */
- Yii.CProfileLogRoute.prototype.setReport = function (value) {
- if(value==='summary' || value==='callstack') {
- this._report=value;
- }
- else {
- throw new Yii.CException(Yii.t('yii','CProfileLogRoute.report "{report}" is invalid. Valid values include "summary" and "callstack".',
- {'{report}':value}));
- }
- };
- /**
- * Displays the log messages.
- * @param {Array} logs list of log messages
- */
- Yii.CProfileLogRoute.prototype.processLogs = function (logs) {
- var app;
- app=Yii.app();
-
- if(!(app instanceof Yii.CWebApplication) || app.getRequest().getIsAjaxRequest()) {
- return;
- }
-
- if(this.getReport()==='summary') {
- this.displaySummary(logs);
- }
- else {
- this.displayCallstack(logs);
- }
- };
- /**
- * Displays the callstack of the profiling procedures for display.
- * @param {Array} logs list of logs
- */
- Yii.CProfileLogRoute.prototype.displayCallstack = function (logs) {
- var stack, results, n, i, log, message, token, last, delta, now;
- stack=[];
- results={};
- n=0;
- for (i in logs) {
- if (logs.hasOwnProperty(i)) {
- log = logs[i];
- if(log[1]!==Yii.CLogger.prototype.LEVEL_PROFILE) {
- continue;
- }
- message=log[0];
- if(!php.strncasecmp(message,'begin:',6)){
- log[0]=message.slice(6);
- log[4]=n;
- stack.push(log);
- n++;
- }
- else if(!php.strncasecmp(message,'end:',4)) {
- token=message.slice(4);
- if((last=php.array_pop(stack))!==null && last[0]===token) {
- delta=log[3]-last[3];
- results[last[4]]=[token,delta,php.count(stack)];
- }
- else {
- throw new Yii.CException(Yii.t('yii','CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.',
- {'{token}':token}));
- }
- }
- }
- }
- // remaining entries should be closed here
- now=php.microtime(true);
- while((last=php.array_pop(stack))!==null) {
- results[last[4]]=[last[0],now-last[3],php.count(stack)];
- }
- php.ksort(results);
- this.render('profile-callstack',results);
- };
- /**
- * Displays the summary report of the profiling result.
- * @param {Array} logs list of logs
- */
- Yii.CProfileLogRoute.prototype.displaySummary = function (logs) {
- var stack, i, log, message, token, last, delta, results = {}, now, entries, func, data;
- stack=[];
- for (i in logs) {
- if (logs.hasOwnProperty(i)) {
-
- log = logs[i];
-
- if(log[1]!==Yii.CLogger.prototype.LEVEL_PROFILE) {
- continue;
- }
- message=log[0];
-
- if(!php.strncasecmp(message,'begin:',6)) {
- log[0]=message.slice(6);
- stack.push(log);
- }
- else if(!php.strncasecmp(message,'end:',4)) {
- token=message.slice(4);
-
- if((last=php.array_pop(stack))!==null && last[0]===token) {
- delta=log[3]-last[3];
- if(!this.groupByToken) {
- token=log[2];
- }
- if(results[token] !== undefined) {
-
- results[token]=this.aggregateResult(results[token],delta);
- }
- else {
- results[token]=[token,1,delta,delta,delta];
- }
- }
- else {
-
- throw new Yii.CException(Yii.t('yii','CProfileLogRoute found a mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.',
- {'{token}':token}));
- }
- }
- }
- }
-
- now=php.microtime(true);
- while((last=php.array_pop(stack))!==null) {
- delta=now-last[3];
- token=this.groupByToken ? last[0] : last[2];
- if(results[token] !== undefined) {
- results[token]=this.aggregateResult(results[token],delta);
- }
- else {
- results[token]=[token,1,delta,delta,delta];
- }
- }
- entries=php.array_values(results);
- func = function(a,b) {
- return a[4] < b[4] ? 1 : 0;
- };
- php.usort(entries,func);
- data = {
- time: php.sprintf('%0.5f',Yii.getLogger().getExecutionTime()),
- entries: []
- };
-
- Yii.forEach(entries, function(k, entry) {
- data.entries.push({
- 'proc': Yii.CHtml.encode(entry[0]),
- 'count': php.sprintf('%5d',entry[1]),
- 'min': php.sprintf('%0.5f',entry[2]),
- 'max': php.sprintf('%0.5f',entry[3]),
- 'total': php.sprintf('%0.5f',entry[4]),
- 'average': php.sprintf('%0.5f',entry[4] / entry[1])
- });
- });
- if (this.showInFireBug && window['console'] !== undefined) {
- if (console.group !== undefined) {
- console.group("Profiling Summary Report");
- }
- console.log(" count total average min max ");
- Yii.forEach(data.entries, function(k, entry) {
- console.log(" " + entry.count + " " + entry.total + " " + entry.average + " " + entry.min + " " + entry.max + " " + entry.proc);
- });
- if (console.group !== undefined) {
- console.groupEnd();
- }
- }
- else {
- this.render('profile-summary',data);
- }
- };
- /**
- * Aggregates the report result.
- * @param {Array} result log result for this code block
- * @param {Float} delta time spent for this code block
- */
- Yii.CProfileLogRoute.prototype.aggregateResult = function (result, delta) {
- var token, calls, min, max, total;
- token = result[0];
- calls = result[1];
- min = result[2];
- max = result[3];
- total = result[4];
- if(delta<min) {
- min=delta;
- }
- else if(delta>max) {
- max=delta;
- }
- calls++;
- total+=delta;
- return [token,calls,min,max,total];
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CDateTimeParser converts a date/time string to a UNIX timestamp according to the specified pattern.
- *
- * The following pattern characters are recognized:
- * <pre>
- * Pattern | Description
- * ----------------------------------------------------
- * d | Day of month 1 to 31, no padding
- * dd | Day of month 01 to 31, zero leading
- * M | Month digit 1 to 12, no padding
- * MM | Month digit 01 to 12, zero leading
- * yy | 2 year digit, e+g+, 96, 05
- * yyyy | 4 year digit, e+g+, 2005
- * h | Hour in 0 to 23, no padding
- * hh | Hour in 00 to 23, zero leading
- * H | Hour in 0 to 23, no padding
- * HH | Hour in 00 to 23, zero leading
- * m | Minutes in 0 to 59, no padding
- * mm | Minutes in 00 to 59, zero leading
- * s | Seconds in 0 to 59, no padding
- * ss | Seconds in 00 to 59, zero leading
- * a | AM or PM, case-insensitive (since version 1.1.5)
- * ----------------------------------------------------
- * </pre>
- * All other characters must appear in the date string at the corresponding positions.
- *
- * For example, to parse a date string '21/10/2008', use the following:
- * <pre>
- * timestamp=Yii.CDateTimeParser.parse('21/10/2008','dd/MM/yyyy');
- * </pre>
- *
- * To format a timestamp to a date string, please use {@link CDateFormatter}.
- *
- * @originalAuthor Wei Zhuo <weizhuo[at]gmail[dot]com>
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CDateTimeParser.php 2928 2011-02-01 17:41:51Z alexander.makarow $
- * @package system.utils
- * @since 1.0
- * @author Charles Pick
- * @class
- */
- Yii.CDateTimeParser = {
-
- };
- /**
- * Converts a date string to a timestamp.
- * @param {String} value the date string to be parsed
- * @param {String} pattern the pattern that the date string is following
- * @param {Array} defaults the default values for year, month, day, hour, minute and second.
- * The default values will be used in case when the pattern doesn't specify the
- * corresponding fields. For example, if the pattern is 'MM/dd/yyyy' and this
- * parameter is array('minute'=>0, 'second'=>0), then the actual minute and second
- * for the parsing result will take value 0, while the actual hour value will be
- * the current hour obtained by date('H'). This parameter has been available since version 1.1.5.
- * @returns {Integer} timestamp for the date string. False if parsing fails.
- */
- Yii.CDateTimeParser.parse = function (value, pattern, defaults) {
- var tokens, i, n, j, token, year, month, day, hour, minute, second, ampm, tn;
- if (pattern === undefined) {
- pattern = 'MM/dd/yyyy';
- }
- if (defaults === undefined) {
- defaults = [];
- }
- tokens=this.tokenize(pattern);
- i=0;
- n=php.strlen(value);
- for (j in tokens)
- {
- if (tokens.hasOwnProperty(j)) {
- token = tokens[j];
- switch(token)
- {
- case 'yyyy':
- if((year=this.parseInteger(value,i,4,4))===false) {
- return false;
- }
- i+=4;
- break;
- case 'yy':
- if((year=this.parseInteger(value,i,1,2))===false) {
- return false;
- }
- i+=php.strlen(year);
- break;
- case 'MM':
- if((month=this.parseInteger(value,i,2,2))===false) {
- return false;
- }
- i+=2;
- break;
- case 'M':
- if((month=this.parseInteger(value,i,1,2))===false) {
- return false;
- }
- i+=php.strlen(month);
- break;
- case 'dd':
- if((day=this.parseInteger(value,i,2,2))===false) {
- return false;
- }
- i+=2;
- break;
- case 'd':
- if((day=this.parseInteger(value,i,1,2))===false) {
- return false;
- }
- i+=php.strlen(day);
- break;
- case 'h':
- case 'H':
- if((hour=this.parseInteger(value,i,1,2))===false) {
- return false;
- }
- i+=php.strlen(hour);
- break;
- case 'hh':
- case 'HH':
- if((hour=this.parseInteger(value,i,2,2))===false) {
- return false;
- }
- i+=2;
- break;
- case 'm':
- if((minute=this.parseInteger(value,i,1,2))===false) {
- return false;
- }
- i+=php.strlen(minute);
- break;
- case 'mm':
- if((minute=this.parseInteger(value,i,2,2))===false) {
- return false;
- }
- i+=2;
- break;
- case 's':
- if((second=this.parseInteger(value,i,1,2))===false) {
- return false;
- }
- i+=php.strlen(second);
- break;
- case 'ss':
- if((second=this.parseInteger(value,i,2,2))===false) {
- return false;
- }
- i+=2;
- break;
- case 'a':
- if((ampm=this.parseAmPm(value,i))===false) {
- return false;
- }
- if(hour !== undefined)
- {
- if(hour==12 && ampm==='am') {
- hour=0;
- }
- else if(hour<12 && ampm==='pm') {
- hour+=12;
- }
- }
- i+=2;
- break;
- default:
- tn=php.strlen(token);
- if(i>=n || value.slice(i, tn)!==token) {
- return false;
- }
- i+=tn;
- break;
- }
- }
- }
- if(i<n) {
- return false;
- }
- if(year === undefined) {
- year=defaults.year !== undefined ? defaults.year : php.date('Y');
- }
- if(month === undefined) {
- month=defaults.month !== undefined ? defaults.month : php.date('n');
- }
- if(day === undefined) {
- day=defaults.day !== undefined ? defaults.day : php.date('j');
- }
- if(php.strlen(year)===2) {
- if(year>=70) {
- year+=1900;
- }
- else {
- year+=2000;
- }
- }
- year=Number(year);
- month=Number(month);
- day=Number(day);
- if(hour === undefined && minute === undefined && second === undefined && defaults.hour === undefined && defaults.minute === undefined && defaults.second === undefined) {
- hour=minute=second=0;
- }
- else {
- if(hour === undefined) {
- hour=defaults.hour !== undefined ? defaults.hour : php.date('H');
- }
- if(minute === undefined) {
- minute=defaults.minute !== undefined ? defaults.minute : php.date('i');
- }
- if(second === undefined) {
- second=defaults.second !== undefined ? defaults.second : php.date('s');
- }
- hour=Number(hour);
- minute=Number(minute);
- second=Number(second);
- }
- if(Yii.CTimestamp.isValidDate(year,month,day) && Yii.CTimestamp.isValidTime(hour,minute,second)) {
- return Yii.CTimestamp.getTimestamp(hour,minute,second,month,day,year);
- }
- else {
- return false;
- }
- };
- Yii.CDateTimeParser.tokenize = function (pattern) {
- var n, tokens, c0, start, i, c;
- if(!(n=php.strlen(pattern))) {
- return [];
- }
- tokens=[];
- for(c0=pattern[0],start=0,i=1;i<n;++i) {
- if((c=pattern[i])!==c0) {
- tokens.push(pattern.slice(start, i-start));
- c0=c;
- start=i;
- }
- }
- tokens.push(pattern.slice(start, n-start));
- return tokens;
- };
- Yii.CDateTimeParser.parseInteger = function (value, offset, minLength, maxLength) {
- var len, v;
- for(len=maxLength;len>=minLength;--len) {
- v=value.slice(offset, len);
- if(php.ctype_digit(v) && php.strlen(v)>=minLength) {
- return v;
- }
- }
- return false;
- };
- Yii.CDateTimeParser.parseAmPm = function (value, offset) {
- var v;
- v=value.slice(offset, 2).toLowerCase();
- return v==='am' || v==='pm' ? v : false;
- }/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CFormatter provides a set of commonly used data formatting methods.
- *
- * The formatting methods provided by CFormatter are all named in the form of <code>formatXyz</code>.
- * The behavior of some of them may be configured via the properties of CFormatter. For example,
- * by configuring {@link dateFormat}, one may control how {@link formatDate} formats the value into a date string.
- *
- * For convenience, CFormatter also implements the mechanism of calling formatting methods with their shortcuts (called types).
- * In particular, if a formatting method is named <code>formatXyz</code>, then its shortcut method is <code>xyz</code>
- * (case-insensitive). For example, calling <code>$formatter->date($value)</code> is equivalent to calling
- * <code>$formatter->formatDate($value)</code>.
- *
- * Currently, the following types are recognizable:
- * <ul>
- * <li>raw: the attribute value will not be changed at all.</li>
- * <li>text: the attribute value will be HTML-encoded when rendering.</li>
- * <li>ntext: the {@link formatNtext} method will be called to format the attribute value as a HTML-encoded plain text with newlines converted as the HTML <br /> tags.</li>
- * <li>html: the attribute value will be purified and then returned.</li>
- * <li>date: the {@link formatDate} method will be called to format the attribute value as a date.</li>
- * <li>time: the {@link formatTime} method will be called to format the attribute value as a time.</li>
- * <li>datetime: the {@link formatDatetime} method will be called to format the attribute value as a date with time.</li>
- * <li>boolean: the {@link formatBoolean} method will be called to format the attribute value as a boolean display.</li>
- * <li>number: the {@link formatNumber} method will be called to format the attribute value as a number display.</li>
- * <li>email: the {@link formatEmail} method will be called to format the attribute value as a mailto link.</li>
- * <li>image: the {@link formatImage} method will be called to format the attribute value as an image tag where the attribute value is the image URL.</li>
- * <li>url: the {@link formatUrl} method will be called to format the attribute value as a hyperlink where the attribute value is the URL.</li>
- * </ul>
- *
- * By default, {@link CApplication} registers {@link CFormatter} as an application component whose ID is 'format'.
- * Therefore, one may call <code>Yii::app()->format->boolean(1)</code>.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CFormatter.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.utils
- * @since 1.1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CApplicationComponent
- */
- Yii.CFormatter = function CFormatter() {
- };
- Yii.CFormatter.prototype = new Yii.CApplicationComponent();
- Yii.CFormatter.prototype.constructor = Yii.CFormatter;
- Yii.CFormatter.prototype._htmlPurifier = null;
- /**
- * @var {String} the format string to be used to format a date using PHP date() function. Defaults to 'Y/m/d'.
- */
- Yii.CFormatter.prototype.dateFormat = 'Y/m/d';
- /**
- * @var {String} the format string to be used to format a time using PHP date() function. Defaults to 'h:i:s A'.
- */
- Yii.CFormatter.prototype.timeFormat = 'h:i:s A';
- /**
- * @var {String} the format string to be used to format a date and time using PHP date() function. Defaults to 'Y/m/d h:i:s A'.
- */
- Yii.CFormatter.prototype.datetimeFormat = 'Y/m/d h:i:s A';
- /**
- * @var {Array} the format used to format a number with PHP number_format() function.
- * Three elements may be specified: "decimals", "decimalSeparator" and "thousandSeparator". They
- * correspond to the number of digits after the decimal point, the character displayed as the decimal point,
- * and the thousands separator character.
- */
- Yii.CFormatter.prototype.numberFormat = {
- 'decimals':null,
- 'decimalSeparator':null,
- 'thousandSeparator':null
- };
- /**
- * @var {Array} the text to be displayed when formatting a boolean value. The first element corresponds
- * to the text display for false, the second element for true. Defaults to <code>array('No', 'Yes')</code>.
- */
- Yii.CFormatter.prototype.booleanFormat = ['No','Yes'];
- /**
- * Calls the format method when its shortcut is invoked.
- * This is a PHP magic method that we override to implement the shortcut format methods.
- * @param {String} name the method name
- * @param {Array} parameters method parameters
- * @returns {Mixed} the method return value
- */
- Yii.CFormatter.prototype.call = function (name, parameters) {
- if(php.method_exists(this,'format'+name)) {
- return php.call_user_func_array([this,'format'+name],parameters);
- }
- else {
- return parent.call(name,parameters);
- }
- };
- /**
- * Formats a value based on the given type.
- * @param {Mixed} value the value to be formatted
- * @param {String} type the data type. This must correspond to a format method available in CFormatter.
- * For example, we can use 'text' here because there is method named {@link formatText}.
- * @returns {String} the formatted data
- */
- Yii.CFormatter.prototype.format = function (value, type) {
- var method;
- method='format'+php.ucfirst(type);
- if(php.method_exists(this,method)) {
- return this[method](value);
- }
- else {
- throw new Yii.CException(Yii.t('yii','Unknown type "{type}".',{'{type}':type}));
- }
- };
- /**
- * Formats the value as is without any formatting.
- * This method simply returns back the parameter without any format.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- */
- Yii.CFormatter.prototype.formatRaw = function (value) {
- return value;
- };
- /**
- * Formats the value as a HTML-encoded plain text.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- */
- Yii.CFormatter.prototype.formatText = function (value) {
- return Yii.CHtml.encode(value);
- };
- /**
- * Formats the value as a HTML-encoded plain text and converts newlines with HTML br tags.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- */
- Yii.CFormatter.prototype.formatNtext = function (value) {
- return php.nl2br(Yii.CHtml.encode(value));
- };
- /**
- * Formats the value as HTML text without any encoding.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- */
- Yii.CFormatter.prototype.formatHtml = function (value) {
- return this.getHtmlPurifier().purify(value);
- };
- /**
- * Formats the value as a date.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- * @see dateFormat
- */
- Yii.CFormatter.prototype.formatDate = function (value) {
- return php.date(this.dateFormat,value);
- };
- /**
- * Formats the value as a time.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- * @see timeFormat
- */
- Yii.CFormatter.prototype.formatTime = function (value) {
- return php.date(this.timeFormat,value);
- };
- /**
- * Formats the value as a date and time.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- * @see datetimeFormat
- */
- Yii.CFormatter.prototype.formatDatetime = function (value) {
- return php.date(this.datetimeFormat,value);
- };
- /**
- * Formats the value as a boolean.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- * @see trueText
- * @see falseText
- */
- Yii.CFormatter.prototype.formatBoolean = function (value) {
- return value ? this.booleanFormat[1] : this.booleanFormat[0];
- };
- /**
- * Formats the value as a mailto link.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- */
- Yii.CFormatter.prototype.formatEmail = function (value) {
- return Yii.CHtml.mailto(value);
- };
- /**
- * Formats the value as an image tag.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- */
- Yii.CFormatter.prototype.formatImage = function (value) {
- return Yii.CHtml.image(value);
- };
- /**
- * Formats the value as a hyperlink.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- */
- Yii.CFormatter.prototype.formatUrl = function (value) {
- var url;
- url=value;
- if(php.strpos(url,'http://')!==0 && php.strpos(url,'https://')!==0) {
- url='http://'+url;
- }
- return Yii.CHtml.link(Yii.CHtml.encode(value),url);
- };
- /**
- * Formats the value as a number using PHP number_format() function.
- * @param {Mixed} value the value to be formatted
- * @returns {String} the formatted result
- * @see numberFormat
- */
- Yii.CFormatter.prototype.formatNumber = function (value) {
- return php.number_format(value,this.numberFormat['decimals'],this.numberFormat['decimalSeparator'],this.numberFormat['thousandSeparator']);
- };
- /**
- * @returns {Yii.CHtmlPurifier} the HTML purifier instance
- */
- Yii.CFormatter.prototype.getHtmlPurifier = function () {
- if(this._htmlPurifier===null) {
- this._htmlPurifier=new Yii.CHtmlPurifier();
- }
- return this._htmlPurifier;
- }/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CTimestamp represents a timestamp.
- *
- * Part of this class was adapted from the ADOdb Date Library
- * {@link http://phplens.com/phpeverywhere/ ADOdb abstraction library}.
- * The original source code was released under both BSD and GNU Lesser GPL
- * library license, with the following copyright notice:
- * Copyright (c) 2000, 2001, 2002, 2003, 2004 John Lim
- * All rights reserved.
- *
- * This class is provided to support UNIX timestamp that is beyond the range
- * of 1901-2038 on Unix and1970-2038 on Windows. Except {@link getTimestamp},
- * all other methods in this class can work with the extended timestamp range.
- * For {@link getTimestamp}, because it is merely a wrapper of
- * {@link mktime http://php.net/manual/en/function.mktime.php}, it may still
- * be subject to the limit of timestamp range on certain platforms. Please refer
- * to the PHP manual for more information.
- *
- * @originalAuthor Wei Zhuo <weizhuo[at]gmail[dot]com>
- * @version $Id: CTimestamp.php 3046 2011-03-12 01:48:15Z qiang.xue $
- * @package system.utils
- * @since 1.0
- * @author Charles Pick
- * @class
- */
- Yii.CTimestamp = {
- };
- /**
- * Gets day of week, 0 = Sunday,... 6=Saturday.
- * Algorithm from PEAR::Date_Calc
- * @param {Integer} year year
- * @param {Integer} month month
- * @param {Integer} day day
- * @returns {Integer} day of week
- */
- Yii.CTimestamp.getDayofWeek = function (year, month, day) {
- var greg_correction;
- /*
- Pope Gregory removed 10 days - October 5 to October 14 - from the year 1582 and
- proclaimed that from that time onwards 3 days would be dropped from the calendar
- every 400 years.
- Thursday, October 4, 1582 (Julian) was followed immediately by Friday, October 15, 1582 (Gregorian).
- */
- if (year <= 1582) {
- if (year < 1582 || (year == 1582 && (month < 10 || (month == 10 && day < 15)))) {
- greg_correction = 3;
- }
- else {
- greg_correction = 0;
- }
- }
- else {
- greg_correction = 0;
- }
- if(month > 2) {
- month -= 2;
- }
- else {
- month += 10;
- year--;
- }
- day = php.floor((13 * month - 1) / 5) +
- day + (year % 100) +
- php.floor((year % 100) / 4) +
- php.floor((year / 100) / 4) - 2 *
- php.floor(year / 100) + 77 + greg_correction;
- return day - 7 * php.floor(day / 7);
- };
- /**
- * Checks for leap year, returns true if it is. No 2-digit year check. Also
- * handles julian calendar correctly.
- * @param {Integer} year year to check
- * @returns {Boolean} true if is leap year
- */
- Yii.CTimestamp.isLeapYear = function (year) {
- year = this.digitCheck(year);
- if (year % 4 !== 0) {
- return false;
- }
- if (year % 400 === 0) {
- return true;
- }
- // if gregorian calendar (>1582), century not-divisible by 400 is not leap
- else if (year > 1582 && year % 100 === 0 ) {
- return false;
- }
- return true;
- };
- /**
- * Fix 2-digit years. Works for any century.
- * Assumes that if 2-digit is more than 30 years in future, then previous century.
- * @param {Integer} y year
- * @returns {Integer} change two digit year into multiple digits
- */
- Yii.CTimestamp.digitCheck = function (y) {
- var yr, century, c1, c0;
- if (y < 100){
- yr = Number(php.date("Y"));
- century = Number((yr /100));
- if (yr%100 > 50) {
- c1 = century + 1;
- c0 = century;
- } else {
- c1 = century;
- c0 = century - 1;
- }
- c1 *= 100;
- // if 2-digit year is less than 30 years in future, set it to this century
- // otherwise if more than 30 years in future, then we set 2-digit year to the prev century.
- if ((y + c1) < yr+30) { y = y + c1;
- }
- else { y = y + c0*100;
- }
- }
- return y;
- };
- /**
- * Returns 4-digit representation of the year.
- * @param {Integer} y year
- * @returns {Integer} 4-digit representation of the year
- */
- Yii.CTimestamp.get4DigitYear = function (y) {
- return this.digitCheck(y);
- };
- /**
- * @returns {Integer} get local time zone offset from GMT
- */
- Yii.CTimestamp.getGMTDiff = function () {
- var TZ;
- if (TZ !== undefined) { return TZ; }
- TZ = php.mktime(0,0,0,1,2,1970) - php.gmmktime(0,0,0,1,2,1970);
- return TZ;
- };
- /**
- * Returns the getdate() array.
- * @param {Integer} d original date timestamp. False to use the current timestamp.
- * @param {Boolean} fast false to compute the day of the week, default is true
- * @param {Boolean} gmt true to calculate the GMT dates (ignored for now)
- * @returns {Array} an array with date info.
- */
- Yii.CTimestamp.getDate = function (d, fast, gmt) {
- var tz, result;
- if (d === undefined) {
- d = false;
- }
- if (fast === undefined) {
- fast = false;
- }
- if (gmt === undefined) {
- gmt = false;
- }
- result = php.getdate(d);
-
- return result;
- };
- /**
- * Checks to see if the year, month, day are valid combination.
- * @param {Integer} y year
- * @param {Integer} m month
- * @param {Integer} d day
- * @returns {Boolean} true if valid date, semantic check only.
- */
- Yii.CTimestamp.isValidDate = function (y, m, d) {
- return php.checkdate(m, d, y);
- };
- /**
- * Checks to see if the hour, minute and second are valid.
- * @param {Integer} h hour
- * @param {Integer} m minute
- * @param {Integer} s second
- * @param {Boolean} hs24 whether the hours should be 0 through 23 (default) or 1 through 12.
- * @returns {Boolean} true if valid date, semantic check only.
- * @since 1.0.5
- */
- Yii.CTimestamp.isValidTime = function (h, m, s, hs24) {
- if (hs24 === undefined) {
- hs24 = true;
- }
- if(hs24 && (h < 0 || h > 23) || !hs24 && (h < 1 || h > 12)) {
- return false;
- }
- if(m > 59 || m < 0) {
- return false;
- }
- if(s > 59 || s < 0) {
- return false;
- }
- return true;
- };
- /**
- * Formats a timestamp to a date string.
- * @param {String} fmt format pattern
- * @param {Integer} d timestamp
- * @param {Boolean} is_gmt whether this is a GMT timestamp
- * @returns {String} formatted date based on timestamp $d
- */
- Yii.CTimestamp.formatDate = function (fmt, d, is_gmt) {
- var _day_power, arr, year, month, day, hour, min, secs, max, dates, i, gmt, d10, hh;
- if (d === undefined) {
- d = false;
- }
- if (is_gmt === undefined) {
- is_gmt = false;
- }
- if (d === false) {
- return (is_gmt)? php.gmdate(fmt): php.date(fmt);
- }
- // check if number in 32-bit signed range
- if ((php.abs(d) <= 0x7FFFFFFF)) {
- // if windows, must be +ve integer
- if (d >= 0) {
- return (is_gmt)? php.gmdate(fmt,d): php.date(fmt,d);
- }
- }
- _day_power = 86400;
- arr = this.getDate(d,true,is_gmt);
- year = arr.year;
- month = arr.mon;
- day = arr.mday;
- hour = arr.hours;
- min = arr.minutes;
- secs = arr.seconds;
- max = php.strlen(fmt);
- dates = '';
- /*
- at this point, we have the following integer vars to manipulate:
- $year, $month, $day, $hour, $min, $secs
- */
- for (i=0; i < max; i++)
- {
- switch(fmt[i])
- {
- case 'T':
- dates += php.date('T');
- break;
- // YEAR
- case 'L':
- dates += arr.leap ? '1' : '0';
- break;
- case 'r': // Thu, 21 Dec 2000 16:01:07 +0200
- // 4.3.11 uses '04 Jun 2004'
- // 4.3.8 uses ' 4 Jun 2004'
- dates += php.gmdate('D',_day_power*(3+this.getDayOfWeek(year,month,day)))+', ' + (day<10?'0'+day:day) + ' '+php.date('M',php.mktime(0,0,0,month,2,1971))+' '+year+' ';
- if (hour < 10) {
- dates += '0'+hour;
- }
- else {
- dates += hour;
- }
- if (min < 10) {
- dates += ':0'+min;
- }
- else {
- dates += ':'+min;
- }
- if (secs < 10) {
- dates += ':0'+secs;
- }
- else {
- dates += ':'+secs;
- }
- gmt = this.getGMTDiff();
- dates += php.sprintf(' %s%04d',(gmt<=0)?'+':'-',php.abs(gmt)/36);
- break;
- case 'Y':
- dates += year;
- break;
- case 'y':
- dates += year.slice(php.strlen(year)-2, 2);
- break;
- // MONTH
- case 'm':
- if (month<10) {
- dates += '0'+month;
- }
- else {
- dates += month;
- }
- break;
- case 'Q':
- dates += (month+3)>>2;
- break;
- case 'n':
- dates += month;
- break;
- case 'M':
- dates += php.date('M',php.mktime(0,0,0,month,2,1971));
- break;
- case 'F':
- dates += php.date('F',php.mktime(0,0,0,month,2,1971));
- break;
- // DAY
- case 't':
- dates += arr.ndays;
- break;
- case 'z':
- dates += arr.yday;
- break;
- case 'w':
- dates += this.getDayOfWeek(year,month,day);
- break;
- case 'l':
- dates += php.gmdate('l',_day_power*(3+this.getDayOfWeek(year,month,day)));
- break;
- case 'D':
- dates += php.gmdate('D',_day_power*(3+this.getDayOfWeek(year,month,day)));
- break;
- case 'j':
- dates += day;
- break;
- case 'd':
- if (day<10) {
- dates += '0'+day;
- }
- else {
- dates += day;
- }
- break;
- case 'S':
- d10 = day % 10;
- if (d10 == 1) {
- dates += 'st';
- }
- else if (d10 == 2 && day != 12) {
- dates += 'nd';
- }
- else if (d10 == 3) {
- dates += 'rd';
- }
- else {
- dates += 'th';
- }
- break;
- // HOUR
- case 'Z':
- dates += (is_gmt) ? 0 : -this.getGMTDiff();
- break;
- case 'O':
- gmt = (is_gmt) ? 0 : this.getGMTDiff();
- dates += php.sprintf('%s%04d',(gmt<=0)?'+':'-',php.abs(gmt)/36);
- break;
- case 'H':
- if (hour < 10) {
- dates += '0'+hour;
- }
- else {
- dates += hour;
- }
- break;
- case 'h':
- if (hour > 12) {
- hh = hour - 12;
- }
- else {
- if (hour === 0) {
- hh = '12';
- }
- else {
- hh = hour;
- }
- }
- if (hh < 10) {
- dates += '0'+hh;
- }
- else {
- dates += hh;
- }
- break;
- case 'G':
- dates += hour;
- break;
- case 'g':
- if (hour > 12) {
- hh = hour - 12;
- }
- else {
- if (hour === 0) {
- hh = '12';
- }
- else {
- hh = hour;
- }
- }
- dates += hh;
- break;
- // MINUTES
- case 'i':
- if (min < 10) {
- dates += '0'+min;
- }
- else {
- dates += min;
- }
- break;
- // SECONDS
- case 'U':
- dates += d;
- break;
- case 's':
- if (secs < 10) {
- dates += '0'+secs;
- }
- else {
- dates += secs;
- }
- break;
- // AM/PM
- // Note 00:00 to 11:59 is AM, while 12:00 to 23:59 is PM
- case 'a':
- if (hour>=12) {
- dates += 'pm';
- }
- else {
- dates += 'am';
- }
- break;
- case 'A':
- if (hour>=12) {
- dates += 'PM';
- }
- else {
- dates += 'AM';
- }
- break;
- default:
- dates += fmt[i];
- break;
- // ESCAPE
- case "\\":
- i++;
- if (i < max) {
- dates += fmt[i];
- }
- break;
- }
- }
- return dates;
- };
- /**
- * Generates a timestamp.
- * This is the same as the PHP function {@link mktime http://php.net/manual/en/function.mktime.php}.
- * @param {Integer} hr hour
- * @param {Integer} min minute
- * @param {Integer} sec second
- * @param {Integer} mon month
- * @param {Integer} day day
- * @param {Integer} year year
- * @param {Boolean} is_gmt whether this is GMT time. If true, gmmktime() will be used.
- * @returns {Integer|float} a timestamp given a local time.
- */
- Yii.CTimestamp.getTimestamp = function (hr, min, sec, mon, day, year, is_gmt) {
- if (mon === undefined) {
- mon = false;
- }
- if (day === undefined) {
- day = false;
- }
- if (year === undefined) {
- year = false;
- }
- if (is_gmt === undefined) {
- is_gmt = false;
- }
- if (mon === false) {
- return is_gmt? php.gmmktime(hr,min,sec): php.mktime(hr,min,sec);
- }
- return is_gmt ? php.gmmktime(hr,min,sec,mon,day,year) : php.mktime(hr,min,sec,mon,day,year);
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CBooleanValidator validates that the attribute value is either {@link trueValue} or {@link falseValue}.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CBooleanValidator.php 3120 2011-03-25 01:50:48Z qiang.xue $
- * @package system.validators
- * @since 1.0.10
- * @author Charles Pick
- * @class
- * @extends Yii.CValidator
- */
- Yii.CBooleanValidator = function CBooleanValidator() {
- };
- Yii.CBooleanValidator.prototype = new Yii.CValidator();
- Yii.CBooleanValidator.prototype.constructor = Yii.CBooleanValidator;
- /**
- * @var {Mixed} the value representing true status. Defaults to '1'.
- */
- Yii.CBooleanValidator.prototype.trueValue = '1';
- /**
- * @var {Mixed} the value representing false status. Defaults to '0'.
- */
- Yii.CBooleanValidator.prototype.falseValue = '0';
- /**
- * @var {Boolean} whether the comparison to {@link trueValue} and {@link falseValue} is strict.
- * When this is true, the attribute value and type must both match those of {@link trueValue} or {@link falseValue}.
- * Defaults to false, meaning only the value needs to be matched.
- */
- Yii.CBooleanValidator.prototype.strict = false;
- /**
- * @var {Boolean} whether the attribute value can be null or empty. Defaults to true,
- * meaning that if the attribute is empty, it is considered valid.
- */
- Yii.CBooleanValidator.prototype.allowEmpty = true;
- /**
- * Validates the attribute of the object.
- * If there is any error, the error message is added to the object.
- * @param {Yii.CModel} object the object being validated
- * @param {String} attribute the attribute being validated
- */
- Yii.CBooleanValidator.prototype.validateAttribute = function (object, attribute) {
- var value, message;
- value=object.get(attribute);
- if(this.allowEmpty && this.isEmpty(value)) {
- return;
- }
- if(!this.strict && value!=this.trueValue && value!=this.falseValue || this.strict && value!==this.trueValue && value!==this.falseValue) {
- message=this.message!==null?this.message:Yii.t('yii','{attribute} must be either {true} or {false}.');
- this.addError(object,attribute,message,{
- '{true}':this.trueValue,
- '{false}':this.falseValue
- });
- }
- };
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CEmailValidator validates that the attribute value is a valid email address.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CEmailValidator.php 3120 2011-03-25 01:50:48Z qiang.xue $
- * @package system.validators
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CValidator
- */
- Yii.CEmailValidator = function CEmailValidator() {
- };
- Yii.CEmailValidator.prototype = new Yii.CValidator();
- Yii.CEmailValidator.prototype.constructor = Yii.CEmailValidator;
- /**
- * @var {String} the regular expression used to validate the attribute value.
- * @see http://www.regular-expressions.info/email.html
- */
- Yii.CEmailValidator.prototype.pattern = '^[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?$';
- /**
- * @var {String} the regular expression used to validate email addresses with the name part.
- * This property is used only when {@link allowName} is true.
- * @since 1.0.5
- * @see allowName
- */
- Yii.CEmailValidator.prototype.fullPattern = '^[^@]*<[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+(?:\\.[a-zA-Z0-9!#$%&\'*+\\/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?>$';
- /**
- * @var {Boolean} whether to allow name in the email address (e.g. "Qiang Xue <qiang.xue@gmail.com>"). Defaults to false.
- * @since 1.0.5
- * @see fullPattern
- */
- Yii.CEmailValidator.prototype.allowName = false;
- /**
- * @var {Boolean} whether the attribute value can be null or empty. Defaults to true,
- * meaning that if the attribute is empty, it is considered valid.
- */
- Yii.CEmailValidator.prototype.allowEmpty = true;
- /**
- * Validates the attribute of the object.
- * If there is any error, the error message is added to the object.
- * @param {Yii.CModel} object the object being validated
- * @param {String} attribute the attribute being validated
- */
- Yii.CEmailValidator.prototype.validateAttribute = function (object, attribute) {
- var value, message;
-
- value=object[attribute];
- if(this.allowEmpty && this.isEmpty(value)) {
- return;
- }
- if(!this.validateValue(value)) {
- message=this.message!==null?this.message:Yii.t('yii','{attribute} is not a valid email address.');
-
- this.addError(object,attribute,message);
- }
- };
- /**
- * Validates a static value to see if it is a valid email.
- * Note that this method does not respect {@link allowEmpty} property.
- * This method is provided so that you can call it directly without going through the model validation rule mechanism.
- * @param {Mixed} value the value to be validated
- * @returns {Boolean} whether the value is a valid email
- * @since 1.1.1
- */
- Yii.CEmailValidator.prototype.validateValue = function (value) {
-
- var valid, re, reFull;
- re = new RegExp(this.pattern);
- reFull = new RegExp(this.fullPattern);
-
- valid=typeof(value) === 'string' && (re.exec(value) || this.allowName && reFull.exec(value));
-
- return valid;
- };
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CInlineValidator represents a validator which is defined as a method in the object being validated.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CInlineValidator.php 2799 2011-01-01 19:31:13Z qiang.xue $
- * @package system.validators
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CValidator
- */
- Yii.CInlineValidator = function CInlineValidator() {
- };
- Yii.CInlineValidator.prototype = new Yii.CValidator();
- Yii.CInlineValidator.prototype.constructor = Yii.CInlineValidator;
- /**
- * @var {String} the name of the validation method defined in the active record class
- */
- Yii.CInlineValidator.prototype.method = null;
- /**
- * @var {Array} additional parameters that are passed to the validation method
- */
- Yii.CInlineValidator.prototype.params = null;
- /**
- * Validates the attribute of the object.
- * If there is any error, the error message is added to the object.
- * @param {Yii.CModel} object the object being validated
- * @param {String} attribute the attribute being validated
- */
- Yii.CInlineValidator.prototype.validateAttribute = function (object, attribute) {
- var method;
- method=this.method;
- object[method](attribute,this.params);
- };/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CNumberValidator validates that the attribute value is a number.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CNumberValidator.php 3120 2011-03-25 01:50:48Z qiang.xue $
- * @package system.validators
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CValidator
- */
- Yii.CNumberValidator = function CNumberValidator() {
- };
- Yii.CNumberValidator.prototype = new Yii.CValidator();
- Yii.CNumberValidator.prototype.constructor = Yii.CNumberValidator;
- /**
- * @var {Boolean} whether the attribute value can only be an integer. Defaults to false.
- */
- Yii.CNumberValidator.prototype.integerOnly = false;
- /**
- * @var {Boolean} whether the attribute value can be null or empty. Defaults to true,
- * meaning that if the attribute is empty, it is considered valid.
- */
- Yii.CNumberValidator.prototype.allowEmpty = true;
- /**
- * @var {Integer|float} upper limit of the number. Defaults to null, meaning no upper limit.
- */
- Yii.CNumberValidator.prototype.max = null;
- /**
- * @var {Integer|float} lower limit of the number. Defaults to null, meaning no lower limit.
- */
- Yii.CNumberValidator.prototype.min = null;
- /**
- * @var {String} user-defined error message used when the value is too big.
- */
- Yii.CNumberValidator.prototype.tooBig = null;
- /**
- * @var {String} user-defined error message used when the value is too small.
- */
- Yii.CNumberValidator.prototype.tooSmall = null;
- /**
- * @var {String} the regular expression for matching integers.
- * @since 1.1.7
- */
- Yii.CNumberValidator.prototype.integerPattern = '^\\s*[+-]?\\d+\\s*$';
- /**
- * @var {String} the regular expression for matching numbers.
- * @since 1.1.7
- */
- Yii.CNumberValidator.prototype.numberPattern = '^\\s*[-+]?[0-9]*\\.?[0-9]+([eE][-+]?[0-9]+)?\\s*$';
- /**
- * Validates the attribute of the object.
- * If there is any error, the error message is added to the object.
- * @param {Yii.CModel} object the object being validated
- * @param {String} attribute the attribute being validated
- */
- Yii.CNumberValidator.prototype.validateAttribute = function (object, attribute) {
- var value, message, intRe = new RegExp(this.integerPattern), numRe = new RegExp(this.numberPattern);
- value=String(object[attribute]);
- if(this.allowEmpty && this.isEmpty(value)) {
- return;
- }
- if(this.integerOnly) {
- if(!intRe.exec(value)) {
- message=this.message!==null?this.message:Yii.t('yii','{attribute} must be an integer.');
- this.addError(object,attribute,message);
- }
- }
- else {
- if(!numRe.exec(value)) {
- message=this.message!==null?this.message:Yii.t('yii','{attribute} must be a number.');
- this.addError(object,attribute,message);
- }
- }
- if(this.min!==null && value<this.min) {
- message=this.tooSmall!==null?this.tooSmall:Yii.t('yii','{attribute} is too small (minimum is {min}).');
- this.addError(object,attribute,message,{'{min}':this.min});
- }
- if(this.max!==null && value>this.max) {
- message=this.tooBig!==null?this.tooBig:Yii.t('yii','{attribute} is too big (maximum is {max}).');
- this.addError(object,attribute,message,{'{max}':this.max});
- }
- };
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CRangeValidator validates that the attribute value is among the list (specified via {@link range}).
- * You may invert the validation logic with help of the {@link not} property (available since 1.1.5).
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CRangeValidator.php 3120 2011-03-25 01:50:48Z qiang.xue $
- * @package system.validators
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CValidator
- */
- Yii.CRangeValidator = function CRangeValidator() {
- };
- Yii.CRangeValidator.prototype = new Yii.CValidator();
- Yii.CRangeValidator.prototype.constructor = Yii.CRangeValidator;
- /**
- * @var {Array} list of valid values that the attribute value should be among
- */
- Yii.CRangeValidator.prototype.range = null;
- /**
- * @var {Boolean} whether the comparison is strict (both type and value must be the same)
- */
- Yii.CRangeValidator.prototype.strict = false;
- /**
- * @var {Boolean} whether the attribute value can be null or empty. Defaults to true,
- * meaning that if the attribute is empty, it is considered valid.
- */
- Yii.CRangeValidator.prototype.allowEmpty = true;
- /**
- * @var {Boolean} whether to invert the validation logic. Defaults to false. If set to true,
- * the attribute value should NOT be among the list of values defined via {@link range}.
- * @since 1.1.5
- */
- Yii.CRangeValidator.prototype.not = false;
- /**
- * Validates the attribute of the object.
- * If there is any error, the error message is added to the object.
- * @param {Yii.CModel} object the object being validated
- * @param {String} attribute the attribute being validated
- */
- Yii.CRangeValidator.prototype.validateAttribute = function (object, attribute) {
- var value, message;
- value=object.get(attribute);
-
- if(this.allowEmpty && this.isEmpty(value)) {
- return;
- }
- if(Object.prototype.toString.call(this.range) !== '[object Array]') {
- throw new Yii.CException(Yii.t('yii','The "range" property must be specified with a list of values.'));
- }
- if(!this.not && !php.in_array(value,this.range,this.strict))
- {
- message=this.message!==null?this.message:Yii.t('yii','{attribute} is not in the list.');
- this.addError(object,attribute,message);
- }
- else if(this.not && php.in_array(value,this.range,this.strict))
- {
- message=this.message!==null?this.message:Yii.t('yii','{attribute} is in the list.');
- this.addError(object,attribute,message);
- }
- };
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CRequiredValidator validates that the specified attribute does not have null or empty value.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CRequiredValidator.php 3157 2011-04-02 19:21:06Z qiang.xue $
- * @package system.validators
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CValidator
- */
- Yii.CRequiredValidator = function CRequiredValidator() {
- };
- Yii.CRequiredValidator.prototype = new Yii.CValidator();
- Yii.CRequiredValidator.prototype.constructor = Yii.CRequiredValidator;
- /**
- * @var {Mixed} the desired value that the attribute must have.
- * If this is null, the validator will validate that the specified attribute does not have null or empty value.
- * If this is set as a value that is not null, the validator will validate that
- * the attribute has a value that is the same as this property value.
- * Defaults to null.
- * @since 1.0.10
- */
- Yii.CRequiredValidator.prototype.requiredValue = null;
- /**
- * @var {Boolean} whether the comparison to {@link requiredValue} is strict.
- * When this is true, the attribute value and type must both match those of {@link requiredValue}.
- * Defaults to false, meaning only the value needs to be matched.
- * This property is only used when {@link requiredValue} is not null.
- * @since 1.0.10
- */
- Yii.CRequiredValidator.prototype.strict = false;
- /**
- * Validates the attribute of the object.
- * If there is any error, the error message is added to the object.
- * @param {Yii.CModel} object the object being validated
- * @param {String} attribute the attribute being validated
- */
- Yii.CRequiredValidator.prototype.validateAttribute = function (object, attribute) {
- var value, message;
- value=object.get(attribute);
-
- if(this.requiredValue!==null) {
- if(!this.strict && value!=this.requiredValue || this.strict && value!==this.requiredValue) {
- message=this.message!==null?this.message:Yii.t('yii','{attribute} must be {value}.',
- {'{value}':this.requiredValue});
- this.addError(object,attribute,message);
- }
- }
- else if(this.isEmpty(value,true)) {
- message=this.message!==null?this.message:Yii.t('yii','{attribute} cannot be blank.');
- this.addError(object,attribute,message);
- }
- };
- /*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CTypeValidator verifies if the attribute is of the type specified by {@link type}.
- *
- * The following data types are supported:
- * <ul>
- * <li><b>integer</b> A 32-bit signed integer data type.</li>
- * <li><b>float</b> A double-precision floating point number data type.</li>
- * <li><b>string</b> A string data type.</li>
- * <li><b>array</b> An array value. </li>
- * <li><b>date</b> A date data type.</li>
- * <li><b>time</b> A time data type (available since version 1.0.5).</li>
- * <li><b>datetime</b> A date and time data type (available since version 1.0.5).</li>
- * </ul>
- *
- * For <b>date</b> type, the property {@link dateFormat}
- * will be used to determine how to parse the date string. If the given date
- * value doesn't follow the format, the attribute is considered as invalid.
- *
- * Starting from version 1.1.7, we have a dedicated date validator {@link CDateValidator}.
- * Please consider using this validator to validate a date-typed value.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CTypeValidator.php 3052 2011-03-12 14:27:07Z qiang.xue $
- * @package system.validators
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CValidator
- */
- Yii.CTypeValidator = function CTypeValidator() {
- };
- Yii.CTypeValidator.prototype = new Yii.CValidator();
- Yii.CTypeValidator.prototype.constructor = Yii.CTypeValidator;
- /**
- * @var {String} the data type that the attribute should be. Defaults to 'string'.
- * Valid values include 'string', 'integer', 'float', 'array', 'date', 'time' and 'datetime'.
- * Note that 'time' and 'datetime' have been available since version 1.0.5.
- */
- Yii.CTypeValidator.prototype.type = 'string';
- /**
- * @var {String} the format pattern that the date value should follow. Defaults to 'MM/dd/yyyy'.
- * Please see {@link CDateTimeParser} for details about how to specify a date format.
- * This property is effective only when {@link type} is 'date'.
- */
- Yii.CTypeValidator.prototype.dateFormat = 'MM/dd/yyyy';
- /**
- * @var {String} the format pattern that the time value should follow. Defaults to 'hh:mm'.
- * Please see {@link CDateTimeParser} for details about how to specify a time format.
- * This property is effective only when {@link type} is 'time'.
- * @since 1.0.5
- */
- Yii.CTypeValidator.prototype.timeFormat = 'hh:mm';
- /**
- * @var {String} the format pattern that the datetime value should follow. Defaults to 'MM/dd/yyyy hh:mm'.
- * Please see {@link CDateTimeParser} for details about how to specify a datetime format.
- * This property is effective only when {@link type} is 'datetime'.
- * @since 1.0.5
- */
- Yii.CTypeValidator.prototype.datetimeFormat = 'MM/dd/yyyy hh:mm';
- /**
- * @var {Boolean} whether the attribute value can be null or empty. Defaults to true,
- * meaning that if the attribute is empty, it is considered valid.
- */
- Yii.CTypeValidator.prototype.allowEmpty = true;
- /**
- * Validates the attribute of the object.
- * If there is any error, the error message is added to the object.
- * @param {Yii.CModel} object the object being validated
- * @param {String} attribute the attribute being validated
- */
- Yii.CTypeValidator.prototype.validateAttribute = function (object, attribute) {
- var value, valid, message;
- value=object.get(attribute);
- if(this.allowEmpty && this.isEmpty(value)) {
- return;
- }
- if(this.type==='integer') {
- valid=/^[\-+]?[0-9]+$/.exec(php.trim(value));
- }
- else if(this.type==='float') {
- valid=/^[\-+]?([0-9]*\.)?[0-9]+([eE][\-+]?[0-9]+)?$/.exec(php.trim(value));
- }
- else if(this.type==='date') {
- valid=Yii.CDateTimeParser.parse(value,this.dateFormat,{'month':1,'day':1,'hour':0,'minute':0,'second':0})!==false;
- }
- else if(this.type==='time') {
- valid=Yii.CDateTimeParser.parse(value,this.timeFormat)!==false;
- }
- else if(this.type==='datetime') {
- valid=Yii.CDateTimeParser.parse(value,this.datetimeFormat, {'month':1,'day':1,'hour':0,'minute':0,'second':0})!==false;
- }
- else if(this.type==='array') {
- valid=Object.prototype.toString.call(value) === '[object Array]';
- }
- else {
- return;
- }
- if(!valid) {
- message=this.message!==null?this.message : Yii.t('yii','{attribute} must be {type}.');
- this.addError(object,attribute,message,{'{type}':this.type});
- }
- }/*global Yii, php, $, jQuery, alert, clearInterval, clearTimeout, document, event, frames, history, Image, location, name, navigator, Option, parent, screen, setInterval, setTimeout, window, XMLHttpRequest */
- /**
- * CUrlValidator validates that the attribute value is a valid http or https URL.
- *
- * @originalAuthor Qiang Xue <qiang.xue@gmail.com>
- * @version $Id: CUrlValidator.php 3120 2011-03-25 01:50:48Z qiang.xue $
- * @package system.validators
- * @since 1.0
- * @author Charles Pick
- * @class
- * @extends Yii.CValidator
- */
- Yii.CUrlValidator = function CUrlValidator() {
-
- };
- Yii.CUrlValidator.prototype = new Yii.CValidator();
- Yii.CUrlValidator.prototype.constructor = Yii.CUrlValidator;
- /**
- * @var {String} the regular expression used to validate the attribute value.
- * Since version 1.1.7 the pattern may contain a {schemes} token that will be replaced
- * by a regular expression which represents the {@see validSchemes}.
- */
- Yii.CUrlValidator.prototype.pattern = '^{schemes}:\\/\\/(([A-Z0-9][A-Z0-9_-]*)(\\.[A-Z0-9][A-Z0-9_-]*)+)';
- /**
- * @var {Array} list of URI schemes which should be considered valid. By default, http and https
- * are considered to be valid schemes.
- * @since 1.1.7
- */
- Yii.CUrlValidator.prototype.validSchemes = ['http','https'];
- /**
- * @var {String} the default URI scheme. If the input doesn't contain the scheme part, the default
- * scheme will be prepended to it (thus changing the input). Defaults to null, meaning a URL must
- * contain the scheme part.
- * @since 1.1.7
- */
- Yii.CUrlValidator.prototype.defaultScheme = null;
- /**
- * @var {Boolean} whether the attribute value can be null or empty. Defaults to true,
- * meaning that if the attribute is empty, it is considered valid.
- */
- Yii.CUrlValidator.prototype.allowEmpty = true;
- /**
- * Validates the attribute of the object.
- * If there is any error, the error message is added to the object.
- * @param {Yii.CModel} object the object being validated
- * @param {String} attribute the attribute being validated
- */
- Yii.CUrlValidator.prototype.validateAttribute = function (object, attribute) {
- var value, message;
- value=object.get(attribute);
- if(this.allowEmpty && this.isEmpty(value)) {
- return;
- }
- if((value=this.validateValue(value))!==false) {
- object[attribute]=value;
- }
- else {
- message=this.message!==null?this.message:Yii.t('yii','{attribute} is not a valid URL.');
- this.addError(object,attribute,message);
- }
- };
- /**
- * Validates a static value to see if it is a valid URL.
- * Note that this method does not respect {@link allowEmpty} property.
- * This method is provided so that you can call it directly without going through the model validation rule mechanism.
- * @param {Mixed} value the value to be validated
- * @returns {Mixed} false if the the value is not a valid URL, otherwise the possibly modified value ({@see defaultScheme})
- * @since 1.1.1
- */
- Yii.CUrlValidator.prototype.validateValue = function (value) {
- var pattern, re;
- if(typeof(value) === 'string') {
- if(this.defaultScheme!==null && php.strpos(value,'://')===false) {
- value=this.defaultScheme+'://'+value;
- }
- if(php.strpos(this.pattern,'{schemes}')!==false) {
- pattern=php.str_replace('{schemes}','('+this.validSchemes.join('|')+')',this.pattern);
- }
- else {
- pattern=this.pattern;
- }
- re = new RegExp(this.pattern,"i");
- if(re.exec(value)) {
- return value;
- }
- }
- return false;
- };
- /*
- * Original script by Josh Fraser (http://www.onlineaspect.com)
- * Continued by Jon Nylander, (jon at pageloom dot com)
- * According to both of us, you are absolutely free to do whatever
- * you want with this code.
- *
- * This code is maintained at bitbucket.org as jsTimezoneDetect.
- */
-
- /**
- * Namespace to hold all the code for timezone detection.
- */
- var jzTimezoneDetector = {};
-
- jzTimezoneDetector.HEMISPHERE_SOUTH = 'SOUTH';
- jzTimezoneDetector.HEMISPHERE_NORTH = 'NORTH';
- jzTimezoneDetector.HEMISPHERE_UNKNOWN = 'N/A';
- jzTimezoneDetector.olson = {};
-
- /**
- * A simple object containing information of utc_offset, which olson timezone key to use,
- * and if the timezone cares about daylight savings or not.
- *
- * @constructor
- * @param {string} offset - for example '-11:00'
- * @param {string} olson_tz - the olson Identifier, such as "America/Denver"
- * @param {boolean} uses_dst - flag for whether the time zone somehow cares about daylight savings.
- */
- jzTimezoneDetector.TimeZone = function (offset, olson_tz, uses_dst) {
- this.utc_offset = offset;
- this.olson_tz = olson_tz;
- this.uses_dst = uses_dst;
- };
-
- /**
- * Prints out the result.
- * But before it does that, it calls this.ambiguity_check.
- */
- jzTimezoneDetector.TimeZone.prototype.display = function() {
- this.ambiguity_check();
- var response_text = '<b>UTC-offset</b>: ' + this.utc_offset + '<br/>';
- response_text += '<b>Zoneinfo key</b>: ' + this.olson_tz + '<br/>';
- response_text += '<b>Zone uses DST</b>: ' + (this.uses_dst ? 'yes' : 'no') + '<br/>';
-
- return response_text;
- };
-
- /**
- * Checks if a timezone has possible ambiguities. I.e timezones that are similar.
- *
- * If the preliminary scan determines that we're in America/Denver. We double check
- * here that we're really there and not in America/Mazatlan.
- *
- * This is done by checking known dates for when daylight savings start for different
- * timezones.
- */
- jzTimezoneDetector.TimeZone.prototype.ambiguity_check = function() {
- var local_ambiguity_list = jzTimezoneDetector.olson.ambiguity_list[this.olson_tz];
-
- if (typeof(local_ambiguity_list) == 'undefined') {
- return;
- }
-
- var length = local_ambiguity_list.length;
-
- for (var i = 0; i < length; i++) {
- var tz = local_ambiguity_list[i];
-
- if (jzTimezoneDetector.date_is_dst(jzTimezoneDetector.olson.dst_start_dates[tz])) {
- this.olson_tz = tz;
- return;
- }
- }
- };
-
- /**
- * Checks whether a given date is in daylight savings time.
- *
- * If the date supplied is after june, we assume that we're checking
- * for southern hemisphere DST.
- *
- * @param {Date} date
- * @returns {boolean}
- */
- jzTimezoneDetector.date_is_dst = function (date) {
- var base_offset, date_offset;
- base_offset = ( (date.getMonth() > 5 ? jzTimezoneDetector.get_june_offset() : jzTimezoneDetector.get_january_offset()) );
- date_offset = jzTimezoneDetector.get_date_offset(date);
-
- return (base_offset - date_offset) !== 0;
- };
-
- /**
- * Gets the offset in minutes from UTC for a certain date.
- *
- * @param date
- * @returns {number}
- */
- jzTimezoneDetector.get_date_offset = function (date) {
- return -date.getTimezoneOffset();
- };
-
- /**
- * This function does some basic calculations to create information about
- * the user's timezone.
- *
- * Returns a primitive object on the format
- * {'utc_offset' : -9, 'dst': 1, hemisphere' : 'north'}
- * where dst is 1 if the region uses daylight savings.
- *
- * @returns {Object}
- */
- jzTimezoneDetector.get_timezone_info = function () {
- var january_offset = jzTimezoneDetector.get_january_offset();
-
- var june_offset = jzTimezoneDetector.get_june_offset();
-
- var diff = january_offset - june_offset;
-
- if (diff < 0) {
- return {'utc_offset' : january_offset,
- 'dst': 1,
- 'hemisphere' : jzTimezoneDetector.HEMISPHERE_NORTH};
- }
- else if (diff > 0) {
- return {'utc_offset' : june_offset,
- 'dst' : 1,
- 'hemisphere' : jzTimezoneDetector.HEMISPHERE_SOUTH};
- }
- return {'utc_offset' : january_offset,
- 'dst': 0,
- 'hemisphere' : jzTimezoneDetector.HEMISPHERE_UNKNOWN};
- };
-
- jzTimezoneDetector.get_january_offset = function () {
- return jzTimezoneDetector.get_date_offset(new Date(2011, 0, 1, 0, 0, 0, 0));
- };
-
- jzTimezoneDetector.get_june_offset = function () {
- return jzTimezoneDetector.get_date_offset(new Date(2011, 5, 1, 0, 0, 0, 0));
- };
-
- /**
- * Uses get_timezone_info() to formulate a key to use in the olson.timezones dictionary.
- *
- * Returns a primitive object on the format:
- * {'timezone': TimeZone, 'key' : 'the key used to find the TimeZone object'}
- *
- * @returns Object
- */
- jzTimezoneDetector.determine_timezone = function () {
- var tz_key, timezone_key_info = jzTimezoneDetector.get_timezone_info(), hemisphere_suffix = '';
-
- if (timezone_key_info.hemisphere == jzTimezoneDetector.HEMISPHERE_SOUTH) {
- hemisphere_suffix = ',s';
- }
-
- tz_key = timezone_key_info.utc_offset + ',' + timezone_key_info.dst + hemisphere_suffix;
-
- return {'timezone' : jzTimezoneDetector.olson.timezones[tz_key], 'key' : tz_key};
- };
-
- /**
- * The keys in this dictionary are comma separated as such:
- *
- * First the offset compared to UTC time in minutes.
- *
- * Then a flag which is 0 if the timezone does not take daylight savings into account and 1 if it does.
- *
- * Thirdly an optional 's' signifies that the timezone is in the southern hemisphere, only interesting for timezones with DST.
- *
- * The values of the dictionary are TimeZone objects.
- */
- jzTimezoneDetector.olson.timezones = {
- '-720,0' : new jzTimezoneDetector.TimeZone('-12:00','Etc/GMT+12', false),
- '-660,0' : new jzTimezoneDetector.TimeZone('-11:00','Pacific/Pago_Pago', false),
- '-600,1' : new jzTimezoneDetector.TimeZone('-11:00','America/Adak',true),
- '-660,1,s' : new jzTimezoneDetector.TimeZone('-11:00','Pacific/Apia', true),
- '-600,0' : new jzTimezoneDetector.TimeZone('-10:00','Pacific/Honolulu', false),
- '-570,0' : new jzTimezoneDetector.TimeZone('-10:30','Pacific/Marquesas',false),
- '-540,0' : new jzTimezoneDetector.TimeZone('-09:00','Pacific/Gambier',false),
- '-540,1' : new jzTimezoneDetector.TimeZone('-09:00','America/Anchorage', true),
- '-480,1' : new jzTimezoneDetector.TimeZone('-08:00','America/Los_Angeles', true),
- '-480,0' : new jzTimezoneDetector.TimeZone('-08:00','Pacific/Pitcairn',false),
- '-420,0' : new jzTimezoneDetector.TimeZone('-07:00','America/Phoenix', false),
- '-420,1' : new jzTimezoneDetector.TimeZone('-07:00','America/Denver', true),
- '-360,0' : new jzTimezoneDetector.TimeZone('-06:00','America/Guatemala', false),
- '-360,1' : new jzTimezoneDetector.TimeZone('-06:00','America/Chicago', true),
- '-360,1,s' : new jzTimezoneDetector.TimeZone('-06:00','Pacific/Easter',true),
- '-300,0' : new jzTimezoneDetector.TimeZone('-05:00','America/Bogota', false),
- '-300,1' : new jzTimezoneDetector.TimeZone('-05:00','America/New_York', true),
- '-270,0' : new jzTimezoneDetector.TimeZone('-04:30','America/Caracas', false),
- '-240,1' : new jzTimezoneDetector.TimeZone('-04:00','America/Halifax', true),
- '-240,0' : new jzTimezoneDetector.TimeZone('-04:00','America/Santo_Domingo', false),
- '-240,1,s' : new jzTimezoneDetector.TimeZone('-04:00','America/Asuncion', true),
- '-210,1' : new jzTimezoneDetector.TimeZone('-03:30','America/St_Johns', true),
- '-180,1' : new jzTimezoneDetector.TimeZone('-03:00','America/Godthab', true),
- '-180,0' : new jzTimezoneDetector.TimeZone('-03:00','America/Argentina/Buenos_Aires', false),
- '-180,1,s' : new jzTimezoneDetector.TimeZone('-03:00','America/Montevideo', true),
- '-120,0' : new jzTimezoneDetector.TimeZone('-02:00','America/Noronha', false),
- '-120,1' : new jzTimezoneDetector.TimeZone('-02:00','Etc/GMT+2', true),
- '-60,1' : new jzTimezoneDetector.TimeZone('-01:00','Atlantic/Azores', true),
- '-60,0' : new jzTimezoneDetector.TimeZone('-01:00','Atlantic/Cape_Verde', false),
- '0,0' : new jzTimezoneDetector.TimeZone('00:00','Etc/UTC', false),
- '0,1' : new jzTimezoneDetector.TimeZone('00:00','Europe/London', true),
- '60,1' : new jzTimezoneDetector.TimeZone('+01:00','Europe/Berlin', true),
- '60,0' : new jzTimezoneDetector.TimeZone('+01:00','Africa/Lagos', false),
- '60,1,s' : new jzTimezoneDetector.TimeZone('+01:00','Africa/Windhoek',true),
- '120,1' : new jzTimezoneDetector.TimeZone('+02:00','Asia/Beirut', true),
- '120,0' : new jzTimezoneDetector.TimeZone('+02:00','Africa/Johannesburg', false),
- '180,1' : new jzTimezoneDetector.TimeZone('+03:00','Europe/Moscow', true),
- '180,0' : new jzTimezoneDetector.TimeZone('+03:00','Asia/Baghdad', false),
- '210,1' : new jzTimezoneDetector.TimeZone('+03:30','Asia/Tehran', true),
- '240,0' : new jzTimezoneDetector.TimeZone('+04:00','Asia/Dubai', false),
- '240,1' : new jzTimezoneDetector.TimeZone('+04:00','Asia/Yerevan', true),
- '270,0' : new jzTimezoneDetector.TimeZone('+04:30','Asia/Kabul', false),
- '300,1' : new jzTimezoneDetector.TimeZone('+05:00','Asia/Yekaterinburg', true),
- '300,0' : new jzTimezoneDetector.TimeZone('+05:00','Asia/Karachi', false),
- '330,0' : new jzTimezoneDetector.TimeZone('+05:30','Asia/Kolkata', false),
- '345,0' : new jzTimezoneDetector.TimeZone('+05:45','Asia/Kathmandu', false),
- '360,0' : new jzTimezoneDetector.TimeZone('+06:00','Asia/Dhaka', false),
- '360,1' : new jzTimezoneDetector.TimeZone('+06:00','Asia/Omsk', true),
- '390,0' : new jzTimezoneDetector.TimeZone('+06:30','Asia/Rangoon', false),
- '420,1' : new jzTimezoneDetector.TimeZone('+07:00','Asia/Krasnoyarsk', true),
- '420,0' : new jzTimezoneDetector.TimeZone('+07:00','Asia/Jakarta', false),
- '480,0' : new jzTimezoneDetector.TimeZone('+08:00','Asia/Shanghai', false),
- '480,1' : new jzTimezoneDetector.TimeZone('+08:00','Asia/Irkutsk', true),
- '525,0' : new jzTimezoneDetector.TimeZone('+08:45','Australia/Eucla', true),
- '525,1,s' : new jzTimezoneDetector.TimeZone('+08:45','Australia/Eucla', true),
- '540,1' : new jzTimezoneDetector.TimeZone('+09:00','Asia/Yakutsk', true),
- '540,0' : new jzTimezoneDetector.TimeZone('+09:00','Asia/Tokyo', false),
- '570,0' : new jzTimezoneDetector.TimeZone('+09:30','Australia/Darwin', false),
- '570,1,s' : new jzTimezoneDetector.TimeZone('+09:30','Australia/Adelaide', true),
- '600,0' : new jzTimezoneDetector.TimeZone('+10:00','Australia/Brisbane', false),
- '600,1' : new jzTimezoneDetector.TimeZone('+10:00','Asia/Vladivostok', true),
- '600,1,s' : new jzTimezoneDetector.TimeZone('+10:00','Australia/Sydney', true),
- '630,1,s' : new jzTimezoneDetector.TimeZone('+10:30','Australia/Lord_Howe', true),
- '660,1' : new jzTimezoneDetector.TimeZone('+11:00','Asia/Kamchatka', true),
- '660,0' : new jzTimezoneDetector.TimeZone('+11:00','Pacific/Noumea', false),
- '690,0' : new jzTimezoneDetector.TimeZone('+11:30','Pacific/Norfolk', false),
- '720,1,s' : new jzTimezoneDetector.TimeZone('+12:00','Pacific/Auckland', true),
- '720,0' : new jzTimezoneDetector.TimeZone('+12:00','Pacific/Tarawa', false),
- '765,1,s' : new jzTimezoneDetector.TimeZone('+12:45','Pacific/Chatham', true),
- '780,0' : new jzTimezoneDetector.TimeZone('+13:00','Pacific/Tongatapu', false),
- '840,0' : new jzTimezoneDetector.TimeZone('+14:00','Pacific/Kiritimati', false)
- };
-
- /**
- * This object contains information on when daylight savings starts for
- * different timezones.
- *
- * The list is short for a reason. Often we do not have to be very specific
- * to single out the correct timezone. But when we do, this list comes in
- * handy.
- *
- * Each value is a date denoting when daylight savings starts for that timezone.
- */
- jzTimezoneDetector.olson.dst_start_dates = {
- 'America/Denver' : new Date(2011, 2, 13, 3, 0, 0, 0),
- 'America/Mazatlan' : new Date(2011, 3, 3, 3, 0, 0, 0),
- 'America/Chicago' : new Date(2011, 2, 13, 3, 0, 0, 0),
- 'America/Mexico_City' : new Date(2011, 3, 3, 3, 0, 0, 0),
- 'Atlantic/Stanley' : new Date(2011, 8, 4, 7, 0, 0, 0),
- 'America/Asuncion' : new Date(2011, 9, 2, 3, 0, 0, 0),
- 'America/Santiago' : new Date(2011, 9, 9, 3, 0, 0, 0),
- 'America/Campo_Grande' : new Date(2011, 9, 16, 5, 0, 0, 0),
- 'America/Montevideo' : new Date(2011, 9, 2, 3, 0, 0, 0),
- 'America/Sao_Paulo' : new Date(2011, 9, 16, 5, 0, 0, 0),
- 'America/Los_Angeles' : new Date(2011, 2, 13, 8, 0, 0, 0),
- 'America/Santa_Isabel' : new Date(2011, 3, 5, 8, 0, 0, 0),
- 'America/Havana' : new Date(2011, 2, 13, 2, 0, 0, 0),
- 'America/New_York' : new Date(2011, 2, 13, 7, 0, 0, 0),
- 'Asia/Gaza' : new Date(2011, 2, 26, 23, 0, 0, 0),
- 'Asia/Beirut' : new Date(2011, 2, 27, 1, 0, 0, 0),
- 'Europe/Minsk' : new Date(2011, 2, 27, 3, 0, 0, 0),
- 'Europe/Istanbul' : new Date(2011, 2, 27, 7, 0, 0, 0),
- 'Asia/Damascus' : new Date(2011, 3, 1, 2, 0, 0, 0),
- 'Asia/Jerusalem' : new Date(2011, 3, 1, 6, 0, 0, 0),
- 'Africa/Cairo' : new Date(2011, 3, 29, 4, 0, 0, 0),
- 'Asia/Yerevan' : new Date(2011, 2, 27, 4, 0, 0, 0),
- 'Asia/Baku' : new Date(2011, 2, 27, 8, 0, 0, 0),
- 'Pacific/Auckland' : new Date(2011, 8, 26, 7, 0, 0, 0),
- 'Pacific/Fiji' : new Date(2010, 11, 29, 23, 0, 0, 0),
- 'America/Halifax' : new Date(2011, 2, 13, 6, 0, 0, 0),
- 'America/Goose_Bay' : new Date(2011, 2, 13, 2, 1, 0, 0),
- 'America/Miquelon' : new Date(2011, 2, 13, 5, 0, 0, 0),
- 'America/Godthab' : new Date(2011, 2, 27, 1, 0, 0, 0)
- };
-
- /**
- * The keys in this object are timezones that we know may be ambiguous after
- * a preliminary scan through the olson_tz object.
- *
- * The array of timezones to compare must be in the order that daylight savings
- * starts for the regions.
- */
- jzTimezoneDetector.olson.ambiguity_list = {
- 'America/Denver' : ['America/Denver','America/Mazatlan'],
- 'America/Chicago' : ['America/Chicago','America/Mexico_City'],
- 'America/Asuncion' : ['Atlantic/Stanley', 'America/Asuncion', 'America/Santiago','America/Campo_Grande'],
- 'America/Montevideo' : ['America/Montevideo', 'America/Sao_Paulo'],
- 'Asia/Beirut' : ['Asia/Gaza','Asia/Beirut', 'Europe/Minsk', 'Europe/Istanbul', 'Asia/Damascus', 'Asia/Jerusalem','Africa/Cairo'],
- 'Asia/Yerevan' : ['Asia/Yerevan', 'Asia/Baku'],
- 'Pacific/Auckland' : ['Pacific/Auckland', 'Pacific/Fiji'],
- 'America/Los_Angeles' : ['America/Los_Angeles', 'America/Santa_Isabel'],
- 'America/New_York' : ['America/Havana','America/New_York'],
- 'America/Halifax' : ['America/Goose_Bay','America/Halifax'],
- 'America/Godthab' : ['America/Miquelon', 'America/Godthab']
- };
- /*
- mustache.js — Logic-less templates in JavaScript
- See http://mustache.github.com/ for more info.
- */
- var Mustache = function() {
- var Renderer = function() {};
- Renderer.prototype = {
- otag: "{{",
- ctag: "}}",
- pragmas: {},
- buffer: [],
- pragmas_implemented: {
- "IMPLICIT-ITERATOR": true
- },
- context: {},
- render: function(template, context, partials, in_recursion) {
- // reset buffer & set context
- if(!in_recursion) {
- this.context = context;
- this.buffer = []; // TODO: make this non-lazy
- }
- // fail fast
- if(!this.includes("", template)) {
- if(in_recursion) {
- return template;
- } else {
- this.send(template);
- return;
- }
- }
- template = this.render_pragmas(template);
- var html = this.render_section(template, context, partials);
- if(in_recursion) {
- return this.render_tags(html, context, partials, in_recursion);
- }
- this.render_tags(html, context, partials, in_recursion);
- },
- /*
- Sends parsed lines
- */
- send: function(line) {
- if(line != "") {
- this.buffer.push(line);
- }
- },
- /*
- Looks for %PRAGMAS
- */
- render_pragmas: function(template) {
- // no pragmas
- if(!this.includes("%", template)) {
- return template;
- }
- var that = this;
- var regex = new RegExp(this.otag + "%([\\w-]+) ?([\\w]+=[\\w]+)?" +
- this.ctag);
- return template.replace(regex, function(match, pragma, options) {
- if(!that.pragmas_implemented[pragma]) {
- throw({message:
- "This implementation of mustache doesn't understand the '" +
- pragma + "' pragma"});
- }
- that.pragmas[pragma] = {};
- if(options) {
- var opts = options.split("=");
- that.pragmas[pragma][opts[0]] = opts[1];
- }
- return "";
- // ignore unknown pragmas silently
- });
- },
- /*
- Tries to find a partial in the curent scope and render it
- */
- render_partial: function(name, context, partials) {
- name = this.trim(name);
- if(!partials || partials[name] === undefined) {
- throw({message: "unknown_partial '" + name + "'"});
- }
- if(typeof(context[name]) != "object") {
- return this.render(partials[name], context, partials, true);
- }
- return this.render(partials[name], context[name], partials, true);
- },
- /*
- Renders inverted (^) and normal (#) sections
- */
- render_section: function(template, context, partials) {
- if(!this.includes("#", template) && !this.includes("^", template)) {
- return template;
- }
- var that = this;
- // CSW - Added "+?" so it finds the tighest bound, not the widest
- var regex = new RegExp(this.otag + "(\\^|\\#)\\s*(.+)\\s*" + this.ctag +
- "\n*([\\s\\S]+?)" + this.otag + "\\/\\s*\\2\\s*" + this.ctag +
- "\\s*", "mg");
- // for each {{#foo}}{{/foo}} section do...
- return template.replace(regex, function(match, type, name, content) {
- var value = that.find(name, context);
- if(type == "^") { // inverted section
- if(!value || that.is_array(value) && value.length === 0) {
- // false or empty list, render it
- return that.render(content, context, partials, true);
- } else {
- return "";
- }
- } else if(type == "#") { // normal section
- if(that.is_array(value)) { // Enumerable, Let's loop!
- return that.map(value, function(row) {
- return that.render(content, that.create_context(row),
- partials, true);
- }).join("");
- } else if(that.is_object(value)) { // Object, Use it as subcontext!
- return that.render(content, that.create_context(value),
- partials, true);
- } else if(typeof value === "function") {
- // higher order section
- return value.call(context, content, function(text) {
- return that.render(text, context, partials, true);
- });
- } else if(value) { // boolean section
- return that.render(content, context, partials, true);
- } else {
- return "";
- }
- }
- });
- },
- /*
- Replace {{foo}} and friends with values from our view
- */
- render_tags: function(template, context, partials, in_recursion) {
- // tit for tat
- var that = this;
- var new_regex = function() {
- return new RegExp(that.otag + "(=|!|>|\\{|%)?([^\\/#\\^]+?)\\1?" +
- that.ctag + "+", "g");
- };
- var regex = new_regex();
- var tag_replace_callback = function(match, operator, name) {
- switch(operator) {
- case "!": // ignore comments
- return "";
- case "=": // set new delimiters, rebuild the replace regexp
- that.set_delimiters(name);
- regex = new_regex();
- return "";
- case ">": // render partial
- return that.render_partial(name, context, partials);
- case "{": // the triple mustache is unescaped
- return that.find(name, context);
- default: // escape the value
- return that.escape(that.find(name, context));
- }
- };
- var lines = template.split("\n");
- for(var i = 0; i < lines.length; i++) {
- lines[i] = lines[i].replace(regex, tag_replace_callback, this);
- if(!in_recursion) {
- this.send(lines[i]);
- }
- }
- if(in_recursion) {
- return lines.join("\n");
- }
- },
- set_delimiters: function(delimiters) {
- var dels = delimiters.split(" ");
- this.otag = this.escape_regex(dels[0]);
- this.ctag = this.escape_regex(dels[1]);
- },
- escape_regex: function(text) {
- // thank you Simon Willison
- if(!arguments.callee.sRE) {
- var specials = [
- '/', '.', '*', '+', '?', '|',
- '(', ')', '[', ']', '{', '}', '\\'
- ];
- arguments.callee.sRE = new RegExp(
- '(\\' + specials.join('|\\') + ')', 'g'
- );
- }
- return text.replace(arguments.callee.sRE, '\\$1');
- },
- /*
- find `name` in current `context`. That is find me a value
- from the view object
- */
- find: function(name, context) {
- name = this.trim(name);
- // Checks whether a value is thruthy or false or 0
- function is_kinda_truthy(bool) {
- return bool === false || bool === 0 || bool;
- }
- var value = context;
- var path = name.split(/\./);
- for(var i = 0; i < path.length; i++) {
- name = path[i];
- if(value && is_kinda_truthy(value[name])) {
- value = value[name];
- } else if(i == 0 && is_kinda_truthy(this.context[name])) {
- value = this.context[name];
- } else {
- value = undefined;
- }
- }
- if(typeof value === "function") {
- return value.apply(context);
- }
- if(value !== undefined) {
- return value;
- }
- // silently ignore unkown variables
- return "";
- },
- // Utility methods
- /* includes tag */
- includes: function(needle, haystack) {
- return haystack.indexOf(this.otag + needle) != -1;
- },
- /*
- Does away with nasty characters
- */
- escape: function(s) {
- s = String(s === null ? "" : s);
- return s.replace(/&(?!\w+;)|["'<>\\]/g, function(s) {
- switch(s) {
- case "&": return "&";
- case "\\": return "\\\\";
- case '"': return '"';
- case "'": return ''';
- case "<": return "<";
- case ">": return ">";
- default: return s;
- }
- });
- },
- // by @langalex, support for arrays of strings
- create_context: function(_context) {
- if(this.is_object(_context)) {
- return _context;
- } else {
- var iterator = ".";
- if(this.pragmas["IMPLICIT-ITERATOR"]) {
- iterator = this.pragmas["IMPLICIT-ITERATOR"].iterator;
- }
- var ctx = {};
- ctx[iterator] = _context;
- return ctx;
- }
- },
- is_object: function(a) {
- return a && typeof a == "object";
- },
- is_array: function(a) {
- return Object.prototype.toString.call(a) === '[object Array]';
- },
- /*
- Gets rid of leading and trailing whitespace
- */
- trim: function(s) {
- return s.replace(/^\s*|\s*$/g, "");
- },
- /*
- Why, why, why? Because IE. Cry, cry cry.
- */
- map: function(array, fn) {
- if (typeof array.map == "function") {
- return array.map(fn);
- } else {
- var r = [];
- var l = array.length;
- for(var i = 0; i < l; i++) {
- r.push(fn(array[i]));
- }
- return r;
- }
- }
- };
- return({
- name: "mustache.js",
- version: "0.3.1-dev",
- /*
- Turns a template and view into HTML
- */
- to_html: function(template, view, partials, send_fun) {
- var renderer = new Renderer();
- if(send_fun) {
- renderer.send = send_fun;
- }
- renderer.render(template, view, partials);
- if(!send_fun) {
- return renderer.buffer.join("\n");
- }
- }
- });
- }();
- /*
- * More info at: http://phpjs.org
- *
- * This is version: 3.24
- * php.js is copyright 2011 Kevin van Zonneveld.
- *
- * Portions copyright Brett Zamir (http://brett-zamir.me), Kevin van Zonneveld
- * (http://kevin.vanzonneveld.net), Onno Marsman, Theriault, Michael White
- * (http://getsprink.com), Waldo Malqui Silva, Paulo Freitas, Jonas Raoni
- * Soares Silva (http://www.jsfromhell.com), Jack, Philip Peterson, Ates Goral
- * (http://magnetiq.com), Legaev Andrey, Ratheous, Alex, Martijn Wieringa,
- * Nate, lmeyrick (https://sourceforge.net/projects/bcmath-js/), Enrique
- * Gonzalez, Philippe Baumann, Rafał Kukawski (http://blog.kukawski.pl),
- * Webtoolkit.info (http://www.webtoolkit.info/), Ole Vrijenhoek, Ash Searle
- * (http://hexmen.com/blog/), travc, Carlos R. L. Rodrigues
- * (http://www.jsfromhell.com), Jani Hartikainen, stag019, GeekFG
- * (http://geekfg.blogspot.com), WebDevHobo (http://webdevhobo.blogspot.com/),
- * Erkekjetter, pilus, Rafał Kukawski (http://blog.kukawski.pl/), Johnny Mast
- * (http://www.phpvrouwen.nl), T.Wild,
- * http://stackoverflow.com/questions/57803/how-to-convert-decimal-to-hex-in-javascript,
- * d3x, Michael Grier, Andrea Giammarchi (http://webreflection.blogspot.com),
- * marrtins, Mailfaker (http://www.weedem.fr/), Steve Hilder, gettimeofday,
- * mdsjack (http://www.mdsjack.bo.it), felix, majak, Steven Levithan
- * (http://blog.stevenlevithan.com), Mirek Slugen, Oleg Eremeev, Felix
- * Geisendoerfer (http://www.debuggable.com/felix), Martin
- * (http://www.erlenwiese.de/), gorthaur, Lars Fischer, Joris, AJ, Paul Smith,
- * Tim de Koning (http://www.kingsquare.nl), KELAN, Josh Fraser
- * (http://onlineaspect.com/2007/06/08/auto-detect-a-time-zone-with-javascript/),
- * Chris, Marc Palau, Kevin van Zonneveld (http://kevin.vanzonneveld.net/),
- * Arpad Ray (mailto:arpad@php.net), Breaking Par Consulting Inc
- * (http://www.breakingpar.com/bkp/home.nsf/0/87256B280015193F87256CFB006C45F7),
- * Nathan, Karol Kowalski, David, Dreamer, Diplom@t (http://difane.com/), Caio
- * Ariede (http://caioariede.com), Robin, Imgen Tata (http://www.myipdf.com/),
- * Pellentesque Malesuada, saulius, Aman Gupta, Sakimori, Tyler Akins
- * (http://rumkin.com), Thunder.m, Public Domain
- * (http://www.json.org/json2.js), Michael White, Kankrelune
- * (http://www.webfaktory.info/), Alfonso Jimenez
- * (http://www.alfonsojimenez.com), Frank Forte, vlado houba, Marco, Billy,
- * David James, madipta, noname, sankai, class_exists, Jalal Berrami, ger,
- * Itsacon (http://www.itsacon.net/), Scott Cariss, nobbler, Arno, Denny
- * Wardhana, ReverseSyntax, Mateusz "loonquawl" Zalega, Slawomir Kaniecki,
- * Francois, Fox, mktime, Douglas Crockford (http://javascript.crockford.com),
- * john (http://www.jd-tech.net), Oskar Larsson Högfeldt
- * (http://oskar-lh.name/), marc andreu, Nick Kolosov (http://sammy.ru), date,
- * Marc Jansen, Steve Clay, Olivier Louvignes (http://mg-crea.com/), Soren
- * Hansen, merabi, Subhasis Deb, josh, T0bsn, Tim Wiel, Brad Touesnard, MeEtc
- * (http://yass.meetcweb.com), Peter-Paul Koch
- * (http://www.quirksmode.org/js/beat.html), Pyerre, Jon Hohle, duncan, Bayron
- * Guevara, Adam Wallner (http://web2.bitbaro.hu/), paulo kuong, Gilbert,
- * Lincoln Ramsay, Thiago Mata (http://thiagomata.blog.com), Linuxworld,
- * lmeyrick (https://sourceforge.net/projects/bcmath-js/this.), djmix, Bryan
- * Elliott, David Randall, Sanjoy Roy, jmweb, Francesco, Stoyan Kyosev
- * (http://www.svest.org/), J A R, kenneth, T. Wild, Ole Vrijenhoek
- * (http://www.nervous.nl/), Raphael (Ao RUDLER), Shingo, LH, JB, nord_ua, jd,
- * JT, Thomas Beaucourt (http://www.webapp.fr), Ozh, XoraX
- * (http://www.xorax.info), EdorFaus, Eugene Bulkin (http://doubleaw.com/),
- * Der Simon (http://innerdom.sourceforge.net/), 0m3r, echo is bad,
- * FremyCompany, stensi, Kristof Coomans (SCK-CEN Belgian Nucleair Research
- * Centre), Devan Penner-Woelk, Pierre-Luc Paour, Martin Pool, Brant Messenger
- * (http://www.brantmessenger.com/), Kirk Strobeck, Saulo Vallory, Christoph,
- * Wagner B. Soares, Artur Tchernychev, Valentina De Rosa, Jason Wong
- * (http://carrot.org/), Daniel Esteban, strftime, Rick Waldron, Mick@el,
- * Anton Ongson, Bjorn Roesbeke (http://www.bjornroesbeke.be/), Simon Willison
- * (http://simonwillison.net), Gabriel Paderni, Philipp Lenssen, Marco van
- * Oort, Bug?, Blues (http://tech.bluesmoon.info/), Tomasz Wesolowski, rezna,
- * Eric Nagel, Evertjan Garretsen, Luke Godfrey, Pul, Bobby Drake, uestla,
- * Alan C, Ulrich, Zahlii, Yves Sucaet, sowberry, Norman "zEh" Fuchs, hitwork,
- * johnrembo, Brian Tafoya (http://www.premasolutions.com/), Nick Callen,
- * Steven Levithan (stevenlevithan.com), ejsanders, Scott Baker, Philippe
- * Jausions (http://pear.php.net/user/jausions), Aidan Lister
- * (http://aidanlister.com/), Rob, e-mike, HKM, ChaosNo1, metjay, strcasecmp,
- * strcmp, Taras Bogach, jpfle, Alexander Ermolaev
- * (http://snippets.dzone.com/user/AlexanderErmolaev), DxGx, kilops, Orlando,
- * dptr1988, Le Torbi, James (http://www.james-bell.co.uk/), Pedro Tainha
- * (http://www.pedrotainha.com), James, penutbutterjelly, Arnout Kazemier
- * (http://www.3rd-Eden.com), 3D-GRAF, daniel airton wermann
- * (http://wermann.com.br), jakes, Yannoo, FGFEmperor, gabriel paderni, Atli
- * Þór, Maximusya, Diogo Resende, Rival, Howard Yeend, Allan Jensen
- * (http://www.winternet.no), davook, Benjamin Lupton, baris ozdil, Greg
- * Frazier, Manish, Matt Bradley, Cord, fearphage
- * (http://http/my.opera.com/fearphage/), Matteo, Victor, taith, Tim de
- * Koning, Ryan W Tenney (http://ryan.10e.us), Tod Gentille, Alexander M
- * Beedie, Riddler (http://www.frontierwebdev.com/), Luis Salazar
- * (http://www.freaky-media.com/), Rafał Kukawski, T.J. Leahy, Luke Smith
- * (http://lucassmith.name), Kheang Hok Chin (http://www.distantia.ca/),
- * Russell Walker (http://www.nbill.co.uk/), Jamie Beck
- * (http://www.terabit.ca/), Garagoth, Andrej Pavlovic, Dino, Le Torbi
- * (http://www.letorbi.de/), Ben (http://benblume.co.uk/), DtTvB
- * (http://dt.in.th/2008-09-16.string-length-in-bytes.html), Michael, Chris
- * McMacken, setcookie, YUI Library:
- * http://developer.yahoo.com/yui/docs/YAHOO.util.DateLocale.html, Andreas,
- * Blues at http://hacks.bluesmoon.info/strftime/strftime.js, rem, Josep Sanz
- * (http://www.ws3.es/), Cagri Ekin, Lorenzo Pisani, incidence, Amirouche, Jay
- * Klehr, Amir Habibi (http://www.residence-mixte.com/), Tony, booeyOH, meo,
- * William, Greenseed, Yen-Wei Liu, Ben Bryan, Leslie Hoare, mk.keck
- *
- * Dual licensed under the MIT (MIT-LICENSE.txt)
- * and GPL (GPL-LICENSE.txt) licenses.
- *
- * Permission is hereby granted, free of charge, to any person obtaining a
- * copy of this software and associated documentation files (the
- * "Software"), to deal in the Software without restriction, including
- * without limitation the rights to use, copy, modify, merge, publish,
- * distribute, sublicense, and/or sell copies of the Software, and to
- * permit persons to whom the Software is furnished to do so, subject to
- * the following conditions:
- *
- * The above copyright notice and this permission notice shall be included
- * in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
- * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
- * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
- * IN NO EVENT SHALL KEVIN VAN ZONNEVELD BE LIABLE FOR ANY CLAIM, DAMAGES
- * OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
- * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- * OTHER DEALINGS IN THE SOFTWARE.
- */
-
-
- // jslint.com configuration options. See: http://wiki.github.com/kvz/phpjs/jslint-options
- /* global window */
- /* jslint adsafe: false, bitwise: false, browser: false, cap: false, css: false, debug: false, devel: false, eqeqeq: true, evil: false, forin: false, fragment: false, immed: true, indent: 4, laxbreak: false, maxerr: 100, maxlen: 80, newcap: true, nomen: false, on: true, onevar: false, passfail: false, plusplus: false, regexp: false, rhino: false, safe: false, sidebar: false, strict: false, sub: false, undef: true, white: false, widget: false */
-
- // Our idea with CommonJS is that you can do the following:
- // var php = require('php');
- // php.md5('test');
- var php = {};
-
- php.ini_set = function (varname, newvalue) {
- // http://kevin.vanzonneveld.net
- // + original by: Brett Zamir (http://brett-zamir.me)
- // % note 1: This will not set a global_value or access level for the ini item
- // * example 1: ini_set('date.timezone', 'America/Chicago');
- // * returns 1: 'Asia/Hong_Kong'
-
- var oldval = '',
- that = this;
- this.php_js = this.php_js || {};
- this.php_js.ini = this.php_js.ini || {};
- this.php_js.ini[varname] = this.php_js.ini[varname] || {};
- oldval = this.php_js.ini[varname].local_value;
-
- var _setArr = function (oldval) { // Although these are set individually, they are all accumulated
- if (typeof oldval === 'undefined') {
- that.php_js.ini[varname].local_value = [];
- }
- that.php_js.ini[varname].local_value.push(newvalue);
- };
-
- switch (varname) {
- case 'extension':
- if (typeof this.dl === 'function') {
- this.dl(newvalue); // This function is only experimental in php.js
- }
- _setArr(oldval, newvalue);
- break;
- default:
- this.php_js.ini[varname].local_value = newvalue;
- break;
- }
- return oldval;
- };
- php.ini_get = function (varname) {
- // http://kevin.vanzonneveld.net
- // + original by: Brett Zamir (http://brett-zamir.me)
- // % note 1: The ini values must be set by ini_set or manually within an ini file
- // * example 1: ini_get('date.timezone');
- // * returns 1: 'Asia/Hong_Kong'
- if (this.php_js && this.php_js.ini && this.php_js.ini[varname] && this.php_js.ini[varname].local_value !== undefined) {
- if (this.php_js.ini[varname].local_value === null) {
- return '';
- }
- return this.php_js.ini[varname].local_value;
- }
- return '';
- }
-
- php.ctype_digit = function (text) {
- // http://kevin.vanzonneveld.net
- // + original by: Brett Zamir (http://brett-zamir.me)
- // - depends on: setlocale
- // * example 1: ctype_digit('150');
- // * returns 1: true
- if (typeof text !== 'string') {
- return false;
- }
- // BEGIN REDUNDANT
- this.setlocale('LC_ALL', 0); // ensure setup of localization variables takes place
- // END REDUNDANT
- return text.search(this.php_js.locales[this.php_js.localeCategories.LC_CTYPE].LC_CTYPE.dg) !== -1;
- };
- php.gmmktime = function () {
- // http://kevin.vanzonneveld.net
- // + original by: Brett Zamir (http://brett-zamir.me)
- // + derived from: mktime
- // * example 1: gmmktime(14, 10, 2, 2, 1, 2008);
- // * returns 1: 1201875002
- // * example 2: gmmktime(0, 0, -1, 1, 1, 1970);
- // * returns 2: -1
- var d = new Date(),
- r = arguments,
- i = 0,
- e = ['Hours', 'Minutes', 'Seconds', 'Month', 'Date', 'FullYear'];
-
- for (i = 0; i < e.length; i++) {
- if (typeof r[i] === 'undefined') {
- r[i] = d['getUTC' + e[i]]();
- r[i] += (i === 3); // +1 to fix JS months.
- } else {
- r[i] = parseInt(r[i], 10);
- if (isNaN(r[i])) {
- return false;
- }
- }
- }
-
- // Map years 0-69 to 2000-2069 and years 70-100 to 1970-2000.
- r[5] += (r[5] >= 0 ? (r[5] <= 69 ? 2e3 : (r[5] <= 100 ? 1900 : 0)) : 0);
-
- // Set year, month (-1 to fix JS months), and date.
- // !This must come before the call to setHours!
- d.setUTCFullYear(r[5], r[3] - 1, r[4]);
-
- // Set hours, minutes, and seconds.
- d.setUTCHours(r[0], r[1], r[2]);
-
- // Divide milliseconds by 1000 to return seconds and drop decimal.
- // Add 1 second if negative or it'll be off from PHP by 1 second.
- return (d.getTime() / 1e3 >> 0) - (d.getTime() < 0);
- };
- php.getdate = function (timestamp) {
- // http://kevin.vanzonneveld.net
- // + original by: Paulo Freitas
- // + input by: Alex
- // + bugfixed by: Brett Zamir (http://brett-zamir.me)
- // * example 1: getdate(1055901520);
- // * returns 1: {'seconds': 40, 'minutes': 58, 'hours': 21, 'mday': 17, 'wday': 2, 'mon': 6, 'year': 2003, 'yday': 167, 'weekday': 'Tuesday', 'month': 'June', '0': 1055901520}
- var _w = ['Sun', 'Mon', 'Tues', 'Wednes', 'Thurs', 'Fri', 'Satur'];
- var _m = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
- var d = ((typeof(timestamp) == 'undefined') ? new Date() : // Not provided
- (typeof(timestamp) == 'object') ? new Date(timestamp) : // Javascript Date()
- new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
- );
- var w = d.getDay();
- var m = d.getMonth();
- var y = d.getFullYear();
- var r = {};
-
- r.seconds = d.getSeconds();
- r.minutes = d.getMinutes();
- r.hours = d.getHours();
- r.mday = d.getDate();
- r.wday = w;
- r.mon = m + 1;
- r.year = y;
- r.yday = Math.floor((d - (new Date(y, 0, 1))) / 86400000);
- r.weekday = _w[w] + 'day';
- r.month = _m[m];
- r['0'] = parseInt(d.getTime() / 1000, 10);
-
- return r;
- };
- php.checkdate = function (m, d, y) {
- // Returns true(1) if it is a valid date in gregorian calendar
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/checkdate
- // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + improved by: Pyerre
- // + improved by: Theriault
- // * example 1: checkdate(12, 31, 2000);
- // * returns 1: true
- // * example 2: checkdate(2, 29, 2001);
- // * returns 2: false
- // * example 3: checkdate(3, 31, 2008);
- // * returns 3: true
- // * example 4: checkdate(1, 390, 2000);
- // * returns 4: false
- return m > 0 && m < 13 && y > 0 && y < 32768 && d > 0 && d <= (new Date(y, m, 0)).getDate();
- };
- php.gmdate = function (format, timestamp) {
- // Format a GMT date/time
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/gmdate
- // + original by: Brett Zamir (http://brett-zamir.me)
- // + input by: Alex
- // + bugfixed by: Brett Zamir (http://brett-zamir.me)
- // - depends on: date
- // * example 1: gmdate('H:m:s \\m \\i\\s \\m\\o\\n\\t\\h', 1062402400); // Return will depend on your timezone
- // * returns 1: '07:09:40 m is month'
- var dt = ((typeof(timestamp) == 'undefined') ? new Date() : // Not provided
- (typeof(timestamp) == 'object') ? new Date(timestamp) : // Javascript Date()
- new Date(timestamp * 1000) // UNIX timestamp (auto-convert to int)
- );
- timestamp = Date.parse(dt.toUTCString().slice(0, -4)) / 1000;
- return this.date(format, timestamp);
- };
- php.mt_rand = function (min, max) {
- // Returns a random number from Mersenne Twister
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/mt_rand
- // + original by: Onno Marsman
- // * example 1: mt_rand(1, 1);
- // * returns 1: 1
- var argc = arguments.length;
- if (argc === 0) {
- min = 0;
- max = 2147483647;
- } else if (argc === 1) {
- throw new Error('Warning: mt_rand() expects exactly 2 parameters, 1 given');
- }
- return Math.floor(Math.random() * (max - min + 1)) + min;
- };
-
- php.abs = function (mixed_number) {
- // Return the absolute value of the number
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/abs
- // + original by: Waldo Malqui Silva
- // + improved by: Karol Kowalski
- // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + improved by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
- // * example 1: \php.abs(4.2);
- // * returns 1: 4.2
- // * example 2: \php.abs(-4.2);
- // * returns 2: 4.2
- // * example 3: \php.abs(-5);
- // * returns 3: 5
- // * example 4: \php.abs('_argos');
- // * returns 4: 0
- return Math.abs(mixed_number) || 0;
- };
-
- php.addcslashes = function (str, charlist) {
- // Escapes all chars mentioned in charlist with backslash. It creates octal representations if asked to backslash characters with 8th bit set or with ASCII<32 (except '\n', '\r', '\t' etc...)
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/addcslashes
- // + original by: Brett Zamir (http://brett-zamir.me)
- // % note 1: We show double backslashes in the return value example code below because a JavaScript string will not
- // % note 1: render them as backslashes otherwise
- // * example 1: \php.addcslashes('foo[ ]', 'A..z'); // Escape all ASCII within capital A to lower z range, including square brackets
- // * returns 1: "\\f\\o\\o\\[ \\]"
- // * example 2: \php.addcslashes("zoo['.']", 'z..A'); // Only escape z, period, and A here since not a lower-to-higher range
- // * returns 2: "\\zoo['\\.']"
- // * example 3: \php.addcslashes("@a\u0000\u0010\u00A9", "\0..\37!@\177..\377") == '\\@a\\000\\020\\302\\251'); // Escape as octals those specified and less than 32 (0x20) or greater than 126 (0x7E), but not otherwise
- // * returns 3: true
- // * example 4: \php.addcslashes("\u0020\u007E", "\40..\175") == '\\ ~'); // Those between 32 (0x20 or 040) and 126 (0x7E or 0176) decimal value will be backslashed if specified (not octalized)
- // * returns 4: true
- // * example 5: \php.addcslashes("\r\u0007\n", '\0..\37'); // Recognize C escape sequences if specified
- // * returns 5: "\\r\\a\\n"
- // * example 6: \php.addcslashes("\r\u0007\n", '\0'); // Do not recognize C escape sequences if not specified
- // * returns 7: "\r\u0007\n"
- var target = '',
- chrs = [],
- i = 0,
- j = 0,
- c = '',
- next = '',
- rangeBegin = '',
- rangeEnd = '',
- chr = '',
- begin = 0,
- end = 0,
- octalLength = 0,
- postOctalPos = 0,
- cca = 0,
- escHexGrp = [],
- encoded = '',
- percentHex = /%([\dA-Fa-f]+)/g;
- var _pad = function (n, c) {
- if ((n = n + "").length < c) {
- return new Array(++c - n.length).join("0") + n;
- } else {
- return n;
- }
- };
-
- for (i = 0; i < charlist.length; i++) {
- c = charlist.charAt(i);
- next = charlist.charAt(i + 1);
- if (c === '\\' && next && (/\d/).test(next)) { // Octal
- rangeBegin = charlist.slice(i + 1).match(/^\d+/)[0];
- octalLength = rangeBegin.length;
- postOctalPos = i + octalLength + 1;
- if (charlist.charAt(postOctalPos) + charlist.charAt(postOctalPos + 1) === '..') { // Octal begins range
- begin = rangeBegin.charCodeAt(0);
- if ((/\\\d/).test(charlist.charAt(postOctalPos + 2) + charlist.charAt(postOctalPos + 3))) { // Range ends with octal
- rangeEnd = charlist.slice(postOctalPos + 3).match(/^\d+/)[0];
- i += 1; // Skip range end backslash
- } else if (charlist.charAt(postOctalPos + 2)) { // Range ends with character
- rangeEnd = charlist.charAt(postOctalPos + 2);
- } else {
- throw 'Range with no end point';
- }
- end = rangeEnd.charCodeAt(0);
- if (end > begin) { // Treat as a range
- for (j = begin; j <= end; j++) {
- chrs.push(String.fromCharCode(j));
- }
- } else { // Supposed to treat period, begin and end as individual characters only, not a range
- chrs.push('.', rangeBegin, rangeEnd);
- }
- i += rangeEnd.length + 2; // Skip dots and range end (already skipped range end backslash if present)
- } else { // Octal is by itself
- chr = String.fromCharCode(parseInt(rangeBegin, 8));
- chrs.push(chr);
- }
- i += octalLength; // Skip range begin
- } else if (next + charlist.charAt(i + 2) === '..') { // Character begins range
- rangeBegin = c;
- begin = rangeBegin.charCodeAt(0);
- if ((/\\\d/).test(charlist.charAt(i + 3) + charlist.charAt(i + 4))) { // Range ends with octal
- rangeEnd = charlist.slice(i + 4).match(/^\d+/)[0];
- i += 1; // Skip range end backslash
- } else if (charlist.charAt(i + 3)) { // Range ends with character
- rangeEnd = charlist.charAt(i + 3);
- } else {
- throw 'Range with no end point';
- }
- end = rangeEnd.charCodeAt(0);
- if (end > begin) { // Treat as a range
- for (j = begin; j <= end; j++) {
- chrs.push(String.fromCharCode(j));
- }
- } else { // Supposed to treat period, begin and end as individual characters only, not a range
- chrs.push('.', rangeBegin, rangeEnd);
- }
- i += rangeEnd.length + 2; // Skip dots and range end (already skipped range end backslash if present)
- } else { // Character is by itself
- chrs.push(c);
- }
- }
-
- for (i = 0; i < str.length; i++) {
- c = str.charAt(i);
- if (chrs.indexOf(c) !== -1) {
- target += '\\';
- cca = c.charCodeAt(0);
- if (cca < 32 || cca > 126) { // Needs special escaping
- switch (c) {
- case '\n':
- target += 'n';
- break;
- case '\t':
- target += 't';
- break;
- case '\u000D':
- target += 'r';
- break;
- case '\u0007':
- target += 'a';
- break;
- case '\v':
- target += 'v';
- break;
- case '\b':
- target += 'b';
- break;
- case '\f':
- target += 'f';
- break;
- default:
- //target += _pad(cca.toString(8), 3);break; // Sufficient for UTF-16
- encoded = encodeURIComponent(c);
-
- // 3-length-padded UTF-8 octets
- if ((escHexGrp = percentHex.exec(encoded)) !== null) {
- target += _pad(parseInt(escHexGrp[1], 16).toString(8), 3); // already added a slash above
- }
- while ((escHexGrp = percentHex.exec(encoded)) !== null) {
- target += '\\' + _pad(parseInt(escHexGrp[1], 16).toString(8), 3);
- }
- break;
- }
- } else { // Perform regular backslashed escaping
- target += c;
- }
- } else { // Just add the character unescaped
- target += c;
- }
- }
- return target;
- };
-
- php.addslashes = function (str) {
- // Escapes single quote, double quotes and backslash characters in a string with backslashes
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/addslashes
- // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + improved by: Ates Goral (http://magnetiq.com)
- // + improved by: marrtins
- // + improved by: Nate
- // + improved by: Onno Marsman
- // + input by: Denny Wardhana
- // + improved by: Brett Zamir (http://brett-zamir.me)
- // + improved by: Oskar Larsson Högfeldt (http://oskar-lh.name/)
- // * example 1: \php.addslashes("kevin's birthday");
- // * returns 1: 'kevin\'s birthday'
- return (str + '').replace(/[\\"']/g, '\\$&').replace(/\u0000/g, '\\0');
- };
-
- php.array_chunk = function (input, size) {
- // Split array into chunks
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_chunk
- // + original by: Carlos R. L. Rodrigues (http://www.jsfromhell.com)
- // * example 1: \php.array_chunk(['Kevin', 'van', 'Zonneveld'], 2);
- // * returns 1: {0 : {0: 'Kevin', 1: 'van'} , 1 : {0: 'Zonneveld'}}
- for (var x, i = 0, c = -1, l = input.length, n = []; i < l; i++) {
- (x = i % size) ? n[c][x] = input[i] : n[++c] = [input[i]];
- }
-
- return n;
- };
-
- php.array_combine = function (keys, values) {
- // Creates an array by using the elements of the first parameter as keys and the elements of the second as the corresponding values
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_combine
- // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + improved by: Brett Zamir (http://brett-zamir.me)
- // * example 1: \php.array_combine([0,1,2], ['kevin','van','zonneveld']);
- // * returns 1: {0: 'kevin', 1: 'van', 2: 'zonneveld'}
- var new_array = {},
- keycount = keys && keys.length,
- i = 0;
-
- // input sanitation
- if (typeof keys !== 'object' || typeof values !== 'object' || // Only accept arrays or array-like objects
- typeof keycount !== 'number' || typeof values.length !== 'number' || !keycount) { // Require arrays to have a count
- return false;
- }
-
- // number of elements does not match
- if (keycount != values.length) {
- return false;
- }
-
- for (i = 0; i < keycount; i++) {
- new_array[keys[i]] = values[i];
- }
-
- return new_array;
- };
-
- php.array_diff = function () {
- // Returns the entries of arr1 that have values which are not present in any of the others arguments.
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_diff
- // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + improved by: Sanjoy Roy
- // + revised by: Brett Zamir (http://brett-zamir.me)
- // * example 1: \php.array_diff(['Kevin', 'van', 'Zonneveld'], ['van', 'Zonneveld']);
- // * returns 1: {0:'Kevin'}
- var arr1 = arguments[0],
- retArr = {};
- var k1 = '',
- i = 1,
- k = '',
- arr = {};
-
- arr1keys: for (k1 in arr1) {
- for (i = 1; i < arguments.length; i++) {
- arr = arguments[i];
- for (k in arr) {
- if (arr[k] === arr1[k1]) {
- // If it reaches here, it was found in at least one array, so try next value
- continue arr1keys;
- }
- }
- retArr[k1] = arr1[k1];
- }
- }
-
- return retArr;
- };
-
- php.array_fill = function (start_index, num, mixed_val) {
- // Create an array containing num elements starting with index start_key each initialized to val
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_fill
- // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + improved by: Waldo Malqui Silva
- // * example 1: \php.array_fill(5, 6, 'banana');
- // * returns 1: { 5: 'banana', 6: 'banana', 7: 'banana', 8: 'banana', 9: 'banana', 10: 'banana' }
- var key, tmp_arr = {};
-
- if (!isNaN(start_index) && !isNaN(num)) {
- for (key = 0; key < num; key++) {
- tmp_arr[(key + start_index)] = mixed_val;
- }
- }
-
- return tmp_arr;
- };
-
- php.array_fill_keys = function (keys, value) {
- // Create an array using the elements of the first parameter as keys each initialized to val
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_fill_keys
- // + original by: Brett Zamir (http://brett-zamir.me)
- // + bugfixed by: Brett Zamir (http://brett-zamir.me)
- // * example 1: \php.keys = {'a': 'foo', 2: 5, 3: 10, 4: 'bar'}
- // * example 1: \php.array_fill_keys(keys, 'banana')
- // * returns 1: {"foo": "banana", 5: "banana", 10: "banana", "bar": "banana"}
- var retObj = {},
- key = '';
-
- for (key in keys) {
- retObj[keys[key]] = value;
- }
-
- return retObj;
- };
-
- php.array_filter = function (arr, func) {
- // Filters elements from the array via the callback.
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_filter
- // + original by: Brett Zamir (http://brett-zamir.me)
- // % note 1: Takes a function as an argument, not a function's name
- // * example 1: \php.var odd = function (num) {return (num & 1);};
- // * example 1: \php.array_filter({"a": 1, "b": 2, "c": 3, "d": 4, "e": 5}, odd);
- // * returns 1: {"a": 1, "c": 3, "e": 5}
- // * example 2: \php.var even = function (num) {return (!(num & 1));}
- // * example 2: \php.array_filter([6, 7, 8, 9, 10, 11, 12], even);
- // * returns 2: {0: 6, 2: 8, 4: 10, 6: 12}
- var retObj = {},
- k;
-
- for (k in arr) {
- if (func(arr[k])) {
- retObj[k] = arr[k];
- }
- }
-
- return retObj;
- };
-
- php.array_flip = function (trans) {
- // Return array with key <-> value flipped
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_flip
- // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // * example 1: \php.array_flip( {a: 1, b: 1, c: 2} );
- // * returns 1: {1: 'b', 2: 'c'}
- var key, tmp_ar = {};
-
- for (key in trans) {
- tmp_ar[trans[key]] = key;
- }
-
- return tmp_ar;
- };
-
- php.array_intersect = function () {
- // Returns the entries of arr1 that have values which are present in all the other arguments
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_intersect
- // + original by: Brett Zamir (http://brett-zamir.me)
- // % note 1: These only output associative arrays (would need to be
- // % note 1: all numeric and counting from zero to be numeric)
- // * example 1: $array1 = {'a' : 'green', 0:'red', 1: 'blue'};
- // * example 1: $array2 = {'b' : 'green', 0:'yellow', 1:'red'};
- // * example 1: $array3 = ['green', 'red'];
- // * example 1: $result = array_intersect($array1, $array2, $array3);
- // * returns 1: {0: 'red', a: 'green'}
- var arr1 = arguments[0],
- retArr = {};
- var k1 = '',
- arr = {},
- i = 0,
- k = '';
-
- arr1keys: for (k1 in arr1) {
- arrs: for (i = 1; i < arguments.length; i++) {
- arr = arguments[i];
- for (k in arr) {
- if (arr[k] === arr1[k1]) {
- if (i === arguments.length - 1) {
- retArr[k1] = arr1[k1];
- }
- // If the innermost loop always leads at least once to an equal value, continue the loop until done
- continue arrs;
- }
- }
- // If it reaches here, it wasn't found in at least one array, so try next value
- continue arr1keys;
- }
- }
-
- return retArr;
- };
-
- php.array_key_exists = function (key, search) {
- // Checks if the given key or index exists in the array
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_key_exists
- // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + improved by: Felix Geisendoerfer (http://www.debuggable.com/felix)
- // * example 1: \php.array_key_exists('kevin', {'kevin': 'van Zonneveld'});
- // * returns 1: true
- // input sanitation
- if (!search || (search.constructor !== Array && search.constructor !== Object)) {
- return false;
- }
-
- return key in search;
- };
-
- php.array_keys = function (input, search_value, argStrict) {
- // Return just the keys from the input array, optionally only for the specified search_value
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_keys
- // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + input by: Brett Zamir (http://brett-zamir.me)
- // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + improved by: jd
- // + improved by: Brett Zamir (http://brett-zamir.me)
- // * example 1: \php.array_keys( {firstname: 'Kevin', surname: 'van Zonneveld'} );
- // * returns 1: {0: 'firstname', 1: 'surname'}
- var search = typeof search_value !== 'undefined',
- tmp_arr = [],
- strict = !!argStrict,
- include = true,
- key = '';
-
- for (key in input) {
- if (input.hasOwnProperty(key)) {
- include = true;
- if (search) {
- if (strict && input[key] !== search_value) {
- include = false;
- }
- else if (input[key] != search_value) {
- include = false;
- }
- }
-
- if (include) {
- tmp_arr[tmp_arr.length] = key;
- }
- }
- }
-
- return tmp_arr;
- };
-
- php.array_map = function (callback) {
- // Applies the callback to the elements in given arrays.
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_map
- // + original by: Andrea Giammarchi (http://webreflection.blogspot.com)
- // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + improved by: Brett Zamir (http://brett-zamir.me)
- // % note 1: Takes a function as an argument, not a function's name
- // % note 2: If the callback is a string, it can only work if the function name is in the global context
- // * example 1: \php.array_map( function (a){return (a * a * a)}, [1, 2, 3, 4, 5] );
- // * returns 1: [ 1, 8, 27, 64, 125 ]
- var argc = arguments.length,
- argv = arguments;
- var j = argv[1].length,
- i = 0,
- k = 1,
- m = 0;
- var tmp = [],
- tmp_ar = [];
-
- while (i < j) {
- while (k < argc) {
- tmp[m++] = argv[k++][i];
- }
-
- m = 0;
- k = 1;
-
- if (callback) {
- if (typeof callback === 'string') {
- callback = this.window[callback];
- }
- tmp_ar[i++] = callback.apply(null, tmp);
- } else {
- tmp_ar[i++] = tmp;
- }
-
- tmp = [];
- }
-
- return tmp_ar;
- };
-
- php.array_merge = function () {
- // Merges elements from passed arrays into one array
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_merge
- // + original by: Brett Zamir (http://brett-zamir.me)
- // + bugfixed by: Nate
- // + input by: josh
- // + bugfixed by: Brett Zamir (http://brett-zamir.me)
- // * example 1: \php.arr1 = {"color": "red", 0: 2, 1: 4}
- // * example 1: \php.arr2 = {0: "a", 1: "b", "color": "green", "shape": "trapezoid", 2: 4}
- // * example 1: \php.array_merge(arr1, arr2)
- // * returns 1: {"color": "green", 0: 2, 1: 4, 2: "a", 3: "b", "shape": "trapezoid", 4: 4}
- // * example 2: \php.arr1 = []
- // * example 2: \php.arr2 = {1: "data"}
- // * example 2: \php.array_merge(arr1, arr2)
- // * returns 2: {0: "data"}
- var args = Array.prototype.slice.call(arguments),
- retObj = {},
- k, j = 0,
- i = 0,
- retArr = true;
-
- for (i = 0; i < args.length; i++) {
- if (!(args[i] instanceof Array)) {
- retArr = false;
- break;
- }
- }
-
- if (retArr) {
- retArr = [];
- for (i = 0; i < args.length; i++) {
- retArr = retArr.concat(args[i]);
- }
- return retArr;
- }
- var ct = 0;
-
- for (i = 0, ct = 0; i < args.length; i++) {
- if (args[i] instanceof Array) {
- for (j = 0; j < args[i].length; j++) {
- retObj[ct++] = args[i][j];
- }
- } else {
- for (k in args[i]) {
- if (args[i].hasOwnProperty(k)) {
- if (parseInt(k, 10) + '' === k) {
- retObj[ct++] = args[i][k];
- } else {
- retObj[k] = args[i][k];
- }
- }
- }
- }
- }
- return retObj;
- };
-
- php.array_merge_recursive = function (arr1, arr2) {
- // Recursively merges elements from passed arrays into one array
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_merge_recursive
- // + original by: Subhasis Deb
- // + input by: Brett Zamir (http://brett-zamir.me)
- // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // - depends on: array_merge
- // * example 1: \php.arr1 = {'color': {'favourite': 'read'}, 0: 5}
- // * example 1: \php.arr2 = {0: 10, 'color': {'favorite': 'green', 0: 'blue'}}
- // * example 1: \php.array_merge_recursive(arr1, arr2)
- // * returns 1: {'color': {'favorite': {0: 'red', 1: 'green'}, 0: 'blue'}, 1: 5, 1: 10}
- var idx = '';
-
- if ((arr1 && (arr1 instanceof Array)) && (arr2 && (arr2 instanceof Array))) {
- for (idx in arr2) {
- arr1.push(arr2[idx]);
- }
- } else if ((arr1 && (arr1 instanceof Object)) && (arr2 && (arr2 instanceof Object))) {
- for (idx in arr2) {
- if (idx in arr1) {
- if (typeof arr1[idx] == 'object' && typeof arr2 == 'object') {
- arr1[idx] = this.array_merge(arr1[idx], arr2[idx]);
- } else {
- arr1[idx] = arr2[idx];
- }
- } else {
- arr1[idx] = arr2[idx];
- }
- }
- }
-
- return arr1;
- };
-
- php.array_pop = function (inputArr) {
- // Pops an element off the end of the array
- //
- // version: 1103.1210
- // discuss at: http://phpjs.org/functions/array_pop
- // + original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + input by: Brett Zamir (http://brett-zamir.me)
- // + bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
- // + bugfixed by: Brett Zamir (http://brett-zamir.me)
- // + input by: Theriault
- // % note 1: While IE (and other browsers) support iterating an object's
- // % note 1: own properties in order, if one attempts to add back properties
- // % note 1: in IE, they may end up in their former position due to their position
- // % note 1: being retained. So use of this function with "associative arrays"
- // % note 1: (objects) may lead to unexpected behavior in an IE environment if
- // % note 1: you add back properties with the same keys that you removed
-