code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
<?php define('SHCMS_ENGINE',true); include_once('../engine/system/core.php'); $templates->template('SHCMS: Система'); echo engine::admin($users['group']); if($users['group'] == 15) { header('Location: ../admin.php'); exit; }
shcms5/shcms_engine
admin/index.php
PHP
gpl-2.0
249
#include "CounterpartyTypeDelegate.h" CounterpartyTypeDelegate::CounterpartyTypeDelegate(QObject *parent) : QSqlRelationalDelegate(parent) { } void CounterpartyTypeDelegate::setModelData(QWidget *editor, QAbstractItemModel *model, const QModelIndex &index) const { QComboBox *comboBox = dynamic_cast<QComboBox*>(editor); if(comboBox && (comboBox->objectName().compare("comboBoxType") == 0) && (comboBox->count() > 0)) { const int myCompany = ( (comboBox->count() > 1) ? 1 : 0) + 1;//skips my company and adds 1 because SQL starts from 1 model->setData(index, comboBox->currentIndex() + myCompany, Qt::EditRole); } else { QSqlRelationalDelegate::setModelData(editor, model, index); } }
tkQCompany/qcompany
qfaktury/src/ui/CounterpartyTypeDelegate.cpp
C++
gpl-2.0
832
<?php /** * File containing the LogicalNot Criterion parser class * * @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved. * @license http://ez.no/licenses/gnu_gpl GNU General Public License v2.0 * @version 2012.9 */ namespace eZ\Publish\Core\REST\Server\Input\Parser\Criterion; use eZ\Publish\Core\REST\Server\Input\Parser\Criterion as CriterionParser; use eZ\Publish\Core\REST\Common\Input\ParsingDispatcher; use eZ\Publish\Core\REST\Common\UrlHandler; use eZ\Publish\Core\REST\Common\Exceptions; use eZ\Publish\API\Repository\Values\Content\Query\Criterion\LogicalNot as LogicalNotCriterion; /** * Parser for LogicalNot Criterion */ class LogicalNot extends CriterionParser { /** * Parses input structure to a Criterion object * * @param array $data * @param \eZ\Publish\Core\REST\Common\Input\ParsingDispatcher $parsingDispatcher * * @throws \eZ\Publish\Core\REST\Common\Exceptions\Parser * @return \eZ\Publish\API\Repository\Values\Content\Query\Criterion\LogicalNot */ public function parse( array $data, ParsingDispatcher $parsingDispatcher ) { if ( !array_key_exists( "NOT", $data ) && !is_array( $data["NOT"] ) ) { throw new Exceptions\Parser( "Invalid <NOT> format" ); } if ( count( $data['NOT'] ) > 1 ) { throw new Exceptions\Parser( "NOT element can only contain one subitem" ); } list( $criterionName, $criterionData ) = each( $data['NOT'] ); $criteria = $this->dispatchCriterion( $criterionName, $criterionData, $parsingDispatcher ); return new LogicalNotCriterion( $criteria ); } }
davidrousse/ezpuplish
vendor/ezsystems/ezpublish/eZ/Publish/Core/REST/Server/Input/Parser/Criterion/LogicalNot.php
PHP
gpl-2.0
1,678
#include "fast.h" #include <fstream> #include <strstream> using namespace std; AikSaurusFAST::AikSaurusFAST() { ifstream fin("thesaurus.in"); string index, words; while(fin >> index >> words) { vector<string> foo; for(unsigned int i = 0;i < words.size();++i) { if (words[i] == ',') words[i] = ' '; } istrstream ss(words.c_str()); string str; while(ss >> str) foo.push_back(str); d_data.insert(make_pair(index, foo)); } } const vector<string>& AikSaurusFAST::getSynonyms(const string& word) { map<string, vector<string> >::iterator thing = d_data.find(word); if (thing == d_data.end()) { return d_null; } else { return thing->second; } }
AbiWord/aiksaurus
data/0.12-dev/gen_pms/fast.cpp
C++
gpl-2.0
810
package com.ucan.app.common.utils; import java.io.File; import android.content.ContentValues; import android.content.Context; import android.content.Intent; import android.net.Uri; import android.provider.MediaStore; import android.text.TextUtils; public class ExportImgUtil { private static final String TAG = "UCAN.ExportImgUtil"; public static void refreshingMediaScanner(Context context , String pathName) { if(TextUtils.isEmpty(pathName)) { return ; } File dir = new File(FileAccessor.EXPORT_DIR , pathName); // exportToGallery(context,dir.getAbsolutePath()); Uri uri = Uri.fromFile(dir); Intent action = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE ,uri); context.sendBroadcast(action); LogUtil.d(TAG , String.format("refreshing media scanner on path=%s" ,new Object[]{pathName})); } private static Uri exportToGallery(Context context ,String filename) { // Save the name and description of a video in a ContentValues map. final ContentValues values = new ContentValues(2); values.put(MediaStore.Video.Media.MIME_TYPE, "image/jpeg"); values.put(MediaStore.Video.Media.DATA, filename); // Add a new record (identified by uri) final Uri uri = context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); return uri; } }
sosoyiyi/ucan
src/com/ucan/app/common/utils/ExportImgUtil.java
Java
gpl-2.0
1,432
<?php /** * @file * Drupal site-specific configuration file. * * IMPORTANT NOTE: * This file may have been set to read-only by the Drupal installation program. * If you make changes to this file, be sure to protect it again after making * your modifications. Failure to remove write permissions to this file is a * security risk. * * The configuration file to be loaded is based upon the rules below. However * if the multisite aliasing file named sites/sites.php is present, it will be * loaded, and the aliases in the array $sites will override the default * directory rules below. See sites/example.sites.php for more information about * aliases. * * The configuration directory will be discovered by stripping the website's * hostname from left to right and pathname from right to left. The first * configuration file found will be used and any others will be ignored. If no * other configuration file is found then the default configuration file at * 'sites/default' will be used. * * For example, for a fictitious site installed at * http://www.drupal.org:8080/mysite/test/, the 'settings.php' file is searched * for in the following directories: * * - sites/8080.www.drupal.org.mysite.test * - sites/www.drupal.org.mysite.test * - sites/drupal.org.mysite.test * - sites/org.mysite.test * * - sites/8080.www.drupal.org.mysite * - sites/www.drupal.org.mysite * - sites/drupal.org.mysite * - sites/org.mysite * * - sites/8080.www.drupal.org * - sites/www.drupal.org * - sites/drupal.org * - sites/org * * - sites/default * * Note that if you are installing on a non-standard port number, prefix the * hostname with that number. For example, * http://www.drupal.org:8080/mysite/test/ could be loaded from * sites/8080.www.drupal.org.mysite.test/. * * @see example.sites.php * @see conf_path() */ /** * Database settings: * * The $databases array specifies the database connection or * connections that Drupal may use. Drupal is able to connect * to multiple databases, including multiple types of databases, * during the same request. * * Each database connection is specified as an array of settings, * similar to the following: * @code * array( * 'driver' => 'mysql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'port' => 3306, * 'prefix' => 'myprefix_', * 'collation' => 'utf8_general_ci', * ); * @endcode * * The "driver" property indicates what Drupal database driver the * connection should use. This is usually the same as the name of the * database type, such as mysql or sqlite, but not always. The other * properties will vary depending on the driver. For SQLite, you must * specify a database file name in a directory that is writable by the * webserver. For most other drivers, you must specify a * username, password, host, and database name. * * Transaction support is enabled by default for all drivers that support it, * including MySQL. To explicitly disable it, set the 'transactions' key to * FALSE. * Note that some configurations of MySQL, such as the MyISAM engine, don't * support it and will proceed silently even if enabled. If you experience * transaction related crashes with such configuration, set the 'transactions' * key to FALSE. * * For each database, you may optionally specify multiple "target" databases. * A target database allows Drupal to try to send certain queries to a * different database if it can but fall back to the default connection if not. * That is useful for master/slave replication, as Drupal may try to connect * to a slave server when appropriate and if one is not available will simply * fall back to the single master server. * * The general format for the $databases array is as follows: * @code * $databases['default']['default'] = $info_array; * $databases['default']['slave'][] = $info_array; * $databases['default']['slave'][] = $info_array; * $databases['extra']['default'] = $info_array; * @endcode * * In the above example, $info_array is an array of settings described above. * The first line sets a "default" database that has one master database * (the second level default). The second and third lines create an array * of potential slave databases. Drupal will select one at random for a given * request as needed. The fourth line creates a new database with a name of * "extra". * * For a single database configuration, the following is sufficient: * @code * $databases['default']['default'] = array( * 'driver' => 'mysql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'prefix' => 'main_', * 'collation' => 'utf8_general_ci', * ); * @endcode * * For handling full UTF-8 in MySQL, including multi-byte characters such as * emojis, Asian symbols, and mathematical symbols, you may set the collation * and charset to "utf8mb4" prior to running install.php: * @code * $databases['default']['default'] = array( * 'driver' => 'mysql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'charset' => 'utf8mb4', * 'collation' => 'utf8mb4_general_ci', * ); * @endcode * When using this setting on an existing installation, ensure that all existing * tables have been converted to the utf8mb4 charset, for example by using the * utf8mb4_convert contributed project available at * https://www.drupal.org/project/utf8mb4_convert, so as to prevent mixing data * with different charsets. * Note this should only be used when all of the following conditions are met: * - In order to allow for large indexes, MySQL must be set up with the * following my.cnf settings: * [mysqld] * innodb_large_prefix=true * innodb_file_format=barracuda * innodb_file_per_table=true * These settings are available as of MySQL 5.5.14, and are defaults in * MySQL 5.7.7 and up. * - The PHP MySQL driver must support the utf8mb4 charset (libmysqlclient * 5.5.3 and up, as well as mysqlnd 5.0.9 and up). * - The MySQL server must support the utf8mb4 charset (5.5.3 and up). * * You can optionally set prefixes for some or all database table names * by using the 'prefix' setting. If a prefix is specified, the table * name will be prepended with its value. Be sure to use valid database * characters only, usually alphanumeric and underscore. If no prefixes * are desired, leave it as an empty string ''. * * To have all database names prefixed, set 'prefix' as a string: * @code * 'prefix' => 'main_', * @endcode * To provide prefixes for specific tables, set 'prefix' as an array. * The array's keys are the table names and the values are the prefixes. * The 'default' element is mandatory and holds the prefix for any tables * not specified elsewhere in the array. Example: * @code * 'prefix' => array( * 'default' => 'main_', * 'users' => 'shared_', * 'sessions' => 'shared_', * 'role' => 'shared_', * 'authmap' => 'shared_', * ), * @endcode * You can also use a reference to a schema/database as a prefix. This may be * useful if your Drupal installation exists in a schema that is not the default * or you want to access several databases from the same code base at the same * time. * Example: * @code * 'prefix' => array( * 'default' => 'main.', * 'users' => 'shared.', * 'sessions' => 'shared.', * 'role' => 'shared.', * 'authmap' => 'shared.', * ); * @endcode * NOTE: MySQL and SQLite's definition of a schema is a database. * * Advanced users can add or override initial commands to execute when * connecting to the database server, as well as PDO connection settings. For * example, to enable MySQL SELECT queries to exceed the max_join_size system * variable, and to reduce the database connection timeout to 5 seconds: * * @code * $databases['default']['default'] = array( * 'init_commands' => array( * 'big_selects' => 'SET SQL_BIG_SELECTS=1', * ), * 'pdo' => array( * PDO::ATTR_TIMEOUT => 5, * ), * ); * @endcode * * WARNING: These defaults are designed for database portability. Changing them * may cause unexpected behavior, including potential data loss. * * @see DatabaseConnection_mysql::__construct * @see DatabaseConnection_pgsql::__construct * @see DatabaseConnection_sqlite::__construct * * Database configuration format: * @code * $databases['default']['default'] = array( * 'driver' => 'mysql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'prefix' => '', * ); * $databases['default']['default'] = array( * 'driver' => 'pgsql', * 'database' => 'databasename', * 'username' => 'username', * 'password' => 'password', * 'host' => 'localhost', * 'prefix' => '', * ); * $databases['default']['default'] = array( * 'driver' => 'sqlite', * 'database' => '/path/to/databasefilename', * ); * @endcode */ $databases = array ( 'default' => array ( 'default' => array ( 'database' => 'conext', 'username' => 'conext', 'password' => '@uhgkj&*(k', 'host' => 'localhost', 'port' => '', 'driver' => 'mysql', 'prefix' => '', ), ), ); /** * Access control for update.php script. * * If you are updating your Drupal installation using the update.php script but * are not logged in using either an account with the "Administer software * updates" permission or the site maintenance account (the account that was * created during installation), you will need to modify the access check * statement below. Change the FALSE to a TRUE to disable the access check. * After finishing the upgrade, be sure to open this file again and change the * TRUE back to a FALSE! */ $update_free_access = FALSE; /** * Salt for one-time login links and cancel links, form tokens, etc. * * This variable will be set to a random value by the installer. All one-time * login links will be invalidated if the value is changed. Note that if your * site is deployed on a cluster of web servers, you must ensure that this * variable has the same value on each server. If this variable is empty, a hash * of the serialized database credentials will be used as a fallback salt. * * For enhanced security, you may set this variable to a value using the * contents of a file outside your docroot that is never saved together * with any backups of your Drupal files and database. * * Example: * $drupal_hash_salt = file_get_contents('/home/example/salt.txt'); * */ $drupal_hash_salt = 'ed3gSIcBN--3nmq-Ydnmr8DDV5jpBgCG96pSgd4WP1s'; /** * Base URL (optional). * * If Drupal is generating incorrect URLs on your site, which could * be in HTML headers (links to CSS and JS files) or visible links on pages * (such as in menus), uncomment the Base URL statement below (remove the * leading hash sign) and fill in the absolute URL to your Drupal installation. * * You might also want to force users to use a given domain. * See the .htaccess file for more information. * * Examples: * $base_url = 'http://www.example.com'; * $base_url = 'http://www.example.com:8888'; * $base_url = 'http://www.example.com/drupal'; * $base_url = 'https://www.example.com:8888/drupal'; * * It is not allowed to have a trailing slash; Drupal will add it * for you. */ # $base_url = 'http://www.example.com'; // NO trailing slash! /** * PHP settings: * * To see what PHP settings are possible, including whether they can be set at * runtime (by using ini_set()), read the PHP documentation: * http://www.php.net/manual/ini.list.php * See drupal_environment_initialize() in includes/bootstrap.inc for required * runtime settings and the .htaccess file for non-runtime settings. Settings * defined there should not be duplicated here so as to avoid conflict issues. */ /** * Some distributions of Linux (most notably Debian) ship their PHP * installations with garbage collection (gc) disabled. Since Drupal depends on * PHP's garbage collection for clearing sessions, ensure that garbage * collection occurs by using the most common settings. */ ini_set('session.gc_probability', 1); ini_set('session.gc_divisor', 100); /** * Set session lifetime (in seconds), i.e. the time from the user's last visit * to the active session may be deleted by the session garbage collector. When * a session is deleted, authenticated users are logged out, and the contents * of the user's $_SESSION variable is discarded. */ ini_set('session.gc_maxlifetime', 200000); /** * Set session cookie lifetime (in seconds), i.e. the time from the session is * created to the cookie expires, i.e. when the browser is expected to discard * the cookie. The value 0 means "until the browser is closed". */ ini_set('session.cookie_lifetime', 2000000); /** * If you encounter a situation where users post a large amount of text, and * the result is stripped out upon viewing but can still be edited, Drupal's * output filter may not have sufficient memory to process it. If you * experience this issue, you may wish to uncomment the following two lines * and increase the limits of these variables. For more information, see * http://php.net/manual/pcre.configuration.php. */ # ini_set('pcre.backtrack_limit', 200000); # ini_set('pcre.recursion_limit', 200000); /** * Drupal automatically generates a unique session cookie name for each site * based on its full domain name. If you have multiple domains pointing at the * same Drupal site, you can either redirect them all to a single domain (see * comment in .htaccess), or uncomment the line below and specify their shared * base domain. Doing so assures that users remain logged in as they cross * between your various domains. Make sure to always start the $cookie_domain * with a leading dot, as per RFC 2109. */ # $cookie_domain = '.example.com'; /** * Variable overrides: * * To override specific entries in the 'variable' table for this site, * set them here. You usually don't need to use this feature. This is * useful in a configuration file for a vhost or directory, rather than * the default settings.php. Any configuration setting from the 'variable' * table can be given a new value. Note that any values you provide in * these variable overrides will not be modifiable from the Drupal * administration interface. * * The following overrides are examples: * - site_name: Defines the site's name. * - theme_default: Defines the default theme for this site. * - anonymous: Defines the human-readable name of anonymous users. * Remove the leading hash signs to enable. */ # $conf['site_name'] = 'My Drupal site'; # $conf['theme_default'] = 'garland'; # $conf['anonymous'] = 'Visitor'; /** * A custom theme can be set for the offline page. This applies when the site * is explicitly set to maintenance mode through the administration page or when * the database is inactive due to an error. It can be set through the * 'maintenance_theme' key. The template file should also be copied into the * theme. It is located inside 'modules/system/maintenance-page.tpl.php'. * Note: This setting does not apply to installation and update pages. */ # $conf['maintenance_theme'] = 'bartik'; /** * Reverse Proxy Configuration: * * Reverse proxy servers are often used to enhance the performance * of heavily visited sites and may also provide other site caching, * security, or encryption benefits. In an environment where Drupal * is behind a reverse proxy, the real IP address of the client should * be determined such that the correct client IP address is available * to Drupal's logging, statistics, and access management systems. In * the most simple scenario, the proxy server will add an * X-Forwarded-For header to the request that contains the client IP * address. However, HTTP headers are vulnerable to spoofing, where a * malicious client could bypass restrictions by setting the * X-Forwarded-For header directly. Therefore, Drupal's proxy * configuration requires the IP addresses of all remote proxies to be * specified in $conf['reverse_proxy_addresses'] to work correctly. * * Enable this setting to get Drupal to determine the client IP from * the X-Forwarded-For header (or $conf['reverse_proxy_header'] if set). * If you are unsure about this setting, do not have a reverse proxy, * or Drupal operates in a shared hosting environment, this setting * should remain commented out. * * In order for this setting to be used you must specify every possible * reverse proxy IP address in $conf['reverse_proxy_addresses']. * If a complete list of reverse proxies is not available in your * environment (for example, if you use a CDN) you may set the * $_SERVER['REMOTE_ADDR'] variable directly in settings.php. * Be aware, however, that it is likely that this would allow IP * address spoofing unless more advanced precautions are taken. */ # $conf['reverse_proxy'] = TRUE; /** * Specify every reverse proxy IP address in your environment. * This setting is required if $conf['reverse_proxy'] is TRUE. */ # $conf['reverse_proxy_addresses'] = array('a.b.c.d', ...); /** * Set this value if your proxy server sends the client IP in a header * other than X-Forwarded-For. */ # $conf['reverse_proxy_header'] = 'HTTP_X_CLUSTER_CLIENT_IP'; /** * Page caching: * * By default, Drupal sends a "Vary: Cookie" HTTP header for anonymous page * views. This tells a HTTP proxy that it may return a page from its local * cache without contacting the web server, if the user sends the same Cookie * header as the user who originally requested the cached page. Without "Vary: * Cookie", authenticated users would also be served the anonymous page from * the cache. If the site has mostly anonymous users except a few known * editors/administrators, the Vary header can be omitted. This allows for * better caching in HTTP proxies (including reverse proxies), i.e. even if * clients send different cookies, they still get content served from the cache. * However, authenticated users should access the site directly (i.e. not use an * HTTP proxy, and bypass the reverse proxy if one is used) in order to avoid * getting cached pages from the proxy. */ # $conf['omit_vary_cookie'] = TRUE; /** * CSS/JS aggregated file gzip compression: * * By default, when CSS or JS aggregation and clean URLs are enabled Drupal will * store a gzip compressed (.gz) copy of the aggregated files. If this file is * available then rewrite rules in the default .htaccess file will serve these * files to browsers that accept gzip encoded content. This allows pages to load * faster for these users and has minimal impact on server load. If you are * using a webserver other than Apache httpd, or a caching reverse proxy that is * configured to cache and compress these files itself you may want to uncomment * one or both of the below lines, which will prevent gzip files being stored. */ # $conf['css_gzip_compression'] = FALSE; # $conf['js_gzip_compression'] = FALSE; /** * Block caching: * * Block caching may not be compatible with node access modules depending on * how the original block cache policy is defined by the module that provides * the block. By default, Drupal therefore disables block caching when one or * more modules implement hook_node_grants(). If you consider block caching to * be safe on your site and want to bypass this restriction, uncomment the line * below. */ # $conf['block_cache_bypass_node_grants'] = TRUE; /** * String overrides: * * To override specific strings on your site with or without enabling the Locale * module, add an entry to this list. This functionality allows you to change * a small number of your site's default English language interface strings. * * Remove the leading hash signs to enable. */ # $conf['locale_custom_strings_en'][''] = array( # 'forum' => 'Discussion board', # '@count min' => '@count minutes', # ); /** * * IP blocking: * * To bypass database queries for denied IP addresses, use this setting. * Drupal queries the {blocked_ips} table by default on every page request * for both authenticated and anonymous users. This allows the system to * block IP addresses from within the administrative interface and before any * modules are loaded. However on high traffic websites you may want to avoid * this query, allowing you to bypass database access altogether for anonymous * users under certain caching configurations. * * If using this setting, you will need to add back any IP addresses which * you may have blocked via the administrative interface. Each element of this * array represents a blocked IP address. Uncommenting the array and leaving it * empty will have the effect of disabling IP blocking on your site. * * Remove the leading hash signs to enable. */ # $conf['blocked_ips'] = array( # 'a.b.c.d', # ); /** * Fast 404 pages: * * Drupal can generate fully themed 404 pages. However, some of these responses * are for images or other resource files that are not displayed to the user. * This can waste bandwidth, and also generate server load. * * The options below return a simple, fast 404 page for URLs matching a * specific pattern: * - 404_fast_paths_exclude: A regular expression to match paths to exclude, * such as images generated by image styles, or dynamically-resized images. * The default pattern provided below also excludes the private file system. * If you need to add more paths, you can add '|path' to the expression. * - 404_fast_paths: A regular expression to match paths that should return a * simple 404 page, rather than the fully themed 404 page. If you don't have * any aliases ending in htm or html you can add '|s?html?' to the expression. * - 404_fast_html: The html to return for simple 404 pages. * * Add leading hash signs if you would like to disable this functionality. */ $conf['404_fast_paths_exclude'] = '/\/(?:styles)|(?:system\/files)\//'; $conf['404_fast_paths'] = '/\.(?:txt|png|gif|jpe?g|css|js|ico|swf|flv|cgi|bat|pl|dll|exe|asp)$/i'; $conf['404_fast_html'] = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML+RDFa 1.0//EN" "http://www.w3.org/MarkUp/DTD/xhtml-rdfa-1.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><title>404 Not Found</title></head><body><h1>Not Found</h1><p>The requested URL "@path" was not found on this server.</p></body></html>'; /** * By default the page request process will return a fast 404 page for missing * files if they match the regular expression set in '404_fast_paths' and not * '404_fast_paths_exclude' above. 404 errors will simultaneously be logged in * the Drupal system log. * * You can choose to return a fast 404 page earlier for missing pages (as soon * as settings.php is loaded) by uncommenting the line below. This speeds up * server response time when loading 404 error pages and prevents the 404 error * from being logged in the Drupal system log. In order to prevent valid pages * such as image styles and other generated content that may match the * '404_fast_paths' regular expression from returning 404 errors, it is * necessary to add them to the '404_fast_paths_exclude' regular expression * above. Make sure that you understand the effects of this feature before * uncommenting the line below. */ # drupal_fast_404(); /** * External access proxy settings: * * If your site must access the Internet via a web proxy then you can enter * the proxy settings here. Currently only basic authentication is supported * by using the username and password variables. The proxy_user_agent variable * can be set to NULL for proxies that require no User-Agent header or to a * non-empty string for proxies that limit requests to a specific agent. The * proxy_exceptions variable is an array of host names to be accessed directly, * not via proxy. */ # $conf['proxy_server'] = ''; # $conf['proxy_port'] = 8080; # $conf['proxy_username'] = ''; # $conf['proxy_password'] = ''; # $conf['proxy_user_agent'] = ''; # $conf['proxy_exceptions'] = array('127.0.0.1', 'localhost'); /** * Authorized file system operations: * * The Update manager module included with Drupal provides a mechanism for * site administrators to securely install missing updates for the site * directly through the web user interface. On securely-configured servers, * the Update manager will require the administrator to provide SSH or FTP * credentials before allowing the installation to proceed; this allows the * site to update the new files as the user who owns all the Drupal files, * instead of as the user the webserver is running as. On servers where the * webserver user is itself the owner of the Drupal files, the administrator * will not be prompted for SSH or FTP credentials (note that these server * setups are common on shared hosting, but are inherently insecure). * * Some sites might wish to disable the above functionality, and only update * the code directly via SSH or FTP themselves. This setting completely * disables all functionality related to these authorized file operations. * * @see http://drupal.org/node/244924 * * Remove the leading hash signs to disable. */ # $conf['allow_authorize_operations'] = FALSE; /** * Theme debugging: * * When debugging is enabled: * - The markup of each template is surrounded by HTML comments that contain * theming information, such as template file name suggestions. * - Note that this debugging markup will cause automated tests that directly * check rendered HTML to fail. * * For more information about debugging theme templates, see * https://www.drupal.org/node/223440#theme-debug. * * Not recommended in production environments. * * Remove the leading hash sign to enable. */ # $conf['theme_debug'] = TRUE; /** * CSS identifier double underscores allowance: * * To allow CSS identifiers to contain double underscores (.example__selector) * for Drupal's BEM-style naming standards, uncomment the line below. * Note that if you change this value in existing sites, existing page styles * may be broken. * * @see drupal_clean_css_identifier() */ # $conf['allow_css_double_underscores'] = TRUE;
triharyono333/conext
sites/all/libraries/settings.php
PHP
gpl-2.0
26,555
package fr.npellegrin.xebia.mower.exceptions; /** * Represents and exception thrown by the parser. */ public class ParserException extends Exception { private static final long serialVersionUID = -5690949595972473232L; public ParserException() { super(); } public ParserException(final String message, final Throwable cause) { super(message, cause); } public ParserException(final String message) { super(message); } public ParserException(final Throwable cause) { super(cause); } }
npellegrin/MowItNow
src/main/java/fr/npellegrin/xebia/mower/exceptions/ParserException.java
Java
gpl-2.0
508
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("ASPNetWebApi")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ASPNetWebApi")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ac7bacbb-db15-4804-9ca1-ec4ee07874b9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Revision and Build Numbers // by using the '*' as shown below: [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
mesutozturk/ASP-Restfull-Api-Service
ASPNetWebApi/ASPNetWebApi/Properties/AssemblyInfo.cs
C#
gpl-2.0
1,360
<?php /** * Created by PhpStorm. * User: vlad * Date: 27.01.15 * Time: 19:09 */ namespace ModelFramework\FormService\FormField\Strategy; use ModelFramework\FieldTypesService\FieldType\FieldTypeAwareTrait; use ModelFramework\FieldTypesService\FieldType\FieldTypeInterface; use ModelFramework\FormService\FormField\FieldConfig\FieldConfig; use ModelFramework\FormService\FormField\FieldConfig\FieldConfigInterface; use ModelFramework\FormService\FormField\FieldConfig\FieldConfigAwareTrait; use ModelFramework\Utility\Arr; class EmailStrategy implements FormFieldStrategyInterface { use FieldConfigAwareTrait, FieldTypeAwareTrait; /** * @var string */ private $name = ''; /** * @param string $name * * @return $this */ public function setName($name) { $this->name = $name; return $this; } /** * @return string */ public function getName() { return $this->name; } /** * @return string */ public function getType() { return $this->getFieldConfigVerify()->type; } /** * @param array $aConfig * * @return $this * @throws \Exception */ public function parseFieldConfigArray(array $aConfig) { $fieldConfig = new FieldConfig(); $fieldConfig->exchangeArray($aConfig); return $fieldConfig; } /** * @return $this */ public function parse() { return $this->s($this->getFieldConfigVerify(), $this->getFieldTypeVerify()); } /** * @return $this */ public function init() { } public function s( FieldConfigInterface $conf, FieldTypeInterface $_fieldType ) { $_fieldSets = []; $_joins = []; $_fieldType->label = isset($conf->label) ? $conf->label : ucfirst($this->getName()); if (isset($conf->group)) { $_fieldSets[$conf->group]['elements'][$this->getName()] = $_fieldType->label; $_fieldType->group = $conf->group; } //FIXME this does not work for lookup fields, only for source fields. Need update. $_fieldType->default = isset($conf->default) ? $conf->default : ''; $_fieldType->source = $this->getName(); $_fields = [$this->getName() => $_fieldType->toArray()]; $_labels = [$this->getName() => $_fieldType->label]; $_fields = Arr::merge($_fields, [ $this->getName() . '_id' => [ 'type' => 'field', 'fieldtype' => 'source', 'datatype' => 'string', 'default' => 0, 'label' => '', // 'source' => $this->getName(), ] ]); $result = [ 'labels' => $_labels, 'fields' => $_fields, 'joins' => $_joins, 'fieldsets' => $_fieldSets, ]; return $result; } }
modelframework/modelframework
src/ModelFramework/FormService/FormField/Strategy/EmailStrategy.php
PHP
gpl-2.0
3,086
<?php class Jaundies_Directory_Manager { /** * Singleton Instance */ private static $_instance = null; protected $_directories = array(); private function __construct() { self::$_instance = $this; } public static function getInstance() { if (self::$_instance === null) new Jaundies_Directory_Manager; return self::$_instance; } public function directoryExists($dir) { return isset($this->_directories[$dir]); } public function __get($dir) { return $this->getDirectory($dir); } public function __set($key, $dir) { $this->addDirectory($key,$dir); } public function addDirectory($key, Jaundies_Directory_Interface $dir) { $this->_directories[$key] = $dir; } public function get($dir, $user = null) { if ($user === null) return $this->getDirectory($dir); else return $this->getUser($dir,$user); } public function getUser($dir, $user) { if ($user instanceof Jaundies_User) $id = $user->getId(); else $id = $user; return $this->getDirectory($dir)->getUser($id); } public function getDirectory($dir) { if (!$this->directoryExists($dir)) throw new Jaundies_Exception('Directory ' .$dir . 'does not exist.'); return $this->_directories[$dir]; } }
Jaundies/Jaundies-Game-Framework
src/Directory/Manager.php
PHP
gpl-2.0
1,232
<?php /** * The plugin bootstrap file * * This file is read by WordPress to generate the plugin information in the plugin * admin area. This file also includes all of the dependencies used by the plugin, * registers the activation and deactivation functions, and defines a function * that starts the plugin. * * @link http://www.askmetisa.com/ * @since 1.0.0 * @package Metisa * * @wordpress-plugin * Plugin Name: Metisa * Plugin URI: http://example.com/metisa-uri/ * Description: Link your WP WooCommerce store data to Metisa for intelligent insights. * Version: 1.0.0 * Author: Altitude Labs * Author URI: http://www.askmetisa.com/ * License: GPL-2.0+ * License URI: http://www.gnu.org/licenses/gpl-2.0.txt * Text Domain: metisa * Domain Path: /languages */ // If this file is called directly, abort. if ( ! defined( 'WPINC' ) ) { die; } /** * The code that runs during plugin activation. * This action is documented in includes/class-metisa-activator.php */ function activate_metisa() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-metisa-activator.php'; Metisa_Activator::activate(); } /** * The code that runs during plugin deactivation. * This action is documented in includes/class-metisa-deactivator.php */ function deactivate_metisa() { require_once plugin_dir_path( __FILE__ ) . 'includes/class-metisa-deactivator.php'; Metisa_Deactivator::deactivate(); } register_activation_hook( __FILE__, 'activate_metisa' ); register_deactivation_hook( __FILE__, 'deactivate_metisa' ); /** * The core plugin class that is used to define internationalization, * admin-specific hooks, and public-facing site hooks. */ require plugin_dir_path( __FILE__ ) . 'includes/class-metisa.php'; // Include the global variables. require plugin_dir_path( __FILE__ ) . 'admin/settings.php'; /** * Begins execution of the plugin. * * Since everything within the plugin is registered via hooks, * then kicking off the plugin from this point in the file does * not affect the page life cycle. * * @since 1.0.0 */ function run_metisa() { $plugin = new Metisa(); $plugin->run(); } run_metisa(); function log_me($message) { if (WP_DEBUG === true) { if (is_array($message) || is_object($message)) { error_log(print_r($message, true)); } else { error_log($message); } } }
altitudelabs/metisa-wordpress-plugin
metisa.php
PHP
gpl-2.0
2,446
package org.schlocknet.kbdb.model; import lombok.Getter; import lombok.Setter; /** * * @author Ryan * * A generic response message that can be used for multiple web service * responses. * @param <T> The type of the responseObject * */ public class ResponseMessage<T> extends JsonBase { private @Getter @Setter boolean success; private @Getter @Setter String msg; private @Getter @Setter T responseObject; public ResponseMessage() { this.success = false; this.msg = null; this.responseObject = null; } public ResponseMessage(boolean success) { this.success = success; this.msg = null; this.responseObject = null; } public ResponseMessage(boolean success, String msg) { this.success = success; this.msg = msg; this.responseObject = null; } public ResponseMessage(boolean success, String msg, T responseObject) { this.success = success; this.msg = msg; this.responseObject = responseObject; } }
lsendel/kbdb
src/main/java/org/schlocknet/kbdb/model/ResponseMessage.java
Java
gpl-2.0
1,087
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace MediaBrowser.Controller.LiveTv { public class TunerChannelMapping { public string Name { get; set; } public string Number { get; set; } public string ProviderChannelNumber { get; set; } public string ProviderChannelName { get; set; } } }
neagix/Emby
MediaBrowser.Controller/LiveTv/TunerChannelMapping.cs
C#
gpl-2.0
412
''' Copyright (C) 2015 Jacob Bieker, jacob@bieker.us, www.jacobbieker.com This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. ''' __author__ = 'Jacob Bieker' print("Starting Google Plus Parsing")
jacobbieker/Insights
insights/google/GPlus2SQLite.py
Python
gpl-2.0
825
<?php /* @copyright:ChronoEngine.com @license:GPLv2 */defined('_JEXEC') or die('Restricted access'); defined("GCORE_SITE") or die; ?> <div class="ui segment tab functions-tab active" data-tab="functions-<?php echo $n; ?>"> <div class="ui top attached tabular menu small G2-tabs"> <a class="item active" data-tab="functions-<?php echo $n; ?>-general"><?php el('General'); ?></a> <a class="item" data-tab="functions-<?php echo $n; ?>-permissions"><?php el('Permissions'); ?></a> </div> <div class="ui bottom attached tab segment active" data-tab="functions-<?php echo $n; ?>-general"> <input type="hidden" value="php" name="Connection[functions][<?php echo $n; ?>][type]"> <div class="two fields"> <div class="field"> <label><?php el('Name'); ?></label> <input type="text" value="" name="Connection[functions][<?php echo $n; ?>][name]"> </div> </div> <div class="field forms_conf"> <label><?php el('Designer Label'); ?></label> <input type="text" value="" name="Connection[functions][<?php echo $n; ?>][label]"> </div> <div class="field"> <label><?php el('Code'); ?></label> <textarea name="Connection[functions][<?php echo $n; ?>][code]" rows="15"></textarea> <small><?php el('PHP code with OUT tags, returned value will be set as var'); ?></small> </div> </div> <div class="ui bottom attached tab segment" data-tab="functions-<?php echo $n; ?>-permissions"> <div class="two fields"> <div class="field"> <label><?php el('Owner id value'); ?></label> <input type="text" value="" name="Connection[functions][<?php echo $n; ?>][owner_id]"> </div> </div> <?php $this->view('views.permissions_manager', ['model' => 'Connection[functions]['.$n.']', 'perms' => ['access' => rl('Access')], 'groups' => $this->get('groups')]); ?> </div> </div>
azharu53/kuwithome
libraries/cegcore2/admin/extensions/chronofc/functions/php/php_config.php
PHP
gpl-2.0
1,828
<?php /** * --------------------------------------------------------------------- * GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2015-2022 Teclib' and contributors. * * http://glpi-project.org * * based on GLPI - Gestionnaire Libre de Parc Informatique * Copyright (C) 2003-2014 by the INDEPNET Development Team. * * --------------------------------------------------------------------- * * LICENSE * * This file is part of GLPI. * * GLPI is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * GLPI is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with GLPI. If not, see <http://www.gnu.org/licenses/>. * --------------------------------------------------------------------- */ include("../inc/includes.php"); if (!isset($_GET["id"])) { $_GET["id"] = ""; } $client = new APIClient(); if (isset($_POST["add"])) { $client->check(-1, CREATE, $_POST); $client->add($_POST); Html::back(); } else if (isset($_POST["update"])) { $client->check($_POST["id"], UPDATE); $client->update($_POST); Html::back(); } else if (isset($_POST["purge"])) { $client->check($_POST["id"], PURGE); $client->delete($_POST); Html::redirect($CFG_GLPI["root_doc"] . "/front/config.form.php"); } else { Html::header(APIClient::getTypeName(1), $_SERVER['PHP_SELF'], "config", "config", "apiclient"); $client->display(['id' => $_GET["id"]]); Html::footer(); }
stweil/glpi
front/apiclient.form.php
PHP
gpl-2.0
1,869
/* ***** BEGIN LICENSE BLOCK ***** * This file is part of Natron <http://www.natron.fr/>, * Copyright (C) 2013-2017 INRIA and Alexandre Gauthier-Foichat * * Natron is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Natron is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with Natron. If not, see <http://www.gnu.org/licenses/gpl-2.0.html> * ***** END LICENSE BLOCK ***** */ // ***** BEGIN PYTHON BLOCK ***** // from <https://docs.python.org/3/c-api/intro.html#include-files>: // "Since Python may define some pre-processor definitions which affect the standard headers on some systems, you must include Python.h before any standard headers are included." #include <Python.h> // ***** END PYTHON BLOCK ***** #include "PickKnobDialog.h" #include <stdexcept> #include <map> #include "Global/Macros.h" #if !defined(Q_MOC_RUN) && !defined(SBK_RUN) #include <boost/shared_ptr.hpp> #endif #include <QGridLayout> #include <QCheckBox> #include <QtCore/QTimer> #include "Engine/Knob.h" // KnobI #include "Engine/KnobTypes.h" // KnobButton... #include "Engine/Node.h" #include "Engine/NodeGroup.h" // NodeCollection #include "Engine/Utils.h" // convertFromPlainText #include "Gui/ComboBox.h" #include "Gui/DialogButtonBox.h" #include "Gui/Label.h" #include "Gui/KnobGui.h" #include "Gui/NodeCreationDialog.h" // CompleterLineEdit #include "Gui/NodeGui.h" #include "Gui/NodeSettingsPanel.h" NATRON_NAMESPACE_ENTER; struct PickKnobDialogPrivate { DockablePanel* panel; QGridLayout* mainLayout; Label* selectNodeLabel; CompleterLineEdit* nodeSelectionCombo; ComboBox* knobSelectionCombo; Label* useAliasLabel; QCheckBox* useAliasCheckBox; Label* destPageLabel; ComboBox* destPageCombo; Label* groupLabel; ComboBox* groupCombo; std::vector<KnobPagePtr > pages; std::vector<KnobGroupPtr > groups; DialogButtonBox* buttons; NodesList allNodes; std::map<QString, boost::shared_ptr<KnobI > > allKnobs; KnobGuiPtr selectedKnob; PickKnobDialogPrivate(DockablePanel* panel) : panel(panel) , mainLayout(0) , selectNodeLabel(0) , nodeSelectionCombo(0) , knobSelectionCombo(0) , useAliasLabel(0) , useAliasCheckBox(0) , destPageLabel(0) , destPageCombo(0) , groupLabel(0) , groupCombo(0) , pages() , groups() , buttons(0) , allNodes() , allKnobs() , selectedKnob() { } KnobGroupPtr getSelectedGroup() const; void onSelectedKnobChanged() { if (!selectedKnob) { return; } KnobParametricPtr isParametric = toKnobParametric( selectedKnob->getKnob() ); if (isParametric) { useAliasCheckBox->setChecked(true); } useAliasLabel->setEnabled(!isParametric); useAliasCheckBox->setEnabled(!isParametric); } }; KnobGroupPtr PickKnobDialogPrivate::getSelectedGroup() const { if ( pages.empty() ) { return KnobGroupPtr(); } std::string selectedItem = groupCombo->getCurrentIndexText().toStdString(); if (selectedItem != "-") { for (std::vector<KnobGroupPtr >::const_iterator it = groups.begin(); it != groups.end(); ++it) { if ( (*it)->getName() == selectedItem ) { return *it; } } } return KnobGroupPtr(); } PickKnobDialog::PickKnobDialog(DockablePanel* panel, QWidget* parent) : QDialog(parent) , _imp( new PickKnobDialogPrivate(panel) ) { NodeSettingsPanel* nodePanel = dynamic_cast<NodeSettingsPanel*>(panel); assert(nodePanel); if (!nodePanel) { throw std::logic_error("PickKnobDialog::PickKnobDialog()"); } NodeGuiPtr nodeGui = nodePanel->getNodeGui(); NodePtr node = nodeGui->getNode(); NodeGroupPtr isGroup = node->isEffectNodeGroup(); NodeCollectionPtr collec = node->getGroup(); NodeGroupPtr isCollecGroup = toNodeGroup(collec); NodesList collectNodes = collec->getNodes(); for (NodesList::iterator it = collectNodes.begin(); it != collectNodes.end(); ++it) { if ((*it)->isActivated() && (*it)->getNodeGui() && ( (*it)->getKnobs().size() > 0 ) ) { _imp->allNodes.push_back(*it); } } if (isCollecGroup) { _imp->allNodes.push_back( isCollecGroup->getNode() ); } if (isGroup) { NodesList groupnodes = isGroup->getNodes(); for (NodesList::iterator it = groupnodes.begin(); it != groupnodes.end(); ++it) { if ( (*it)->getNodeGui() && (*it)->isActivated() && ( (*it)->getKnobs().size() > 0 ) ) { _imp->allNodes.push_back(*it); } } } QStringList nodeNames; for (NodesList::iterator it = _imp->allNodes.begin(); it != _imp->allNodes.end(); ++it) { QString name = QString::fromUtf8( (*it)->getLabel().c_str() ); nodeNames.push_back(name); } nodeNames.sort(); _imp->mainLayout = new QGridLayout(this); _imp->selectNodeLabel = new Label( tr("Node:") ); _imp->nodeSelectionCombo = new CompleterLineEdit(nodeNames, nodeNames, false, this); _imp->nodeSelectionCombo->setToolTip( NATRON_NAMESPACE::convertFromPlainText(tr("Input the name of a node in the current project."), NATRON_NAMESPACE::WhiteSpaceNormal) ); _imp->nodeSelectionCombo->setFocus(Qt::PopupFocusReason); _imp->knobSelectionCombo = new ComboBox(this); QObject::connect( _imp->knobSelectionCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onKnobComboIndexChanged(int)) ); QString useAliasTt = NATRON_NAMESPACE::convertFromPlainText(tr("If checked, an alias of the selected parameter will be created, coyping entirely its state. " "Only the script-name, label and tooltip will be editable.\n" "For choice parameters this will also " "dynamically refresh the menu entries when the original parameter's menu is changed.\n" "When unchecked, a simple expression will be set linking the two parameters, but things such as dynamic menus " "will be disabled."), NATRON_NAMESPACE::WhiteSpaceNormal); _imp->useAliasLabel = new Label(tr("Make Alias:"), this); _imp->useAliasLabel->setToolTip(useAliasTt); _imp->useAliasCheckBox = new QCheckBox(this); _imp->useAliasCheckBox->setToolTip(useAliasTt); _imp->useAliasCheckBox->setChecked(true); QObject::connect( _imp->nodeSelectionCombo, SIGNAL(itemCompletionChosen()), this, SLOT(onNodeComboEditingFinished()) ); _imp->destPageLabel = new Label(tr("Page:"), this); QString pagett = NATRON_NAMESPACE::convertFromPlainText(tr("Select the page into which the parameter will be created."), NATRON_NAMESPACE::WhiteSpaceNormal); _imp->destPageLabel->setToolTip(pagett); _imp->destPageCombo = new ComboBox(this); _imp->destPageCombo->setToolTip(pagett); QObject::connect( _imp->destPageCombo, SIGNAL(currentIndexChanged(int)), this, SLOT(onPageComboIndexChanged(int)) ); const KnobsVec& knobs = node->getKnobs(); for (std::size_t i = 0; i < knobs.size(); ++i) { if ( knobs[i]->isUserKnob() ) { KnobPagePtr isPage = toKnobPage(knobs[i]); if (isPage) { _imp->pages.push_back(isPage); _imp->destPageCombo->addItem( QString::fromUtf8( isPage->getName().c_str() ) ); } else { KnobGroupPtr isGrp = toKnobGroup(knobs[i]); if (isGrp) { _imp->groups.push_back(isGrp); } } } } if (_imp->destPageCombo->count() == 0) { _imp->destPageLabel->hide(); _imp->destPageCombo->hide(); } _imp->groupLabel = new Label(tr("Group:"), this); QString grouptt = NATRON_NAMESPACE::convertFromPlainText(tr("Select the group into which the parameter will be created."), NATRON_NAMESPACE::WhiteSpaceNormal); _imp->groupCombo = new ComboBox(this); _imp->groupLabel->setToolTip(grouptt); _imp->groupCombo->setToolTip(grouptt); onPageComboIndexChanged(0); _imp->buttons = new DialogButtonBox(QDialogButtonBox::StandardButtons(QDialogButtonBox::Ok | QDialogButtonBox::Cancel), Qt::Horizontal, this); QObject::connect( _imp->buttons, SIGNAL(accepted()), this, SLOT(accept()) ); QObject::connect( _imp->buttons, SIGNAL(rejected()), this, SLOT(reject()) ); _imp->mainLayout->addWidget(_imp->selectNodeLabel, 0, 0, 1, 1); _imp->mainLayout->addWidget(_imp->nodeSelectionCombo, 0, 1, 1, 1); _imp->mainLayout->addWidget(_imp->knobSelectionCombo, 0, 2, 1, 1); _imp->mainLayout->addWidget(_imp->useAliasLabel, 1, 0, 1, 1); _imp->mainLayout->addWidget(_imp->useAliasCheckBox, 1, 1, 1, 1); _imp->mainLayout->addWidget(_imp->destPageLabel, 2, 0, 1, 1); _imp->mainLayout->addWidget(_imp->destPageCombo, 2, 1, 1, 1); _imp->mainLayout->addWidget(_imp->groupLabel, 2, 2, 1, 1); _imp->mainLayout->addWidget(_imp->groupCombo, 2, 3, 1, 1); _imp->mainLayout->addWidget(_imp->buttons, 3, 0, 1, 3); QTimer::singleShot( 25, _imp->nodeSelectionCombo, SLOT(showCompleter()) ); } PickKnobDialog::~PickKnobDialog() { } static KnobGuiPtr getKnobGuiForKnob(const NodePtr& selectedNode, const KnobIPtr& knob) { NodeGuiIPtr selectedNodeGuiI = selectedNode->getNodeGui(); assert(selectedNodeGuiI); if (!selectedNodeGuiI) { return KnobGuiPtr(); } NodeGui* selectedNodeGui = dynamic_cast<NodeGui*>( selectedNodeGuiI.get() ); assert(selectedNodeGui); if (!selectedNodeGui) { return KnobGuiPtr(); } NodeSettingsPanel* selectedPanel = selectedNodeGui->getSettingPanel(); bool hadPanelVisible = selectedPanel && !selectedPanel->isClosed(); if (!selectedPanel) { selectedNodeGui->ensurePanelCreated(); selectedPanel = selectedNodeGui->getSettingPanel(); selectedNodeGui->setVisibleSettingsPanel(false); } if (!selectedPanel) { return KnobGuiPtr(); } if (!hadPanelVisible && selectedPanel) { selectedPanel->setClosed(true); } const std::list<std::pair<KnobIWPtr, KnobGuiPtr> >& knobsMap = selectedPanel->getKnobsMapping(); for (std::list<std::pair<KnobIWPtr, KnobGuiPtr> >::const_iterator it = knobsMap.begin(); it != knobsMap.end(); ++it) { if (it->first.lock() == knob) { return it->second; } } return KnobGuiPtr(); } void PickKnobDialog::onKnobComboIndexChanged(int /*idx*/) { QString selectedNodeName = _imp->nodeSelectionCombo->text(); NodePtr selectedNode; std::string currentNodeName = selectedNodeName.toStdString(); for (NodesList::iterator it = _imp->allNodes.begin(); it != _imp->allNodes.end(); ++it) { if ( (*it)->getLabel() == currentNodeName ) { selectedNode = *it; break; } } _imp->selectedKnob.reset(); if (selectedNode) { QString str = _imp->knobSelectionCombo->itemText( _imp->knobSelectionCombo->activeIndex() ); std::map<QString, KnobIPtr >::const_iterator it = _imp->allKnobs.find(str); KnobIPtr selectedKnob; if ( it != _imp->allKnobs.end() ) { selectedKnob = it->second; _imp->selectedKnob = getKnobGuiForKnob(selectedNode, selectedKnob); } } _imp->onSelectedKnobChanged(); } void PickKnobDialog::onNodeComboEditingFinished() { QString index = _imp->nodeSelectionCombo->text(); _imp->knobSelectionCombo->clear(); _imp->allKnobs.clear(); _imp->selectedKnob.reset(); NodePtr selectedNode; std::string currentNodeName = index.toStdString(); for (NodesList::iterator it = _imp->allNodes.begin(); it != _imp->allNodes.end(); ++it) { if ( (*it)->getLabel() == currentNodeName ) { selectedNode = *it; break; } } if (!selectedNode) { return; } const std::vector< KnobIPtr > & knobs = selectedNode->getKnobs(); for (U32 j = 0; j < knobs.size(); ++j) { if ( !knobs[j]->getIsSecret() ) { KnobPagePtr isPage = toKnobPage(knobs[j]); KnobGroupPtr isGroup = toKnobGroup(knobs[j]); if (!isPage && !isGroup) { QString name = QString::fromUtf8( knobs[j]->getName().c_str() ); bool canInsertKnob = true; for (int k = 0; k < knobs[j]->getNDimensions(); ++k) { if ( name.isEmpty() ) { canInsertKnob = false; } } if (canInsertKnob) { if (!_imp->selectedKnob) { _imp->selectedKnob = getKnobGuiForKnob(selectedNode, knobs[j]); } _imp->allKnobs.insert( std::make_pair( name, knobs[j]) ); _imp->knobSelectionCombo->addItem(name); } } } } _imp->onSelectedKnobChanged(); _imp->knobSelectionCombo->setCurrentIndex_no_emit(0); } void PickKnobDialog::onPageComboIndexChanged(int index) { if ( _imp->pages.empty() ) { _imp->groupLabel->hide(); _imp->groupCombo->hide(); } _imp->groupCombo->clear(); _imp->groupCombo->addItem( QString::fromUtf8("-") ); std::string selectedPage = _imp->destPageCombo->itemText(index).toStdString(); KnobPagePtr parentPage; for (std::vector<KnobPagePtr >::iterator it = _imp->pages.begin(); it != _imp->pages.end(); ++it) { if ( (*it)->getName() == selectedPage ) { parentPage = *it; break; } } for (std::vector<KnobGroupPtr >::iterator it = _imp->groups.begin(); it != _imp->groups.end(); ++it) { KnobPagePtr page = (*it)->getTopLevelPage(); assert(page); ///add only grps whose parent page is the selected page if (page == parentPage) { _imp->groupCombo->addItem( QString::fromUtf8( (*it)->getName().c_str() ) ); } } } KnobGuiPtr PickKnobDialog::getSelectedKnob(bool* makeAlias, KnobPagePtr* page, KnobGroupPtr* group) const { int page_i = _imp->destPageCombo->activeIndex(); if ( (page_i >= 0) && ( page_i < (int)_imp->pages.size() ) ) { *page = _imp->pages[page_i]; } *group = _imp->getSelectedGroup(); *makeAlias = _imp->useAliasCheckBox->isChecked(); return _imp->selectedKnob; } NATRON_NAMESPACE_EXIT; NATRON_NAMESPACE_USING; #include "moc_PickKnobDialog.cpp"
kcotugno/Natron
Gui/PickKnobDialog.cpp
C++
gpl-2.0
15,353
<?php // $Revision: 2.0 $ /************************************************************************/ /* phpAdsNew 2 */ /* =========== */ /* */ /* Copyright (c) 2000-2002 by the phpAdsNew developers */ /* For more information visit: http://www.phpadsnew.com */ /* */ /* */ /* */ /* This program is free software. You can redistribute it and/or modify */ /* it under the terms of the GNU General Public License as published by */ /* the Free Software Foundation; either version 2 of the License. */ /************************************************************************/ $GLOBALS['strPluginAffiliate'] = "ÇØ´ç ±¤°í°Ô½ÃÀÚÀÇ ±â·Ï ¸ñ·ÏÀ» »ý¼ºÇÕ´Ï´Ù. º¸°í¼­´Â ½ºÇÁ·¹µå ½ÃÆ®¸¦ À§ÇØ CSV Çü½ÄÀ» »ç¿ëÇÕ´Ï´Ù."; $GLOBALS['strPluginCampaign'] = "ÇØ´ç Ä·ÆäÀÎÀÇ ±â·Ï ¸ñ·ÏÀ» »ý¼ºÇÕ´Ï´Ù. º¸°í¼­´Â ½ºÇÁ·¹µå ½ÃÆ®¸¦ À§ÇØ CSV Çü½ÄÀ» »ç¿ëÇÕ´Ï´Ù."; $GLOBALS['strPluginClient'] = "ÇØ´ç ±¤°íÁÖÀÇ ±â·Ï ¸ñ·ÏÀ» »ý¼ºÇÕ´Ï´Ù. º¸°í¼­´Â ½ºÇÁ·¹µå ½ÃÆ®¸¦ À§ÇØ CSV Çü½ÄÀ» »ç¿ëÇÕ´Ï´Ù."; $GLOBALS['strPluginGlobal'] = "Àüü ±â·Ï ¸ñ·ÏÀ» »ý¼ºÇÕ´Ï´Ù. º¸°í¼­´Â ½ºÇÁ·¹µå ½ÃÆ®¸¦ À§ÇØ CSV Çü½ÄÀ» »ç¿ëÇÕ´Ï´Ù."; $GLOBALS['strPluginZone'] = "¼±ÅÃÇÑ ¿µ¿ªÀÇ ±â·Ï ¸ñ·ÏÀ» »ý¼ºÇÕ´Ï´Ù. º¸°í¼­´Â ½ºÇÁ·¹µå ½ÃÆ®¸¦ À§ÇØ CSV Çü½ÄÀ» »ç¿ëÇÕ´Ï´Ù."; ?>
miller-tamil/openads-plus
language/korean/report.lang.php
PHP
gpl-2.0
1,635
/* * Copyright (c) 1998-2011 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * Free SoftwareFoundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.jsp.java; import com.caucho.jsp.JspParseException; import com.caucho.server.util.CauchoSystem; import com.caucho.util.L10N; import com.caucho.vfs.WriteStream; import com.caucho.xml.QName; import javax.servlet.jsp.HttpJspPage; import java.io.IOException; import java.util.ArrayList; import java.util.Locale; import java.util.logging.*; public class JspDirectivePage extends JspNode { private static final Logger log = Logger.getLogger(JspDirectivePage.class.getName()); static L10N L = new L10N(JspDirectivePage.class); private static final QName IS_EL_IGNORED = new QName("isELIgnored"); private static final QName IS_VELOCITY_ENABLED = new QName("isVelocityEnabled"); private static final QName INFO = new QName("info"); private static final QName CONTENT_TYPE = new QName("contentType"); private static final QName PAGE_ENCODING = new QName("pageEncoding"); private static final QName LANGUAGE = new QName("language"); private static final QName IMPORT = new QName("import"); private static final QName SESSION = new QName("session"); private static final QName BUFFER = new QName("buffer"); private static final QName ERROR_PAGE = new QName("errorPage"); private static final QName IS_ERROR_PAGE = new QName("isErrorPage"); private static final QName AUTO_FLUSH = new QName("autoFlush"); private static final QName IS_THREAD_SAFE = new QName("isThreadSafe"); private static final QName EXTENDS = new QName("extends"); private static final QName TRIM_WS = new QName("trimDirectiveWhitespaces"); private static final QName DEFER = new QName("deferredSyntaxAllowedAsLiteral"); /** * Adds an attribute. * * @param name the attribute name * @param value the attribute value */ public void addAttribute(QName name, String value) throws JspParseException { if (IS_EL_IGNORED.equals(name)) { boolean isIgnored = value.equals("true"); if (_parseState.isELIgnoredPageSpecified() && isIgnored != _parseState.isELIgnored()) throw error(L.l("isELIgnored values conflict")); _parseState.setELIgnored(isIgnored); _parseState.setELIgnoredPageSpecified(true); } /* else if (name.equals("isScriptingInvalid")) _parseState.setScriptingInvalid(value.equals("true")); */ else if (IS_VELOCITY_ENABLED.equals(name)) _parseState.setVelocityEnabled(value.equals("true")); else if (INFO.equals(name)) { String oldInfo = _parseState.getInfo(); if (oldInfo != null && ! value.equals(oldInfo)) throw error(L.l("info '{0}' conflicts with previous value of info '{1}'. Check the .jsp and any included .jsp files for conflicts.", value, oldInfo)); _parseState.setInfo(value); } else if (CONTENT_TYPE.equals(name)) { String oldContentType = _parseState.getContentType(); if (oldContentType != null && ! value.equals(oldContentType)) throw error(L.l("contentType '{0}' conflicts with previous value of contentType '{1}'. Check the .jsp and any included .jsp files for conflicts.", value, oldContentType)); _parseState.setContentType(value); String charEncoding = parseCharEncoding(value); if (charEncoding != null) _parseState.setCharEncoding(charEncoding); } else if (PAGE_ENCODING.equals(name)) { String oldEncoding = _parseState.getPageEncoding(); /* // jsp/01f1 if (oldEncoding != null) { String oldCanonical = Encoding.getMimeName(oldEncoding); String newCanonical = Encoding.getMimeName(value); if (! newCanonical.equals(oldCanonical)) throw error(L.l("pageEncoding '{0}' conflicts with previous value of pageEncoding '{1}'. Check the .jsp and any included .jsp files for conflicts.", value, oldEncoding)); } */ try { _parseState.setPageEncoding(value); // _parseState.setCharEncoding(value); } catch (JspParseException e) { log.log(Level.FINER, e.toString(), e); throw error(e.getMessage()); } } else if (LANGUAGE.equals(name)) { if (! value.equals("java")) throw error(L.l("'{0}' is not supported as a JSP scripting language.", value)); } else if (IMPORT.equals(name)) { _parseState.addImport(value); } else if (SESSION.equals(name)) { boolean isValid = false; if (value.equals("true")) isValid = _parseState.setSession(true); else if (value.equals("false")) isValid = _parseState.setSession(false); else throw error(L.l("session expects 'true' or 'false' at '{0}'", value)); _parseState.markSessionSet(); if (! isValid) throw error(L.l("session is assigned different values.")); } else if (BUFFER.equals(name)) { boolean isValid = _parseState.setBuffer(processBufferSize(value)); _parseState.markBufferSet(); if (! isValid) throw error(L.l("buffer is assigned different values.")); if (_parseState.getBuffer() == 0 && ! _parseState.isAutoFlush()) throw error(L.l("buffer must be non-zero when autoFlush is false.")); } else if (ERROR_PAGE.equals(name)) { String errorPage = _parseState.getErrorPage(); String newErrorPage = getRelativeUrl(value); _parseState.setErrorPage(newErrorPage); if (errorPage != null && ! errorPage.equals(newErrorPage)) { _parseState.setErrorPage(null); throw error(L.l("errorPage is assigned different value '{0}'.", newErrorPage)); } } else if (IS_ERROR_PAGE.equals(name)) { boolean isValid = false; if (value.equals("true")) isValid = _parseState.setErrorPage(true); else if (value.equals("false")) isValid = _parseState.setErrorPage(false); else throw error(L.l("isErrorPage expects 'true' or 'false' at '{0}'", value)); _parseState.markErrorPage(); if (! isValid) throw error(L.l("isErrorPage is assigned different values.")); } else if (AUTO_FLUSH.equals(name)) { boolean isValid = false; if (value.equals("true")) isValid = _parseState.setAutoFlush(true); else if (value.equals("false")) isValid = _parseState.setAutoFlush(false); else throw error(L.l("autoFlush expects 'true' or 'false' at '{0}'", value)); if (! isValid) throw error(L.l("autoFlush is assigned different values.")); if (_parseState.getBuffer() == 0 && ! _parseState.isAutoFlush()) throw error(L.l("buffer must be non-zero when autoFlush is false.")); _parseState.markAutoFlushSet(); } else if (IS_THREAD_SAFE.equals(name)) { boolean isValid = false; if (value.equals("true")) isValid = _parseState.setThreadSafe(true); else if (value.equals("false")) isValid = _parseState.setThreadSafe(false); else throw error(L.l("isThreadSafe expects 'true' or 'false' at '{0}'", value)); _parseState.markThreadSafeSet(); if (! isValid) throw error(L.l("isThreadSafe is assigned different values.")); } else if (EXTENDS.equals(name)) { Class cl = null; try { cl = CauchoSystem.loadClass(value); } catch (Exception e) { throw error(e); } if (! HttpJspPage.class.isAssignableFrom(cl)) throw error(L.l("'{0}' must implement HttpJspPage. The class named by jsp:directive.page extends='...' must implement HttpJspPage.", value)); Class oldExtends = _parseState.getExtends(); if (oldExtends != null && ! cl.equals(oldExtends)) throw error(L.l("extends '{0}' conflicts with previous value of extends '{1}'. Check the .jsp and any included .jsp files for conflicts.", value, oldExtends.getName())); _parseState.setExtends(cl); } else if (TRIM_WS.equals(name)) { if (value.equals("true")) _parseState.setTrimWhitespace(true); else if (value.equals("false")) _parseState.setTrimWhitespace(false); else throw error(L.l("trimDirectiveWhitespaces expects 'true' or 'false' at '{0}'", value)); } else if (DEFER.equals(name)) { if (value.equals("true")) _parseState.setDeferredSyntaxAllowedAsLiteral(true); else if (value.equals("false")) _parseState.setDeferredSyntaxAllowedAsLiteral(false); else throw error(L.l("deferredSyntaxAllowedAsLiteral expects 'true' or 'false' at '{0}'", value)); } else { throw error(L.l("'{0}' is an unknown JSP page directive attribute. See the JSP documentation for a complete list of page directive attributes.", name.getName())); } } /** * Parses the buffer size directive, grabbing the size out from the units. * * @param value buffer size string. * @return the size of the buffer in kb. */ private int processBufferSize(String value) throws JspParseException { if (value.equals("none")) return 0; int i = 0; int kb = 0; for (; i < value.length(); i++) { char ch = value.charAt(i); if (ch >= '0' && ch <= '9') kb = 10 * kb + ch - '0'; else break; } if (! value.substring(i).equals("kb")) throw error(L.l("Expected buffer size at '{0}'. Buffer sizes must end in 'kb'", value)); return 1024 * kb; } protected String getRelativeUrl(String value) { if (value.length() > 0 && value.charAt(0) == '/') return value; else return _parseState.getUriPwd() + value; } /** * Charset can be specific as follows: * test/html; z=9; charset=utf8; w=12 */ static String parseCharEncoding(String type) throws JspParseException { type = type.toLowerCase(Locale.ENGLISH); int i; char ch; while ((i = type.indexOf(';')) >= 0 && i < type.length()) { i++; while (i < type.length() && ((ch = type.charAt(i)) == ' ' || ch == '\t')) i++; if (i >= type.length()) return null; type = type.substring(i); i = type.indexOf('='); if (i >= 0) { if (! type.startsWith("charset")) continue; for (i++; i < type.length() && ((ch = type.charAt(i)) == ' ' || ch == '\t'); i++) { } type = type.substring(i); } for (i = 0; i < type.length() && (ch = type.charAt(i)) != ';' && ch != ' '; i++) { } return type.substring(0, i); } return null; } /** * Called when the tag ends. */ public void endAttributes() throws JspParseException { if (_gen.isTag()) throw error(L.l("page directives are forbidden in tags.")); } /** * Return true if the node only has static text. */ public boolean isStatic() { return true; } /** * Generates the XML text representation for the tag validation. * * @param os write stream to the generated XML. */ public void printXml(WriteStream os) throws IOException { os.print("<jsp:directive.page"); printJspId(os); if (! _parseState.isELIgnored()) os.print(" el-ignored='false'"); /* if (! _parseState.isScriptingEnabled()) os.print(" scripting-enabled='false'"); */ if (_parseState.getContentType() != null) os.print(" content-type='" + _parseState.getContentType() + "'"); ArrayList<String> imports = _parseState.getImportList(); if (imports != null && imports.size() != 0) { os.print(" import='"); for (int i = 0; i < imports.size(); i++) { if (i != 0) os.print(','); os.print(imports.get(i)); } os.print("'"); } os.print("/>"); } /** * Generates the code for the tag * * @param out the output writer for the generated java. */ public void generate(JspJavaWriter out) throws Exception { } }
dlitz/resin
modules/resin/src/com/caucho/jsp/java/JspDirectivePage.java
Java
gpl-2.0
13,277
<?php /** * SportsPress Meta Boxes * * Sets up the write panels used by custom post types * * @author ThemeBoy * @category Admin * @package SportsPress/Admin/Meta_Boxes * @version 1.3.1 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly /** * SP_Admin_Meta_Boxes */ class SP_Admin_Meta_Boxes { /** * Constructor */ public function __construct() { add_action( 'add_meta_boxes', array( $this, 'remove_meta_boxes' ), 10 ); add_action( 'add_meta_boxes', array( $this, 'rename_meta_boxes' ), 20 ); add_action( 'add_meta_boxes', array( $this, 'add_meta_boxes' ), 30 ); add_action( 'save_post', array( $this, 'save_meta_boxes' ), 1, 2 ); // Save Result Meta Boxes add_action( 'sportspress_process_sp_result_meta', 'SP_Meta_Box_Result_Details::save', 10, 2 ); // Save Outcome Meta Boxes add_action( 'sportspress_process_sp_outcome_meta', 'SP_Meta_Box_Outcome_Details::save', 10, 2 ); // Save Metric Meta Boxes add_action( 'sportspress_process_sp_metric_meta', 'SP_Meta_Box_Metric_Details::save', 10, 2 ); // Save Performance Meta Boxes add_action( 'sportspress_process_sp_performance_meta', 'SP_Meta_Box_Performance_Details::save', 10, 2 ); // Save Statistic Meta Boxes add_action( 'sportspress_process_sp_statistic_meta', 'SP_Meta_Box_Statistic_Details::save', 10, 2 ); add_action( 'sportspress_process_sp_statistic_meta', 'SP_Meta_Box_Statistic_Equation::save', 20, 2 ); // Save Column Meta Boxes add_action( 'sportspress_process_sp_column_meta', 'SP_Meta_Box_Column_Details::save', 10, 2 ); add_action( 'sportspress_process_sp_column_meta', 'SP_Meta_Box_Column_Equation::save', 20, 2 ); // Save Event Meta Boxes add_action( 'sportspress_process_sp_event_meta', 'SP_Meta_Box_Event_Format::save', 10, 2 ); add_action( 'sportspress_process_sp_event_meta', 'SP_Meta_Box_Event_Details::save', 20, 2 ); add_action( 'sportspress_process_sp_event_meta', 'SP_Meta_Box_Event_Teams::save', 30, 2 ); add_action( 'sportspress_process_sp_event_meta', 'SP_Meta_Box_Event_Video::save', 40, 2 ); add_action( 'sportspress_process_sp_event_meta', 'SP_Meta_Box_Event_Results::save', 50, 2 ); add_action( 'sportspress_process_sp_event_meta', 'SP_Meta_Box_Event_Performance::save', 60, 2 ); // Save Calendar Meta Boxes add_action( 'sportspress_process_sp_calendar_meta', 'SP_Meta_Box_Calendar_Format::save', 10, 2 ); add_action( 'sportspress_process_sp_calendar_meta', 'SP_Meta_Box_Calendar_Details::save', 20, 2 ); add_action( 'sportspress_process_sp_calendar_meta', 'SP_Meta_Box_Calendar_Data::save', 30, 2 ); // Save Team Meta Boxes add_action( 'sportspress_process_sp_team_meta', 'SP_Meta_Box_Team_Details::save', 10, 2 ); add_action( 'sportspress_process_sp_team_meta', 'SP_Meta_Box_Team_Columns::save', 20, 2 ); add_action( 'sportspress_process_sp_team_meta', 'SP_Meta_Box_Team_Lists::save', 30, 2 ); add_action( 'sportspress_process_sp_team_meta', 'SP_Meta_Box_Team_Tables::save', 40, 2 ); // Save Table Meta Boxes add_action( 'sportspress_process_sp_table_meta', 'SP_Meta_Box_Table_Details::save', 10, 2 ); add_action( 'sportspress_process_sp_table_meta', 'SP_Meta_Box_Table_Data::save', 20, 2 ); // Save Player Meta Boxes add_action( 'sportspress_process_sp_player_meta', 'SP_Meta_Box_Player_Columns::save', 10, 2 ); add_action( 'sportspress_process_sp_player_meta', 'SP_Meta_Box_Player_Details::save', 20, 2 ); add_action( 'sportspress_process_sp_player_meta', 'SP_Meta_Box_Player_Metrics::save', 30, 2 ); add_action( 'sportspress_process_sp_player_meta', 'SP_Meta_Box_Player_Statistics::save', 40, 2 ); // Save List Meta Boxes add_action( 'sportspress_process_sp_list_meta', 'SP_Meta_Box_List_Format::save', 10, 2 ); add_action( 'sportspress_process_sp_list_meta', 'SP_Meta_Box_List_Columns::save', 20, 2 ); add_action( 'sportspress_process_sp_list_meta', 'SP_Meta_Box_List_Details::save', 30, 2 ); add_action( 'sportspress_process_sp_list_meta', 'SP_Meta_Box_List_Data::save', 40, 2 ); // Save Staff Meta Boxes add_action( 'sportspress_process_sp_staff_meta', 'SP_Meta_Box_Staff_Details::save', 10, 2 ); } /** * Add SP Meta boxes */ public function add_meta_boxes() { global $post; // Get post meta array if ( isset( $post ) && isset( $post->ID ) ) $post_meta = get_post_meta( $post->ID ); else $post_meta = array(); // Results add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Result_Details::output', 'sp_result', 'normal', 'high' ); // Outcomes add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Outcome_Details::output', 'sp_outcome', 'normal', 'high' ); // Columns add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Column_Details::output', 'sp_column', 'side', 'default' ); add_meta_box( 'sp_equationdiv', __( 'Equation', 'sportspress' ), 'SP_Meta_Box_Column_Equation::output', 'sp_column', 'normal', 'high' ); // Metrics add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Metric_Details::output', 'sp_metric', 'normal', 'high' ); // Performance add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Performance_Details::output', 'sp_performance', 'normal', 'high' ); // Statistics add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Statistic_Details::output', 'sp_statistic', 'side', 'default' ); add_meta_box( 'sp_equationdiv', __( 'Equation', 'sportspress' ), 'SP_Meta_Box_Statistic_Equation::output', 'sp_statistic', 'normal', 'high' ); // Events add_meta_box( 'sp_shortcodediv', __( 'Shortcodes', 'sportspress' ), 'SP_Meta_Box_Event_Shortcode::output', 'sp_event', 'side', 'default' ); add_meta_box( 'sp_formatdiv', __( 'Format', 'sportspress' ), 'SP_Meta_Box_Event_Format::output', 'sp_event', 'side', 'default' ); add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Event_Details::output', 'sp_event', 'side', 'default' ); add_meta_box( 'sp_teamdiv', __( 'Teams', 'sportspress' ), 'SP_Meta_Box_Event_Teams::output', 'sp_event', 'side', 'default' ); add_meta_box( 'sp_videodiv', __( 'Video', 'sportspress' ), 'SP_Meta_Box_Event_Video::output', 'sp_event', 'side', 'low' ); if ( sizeof( array_filter( sp_array_value( $post_meta, 'sp_team', array() ) ) ) ): add_meta_box( 'sp_resultsdiv', __( 'Team Results', 'sportspress' ), 'SP_Meta_Box_Event_Results::output', 'sp_event', 'normal', 'high' ); add_meta_box( 'sp_performancediv', __( 'Player Performance', 'sportspress' ), 'SP_Meta_Box_Event_Performance::output', 'sp_event', 'normal', 'high' ); endif; add_meta_box( 'sp_editordiv', __( 'Article', 'sportspress' ), 'SP_Meta_Box_Event_Editor::output', 'sp_event', 'normal', 'low' ); // Calendars add_meta_box( 'sp_shortcodediv', __( 'Shortcode', 'sportspress' ), 'SP_Meta_Box_Calendar_Shortcode::output', 'sp_calendar', 'side', 'default' ); add_meta_box( 'sp_formatdiv', __( 'Layout', 'sportspress' ), 'SP_Meta_Box_Calendar_Format::output', 'sp_calendar', 'side', 'default' ); add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Calendar_Details::output', 'sp_calendar', 'side', 'default' ); add_meta_box( 'sp_datadiv', __( 'Events', 'sportspress' ), 'SP_Meta_Box_Calendar_Data::output', 'sp_calendar', 'normal', 'high' ); add_meta_box( 'sp_editordiv', __( 'Description', 'sportspress' ), 'SP_Meta_Box_Calendar_Editor::output', 'sp_calendar', 'normal', 'low' ); // Teams add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Team_Details::output', 'sp_team', 'side', 'default' ); if ( isset( $post ) && isset( $post->ID ) ): add_meta_box( 'sp_listsdiv', __( 'Player Lists', 'sportspress' ), 'SP_Meta_Box_Team_Lists::output', 'sp_team', 'normal', 'high' ); add_meta_box( 'sp_tablesdiv', __( 'League Tables', 'sportspress' ), 'SP_Meta_Box_Team_Tables::output', 'sp_team', 'normal', 'high' ); add_meta_box( 'sp_columnssdiv', __( 'Table Columns', 'sportspress' ), 'SP_Meta_Box_Team_Columns::output', 'sp_team', 'normal', 'high' ); endif; add_meta_box( 'sp_editordiv', __( 'Profile', 'sportspress' ), 'SP_Meta_Box_Team_Editor::output', 'sp_team', 'normal', 'low' ); // Tables add_meta_box( 'sp_shortcodediv', __( 'Shortcode', 'sportspress' ), 'SP_Meta_Box_Table_Shortcode::output', 'sp_table', 'side', 'default' ); add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Table_Details::output', 'sp_table', 'side', 'default' ); add_meta_box( 'sp_datadiv', __( 'League Table', 'sportspress' ), 'SP_Meta_Box_Table_Data::output', 'sp_table', 'normal', 'high' ); add_meta_box( 'sp_editordiv', __( 'Description', 'sportspress' ), 'SP_Meta_Box_Table_Editor::output', 'sp_table', 'normal', 'low' ); // Players add_meta_box( 'sp_shortcodediv', __( 'Shortcodes', 'sportspress' ), 'SP_Meta_Box_Player_Shortcode::output', 'sp_player', 'side', 'default' ); add_meta_box( 'sp_columnsdiv', __( 'Columns', 'sportspress' ), 'SP_Meta_Box_Player_Columns::output', 'sp_player', 'side', 'default' ); add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Player_Details::output', 'sp_player', 'side', 'default' ); add_meta_box( 'sp_metricsdiv', __( 'Metrics', 'sportspress' ), 'SP_Meta_Box_Player_Metrics::output', 'sp_player', 'side', 'default' ); if ( isset( $post ) && isset( $post->ID ) ): add_meta_box( 'sp_statisticsdiv', __( 'Statistics', 'sportspress' ), 'SP_Meta_Box_Player_Statistics::output', 'sp_player', 'normal', 'high' ); endif; add_meta_box( 'sp_editordiv', __( 'Profile', 'sportspress' ), 'SP_Meta_Box_Player_Editor::output', 'sp_player', 'normal', 'low' ); // Lists add_meta_box( 'sp_shortcodediv', __( 'Shortcode', 'sportspress' ), 'SP_Meta_Box_List_Shortcode::output', 'sp_list', 'side', 'default' ); add_meta_box( 'sp_formatdiv', __( 'Layout', 'sportspress' ), 'SP_Meta_Box_List_Format::output', 'sp_list', 'side', 'default' ); add_meta_box( 'sp_columnsdiv', __( 'Columns', 'sportspress' ), 'SP_Meta_Box_List_Columns::output', 'sp_list', 'side', 'default' ); add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_List_Details::output', 'sp_list', 'side', 'default' ); add_meta_box( 'sp_datadiv', __( 'Player List', 'sportspress' ), 'SP_Meta_Box_List_Data::output', 'sp_list', 'normal', 'high' ); add_meta_box( 'sp_editordiv', __( 'Description', 'sportspress' ), 'SP_Meta_Box_List_Editor::output', 'sp_list', 'normal', 'low' ); // Staff add_meta_box( 'sp_detailsdiv', __( 'Details', 'sportspress' ), 'SP_Meta_Box_Staff_Details::output', 'sp_staff', 'side', 'default' ); add_meta_box( 'sp_editordiv', __( 'Profile', 'sportspress' ), 'SP_Meta_Box_Staff_Editor::output', 'sp_staff', 'normal', 'low' ); } /** * Remove bloat */ public function remove_meta_boxes() { // Events remove_meta_box( 'sp_venuediv', 'sp_event', 'side' ); remove_meta_box( 'sp_leaguediv', 'sp_event', 'side' ); remove_meta_box( 'sp_seasondiv', 'sp_event', 'side' ); // Calendars remove_meta_box( 'sp_seasondiv', 'sp_calendar', 'side' ); remove_meta_box( 'sp_leaguediv', 'sp_calendar', 'side' ); remove_meta_box( 'sp_venuediv', 'sp_calendar', 'side' ); // Teams remove_meta_box( 'sp_leaguediv', 'sp_team', 'side' ); remove_meta_box( 'sp_seasondiv', 'sp_team', 'side' ); remove_meta_box( 'sp_venuediv', 'sp_team', 'side' ); // Tables remove_meta_box( 'sp_seasondiv', 'sp_table', 'side' ); remove_meta_box( 'sp_leaguediv', 'sp_table', 'side' ); // Players remove_meta_box( 'sp_seasondiv', 'sp_player', 'side' ); remove_meta_box( 'sp_leaguediv', 'sp_player', 'side' ); remove_meta_box( 'sp_positiondiv', 'sp_player', 'side' ); // Lists remove_meta_box( 'sp_seasondiv', 'sp_list', 'side' ); remove_meta_box( 'sp_leaguediv', 'sp_list', 'side' ); // Staff remove_meta_box( 'sp_seasondiv', 'sp_staff', 'side' ); remove_meta_box( 'sp_leaguediv', 'sp_staff', 'side' ); } /** * Rename core meta boxes */ public function rename_meta_boxes() { global $post; // Publish/Event if ( isset( $post ) ) { remove_meta_box( 'submitdiv', 'sp_event', 'side' ); add_meta_box( 'submitdiv', __( 'Event', 'sportspress' ), 'post_submit_meta_box', 'sp_event', 'side', 'high' ); } } /** * Check if we're saving, then trigger an action based on the post type * * @param int $post_id * @param object $post */ public function save_meta_boxes( $post_id, $post ) { if ( empty( $post_id ) || empty( $post ) ) return; if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE ) return; if ( is_int( wp_is_post_revision( $post ) ) ) return; if ( is_int( wp_is_post_autosave( $post ) ) ) return; if ( empty( $_POST['sportspress_meta_nonce'] ) || ! wp_verify_nonce( $_POST['sportspress_meta_nonce'], 'sportspress_save_data' ) ) return; if ( ! current_user_can( 'edit_post', $post_id ) ) return; if ( ! is_sp_post_type( $post->post_type ) && ! is_sp_config_type( $post->post_type ) ) return; do_action( 'sportspress_process_' . $post->post_type . '_meta', $post_id, $post ); } } new SP_Admin_Meta_Boxes();
phoebuzz/habsprospect
wp-content/plugins/sportspress/includes/admin/post-types/class-sp-admin-meta-boxes.php
PHP
gpl-2.0
13,147
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace CompanyDirectoryDF.Controllers { public class HomeController : Controller { public ActionResult Index() { return View(); } public ActionResult About() { ViewBag.Message = "Your application description page."; return View(); } public ActionResult Contact() { ViewBag.Message = "Your contact page."; return View(); } } }
Jricklefs/Employee-Directory
CompanyDirectoryDF/Controllers/HomeController.cs
C#
gpl-2.0
587
/* * @file glut_window.cpp * @Brief Glut-based window. * @author Fei Zhu * * This file is part of Physika, a versatile physics simulation library. * Copyright (C) 2013- Physika Group. * * This Source Code Form is subject to the terms of the GNU General Public License v2.0. * If a copy of the GPL was not distributed with this file, you can obtain one at: * http://www.gnu.org/licenses/gpl-2.0.html * */ #include <cstdlib> #include <cstring> #include <iostream> #include <sstream> #include <GL/glew.h> #include <GL/freeglut.h> #include "Physika_Core/Utilities/physika_assert.h" #include "Physika_Core/Utilities/physika_exception.h" #include "Physika_Core/Image/image.h" #include "Physika_IO/Image_IO/image_io.h" #include "Physika_GUI/Glut_Window/glut_window.h" #include "Physika_Render/OpenGL_Primitives/opengl_primitives.h" #include "Physika_Render/Lights/flash_light.h" namespace Physika{ GlutWindow::GlutWindow() :window_name_(std::string("Physika Glut Window")),window_id_(-1),initial_width_(640),initial_height_(480), display_fps_(true),screen_capture_file_index_(0),event_mode_(false) { background_color_ = Color<double>::Black(); text_color_ = Color<double>::White(); resetMouseState(); initCallbacks(); initOpenGLContext(); RenderSceneConfig & render_scene_config = RenderSceneConfig::getSingleton(); render_scene_config.setCameraAspect(static_cast<double>(initial_width_ / initial_height_)); //reset screen based render manager ScreenBasedRenderManager & render_manager = render_scene_config.screenBasedRenderManager(); render_manager.resetMsaaFBO(initial_width_, initial_height_); } GlutWindow::GlutWindow(const std::string &window_name) :window_name_(window_name),window_id_(-1),initial_width_(640),initial_height_(480), display_fps_(true),screen_capture_file_index_(0), event_mode_(false) { background_color_ = Color<double>::Black(); text_color_ = Color<double>::White(); resetMouseState(); initCallbacks(); initOpenGLContext(); RenderSceneConfig & render_scene_config = RenderSceneConfig::getSingleton(); render_scene_config.setCameraAspect(static_cast<double>(initial_width_ / initial_height_)); //reset screen based render manager ScreenBasedRenderManager & render_manager = render_scene_config.screenBasedRenderManager(); render_manager.resetMsaaFBO(initial_width_, initial_height_); } GlutWindow::GlutWindow(const std::string &window_name, unsigned int width, unsigned int height) :window_name_(window_name),window_id_(-1),initial_width_(width),initial_height_(height), display_fps_(true),screen_capture_file_index_(0), event_mode_(false) { background_color_ = Color<double>::Black(); text_color_ = Color<double>::White(); resetMouseState(); initCallbacks(); initOpenGLContext(); RenderSceneConfig & render_scene_config = RenderSceneConfig::getSingleton(); render_scene_config.setCameraAspect(static_cast<double>(initial_width_ / initial_height_)); //reset screen based render manager ScreenBasedRenderManager & render_manager = render_scene_config.screenBasedRenderManager(); render_manager.resetMsaaFBO(initial_width_, initial_height_); } GlutWindow::~GlutWindow() { } void GlutWindow::createWindow() { glutShowWindow(); glutSetWindowData(this); //bind 'this' pointer with the window glutDisplayFunc(display_function_); glutIdleFunc(idle_function_); glutReshapeFunc(reshape_function_); glutKeyboardFunc(keyboard_function_); glutSpecialFunc(special_function_); glutMotionFunc(motion_function_); glutMouseFunc(mouse_function_); glutMouseWheelFunc(mouse_wheel_function_); resetMouseState(); //reset the state of mouse every time the window is created (*init_function_)(); //call the init function before entering main loop if (event_mode_ == false) glutMainLoop(); } void GlutWindow::closeWindow() { glutLeaveMainLoop(); } const std::string& GlutWindow::name() const { return window_name_; } int GlutWindow::width() const { if(glutGet(GLUT_INIT_STATE)) //window is created return glutGet(GLUT_WINDOW_WIDTH); else return initial_width_; } int GlutWindow::height() const { if(glutGet(GLUT_INIT_STATE)) //window is created return glutGet(GLUT_WINDOW_HEIGHT); else return initial_height_; } void GlutWindow::enableEventMode() { this->event_mode_ = true; } void GlutWindow::disableEventMode() { this->event_mode_ = false; } ////////////////////////////////////////////////// screen shot and display frame-rate//////////////////////////////////////////////////////////////// bool GlutWindow::saveScreen(const std::string &file_name) const { int width = this->width(), height = this->height(); unsigned char *data = new unsigned char[width*height*3]; //RGB PHYSIKA_ASSERT(data); glPixelStorei(GL_PACK_ALIGNMENT, 1); glReadPixels(0,0,width,height,GL_RGB,GL_UNSIGNED_BYTE,(void*)data); Image image(width,height,Image::RGB,data); image.flipVertically(); bool status = ImageIO::save(file_name,&image); delete[] data; return status; } bool GlutWindow::saveScreen() { std::stringstream adaptor; adaptor<<screen_capture_file_index_++; std::string index_str; adaptor>>index_str; std::string file_name = std::string("screen_capture_") + index_str + std::string(".png"); return saveScreen(file_name); } void GlutWindow::displayFrameRate() const { if(!glutGet(GLUT_INIT_STATE)) //window is not created throw PhysikaException("Cannot display frame rate before a window is created."); if(display_fps_) { static unsigned int frame = 0, time = 0, time_base = 0; double fps = 60.0; ++frame; time = glutGet(GLUT_ELAPSED_TIME); //millisecond if(time - time_base > 10) // compute every 10 milliseconds { fps = frame*1000.0/(time-time_base); time_base = time; frame = 0; } std::stringstream adaptor; adaptor.precision(2); std::string str; if(fps>1.0) //show fps { adaptor<<fps; str = std::string("FPS: ") + adaptor.str(); } else //show spf { PHYSIKA_ASSERT(fps>0); adaptor<< 1.0/fps; str = std::string("SPF: ") + adaptor.str(); } //now draw the string int width = this->width(), height = this->height(); glMatrixMode(GL_MODELVIEW); glPushMatrix(); glLoadIdentity(); glMatrixMode(GL_PROJECTION); glPushMatrix(); glLoadIdentity(); glDisable(GL_LIGHTING); glDisable(GL_TEXTURE_2D); gluOrtho2D(0,width,0,height); openGLColor3(text_color_); glRasterPos2i(5,height-19); glPushAttrib(GL_ALL_ATTRIB_BITS); glDisable(GL_DEPTH_TEST); for (unsigned int i = 0; i < str.length(); i++) glutBitmapCharacter (GLUT_BITMAP_HELVETICA_18, str[i]); glPopAttrib(); glPopMatrix(); glMatrixMode(GL_MODELVIEW); glPopMatrix(); glEnable(GL_LIGHTING); } } void GlutWindow::enableDisplayFrameRate() { display_fps_ = true; } void GlutWindow::disableDisplayFrameRate() { display_fps_ = false; } ////////////////////////////////////////////////// set custom callback functions //////////////////////////////////////////////////////////////////// void GlutWindow::setDisplayFunction(void (*func)(void)) { if(func==NULL) { std::cerr<<"NULL callback function provided, use default instead.\n"; display_function_ = GlutWindow::displayFunction; } else display_function_ = func; } void GlutWindow::setIdleFunction(void (*func)(void)) { if(func==NULL) { std::cerr<<"NULL callback function provided, use default instead.\n"; idle_function_ = GlutWindow::idleFunction; } else idle_function_ = func; } void GlutWindow::setReshapeFunction(void (*func)(int width, int height)) { if(func==NULL) { std::cerr<<"NULL callback function provided, use default instead.\n"; reshape_function_ = GlutWindow::reshapeFunction; } else reshape_function_ = func; } void GlutWindow::setKeyboardFunction(void (*func)(unsigned char key, int x, int y)) { if(func==NULL) { std::cerr<<"NULL callback function provided, use default instead.\n"; keyboard_function_ = GlutWindow::keyboardFunction; } else keyboard_function_ = func; } void GlutWindow::setSpecialFunction(void (*func)(int key, int x, int y)) { if(func==NULL) { std::cerr<<"NULL callback function provided, use default instead.\n"; special_function_ = GlutWindow::specialFunction; } else special_function_ = func; } void GlutWindow::setMotionFunction(void (*func)(int x, int y)) { if(func==NULL) { std::cerr<<"NULL callback function provided, use default instead.\n"; motion_function_ = GlutWindow::motionFunction; } else motion_function_ = func; } void GlutWindow::setMouseFunction(void (*func)(int button, int state, int x, int y)) { if(func==NULL) { std::cerr<<"NULL callback function provided, use default instead.\n"; mouse_function_ = GlutWindow::mouseFunction; } else mouse_function_ = func; } void GlutWindow::setMouseWheelFunction(void(*func)(int wheel, int direction, int x, int y)) { if (func == NULL) { std::cerr << "NULL callback function provided, use default instead.\n"; mouse_wheel_function_ = GlutWindow::mouseWheelFunction; } else mouse_wheel_function_ = func; } void GlutWindow::setInitFunction(void (*func)(void)) { if(func==NULL) { std::cerr<<"NULL callback function provided, use default instead.\n"; init_function_ = GlutWindow::initFunction; } else init_function_ = func; } void GlutWindow::bindDefaultKeys(unsigned char key, int x, int y) { GlutWindow::keyboardFunction(key,x,y); } ////////////////////////////////////////////////// default callback functions //////////////////////////////////////////////////////////////////// void GlutWindow::displayFunction(void) { GlutWindow * cur_window = (GlutWindow*)glutGetWindowData(); Color<double> background_color = cur_window->background_color_; glClearColor(background_color.redChannel(), background_color.greenChannel(), background_color.blueChannel(), background_color.alphaChannel()); glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); RenderSceneConfig & render_scene_config = RenderSceneConfig::getSingleton(); ScreenBasedRenderManager & render_manager = render_scene_config.screenBasedRenderManager(); render_manager.render(); cur_window->displayFrameRate(); glutPostRedisplay(); glutSwapBuffers(); } void GlutWindow::idleFunction(void) { glutPostRedisplay(); } void GlutWindow::reshapeFunction(int width, int height) { GlutWindow *window = static_cast<GlutWindow*>(glutGetWindowData()); RenderSceneConfig & render_scene_config = RenderSceneConfig::getSingleton(); PHYSIKA_ASSERT(window); //update the view aspect of camera GLdouble aspect = static_cast<GLdouble>(width)/height; render_scene_config.setCameraAspect(aspect); //update view port glViewport(0, 0, width, height); //reset screen based render manager ScreenBasedRenderManager & render_manager = render_scene_config.screenBasedRenderManager(); render_manager.resetMsaaFBO(width, height); } void GlutWindow::keyboardFunction(unsigned char key, int x, int y) { GlutWindow *window = static_cast<GlutWindow*>(glutGetWindowData()); PHYSIKA_ASSERT(window); switch(key) { case 27: //ESC: close window glutLeaveMainLoop(); break; case 's': //s: save screen shot window->saveScreen(); break; case 'f': //f: enable/disable FPS display (window->display_fps_) = !(window->display_fps_); break; default: break; } } void GlutWindow::specialFunction(int key, int x, int y) { } void GlutWindow::motionFunction(int x, int y) { GlutWindow *window = static_cast<GlutWindow*>(glutGetWindowData()); RenderSceneConfig & render_scene_config = RenderSceneConfig::getSingleton(); PHYSIKA_ASSERT(window); int mouse_delta_x = x - window->mouse_position_[0]; int mouse_delta_y = y - window->mouse_position_[1]; window->mouse_position_[0] = x; window->mouse_position_[1] = y; double scale = 0.02; //sensitivity of the mouse double camera_radius = render_scene_config.cameraRadius(); if(window->left_button_down_) //left button handles camera rotation { render_scene_config.orbitCameraLeft(mouse_delta_x*scale); render_scene_config.orbitCameraUp(mouse_delta_y*scale); } if(window->middle_button_down_) //middle button handles camera zoom in/out { render_scene_config.zoomCameraIn(camera_radius*mouse_delta_y*scale); } if(window->right_button_down_) //right button handles camera translation { scale *= 0.1; render_scene_config.translateCameraLeft(camera_radius*mouse_delta_x*scale); render_scene_config.translateCameraUp(camera_radius*mouse_delta_y*scale); } } void GlutWindow::mouseFunction(int button, int state, int x, int y) { GlutWindow *window = static_cast<GlutWindow*>(glutGetWindowData()); PHYSIKA_ASSERT(window); switch(button) { case GLUT_LEFT_BUTTON: window->left_button_down_ = (state==GLUT_DOWN); break; case GLUT_MIDDLE_BUTTON: window->middle_button_down_ = (state==GLUT_DOWN); break; case GLUT_RIGHT_BUTTON: window->right_button_down_ = (state==GLUT_DOWN); break; default: //PHYSIKA_ERROR("Invalid mouse state."); break; } window->mouse_position_[0] = x; window->mouse_position_[1] = y; } void GlutWindow::mouseWheelFunction(int wheel, int direction, int x, int y) { GlutWindow *window = static_cast<GlutWindow*>(glutGetWindowData()); RenderSceneConfig & render_scene_config = RenderSceneConfig::getSingleton(); PHYSIKA_ASSERT(window); double scale = 0.02; //sensitivity of the mouse double camera_radius = render_scene_config.cameraRadius(); switch (direction) { case 1: //mouse wheel up: zoom out render_scene_config.zoomCameraOut(camera_radius*scale); break; case -1: //mouse wheel down: zoom in render_scene_config.zoomCameraIn(camera_radius*scale); break; default: break; } window->mouse_position_[0] = x; window->mouse_position_[1] = y; } void GlutWindow::initFunction(void) { int width = glutGet(GLUT_WINDOW_WIDTH); int height = glutGet(GLUT_WINDOW_HEIGHT); GlutWindow *window = static_cast<GlutWindow*>(glutGetWindowData()); PHYSIKA_ASSERT(window); glViewport(0, 0, width, height); // set the viewport window->initDefaultLight(); glShadeModel( GL_SMOOTH ); glClearDepth( 1.0 ); // specify the clear value for the depth buffer glEnable( GL_DEPTH_TEST ); glHint( GL_PERSPECTIVE_CORRECTION_HINT, GL_NICEST ); // specify implementation-specific hints Color<double> background_color = window->background_color_; glClearColor(background_color.redChannel(), background_color.greenChannel(), background_color.blueChannel(), background_color.alphaChannel()); } void GlutWindow::initOpenGLContext() { int argc = 1; const int max_length = 1024; //assume length of the window name does not exceed 1024 characters char *argv[1]; char name_str[max_length]; strcpy(name_str, window_name_.c_str()); argv[0] = name_str; glutInit(&argc, argv); glutSetOption(GLUT_ACTION_ON_WINDOW_CLOSE, GLUT_ACTION_CONTINUE_EXECUTION); //this option allows leaving the glut loop without exit program glutInitDisplayMode(GLUT_DOUBLE | GLUT_RGBA | GLUT_DEPTH | GLUT_ALPHA); glutInitWindowSize(initial_width_, initial_height_); window_id_ = glutCreateWindow(window_name_.c_str()); glutHideWindow(); glewExperimental = GL_TRUE; if (glewInit() != GLEW_OK) { std::cerr << "error: can't init glew!\n"; std::exit(EXIT_FAILURE); } std::cout << "openGL Version: " << glGetString(GL_VERSION) << std::endl; } void GlutWindow::initCallbacks() { //set callbacks to default callback functions display_function_ = GlutWindow::displayFunction; idle_function_ = GlutWindow::idleFunction; reshape_function_ = GlutWindow::reshapeFunction; keyboard_function_ = GlutWindow::keyboardFunction; special_function_ = GlutWindow::specialFunction; motion_function_ = GlutWindow::motionFunction; mouse_function_ = GlutWindow::mouseFunction; mouse_wheel_function_ = GlutWindow::mouseWheelFunction; init_function_ = GlutWindow::initFunction; } void GlutWindow::resetMouseState() { left_button_down_ = false; middle_button_down_ = false; right_button_down_ = false; mouse_position_[0] = mouse_position_[1] = 0; } void GlutWindow::initDefaultLight() { std::cout << "info: add default flash light!" << std::endl; std::shared_ptr<FlashLight> flash_light = std::make_shared<FlashLight>(); flash_light->setAmbient(Color4f::Gray()); RenderSceneConfig & render_scene_config = RenderSceneConfig::getSingleton(); render_scene_config.pushBackLight(std::move(flash_light)); } } //end of namespace Physika
suitmyself/Physika
Physika_Src/Physika_GUI/Glut_Window/glut_window.cpp
C++
gpl-2.0
17,741
<?php /** * File containing the ezie module definition * * @copyright Copyright (C) 1999-2012 eZ Systems AS. All rights reserved. * @license http://www.gnu.org/licenses/gpl-2.0.txt GNU General Public License v2 * @version 5.0.0 * @package ezie */ $Module = array( 'name' => 'ezie' ); $ViewList = array(); $ViewList['prepare'] = array('script' => 'prepare.php', 'params' => array( 'object_id', 'edit_language', 'attribute_id', 'version' ), ); // FILTERS $ViewList['filter_bw'] = array( 'script' => 'filter_bw.php' ); $ViewList['filter_sepia'] = array( 'script' => 'filter_sepia.php' ); $ViewList['filter_blur'] = array( 'script' => 'filter_blur.php' ); $ViewList['filter_contrast'] = array( 'script' => 'filter_contrast.php' ); $ViewList['filter_brightness'] = array( 'script' => 'filter_brightness.php' ); // TOOLS $ViewList['tool_flip_hor'] = array( 'script' => 'tool_flip_hor.php' ); $ViewList['tool_flip_ver'] = array( 'script' => 'tool_flip_ver.php' ); $ViewList['tool_rotation'] = array( 'script' => 'tool_rotation.php' ); $ViewList['tool_levels'] = array( 'script' => 'tool_levels.php' ); $ViewList['tool_saturation'] = array( 'script' => 'tool_saturation.php' ); $ViewList['tool_pixelate'] = array( 'script' => 'tool_pixelate.php' ); $ViewList['tool_crop'] = array( 'script' => 'tool_crop.php' ); $ViewList['tool_watermark'] = array( 'script' => 'tool_watermark.php' ); // MENU ACTIONS $ViewList['no_save_and_quit'] = array('script' => 'no_save_and_quit.php'); $ViewList['save_and_quit'] = array('script' => 'save_and_quit.php'); $FunctionList = array(); ?>
medbenhenda/migration-ez5
ezpublish_legacy/extension/ezie/modules/ezie/module.php
PHP
gpl-2.0
1,651
package zeropoint.minecraft.commands.com; import net.minecraft.command.ICommandSender; import net.minecraft.entity.player.EntityPlayer; import zeropoint.minecraft.core.GTBaseCommand; import zeropoint.minecraft.core.util.ChatMsg; /** * [/vanish [on|off|toggle]] Control invisibility * * @author Zero Point */ public class Vanish extends GTBaseCommand { @Override public String getCommandName() { return "vanish"; } @Override public String getCommandHelp(ICommandSender src) { return "Controls invisibility"; } @Override public String getCommandArgs(ICommandSender src) { return "[on|off|toggle]"; } @Override public boolean isFinished() { return true; } @Override public void execute(ICommandSender src, EntityPlayer player, String[] args) { if (args.length > 0) { String arg = args[0].toLowerCase(); if (arg.equals("on")) { player.setInvisible(true); } else if (arg.equals("off")) { player.setInvisible(false); } else if (arg.equals("toggle")) { player.setInvisible( !player.isInvisible()); } else { new ChatMsg(this.getCommandUsage(src)).send(src); } } else { player.setInvisible( !player.isInvisible()); } } }
ZeroPointMC/GlobalTweaks
zeropoint/minecraft/commands/com/Vanish.java
Java
gpl-2.0
1,198
// -*- mode: js; js-indent-level: 4; indent-tabs-mode: nil -*- const Clutter = imports.gi.Clutter; const Lang = imports.lang; const Signals = imports.signals; const Gio = imports.gi.Gio; const GLib = imports.gi.GLib; const Gtk = imports.gi.Gtk; const Pango = imports.gi.Pango; const St = imports.gi.St; const Shell = imports.gi.Shell; const CheckBox = imports.ui.checkBox; const Dialog = imports.ui.dialog; const Main = imports.ui.main; const MessageTray = imports.ui.messageTray; const ModalDialog = imports.ui.modalDialog; const Params = imports.misc.params; const ShellEntry = imports.ui.shellEntry; var LIST_ITEM_ICON_SIZE = 48; const REMEMBER_MOUNT_PASSWORD_KEY = 'remember-mount-password'; /* ------ Common Utils ------- */ function _setLabelText(label, text) { if (text) { label.set_text(text); label.show(); } else { label.set_text(''); label.hide(); } } function _setButtonsForChoices(dialog, choices) { let buttons = []; for (let idx = 0; idx < choices.length; idx++) { let button = idx; buttons.unshift({ label: choices[idx], action: () => { dialog.emit('response', button); } }); } dialog.setButtons(buttons); } function _setLabelsForMessage(content, message) { let labels = message.split('\n'); content.title = labels.shift(); content.body = labels.join('\n'); } function _createIcon(gicon) { return new St.Icon({ gicon: gicon, style_class: 'shell-mount-operation-icon' }) } /* -------------------------------------------------------- */ var ListItem = new Lang.Class({ Name: 'ListItem', _init(app) { this._app = app; let layout = new St.BoxLayout({ vertical: false}); this.actor = new St.Button({ style_class: 'mount-dialog-app-list-item', can_focus: true, child: layout, reactive: true, x_align: St.Align.START, x_fill: true }); this._icon = this._app.create_icon_texture(LIST_ITEM_ICON_SIZE); let iconBin = new St.Bin({ style_class: 'mount-dialog-app-list-item-icon', child: this._icon }); layout.add(iconBin); this._nameLabel = new St.Label({ text: this._app.get_name(), style_class: 'mount-dialog-app-list-item-name' }); let labelBin = new St.Bin({ y_align: St.Align.MIDDLE, child: this._nameLabel }); layout.add(labelBin); this.actor.connect('clicked', this._onClicked.bind(this)); }, _onClicked() { this.emit('activate'); this._app.activate(); } }); Signals.addSignalMethods(ListItem.prototype); var ShellMountOperation = new Lang.Class({ Name: 'ShellMountOperation', _init(source, params) { params = Params.parse(params, { existingDialog: null }); this._dialog = null; this._dialogId = 0; this._existingDialog = params.existingDialog; this._processesDialog = null; this.mountOp = new Shell.MountOperation(); this.mountOp.connect('ask-question', this._onAskQuestion.bind(this)); this.mountOp.connect('ask-password', this._onAskPassword.bind(this)); this.mountOp.connect('show-processes-2', this._onShowProcesses2.bind(this)); this.mountOp.connect('aborted', this.close.bind(this)); this.mountOp.connect('show-unmount-progress', this._onShowUnmountProgress.bind(this)); this._gicon = source.get_icon(); }, _closeExistingDialog() { if (!this._existingDialog) return; this._existingDialog.close(); this._existingDialog = null; }, _onAskQuestion(op, message, choices) { this._closeExistingDialog(); this._dialog = new ShellMountQuestionDialog(this._gicon); this._dialogId = this._dialog.connect('response', (object, choice) => { this.mountOp.set_choice(choice); this.mountOp.reply(Gio.MountOperationResult.HANDLED); this.close(); }); this._dialog.update(message, choices); this._dialog.open(); }, _onAskPassword(op, message, defaultUser, defaultDomain, flags) { if (this._existingDialog) { this._dialog = this._existingDialog; this._dialog.reaskPassword(); } else { this._dialog = new ShellMountPasswordDialog(message, this._gicon, flags); } this._dialogId = this._dialog.connect('response', (object, choice, password, remember) => { if (choice == -1) { this.mountOp.reply(Gio.MountOperationResult.ABORTED); } else { if (remember) this.mountOp.set_password_save(Gio.PasswordSave.PERMANENTLY); else this.mountOp.set_password_save(Gio.PasswordSave.NEVER); this.mountOp.set_password(password); this.mountOp.reply(Gio.MountOperationResult.HANDLED); } }); this._dialog.open(); }, close(op) { this._closeExistingDialog(); this._processesDialog = null; if (this._dialog) { this._dialog.close(); this._dialog = null; } if (this._notifier) { this._notifier.done(); this._notifier = null; } }, _onShowProcesses2(op) { this._closeExistingDialog(); let processes = op.get_show_processes_pids(); let choices = op.get_show_processes_choices(); let message = op.get_show_processes_message(); if (!this._processesDialog) { this._processesDialog = new ShellProcessesDialog(this._gicon); this._dialog = this._processesDialog; this._dialogId = this._processesDialog.connect('response', (object, choice) => { if (choice == -1) { this.mountOp.reply(Gio.MountOperationResult.ABORTED); } else { this.mountOp.set_choice(choice); this.mountOp.reply(Gio.MountOperationResult.HANDLED); } this.close(); }); this._processesDialog.open(); } this._processesDialog.update(message, processes, choices); }, _onShowUnmountProgress(op, message, timeLeft, bytesLeft) { if (!this._notifier) this._notifier = new ShellUnmountNotifier(); if (bytesLeft == 0) this._notifier.done(message); else this._notifier.show(message); }, borrowDialog() { if (this._dialogId != 0) { this._dialog.disconnect(this._dialogId); this._dialogId = 0; } return this._dialog; } }); var ShellUnmountNotifier = new Lang.Class({ Name: 'ShellUnmountNotifier', Extends: MessageTray.Source, _init() { this.parent('', 'media-removable'); this._notification = null; Main.messageTray.add(this); }, show(message) { let [header, text] = message.split('\n', 2); if (!this._notification) { this._notification = new MessageTray.Notification(this, header, text); this._notification.setTransient(true); this._notification.setUrgency(MessageTray.Urgency.CRITICAL); } else { this._notification.update(header, text); } this.notify(this._notification); }, done(message) { if (this._notification) { this._notification.destroy(); this._notification = null; } if (message) { let notification = new MessageTray.Notification(this, message, null); notification.setTransient(true); this.notify(notification); } } }); var ShellMountQuestionDialog = new Lang.Class({ Name: 'ShellMountQuestionDialog', Extends: ModalDialog.ModalDialog, _init(icon) { this.parent({ styleClass: 'mount-dialog' }); this._content = new Dialog.MessageDialogContent({ icon }); this.contentLayout.add(this._content, { x_fill: true, y_fill: false }); }, update(message, choices) { _setLabelsForMessage(this._content, message); _setButtonsForChoices(this, choices); } }); Signals.addSignalMethods(ShellMountQuestionDialog.prototype); var ShellMountPasswordDialog = new Lang.Class({ Name: 'ShellMountPasswordDialog', Extends: ModalDialog.ModalDialog, _init(message, icon, flags) { let strings = message.split('\n'); let title = strings.shift() || null; let body = strings.shift() || null; this.parent({ styleClass: 'prompt-dialog' }); let content = new Dialog.MessageDialogContent({ icon, title, body }); this.contentLayout.add_actor(content); this._passwordBox = new St.BoxLayout({ vertical: false, style_class: 'prompt-dialog-password-box' }); content.messageBox.add(this._passwordBox); this._passwordLabel = new St.Label(({ style_class: 'prompt-dialog-password-label', text: _("Password") })); this._passwordBox.add(this._passwordLabel, { y_fill: false, y_align: St.Align.MIDDLE }); this._passwordEntry = new St.Entry({ style_class: 'prompt-dialog-password-entry', text: "", can_focus: true}); ShellEntry.addContextMenu(this._passwordEntry, { isPassword: true }); this._passwordEntry.clutter_text.connect('activate', this._onEntryActivate.bind(this)); this._passwordEntry.clutter_text.set_password_char('\u25cf'); // ● U+25CF BLACK CIRCLE this._passwordBox.add(this._passwordEntry, {expand: true }); this.setInitialKeyFocus(this._passwordEntry); this._errorMessageLabel = new St.Label({ style_class: 'prompt-dialog-error-label', text: _("Sorry, that didn’t work. Please try again.") }); this._errorMessageLabel.clutter_text.ellipsize = Pango.EllipsizeMode.NONE; this._errorMessageLabel.clutter_text.line_wrap = true; this._errorMessageLabel.hide(); content.messageBox.add(this._errorMessageLabel); if (flags & Gio.AskPasswordFlags.SAVING_SUPPORTED) { this._rememberChoice = new CheckBox.CheckBox(); this._rememberChoice.getLabelActor().text = _("Remember Password"); this._rememberChoice.actor.checked = global.settings.get_boolean(REMEMBER_MOUNT_PASSWORD_KEY); content.messageBox.add(this._rememberChoice.actor); } else { this._rememberChoice = null; } let buttons = [{ label: _("Cancel"), action: this._onCancelButton.bind(this), key: Clutter.Escape }, { label: _("Unlock"), action: this._onUnlockButton.bind(this), default: true }]; this.setButtons(buttons); }, reaskPassword() { this._passwordEntry.set_text(''); this._errorMessageLabel.show(); }, _onCancelButton() { this.emit('response', -1, '', false); }, _onUnlockButton() { this._onEntryActivate(); }, _onEntryActivate() { global.settings.set_boolean(REMEMBER_MOUNT_PASSWORD_KEY, this._rememberChoice && this._rememberChoice.actor.checked); this.emit('response', 1, this._passwordEntry.get_text(), this._rememberChoice && this._rememberChoice.actor.checked); } }); var ShellProcessesDialog = new Lang.Class({ Name: 'ShellProcessesDialog', Extends: ModalDialog.ModalDialog, _init(icon) { this.parent({ styleClass: 'mount-dialog' }); this._content = new Dialog.MessageDialogContent({ icon }); this.contentLayout.add(this._content, { x_fill: true, y_fill: false }); let scrollView = new St.ScrollView({ style_class: 'mount-dialog-app-list'}); scrollView.set_policy(Gtk.PolicyType.NEVER, Gtk.PolicyType.AUTOMATIC); this.contentLayout.add(scrollView, { x_fill: true, y_fill: true }); scrollView.hide(); this._applicationList = new St.BoxLayout({ vertical: true }); scrollView.add_actor(this._applicationList); this._applicationList.connect('actor-added', () => { if (this._applicationList.get_n_children() == 1) scrollView.show(); }); this._applicationList.connect('actor-removed', () => { if (this._applicationList.get_n_children() == 0) scrollView.hide(); }); }, _setAppsForPids(pids) { // remove all the items this._applicationList.destroy_all_children(); pids.forEach(pid => { let tracker = Shell.WindowTracker.get_default(); let app = tracker.get_app_from_pid(pid); if (!app) return; let item = new ListItem(app); this._applicationList.add(item.actor, { x_fill: true }); item.connect('activate', () => { // use -1 to indicate Cancel this.emit('response', -1); }); }); }, update(message, processes, choices) { this._setAppsForPids(processes); _setLabelsForMessage(this._content, message); _setButtonsForChoices(this, choices); } }); Signals.addSignalMethods(ShellProcessesDialog.prototype); const GnomeShellMountOpIface = ` <node> <interface name="org.Gtk.MountOperationHandler"> <method name="AskPassword"> <arg type="s" direction="in" name="object_id"/> <arg type="s" direction="in" name="message"/> <arg type="s" direction="in" name="icon_name"/> <arg type="s" direction="in" name="default_user"/> <arg type="s" direction="in" name="default_domain"/> <arg type="u" direction="in" name="flags"/> <arg type="u" direction="out" name="response"/> <arg type="a{sv}" direction="out" name="response_details"/> </method> <method name="AskQuestion"> <arg type="s" direction="in" name="object_id"/> <arg type="s" direction="in" name="message"/> <arg type="s" direction="in" name="icon_name"/> <arg type="as" direction="in" name="choices"/> <arg type="u" direction="out" name="response"/> <arg type="a{sv}" direction="out" name="response_details"/> </method> <method name="ShowProcesses"> <arg type="s" direction="in" name="object_id"/> <arg type="s" direction="in" name="message"/> <arg type="s" direction="in" name="icon_name"/> <arg type="ai" direction="in" name="application_pids"/> <arg type="as" direction="in" name="choices"/> <arg type="u" direction="out" name="response"/> <arg type="a{sv}" direction="out" name="response_details"/> </method> <method name="Close"/> </interface> </node>`; var ShellMountOperationType = { NONE: 0, ASK_PASSWORD: 1, ASK_QUESTION: 2, SHOW_PROCESSES: 3 }; var GnomeShellMountOpHandler = new Lang.Class({ Name: 'GnomeShellMountOpHandler', _init() { this._dbusImpl = Gio.DBusExportedObject.wrapJSObject(GnomeShellMountOpIface, this); this._dbusImpl.export(Gio.DBus.session, '/org/gtk/MountOperationHandler'); Gio.bus_own_name_on_connection(Gio.DBus.session, 'org.gtk.MountOperationHandler', Gio.BusNameOwnerFlags.REPLACE, null, null); this._dialog = null; this._volumeMonitor = Gio.VolumeMonitor.get(); this._ensureEmptyRequest(); }, _ensureEmptyRequest() { this._currentId = null; this._currentInvocation = null; this._currentType = ShellMountOperationType.NONE; }, _clearCurrentRequest(response, details) { if (this._currentInvocation) { this._currentInvocation.return_value( GLib.Variant.new('(ua{sv})', [response, details])); } this._ensureEmptyRequest(); }, _setCurrentRequest(invocation, id, type) { let oldId = this._currentId; let oldType = this._currentType; let requestId = id + '@' + invocation.get_sender(); this._clearCurrentRequest(Gio.MountOperationResult.UNHANDLED, {}); this._currentInvocation = invocation; this._currentId = requestId; this._currentType = type; if (this._dialog && (oldId == requestId) && (oldType == type)) return true; return false; }, _closeDialog() { if (this._dialog) { this._dialog.close(); this._dialog = null; } }, _createGIcon(iconName) { let realIconName = iconName ? iconName : 'drive-harddisk'; return new Gio.ThemedIcon({ name: realIconName, use_default_fallbacks: true }); }, /** * AskPassword: * @id: an opaque ID identifying the object for which the operation is requested * The ID must be unique in the context of the calling process. * @message: the message to display * @icon_name: the name of an icon to display * @default_user: the default username for display * @default_domain: the default domain for display * @flags: a set of GAskPasswordFlags * @response: a GMountOperationResult * @response_details: a dictionary containing the response details as * entered by the user. The dictionary MAY contain the following properties: * - "password" -> (s): a password to be used to complete the mount operation * - "password_save" -> (u): a GPasswordSave * * The dialog will stay visible until clients call the Close() method, or * another dialog becomes visible. * Calling AskPassword again for the same id will have the effect to clear * the existing dialog and update it with a message indicating the previous * attempt went wrong. */ AskPasswordAsync(params, invocation) { let [id, message, iconName, defaultUser, defaultDomain, flags] = params; if (this._setCurrentRequest(invocation, id, ShellMountOperationType.ASK_PASSWORD)) { this._dialog.reaskPassword(); return; } this._closeDialog(); this._dialog = new ShellMountPasswordDialog(message, this._createGIcon(iconName), flags); this._dialog.connect('response', (object, choice, password, remember) => { let details = {}; let response; if (choice == -1) { response = Gio.MountOperationResult.ABORTED; } else { response = Gio.MountOperationResult.HANDLED; let passSave = remember ? Gio.PasswordSave.PERMANENTLY : Gio.PasswordSave.NEVER; details['password_save'] = GLib.Variant.new('u', passSave); details['password'] = GLib.Variant.new('s', password); } this._clearCurrentRequest(response, details); }); this._dialog.open(); }, /** * AskQuestion: * @id: an opaque ID identifying the object for which the operation is requested * The ID must be unique in the context of the calling process. * @message: the message to display * @icon_name: the name of an icon to display * @choices: an array of choice strings * GetResponse: * @response: a GMountOperationResult * @response_details: a dictionary containing the response details as * entered by the user. The dictionary MAY contain the following properties: * - "choice" -> (i): the chosen answer among the array of strings passed in * * The dialog will stay visible until clients call the Close() method, or * another dialog becomes visible. * Calling AskQuestion again for the same id will have the effect to clear * update the dialog with the new question. */ AskQuestionAsync(params, invocation) { let [id, message, iconName, choices] = params; if (this._setCurrentRequest(invocation, id, ShellMountOperationType.ASK_QUESTION)) { this._dialog.update(message, choices); return; } this._closeDialog(); this._dialog = new ShellMountQuestionDialog(this._createGIcon(iconName), message); this._dialog.connect('response', (object, choice) => { this._clearCurrentRequest(Gio.MountOperationResult.HANDLED, { choice: GLib.Variant.new('i', choice) }); }); this._dialog.update(message, choices); this._dialog.open(); }, /** * ShowProcesses: * @id: an opaque ID identifying the object for which the operation is requested * The ID must be unique in the context of the calling process. * @message: the message to display * @icon_name: the name of an icon to display * @application_pids: the PIDs of the applications to display * @choices: an array of choice strings * @response: a GMountOperationResult * @response_details: a dictionary containing the response details as * entered by the user. The dictionary MAY contain the following properties: * - "choice" -> (i): the chosen answer among the array of strings passed in * * The dialog will stay visible until clients call the Close() method, or * another dialog becomes visible. * Calling ShowProcesses again for the same id will have the effect to clear * the existing dialog and update it with the new message and the new list * of processes. */ ShowProcessesAsync(params, invocation) { let [id, message, iconName, applicationPids, choices] = params; if (this._setCurrentRequest(invocation, id, ShellMountOperationType.SHOW_PROCESSES)) { this._dialog.update(message, applicationPids, choices); return; } this._closeDialog(); this._dialog = new ShellProcessesDialog(this._createGIcon(iconName)); this._dialog.connect('response', (object, choice) => { let response; let details = {}; if (choice == -1) { response = Gio.MountOperationResult.ABORTED; } else { response = Gio.MountOperationResult.HANDLED; details['choice'] = GLib.Variant.new('i', choice); } this._clearCurrentRequest(response, details); }); this._dialog.update(message, applicationPids, choices); this._dialog.open(); }, /** * Close: * * Closes a dialog previously opened by AskPassword, AskQuestion or ShowProcesses. * If no dialog is open, does nothing. */ Close(params, invocation) { this._clearCurrentRequest(Gio.MountOperationResult.UNHANDLED, {}); this._closeDialog(); } });
halfline/gnome-shell
js/ui/shellMountOperation.js
JavaScript
gpl-2.0
23,798
<?php class Qixol_Promo_Block_Banner extends Mage_Core_Block_Template { public function _prepareLayout() { return parent::_prepareLayout(); } public function getBanner() { if (!$this->hasData('banner')) { $this->setData('banner', Mage::registry('banner')); } return $this->getData('banner'); } public function getResizeImage($bannerPath, $groupName, $w = 0, $h = 0) { $name = ''; $_helper = Mage::helper('qixol'); $bannerDirPath = $_helper->updateDirSepereator($bannerPath); $baseDir = Mage::getBaseDir(); $mediaDir = Mage::getBaseDir('media'); $mediaUrl = Mage::getBaseUrl('media'); $resizeDir = $mediaDir . DS . 'custom' . DS . 'banners' . DS . 'resize' . DS; $resizeUrl = $mediaUrl.'Qixol/Promo/banners/resize/'; $imageName = basename($bannerDirPath); if (@file_exists($mediaDir . DS . $bannerDirPath)) { $name = $mediaDir . DS . $bannerPath; $this->checkDir($resizeDir . $groupName); $smallImgPath = $resizeDir . $groupName . DS . $imageName; $smallImg = $resizeUrl . $groupName .'/'. $imageName; } if ($name != '') { $resizeObject = Mage::getModel('qixol/bannerresize'); $resizeObject->setImage($name); if ($resizeObject->resizeLimitwh($w, $h, $smallImgPath) === false) { return $resizeObject->error(); } else { return $smallImg; } } else { return ''; } } protected function checkDir($directory) { if (!is_dir($directory)) { umask(0); mkdir($directory, 0777,true); return true; } } }
Qixol/Qixol.Promo.Magento.Extension
Magento_1.9.x/app/code/community/Qixol/Promo/Block/Banner.php
PHP
gpl-2.0
1,819
package fr.lipn.sts.ir.indexing; import java.io.File; import java.io.IOException; import java.util.Stack; import java.util.Vector; import javax.xml.parsers.ParserConfigurationException; import javax.xml.parsers.SAXParser; import javax.xml.parsers.SAXParserFactory; import org.apache.lucene.document.Document; import org.apache.lucene.document.Field; import org.xml.sax.Attributes; import org.xml.sax.SAXException; import org.xml.sax.helpers.DefaultHandler; public class AquaintXMLHandler extends DefaultHandler { /* A buffer for each XML element */ protected StringBuffer textBuffer = new StringBuffer(); protected StringBuffer titleBuffer = new StringBuffer(); protected String docID = new String(); protected Stack<String> elemStack; protected Document currentDocument; protected Vector<Document> parsedDocuments; public AquaintXMLHandler(File xmlFile) throws ParserConfigurationException, SAXException, IOException { // Now let's move to the parsing stuff SAXParserFactory spf = SAXParserFactory.newInstance(); SAXParser parser = spf.newSAXParser(); this.docID=xmlFile.getName(); try { parser.parse(xmlFile, this); } catch (org.xml.sax.SAXParseException spe) { System.out.println("SAXParser caught SAXParseException at line: " + spe.getLineNumber() + " column " + spe.getColumnNumber() + " details: " + spe.getMessage()); } } // call at document start public void startDocument() throws SAXException { parsedDocuments= new Vector<Document>(); elemStack=new Stack<String>(); } // call at element start public void startElement(String namespaceURI, String localName, String qualifiedName, Attributes attrs) throws SAXException { String eName = localName; if ("".equals(eName)) { eName = qualifiedName; // namespaceAware = false } elemStack.addElement(eName); if(eName=="DOC") { textBuffer.setLength(0); titleBuffer.setLength(0); docID=attrs.getValue("id"); currentDocument=new Document(); } } // call when cdata found public void characters(char[] text, int start, int length) throws SAXException { if(elemStack.peek().equalsIgnoreCase("HEADLINE")){ titleBuffer.append(text, start, length); } else if (elemStack.peek().equalsIgnoreCase("HEADLINE") || elemStack.peek().equalsIgnoreCase("P")) { textBuffer.append(text, start, length); } } // call at element end public void endElement(String namespaceURI, String simpleName, String qualifiedName) throws SAXException { String eName = simpleName; if ("".equals(eName)) { eName = qualifiedName; // namespaceAware = false } elemStack.pop(); if (eName.equals("DOC")){ currentDocument.add(new Field("title", titleBuffer.toString(), Field.Store.YES, Field.Index.ANALYZED)); currentDocument.add(new Field("text", textBuffer.toString(), Field.Store.YES, Field.Index.ANALYZED)); currentDocument.add(new Field("id", this.docID, Field.Store.YES, Field.Index.NOT_ANALYZED)); parsedDocuments.add(currentDocument); } } public Vector<Document> getParsedDocuments() { return this.parsedDocuments; } }
dbuscaldi/SOPA
src/fr/lipn/sts/ir/indexing/AquaintXMLHandler.java
Java
gpl-2.0
3,298
describe("region", function(){ "use strict"; describe("when creating a new region manager and no configuration has been provided", function(){ it("should throw an exception saying an 'el' is required", function(){ expect( Backbone.Marionette.Region.extend({}) ).toThrow("An 'el' must be specified for a region."); }); }); describe("when showing a view", function(){ var MyRegion = Backbone.Marionette.Region.extend({ el: "#region", onShow: function(){} }); var MyView = Backbone.View.extend({ render: function(){ $(this.el).html("some content"); }, onShow: function(){ $(this.el).addClass("onShowClass"); } }); var myRegion, view, showEvent, showContext, showViewPassed; beforeEach(function(){ setFixtures("<div id='region'></div>"); view = new MyView(); spyOn(view, "render").andCallThrough(); myRegion = new MyRegion(); spyOn(myRegion, "onShow"); myRegion.on("show", function(v){ showViewPassed = v === view; showEvent = true; showContext = this; }); myRegion.show(view); }); it("should render the view", function(){ expect(view.render).toHaveBeenCalled(); }); it("should append the rendered HTML to the manager's 'el'", function(){ expect(myRegion.$el).toHaveHtml(view.el); }); it("shoudl call 'onShow' for the view, after the rendered HTML has been added to the DOM", function(){ expect($(view.el)).toHaveClass("onShowClass"); }) it("shoudl call 'onShow' for the region, after the rendered HTML has been added to the DOM", function(){ expect(myRegion.onShow).toHaveBeenCalled(); }) it("should trigger a show event for the view", function(){ expect(showEvent).toBeTruthy(); }); it("should pass the shown view as an argument for the show event", function(){ expect(showViewPassed).toBeTruthy(); }); it("should set 'this' to the manager, from the show event", function(){ expect(showContext).toBe(myRegion); }); }); describe("when a view is already shown and showing another", function(){ var MyRegion = Backbone.Marionette.Region.extend({ el: "#region" }); var MyView = Backbone.View.extend({ render: function(){ $(this.el).html("some content"); }, close: function(){ } }); var myRegion, view1, view2; beforeEach(function(){ setFixtures("<div id='region'></div>"); view1 = new MyView(); view2 = new MyView(); myRegion = new MyRegion(); spyOn(view1, "close"); myRegion.show(view1); myRegion.show(view2); }); it("should call 'close' on the already open view", function(){ expect(view1.close).toHaveBeenCalled(); }); it("should reference the new view as the current view", function(){ expect(myRegion.currentView).toBe(view2); }); }); describe("when a view is already shown and showing the same one", function(){ var MyRegion = Backbone.Marionette.Region.extend({ el: "#region" }); var MyView = Backbone.View.extend({ render: function(){ $(this.el).html("some content"); }, close: function(){ }, open: function(){ } }); var myRegion, view; beforeEach(function(){ setFixtures("<div id='region'></div>"); view = new MyView(); myRegion = new MyRegion(); myRegion.show(view); spyOn(view, "close"); spyOn(myRegion, "open"); spyOn(view, "render"); myRegion.show(view); }); it("should not call 'close' on the view", function(){ expect(view.close).not.toHaveBeenCalled(); }); it("should not call 'open' on the view", function(){ expect(myRegion.open).not.toHaveBeenCalledWith(view); }); it("should call 'render' on the view", function(){ expect(view.render).toHaveBeenCalled(); }); }); describe("when a view is already shown, close, and showing the same one", function(){ var MyRegion = Backbone.Marionette.Region.extend({ el: "#region" }); var MyView = Backbone.Marionette.ItemView.extend({ render: function(){ $(this.el).html("some content"); }, open : function() {} }); var myRegion, view; beforeEach(function(){ setFixtures("<div id='region'></div>"); view = new MyView(); myRegion = new MyRegion(); myRegion.show(view); view.close(); spyOn(view, "close"); spyOn(myRegion, "open"); spyOn(view, "render") myRegion.show(view); }); it("should not call 'close' on the view", function(){ expect(view.close).not.toHaveBeenCalled(); }); it("should call 'open' on the view", function(){ expect(myRegion.open).toHaveBeenCalledWith(view); }); it("should call 'render' on the view", function(){ expect(view.render).toHaveBeenCalled(); }); }); describe("when a view is already closed and showing another", function(){ var MyRegion = Backbone.Marionette.Region.extend({ el: "#region" }); var MyView = Backbone.Marionette.View.extend({ render: function(){ $(this.el).html("some content"); } }); var myRegion, view1, view2; beforeEach(function(){ setFixtures("<div id='region'></div>"); view1 = new MyView(); view2 = new MyView(); myRegion = new MyRegion(); spyOn(view1, "close").andCallThrough(); }); it("shouldn't call 'close' on an already closed view", function(){ myRegion.show(view1); view1.close(); myRegion.show(view2); expect(view1.close.callCount).toEqual(1); }); }); describe("when closing the current view", function(){ var MyRegion = Backbone.Marionette.Region.extend({ el: "#region" }); var MyView = Backbone.View.extend({ render: function(){ $(this.el).html("some content"); }, close: function(){ } }); var myRegion, view, closed, closedContext; beforeEach(function(){ setFixtures("<div id='region'></div>"); view = new MyView(); spyOn(view, "close"); spyOn(view, "remove"); myRegion = new MyRegion(); myRegion.on("close", function(){ closed = true; closedContext = this; }); myRegion.show(view); myRegion.close(); }); it("should trigger a close event", function(){ expect(closed).toBeTruthy(); }); it("should set 'this' to the manager, from the close event", function(){ expect(closedContext).toBe(myRegion); }); it("should call 'close' on the already show view", function(){ expect(view.close).toHaveBeenCalled(); }); it("should not call 'remove' directly, on the view", function(){ expect(view.remove).not.toHaveBeenCalled(); }); it("should delete the current view reference", function(){ expect(myRegion.currentView).toBeUndefined(); }); }); describe("when closing the current view and it does not have a 'close' method", function(){ var MyRegion = Backbone.Marionette.Region.extend({ el: "<div></div>" }); var MyView = Backbone.View.extend({ render: function(){ $(this.el).html("some content"); } }); var myRegion, view; beforeEach(function(){ view = new MyView(); spyOn(view, "remove"); myRegion = new MyRegion(); myRegion.show(view); myRegion.close(); }); it("should call 'remove' on the view", function(){ expect(view.remove).toHaveBeenCalled(); }); }); describe("when initializing a region manager and passing an 'el' option", function(){ var manager, el; beforeEach(function(){ el = "#foo"; manager = new Backbone.Marionette.Region({ el: el }); }); it("should manage the specified el", function(){ expect(manager.el).toBe(el); }); }); describe("when initializing a region manager with an existing view", function(){ var manager, view; beforeEach(function(){ view = new (Backbone.View.extend({ onShow: function(){} }))(); spyOn(view, "render"); spyOn(view, "onShow"); manager = new Backbone.Marionette.Region({ el: "#foo", currentView: view }); }); it("should not render the view", function(){ expect(view.render).not.toHaveBeenCalled(); }); it("should not `show` the view", function(){ expect(view.onShow).not.toHaveBeenCalled(); }); }); describe("when attaching an existing view to a region manager", function(){ var manager, view; beforeEach(function(){ setFixtures("<div id='foo'>bar</div>"); view = new (Backbone.View.extend({onShow: function(){}}))(); spyOn(view, "render"); spyOn(view, "onShow"); manager = new Backbone.Marionette.Region({ el: "#foo" }); manager.attachView(view); }); it("should not render the view", function(){ expect(view.render).not.toHaveBeenCalled(); }); it("should not `show` the view", function(){ expect(view.onShow).not.toHaveBeenCalled(); }); it("should not replace the existing html", function(){ expect($(manager.el).text()).toBe("bar"); }) }); describe("when creating a region instance with an initialize method", function(){ var Manager, actualOptions, expectedOptions; beforeEach(function(){ expectedOptions = {foo: "bar"}; Manager = Backbone.Marionette.Region.extend({ el: "#foo", initialize: function(options){ } }); spyOn(Manager.prototype, "initialize").andCallThrough(); new Manager({ foo: "bar" }); }); it("should call the initialize method with the options from the constructor", function(){ expect(Manager.prototype.initialize).toHaveBeenCalledWith(expectedOptions); }); }); describe("when removing a region", function(){ var MyApp, region; beforeEach(function(){ setFixtures("<div id='region'></div><div id='region2'></div>"); MyApp = new Backbone.Marionette.Application(); MyApp.addRegions({ MyRegion: "#region", anotherRegion: "#region2" }); region = MyApp.MyRegion; spyOn(region, "close"); MyApp.removeRegion('MyRegion') }); it("should be removed from the app", function(){ expect(MyApp.MyRegion).not.toBeDefined() }) it("should call 'close' of the region", function(){ expect(region.close).toHaveBeenCalled() }) }) describe("when resetting a region", function(){ var region; beforeEach(function(){ setFixtures("<div id='region'></div>"); region = new Backbone.Marionette.Region({ el: "#region" }); spyOn(region, "close"); region.ensureEl(); region.reset(); }); it("should not hold on to the region's previous `el`", function(){ expect(region.$el).not.toExist(); }); it("should close any existing view", function(){ expect(region.close).toHaveBeenCalled(); }); }); });
RoryDuncan/Idea-Planner
node_modules/backbone.marionette/spec/javascripts/region.spec.js
JavaScript
gpl-2.0
11,267
/* * Copyright (c) 1998-2011 Caucho Technology -- all rights reserved * * This file is part of Resin(R) Open Source * * Each copy or derived work must preserve the copyright notice and this * notice unmodified. * * Resin Open Source is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * Resin Open Source is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE, or any warranty * of NON-INFRINGEMENT. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with Resin Open Source; if not, write to the * * Free Software Foundation, Inc. * 59 Temple Place, Suite 330 * Boston, MA 02111-1307 USA * * @author Scott Ferguson */ package com.caucho.server.http; import com.caucho.util.L10N; import com.caucho.vfs.OutputStreamWithBuffer; import com.caucho.vfs.Path; import java.io.IOException; import java.io.OutputStream; import java.io.UnsupportedEncodingException; import java.io.Writer; import java.util.Locale; import java.util.logging.Logger; /** * API for handling the PrintWriter/ServletOutputStream */ public class StubResponseStream extends AbstractResponseStream { private final byte []_byteBuffer = new byte[16]; private final char []_charBuffer = new char[16]; /** * Returns true for a Caucho response stream. */ @Override public boolean isCauchoResponseStream() { return true; } /** * Sets the buffer size. */ @Override public void setBufferSize(int size) { } /** * Gets the buffer size. */ @Override public int getBufferSize() { return 0; } /** * Returns the remaining buffer entries. */ @Override public int getRemaining() { return 0; } /** * Returns the stream's buffer. */ public byte []getBuffer() throws IOException { return _byteBuffer; } /** * Returns the stream's buffer offset. */ public int getBufferOffset() throws IOException { return 0; } /** * Sets the stream's buffer length. */ public void setBufferOffset(int offset) throws IOException { } /** * Returns the next buffer. * * @param length the length of the completed buffer * * @return the next buffer */ public byte []nextBuffer(int offset) throws IOException { return _byteBuffer; } /** * Returns the char buffer. */ @Override public char []getCharBuffer() throws IOException { return _charBuffer; } /** * Returns the char buffer offset. */ @Override public int getCharOffset() throws IOException { return 0; } /** * Sets the char buffer offset. */ @Override public void setCharOffset(int offset) throws IOException { } /** * Returns the next char buffer. */ @Override public char []nextCharBuffer(int offset) throws IOException { return _charBuffer; } /** * Writes a byte to the output. */ @Override public void write(int v) throws IOException { } /** * Writes a byte array to the output. */ @Override public void write(byte []buffer, int offset, int length) throws IOException { } /** * Writes a character to the output. */ @Override public void print(int ch) throws IOException { } /** * Writes a char array to the output. */ @Override public void print(char []buffer, int offset, int length) throws IOException { } /** * Clears the output buffer. */ @Override public void clearBuffer() { } /** * Flushes the output buffer. */ @Override public void flushBuffer() throws IOException { } }
dlitz/resin
modules/resin/src/com/caucho/server/http/StubResponseStream.java
Java
gpl-2.0
3,994
(function($) { Drupal.total_gallery_formatter = Drupal.total_gallery_formatter || {}; Drupal.total_gallery_formatter.tgfToBoolean = function(number) { if (number) { return true; } else { return false; } }; Drupal.behaviors.totalGalleryFormatter = { attach : function(context, settings) { var carouselConfiguration = Drupal.settings.totalGalleryFormatter.galleryCarouselConfiguration; var itemsVisible = carouselConfiguration.itemsVisible; var scrollFx = carouselConfiguration.scrollFx; var direction = carouselConfiguration.direction; var slideDuration = carouselConfiguration.slideDuration; var autoplay = carouselConfiguration.autoplay; var circular = carouselConfiguration.circular; var infinite = carouselConfiguration.infinite; var colorbox = carouselConfiguration.colorbox; var easing = carouselConfiguration.easing; var pagDuration = carouselConfiguration.pagDuration; var responsive = carouselConfiguration.responsive; $('body').once('total_gallery_formatter', function() { // Pagination. var pagWidth = null; var pagItems = parseInt(itemsVisible); // Getting main image size. var mainImgWidth = null; var mainImgHeight = null; if (responsive) { mainImgWidth = parseInt($('.tgf-container .tgf-slides img:first', context).attr('width')); mainImgHeight = parseInt($('.tgf-container .tgf-slides img:first', context).attr('height')); var mainImgHeightPercent = (mainImgHeight * 100) / mainImgWidth; mainImgHeight = mainImgHeightPercent + '%'; // Responsive pagination. pagWidth = '100%'; pagItems = null; }; // Building gallery. $('.tgf-container', context).each(function(index){ var $thisCarousel = $(this); $thisCarousel.find('.tgf-slides').carouFredSel({ responsive: Drupal.total_gallery_formatter.tgfToBoolean(responsive), items : { visible : 1, width : mainImgWidth, height : mainImgHeight }, align : 'center', direction : direction, auto : Drupal.total_gallery_formatter.tgfToBoolean(autoplay), scroll : { fx : scrollFx, duration : parseInt(slideDuration), onAfter : function(data) { var slideId = $(data.items.visible[0]).attr('data-slide-id'); $thisCarousel.find('.tgf-pagination .tgf-pag-item').removeClass('selected'); $thisCarousel.find('.tgf-pagination .tgf-pag-item[data-slide-id="' + slideId + '"]').addClass('selected'); } }, prev : { button : $('.tgf-prev-button', $thisCarousel), key : 'left' }, next : { button : $('.tgf-next-button', $thisCarousel), key : 'right' }, }); $thisCarousel.find('.tgf-pagination').carouFredSel({ width : pagWidth, items : { visible : pagItems }, circular: Drupal.total_gallery_formatter.tgfToBoolean(circular), infinite: Drupal.total_gallery_formatter.tgfToBoolean(infinite), auto : false, scroll : { easing : easing, duration : parseInt(pagDuration), }, prev : { button : $thisCarousel.find('.tgf-pag-prev-button') }, next : { button : $thisCarousel.find('.tgf-pag-next-button'), } }); // Setting the selected class. $thisCarousel.find('.tgf-pagination .tgf-pag-item').each(function(index) { $(this).click(function(e) { var slideId = $(this).attr('data-slide-id'); $thisCarousel.find('.tgf-slides').trigger("slideTo", '.tgf-slide-item[data-slide-id="' + slideId + '"]'); $thisCarousel.find('.tgf-pagination .tgf-pag-item').removeClass('selected'); $(this).addClass('selected'); }); }); }); if (!$('.page-admin').length) { if (colorbox) { $('.tgf-slides a').colorbox({returnFocus:false, maxHeight:'98%', maxWidth:'98%', fixed: true}); } } }); } }; })(jQuery);
shweta-sagar/whitemag
sites/all/modules/total_gallery_formatter/js/tgf-gallery-with-carousel.js
JavaScript
gpl-2.0
4,474
<?php /** * Joomla! Content Management System * * @copyright Copyright (C) 2005 - 2019 Open Source Matters, Inc. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ namespace Joomla\CMS\User; \defined('_JEXEC') or die; /** * Interface defining a factory which can create User objects * * @since 4.0.0 */ interface UserFactoryInterface { /** * Method to get an instance of a user for the given id. * * @param int $id The id * * @return User * * @since 4.0.0 */ public function loadUserById(int $id): User; /** * Method to get an instance of a user for the given username. * * @param string $username The username * * @return User * * @since 4.0.0 */ public function loadUserByUsername(string $username): User; }
astridx/joomla-cms
libraries/src/User/UserFactoryInterface.php
PHP
gpl-2.0
825
<?php /** * radio-image Customizer Control. * * @package Kirki * @subpackage Controls * @copyright Copyright (c) 2016, Aristeides Stathopoulos * @license http://opensource.org/licenses/gpl-2.0.php GNU Public License * @since 1.0 */ // Exit if accessed directly if ( ! defined( 'ABSPATH' ) ) { exit; } if ( ! class_exists( 'Kirki_Controls_Radio_Image_Control' ) ) { class Kirki_Controls_Radio_Image_Control extends Kirki_Customize_Control { public $type = 'radio-image'; public function enqueue() { Kirki_Styles_Customizer::enqueue_customizer_control_script( 'kirki-radio-image', 'controls/radio-image', array( 'jquery', 'jquery-ui-button' ) ); } protected function content_template() { ?> <# if ( data.tooltip ) { #> <a href="#" class="tooltip hint--left" data-hint="{{ data.tooltip }}"><span class='dashicons dashicons-info'></span></a> <# } #> <label class="customizer-text"> <# if ( data.label ) { #> <span class="customize-control-title">{{{ data.label }}}</span> <# } #> <# if ( data.description ) { #> <span class="description customize-control-description">{{{ data.description }}}</span> <# } #> </label> <div id="input_{{ data.id }}" class="image"> <# for ( key in data.choices ) { #> <input class="image-select" type="radio" value="{{ key }}" name="_customize-radio-{{ data.id }}" id="{{ data.id }}{{ key }}" {{{ data.link }}}<# if ( data.value === key ) { #> checked="checked"<# } #>> <label for="{{ data.id }}{{ key }}"> <img src="{{ data.choices[ key ] }}"> </label> </input> <# } #> </div> <?php } } }
vvhuang/Agama2
framework/admin/kirki/includes/controls/class-kirki-controls-radio-image-control.php
PHP
gpl-2.0
1,651
<?php /*************************************************************************** * * * Copyright (c) 2004 Simbirsk Technologies Ltd. All rights reserved. * * * * This is commercial software, only users who have purchased a valid * * license and accept to the terms of the License Agreement can install * * and use this program. * * * **************************************************************************** * PLEASE READ THE FULL TEXT OF THE SOFTWARE LICENSE AGREEMENT IN THE * * "copyright.txt" FILE PROVIDED WITH THIS DISTRIBUTION PACKAGE. * ****************************************************************************/ // // $Id: chronopay_form.php 10229 2010-07-27 14:21:39Z 2tl $ // if ( !defined('AREA') ) { if (!empty($_REQUEST['cs1'])) { // Settle data is received DEFINE ('AREA', 'C'); DEFINE ('AREA_NAME' ,'customer'); require './../prepare.php'; require './../init.php'; $order_id = $_REQUEST['cs1']; $order_info = fn_get_order_info($order_id); $processor_data = $order_info['payment_method']; $inner_sign = md5($processor_data['params']['sharedsec'] . $_REQUEST['customer_id'] . $_REQUEST['transaction_id'] . $_REQUEST['transaction_type'] . $order_info['total']); if ($_REQUEST['sign'] == $inner_sign) { fwrite($fp, "\nOK"); $pp_response['order_status'] = 'P'; $pp_response["reason_text"] = 'Approved; Customer ID: ' . $_REQUEST['customer_id']; $pp_response["transaction_id"] = $_REQUEST['transaction_id']; if (fn_check_payment_script('chronopay_form.php', $order_id)) { fn_finish_payment($order_id, $pp_response); } } exit; } else { die('Access denied'); } } if (defined('PAYMENT_NOTIFICATION')) { if ($mode == 'notify') { $order_id = (int) $_REQUEST['order_id']; $order_info = fn_get_order_info($order_id); $processor_data = $order_info['payment_method']; // We are trying to avoid mess with declined and success urls $sign = md5($processor_data['params']['product_id'] . '-' . $order_info['total'] . '-' . $processor_data['params']['sharedsec']); // Because the callback comes only after return we have to make sure that this redirect is successful if (in_array($order_info['status'], array('N', 'D')) && (empty($_REQUEST['sign']) || $sign != $_REQUEST['sign'])) { $pp_response['order_status'] = 'D'; $pp_response["reason_text"] = fn_get_lang_var('text_transaction_declined'); fn_finish_payment($order_id, $pp_response, false); } else { // Set open status until callback from chronopay service is recieved fn_change_order_status($order_id, 'O', $order_info['status'], false); } fn_order_placement_routines($order_id); } } else { if (!defined('AREA') ) { die('Access denied'); } $post_url = Registry::get('config.current_location') . '/payments/chronopay_form.php'; $return_url = Registry::get('config.current_location') . "/$index_script?dispatch=payment_notification.notify&payment=chronopay_form&order_id=$order_id"; $country = db_get_field("SELECT code_A3 FROM ?:countries WHERE code = ?s", $order_info['b_country']); $product_name = ""; // Products if (!empty($order_info['items'])) { foreach ($order_info['items'] as $v) { $product_name = $product_name . str_replace(', ', ' ', $v['product']) . ",<br>\n "; } } // Certificates if (!empty($order_info['gift_certificates'])) { foreach ($order_info['gift_certificates'] as $v) { $product_name = $product_name . str_replace(', ', ' ', $v['gift_cert_code']) . ",<br>\n "; } } // Shippings if (floatval($order_info['shipping_cost'])) { foreach ($order_info['shipping'] as $v) { $product_name .= str_replace(', ', ' ', $v['shipping']) . ",<br>\n "; } } $sign = md5($processor_data['params']['product_id'] . '-' . $order_info['total'] . '-' . $processor_data['params']['sharedsec']); $lang_code = CART_LANGUAGE; echo <<<EOT <html> <body onLoad="javascript: document.process.submit();"> <form action="https://payments.chronopay.com/" method="POST" name="process"> <input type="hidden" name="product_id" value="{$processor_data['params']['product_id']}" /> <input type="hidden" name="product_name" value="{$product_name}" /> <input type="hidden" name="product_price" value="{$order_info['total']}" /> <input type="hidden" name="order_id" value="{$order_id}" /> <input type="hidden" name="cs1" value="{$order_id}" /> <input type="hidden" name="language" value="{$lang_code}" /> <input type="hidden" name="f_name" value="{$order_info['b_firstname']}" /> <input type="hidden" name="s_name" value="{$order_info['b_lastname']}" /> <input type="hidden" name="street" value="{$order_info['b_address']}" /> <input type="hidden" name="city" value="{$order_info['b_city']}" /> <input type="hidden" name="state" value="{$order_info['b_state']}" /> <input type="hidden" name="zip" value="{$order_info['b_zipcode']}" /> <input type="hidden" name="country" value="{$country}" /> <input type="hidden" name="phone" value="{$order_info['phone']}" /> <input type="hidden" name="email" value="{$order_info['email']}" /> <input type="hidden" name="cb_url" value="{$post_url}" /> <input type="hidden" name="success_url" value="{$return_url}&sign={$sign}" /> <input type="hidden" name="decline_url" value="{$return_url}" /> <input type="hidden" name="sign" value="{$sign}" /> EOT; $msg = fn_get_lang_var('text_cc_processor_connection'); $msg = str_replace('[processor]', 'Chronopay server', $msg); echo <<<EOT </form> <p><div align=center>{$msg}</div></p> </body> </html> EOT; die(); } exit; ?>
diedsmiling/busenika
payments/chronopay_form.php
PHP
gpl-2.0
5,787
<?php /* * id = ot_billsafe.php * location = /includes/modules/order_total * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * @package BillSAFE_2 * @copyright (C) 2011 Bernd Blazynski * @license GPLv2 */ class ot_billsafe { var $title, $output; function ot_billsafe() { $this->code = 'ot_billsafe'; $this->title = MODULE_ORDER_TOTAL_BILLSAFE_TITLE; $this->description = MODULE_ORDER_TOTAL_BILLSAFE_DESCRIPTION; $this->enabled = MODULE_ORDER_TOTAL_BILLSAFE_STATUS=='true'?true:false; $this->sort_order = MODULE_ORDER_TOTAL_BILLSAFE_SORT_ORDER; $this->output = array(); $this->amount = 0; $this->original_total = 0; $this->amounts = array(); $this->schg = array(); } function process() { global $order, $xtPrice; if ($this->enabled) { if ($_SESSION['payment'] == 'billsafe_2') { $this->xtc_order_total(); $this->calc_schg(); if ($this->schg['amount'] != 0) { if (stristr(MODULE_PAYMENT_BILLSAFE_2_SCHG, '%')) { $this->output[] = array('title' => MODULE_PAYMENT_BILLSAFE_2_SCHG.'&nbsp;'.MODULE_ORDER_TOTAL_BILLSAFE_SCHG, 'text' => $xtPrice->xtcFormat($this->schg['amount'], true), 'value' => $this->schg['amount']); } else { $this->output[] = array('title' => MODULE_ORDER_TOTAL_BILLSAFE_SCHG, 'text' => $xtPrice->xtcFormat($this->schg['amount'], true), 'value' => $this->schg['amount']); } $order->info['total'] += $this->schg['amount']; // $order->info['tax'] += $this->schg['tax']; } } } } function calc_schg() { global $order; if (MODULE_PAYMENT_BILLSAFE_2_SCHG != '') { $schg_tax_rate = xtc_get_tax_rate(MODULE_PAYMENT_BILLSAFE_2_SCHGTAX); $schg_tax_name = xtc_get_tax_description(MODULE_PAYMENT_BILLSAFE_2_SCHGTAX); if (stristr(MODULE_PAYMENT_BILLSAFE_2_SCHG, '%')) { if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 1) { $schg_amount = xtc_add_tax(($this->amount * MODULE_PAYMENT_BILLSAFE_2_SCHG / 100), $schg_tax_rate); $schg_amount_calc = $this->amount * MODULE_PAYMENT_BILLSAFE_2_SCHG / 100; } else { $schg_amount = $this->amount * MODULE_PAYMENT_BILLSAFE_2_SCHG / 100; $schg_amount_calc = $this->amount * MODULE_PAYMENT_BILLSAFE_2_SCHG / 100; } } else { if ($_SESSION['customers_status']['customers_status_show_price_tax'] == 1) { $schg_amount = xtc_add_tax(MODULE_PAYMENT_BILLSAFE_2_SCHG, $schg_tax_rate); $schg_amount_calc = MODULE_PAYMENT_BILLSAFE_2_SCHG; } else { $schg_amount = MODULE_PAYMENT_BILLSAFE_2_SCHG; $schg_amount_calc = MODULE_PAYMENT_BILLSAFE_2_SCHG; } } $schg_tax = $schg_amount_calc * $schg_tax_rate / 100; } else { $schg_amount = 0; $schg_tax = 0; } if ($schg_tax_rate && ($schg_tax > 0)) { reset($order->info['tax_groups']); while (list($key, $value) = each($order->info['tax_groups'])) { if (strpos($key, $schg_tax_rate.'%')) { $order->info['tax_groups'][$key] += $schg_tax; } else { $order->info['tax_groups'][TAX_ADD_TAX.$schg_tax_name] += $schg_tax; } } } $this->schg['amount'] = $schg_amount; $this->schg['tax'] = $schg_tax; } function xtc_order_total() { global $order; $order_total = $order->info['total']; $products = $_SESSION['cart']->get_products(); for ($i=0; $i < sizeof($products); $i++) { $prid = xtc_get_prid($products[$i]['id']); $gv_query = xtc_db_query('SELECT products_price, products_tax_class_id, products_model FROM '.TABLE_PRODUCTS.' WHERE products_id = "'.$prid.'"'); $gv_result = xtc_db_fetch_array($gv_query); $qty = $_SESSION['cart']->get_quantity($products[$i]['id']); $products_tax = xtc_get_tax_rate($gv_result['products_tax_class_id']); if (preg_match('/^GIFT/', addslashes($gv_result['products_model']))) { if ($this->include_tax =='false') { $gv_amount = $gv_result['products_price'] * $qty; } else { $gv_amount = ($gv_result['products_price'] + xtc_calculate_tax($gv_result['products_price'],$products_tax)) * $qty; } $order_total -= $gv_amount; } else { $this->amounts[(string)$products_tax] += $gv_result['products_price'] * (int)$qty; $this->amounts['total'] += $gv_result['products_price'] * $qty; } } $this->amount = $order_total; } function check() { if (!isset($this->check)) { $check_query = xtc_db_query('SELECT configuration_value FROM '.TABLE_CONFIGURATION.' WHERE configuration_key = "MODULE_ORDER_TOTAL_BILLSAFE_STATUS"'); $this->check = xtc_db_num_rows($check_query); } return $this->check; } function install() { xtc_db_query('INSERT INTO '.TABLE_CONFIGURATION.' (configuration_key, configuration_value, configuration_group_id, sort_order, set_function, date_added) values ("MODULE_ORDER_TOTAL_BILLSAFE_STATUS", "true", "6", "1", "xtc_cfg_select_option(array(\'true\', \'false\'), ", now())'); xtc_db_query('INSERT INTO '.TABLE_CONFIGURATION.' (configuration_key, configuration_value, configuration_group_id, sort_order, date_added) values ("MODULE_ORDER_TOTAL_BILLSAFE_SORT_ORDER", "39", "6", "2", now())'); } function keys() { $keys = array(); $check_query = xtc_db_query('SELECT configuration_key FROM '.TABLE_CONFIGURATION.' WHERE configuration_key LIKE "MODULE_ORDER_TOTAL_BILLSAFE_%" ORDER BY sort_order'); while ($key = xtc_db_fetch_array($check_query)) $keys[] = $key['configuration_key']; return $keys; } function remove() { xtc_db_query('DELETE FROM '.TABLE_CONFIGURATION.' WHERE configuration_key LIKE "MODULE_ORDER_TOTAL_BILLSAFE_%"'); } } ?>
commerceseo/v2next
includes/modules/order_total/ot_billsafe.php
PHP
gpl-2.0
6,027
<?php $kses_filter = array( 'input' => array( 'type' => array(), 'name' => array(), 'id' => array(), 'class' => array(), 'value' => array(), ), ); $clear_api_cache_button = get_submit_button( __( 'Clear Cache', 'wp-rest-api-controller' ), 'secondary', 'clear-wp-rest-api-controller-cache' ); $save_settings_button = get_submit_button( __( 'Save Settings', 'wp-rest-api-controller' ), 'primary', 'save-wp-rest-api-controller-settings' ); ?> <h2><?php esc_html_e( 'WP REST API Controller Settings', 'wp-rest-api-controller' ); ?></h2> <form method="POST" action="options.php"> <?php settings_fields( 'wp-rest-api-controller' ); do_settings_sections( 'wp-rest-api-controller' ); wp_nonce_field( 'clear_wp_rest_api_controller_cache', 'clear_wp_rest_api_controller_cache' ); echo wp_kses_post( '<div class="submit-buttons">' ); echo wp_kses( $save_settings_button, $kses_filter ); echo '<span class="top-right tipso delete-rest-api-cache-tipso" data-tipso-title="' . esc_attr__( 'Delete REST API Cache', 'wp-rest-api-controller' ) . '" data-tipso="' . esc_attr__( 'Clear the WP REST API Cache stored in this plugin. If you recently registered a new post type, or assigned new meta data to a post - click this to update the lists above.', 'wp-rest-api-controller' ) . '">'; echo wp_kses( $clear_api_cache_button, $kses_filter ); echo '</span>'; echo wp_kses_post( '</div>' ); ?> </form>
yikesinc/wp-rest-api-controller
admin/partials/settings-page.php
PHP
gpl-2.0
1,472
<?php /* SLO Cloud - A Cloud-Based SLO Reporting Tool for Higher Education This is a peer-reviewed, open-source, public project made possible by the Open Innovation in Higher Education project. Copyright (C) 2015 Jesse Lawson, San Bernardino Community College District Contributors: Jesse Lawson Jason Brady THIS PROJECT IS LICENSED UNDER GPLv2. YOU MAY COPY, DISTRIBUTE AND MODIFY THE SOFTWARE AS LONG AS YOU TRACK CHANGES/DATES OF IN SOURCE FILES AND KEEP ALL MODIFICATIONS UNDER GPL. YOU CAN DISTRIBUTE YOUR APPLICATION USING A GPL LIBRARY COMMERCIALLY, BUT YOU MUST ALSO DISCLOSE THE SOURCE CODE. GNU General Public License Version 2 Disclaimer: --- This file is part of SLO Cloud SLO Cloud is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later. SLO Cloud is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA or visit http://opensource.org/licenses/GPL-2.0 --- */ use Doctrine\DBAL\Types\Type; if (file_exists('./vendor')) { require_once './vendor/autoload.php'; } else { require_once '../vendor/autoload.php'; } Type::addType('utc_datetime', 'SLOCloud\Model\Storage\Mapping\UTCDateTimeType');
lawsonry/slocloud
src/bootstrap.php
PHP
gpl-2.0
1,650
<?php namespace Augwa\ShortUrlBundle\Controller; /** * Class UserFactoryController * @package Augwa\ShortUrlBundle\Controller */ class UserFactoryController extends FactoryController { /** * @return UserController */ public function make() { $user = new UserController; $user->setContainer($this->container); return $user; } }
augwa/short-url
src/Augwa/ShortUrlBundle/Controller/UserFactoryController.php
PHP
gpl-2.0
383
/*************************************************************************** Copyright (C) 2005-2009 Robby Stephenson <robby@periapsis.org> ***************************************************************************/ /*************************************************************************** * * * This program is free software; you can redistribute it and/or * * modify it under the terms of the GNU General Public License as * * published by the Free Software Foundation; either version 2 of * * the License or (at your option) version 3 or any later version * * accepted by the membership of KDE e.V. (or its successor approved * * by the membership of KDE e.V.), which shall act as a proxy * * defined in Section 14 of version 3 of the license. * * * * This program is distributed in the hope that it will be useful, * * but WITHOUT ANY WARRANTY; without even the implied warranty of * * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * * GNU General Public License for more details. * * * * You should have received a copy of the GNU General Public License * * along with this program. If not, see <http://www.gnu.org/licenses/>. * * * ***************************************************************************/ #include "datefieldwidget.h" #include "datewidget.h" #include "../field.h" using Tellico::GUI::DateFieldWidget; DateFieldWidget::DateFieldWidget(Tellico::Data::FieldPtr field_, QWidget* parent_) : FieldWidget(field_, parent_) { m_widget = new DateWidget(this); connect(m_widget, &DateWidget::signalModified, this, &DateFieldWidget::checkModified); registerWidget(); } QString DateFieldWidget::text() const { return m_widget->text(); } void DateFieldWidget::setTextImpl(const QString& text_) { m_widget->setDate(text_); } void DateFieldWidget::clearImpl() { m_widget->clear(); editMultiple(false); } QWidget* DateFieldWidget::widget() { return m_widget; }
KDE/tellico
src/gui/datefieldwidget.cpp
C++
gpl-2.0
2,371
/* * Distributed bus system for robotic applications * Copyright (C) 2009 University of Cambridge * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License as * published by the Free Software Foundation; either version 2 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA */ package uk.ac.cam.dbs; import static uk.ac.cam.dbs.util.ByteBufferHelper.numFromBytes; import static uk.ac.cam.dbs.util.ByteBufferHelper.numToBytes; import java.io.IOException; import java.util.Vector; import java.util.Hashtable; import java.util.Iterator; import java.util.Enumeration; /** <p>Clock synchronisation protocol implementation.</p> * * <p>The clock synchronisation protocol works on a peer-to-peer basis, * attempting to synchronise to a network clock that is the average of * the internal clocks of all the devices on the network.</p> */ public class ClockSync extends TimeProvider implements DMPMessageListener, Runnable { private static final int PORT = 50123; private static final int UPDATE_PERIOD = 1000; private static final int MAX_STORE_SIZE = 5; /* Contains RecvRecord, keyed by BusConnection */ private Hashtable recvStore; /* Contains SendRecord (sent time), keyed by seq % sentStore.size() */ private long[] sentStore; private Object offsetLock; private long offset; private Object seqLock; private int seq; /* Contains *previous* sequence number */ private double gain; private TimeProvider internalTime; /** Create a new ClockSync service. */ public ClockSync() { this(TimeProvider.systemTimeProvider()); } /** Create a new ClockSync service using a given reference * clock. This is mostly intended for testing. * * @param internalTime TimeProvider instance that the ClockSync * should use as its "reference time". */ public ClockSync(TimeProvider internalTime) { this.internalTime = internalTime; recvStore = new Hashtable(); sentStore = new long[10]; offset = 0; offsetLock = new Object(); seq = 0; seqLock = new Object(); gain = 1.0; } /** Get the current clock offset estimate. * * @return the estimated difference between the internal clock * source and the network clock. */ public long getOffset(long offset) { return offset; } /** <p>Run the clock synchronisation service. Should be executed in * its own thread, e.g.:</p> * * <code>ClockSync service = new ClockSync(); * Thread clockSyncThread = new Thread(service); * clockSyncThread.setDaemon(true); * clockSyncThread.start();</code> * * <p>The function first binds itself to a DMP port. It then * enters a loop which repeatedly sends out clock sync protocol * messages, and updates the current clock estimate based on any * messages that have been received.</p> * */ public void run() { try { SystemBus.getSystemBus().addDMPService(this, PORT); } catch (DMPBindException e) { System.err.println("Could not start clock sync service: " + e.getMessage()); return; } while (true) { /* Send clock sync messages */ Vector connections = SystemBus.getSystemBus().getConnections(); synchronized (connections) { for (int i = 0; i < connections.size(); i++) { try { sendMessage((BusConnection) connections.elementAt(i)); } catch (IOException e) { System.err.println("Failed to send clock message: " + e.getMessage()); continue; } } } /* Sleep for UPDATE_PERIOD + a random delay between 0 and * UPDATE_PERIOD/2. This is to avoid multiple devices * phase-locking their clock sync loops. */ try { int sleepTime = (int) (UPDATE_PERIOD * (1.0 + Math.random() / 2)); Thread.sleep(sleepTime); } catch (InterruptedException e) { System.err.println("Stopping clock sync service."); break; } /* Update estimate */ updateOffset(); } SystemBus.getSystemBus().removeDMPService(this, -1); } /** Get the current estimate of network time. * * @return the current network time estimate in milliseconds. */ public long currentTimeMillis() { long sysTime = internalTime.currentTimeMillis(); return sysTime + offset; } /** Process a clock protocol message. Calculates the roundtrip * latency, and stores message information for the next update to * the clock offset estimate. * * @param connection The connection that the message arrived on. * @param msg The message that was received. */ public void recvDMPMessage(BusConnection connection, DMPMessage msg) { long localTime = System.currentTimeMillis(); /* Parse the message payload */ byte[] buf = msg.getPayload(); if (buf.length != 24) { /* The message appears to be invalid. */ return; } int recvSeq = (int) numFromBytes(buf, 0, 4); long remoteTime = numFromBytes(buf, 4, 8); int oldSeq = (int) numFromBytes(buf, 12, 4); long holdTime = numFromBytes(buf, 16, 8); /* Calculate the latency if we can */ long sentTime = -1; long roundTrip = 0; boolean roundTripValid = false; synchronized (sentStore) { if ((oldSeq == 0) || (oldSeq <= this.seq - 10)) { sentTime = -1; } else { sentTime = sentStore[oldSeq % sentStore.length]; } } if (sentTime >= 0) { roundTrip = localTime - sentTime - holdTime; roundTripValid = true; } /* Do all the synchronized operations last, in one go, to * avoid problems with added latency while waiting to * synchronise */ RecvRecord rec = null; synchronized (recvStore) { rec = (RecvRecord) recvStore.get(connection); if (rec == null) { rec = this.new RecvRecord(); recvStore.put(connection, rec); } synchronized (rec) { rec.seq = recvSeq; rec.remoteTime = remoteTime; rec.localTime = localTime; rec.roundTrip = roundTrip; rec.roundTripValid = roundTripValid; rec.usedForUpdate = false; } } } /** Entry in the record of received packets. */ private class RecvRecord { int seq; long localTime; long remoteTime; long roundTrip; boolean roundTripValid; boolean usedForUpdate; RecvRecord() { roundTripValid = false; usedForUpdate = false; } } /** Send a clock sync message */ private void sendMessage (BusConnection connection) throws IOException { RecvRecord rec = null; synchronized (recvStore) { rec = (RecvRecord) recvStore.get(connection); } long now = internalTime.currentTimeMillis(); byte[] payload = new byte[24]; /* Get the next sequence number */ /* Ensure we never send out a message with seq=0 */ int seq = 0; synchronized (seqLock) { while (seq == 0) { seq = ++this.seq; } } /* Did we receive a message from this connection? */ int oldSeq = 0; long holdTime = 0; if (rec != null) { oldSeq = rec.seq; holdTime = now - rec.localTime; } /* Pack data into the message payload */ numToBytes(seq, payload, 0, 4); numToBytes(now+offset, payload, 4, 8); numToBytes(oldSeq, payload, 12, 4); numToBytes(holdTime, payload, 16, 8); /* Send message */ DMPMessage msg = new DMPMessage(PORT, payload); /* Add to record of sent messages */ synchronized(sentStore) { sentStore[seq % sentStore.length] = now; } SystemBus.getSystemBus().sendDMPMessage(connection, msg); } /** Uses the received messages to calculate a new clock offset. */ private void updateOffset () { synchronized (recvStore) { Enumeration conns = recvStore.keys(); int N = SystemBus.getSystemBus().getConnections().size(); double e = 0.0; synchronized (offsetLock) { while (conns.hasMoreElements()) { Object k = conns.nextElement(); RecvRecord rec = (RecvRecord) recvStore.get(k); synchronized (rec) { if (rec.roundTripValid && !rec.usedForUpdate) { e += rec.remoteTime + rec.roundTrip/2 - rec.localTime - offset; rec.usedForUpdate = true; } } } offset += (long) gain * e / (N+1.0); } } } }
peter-b/distributed-bus-system
nxt-src/uk/ac/cam/dbs/ClockSync.java
Java
gpl-2.0
10,111
<?php // $HeadURL: https://joomgallery.org/svn/joomgallery/JG-3/JG/trunk/administrator/components/com_joomgallery/helpers/html/joomgallery.php $ // $Id: joomgallery.php 4404 2014-06-26 21:23:58Z chraneco $ /******************************************************************************\ ** JoomGallery 3 ** ** By: JoomGallery::ProjectTeam ** ** Copyright (C) 2008 - 2013 JoomGallery::ProjectTeam ** ** Based on: JoomGallery 1.0.0 by JoomGallery::ProjectTeam ** ** Released under GNU GPL Public License ** ** License: http://www.gnu.org/copyleft/gpl.html or have a look ** ** at administrator/components/com_joomgallery/LICENSE.TXT ** \******************************************************************************/ defined( '_JEXEC' ) or die( 'Direct Access to this location is not allowed.' ); /** * Utility class for creating HTML Grids * * @static * @package JoomGallery * @since 1.5.5 */ abstract class JHtmlJoomGallery { /** * Displays the type of an image or category * * @param object $row Data object * @param string $user_uploaded String to display in case of user created objects * @param string $admin_uploaded String to display in case of objects created by an administrator * @return string Html code to display the upload type * @since 1.5.5 */ public static function type($row, $user_uploaded = 'COM_JOOMGALLERY_COMMON_USER_UPLOAD', $admin_uploaded = 'COM_JOOMGALLERY_COMMON_ADMIN_UPLOAD') { $ambit = JoomAmbit::getInstance(); if( (isset($row->useruploaded) && $row->useruploaded) || (!isset($row->useruploaded) && $row->owner) ) { $img = 'users.png'; $title = JText::_($user_uploaded); } else { $img = 'admin.png'; $title = JText::_($admin_uploaded); } $imgsrc = $ambit->getIcon($img); $html = '<img src="'.$imgsrc.'" alt="'.$title.'" title="'.$title.'" />' ; return $html; } /** * Displays the name or user name of a category, image or comment owner * and may link it to the profiles of other extensions (if available). * * @param int $userId The ID of the user who will be displayed * @param boolean $context The context in which the user will be dispayed * @return string The user's name * @since 1.5.5 */ public static function displayName($userId, $context = null) { $userId = intval($userId); if(!$userId) { if(JFactory::getApplication()->isSite()) { return JText::_('COM_JOOMGALLERY_COMMON_NO_DATA'); } else { return JText::_('COM_JOOMGALLERY_COMMON_NO_USER'); } } $config = JoomConfig::getInstance(); $dispatcher = JDispatcher::getInstance(); $realname = $config->get('jg_realname') ? true : false; $plugins = $dispatcher->trigger('onJoomDisplayUser', array($userId, $realname, $context)); foreach($plugins as $plugin) { if($plugin) { return $plugin; } } $user = JFactory::getUser($userId); if($realname) { $username = $user->get('name'); } else { $username = $user->get('username'); } return $username; } /** * Fires onPrepareContent for a text if configured in the gallery * * @param string $text The text to be transformed. * @return string The text after transformation. * @since 1.5.5 */ public static function text($text) { $config = JoomConfig::getInstance(); if($config->get('jg_contentpluginsenabled')) { $text = JHTML::_('content.prepare', $text); } return $text; } /** * Returns the HTML tag of a specified icon * * @param string $icon Filename of the icon * @param string $alt Alternative text of the icon * @param string $extra Additional HTML code in the tag * @param string $path Path to the icon, if null the default path is used * @param boolean $translate Determines whether the text will be translated, defaults to true. * @return string The HTML output * @since 1.5.5 */ public static function icon($icon, $alt = 'Icon', $extra = null, $path = null, $translate = true) { if(is_null($path)) { $ambit = JoomAmbit::getInstance(); $path = $ambit->get('icon_url'); // Make the icons overridable by layout packages if($layout = $ambit->get('layout')) { if(is_file(JPATH_ROOT.'/media/joomgallery/images/'.$layout.'/'.$icon)) { $path = $path.$layout.'/'; } } } if($extra) { $extra = ' '.$extra; } if($translate) { $alt = JText::_($alt); } $class = 'jg-icon-'.str_replace(array('.jpg', '.png', '.gif'), '', $icon); return '<img src="'.$path.$icon.'" alt="'.$alt.'" class="pngfile jg_icon '.$class.'"'.$extra.' />'; } /** * Displays the toplist bar * * @return void * @since 1.5.5 */ public static function toplistbar() { $config = JoomConfig::getInstance(); $separator = " -\n"; echo JText::sprintf('COM_JOOMGALLERY_TOPLIST_TOP', $config->get('jg_toplist')); ?> <?php if($config->get('jg_showrate')) { ?> <a href="<?php echo JRoute::_('index.php?view=toplist&type=toprated'); ?>"> <?php echo JText::_('COM_JOOMGALLERY_COMMON_TOPLIST_TOP_RATED'); ?></a> <?php if($config->get('jg_showlatest') || $config->get('jg_showcom') || $config->get('jg_showmostviewed')) { echo $separator; } } if($config->get('jg_showlatest')) { ?> <a href="<?php echo JRoute::_('index.php?view=toplist&type=lastadded'); ?>"> <?php echo JText::_('COM_JOOMGALLERY_COMMON_TOPLIST_LAST_ADDED'); ?></a> <?php if($config->get('jg_showcom') || $config->get('jg_showmostviewed')) { echo $separator; } } if($config->get('jg_showcom')) { ?> <a href="<?php echo JRoute::_('index.php?view=toplist&type=lastcommented'); ?>"> <?php echo JText::_('COM_JOOMGALLERY_COMMON_TOPLIST_LAST_COMMENTED'); ?></a> <?php if($config->get('jg_showmostviewed')) { echo $separator; } } if($config->get('jg_showmostviewed')) { ?> <a href="<?php echo JRoute::_('index.php?view=toplist'); ?>"> <?php echo JText::_('COM_JOOMGALLERY_COMMON_TOPLIST_MOST_VIEWED'); ?></a> <?php } } /** * Creates the name tags * * @param array $rows An array of name tag objects * @return string The HTML output * @since 1.5.5 */ public static function nametags(&$rows) { if(!count($rows)) { return ''; } $config = JoomConfig::getInstance(); $width = $config->get('jg_nameshields_width'); $html = ''; $i = 1; foreach($rows as $row) { $name = JHTMLJoomGallery::displayName($row->nuserid, 'nametag'); $length = strlen(trim(strip_tags($name))) * $width; $icon = ''; $html .= '<div id="jg-nametag-'.$i.'" style="position:absolute; top:'.$row->nxvalue.'px; left:'.$row->nyvalue.'px; width:'.$length.'px; z-index:'.$row->nzindex.'" class="nameshield'; //if($config->get('jg_nameshields_others')) //{ $user = JFactory::getUser(); if($row->by == $user->get('id') || $row->nuserid == $user->get('id') || $user->authorise('core.manage', _JOOM_OPTION)) { $html .= '" onmouseover="javascript:document.id(\'jg-nametag-remove-icon-'.$row->nid.'\').position({relativeTo: \'jg-nametag-'.$i.'\', position: \'upperRight\', edge: \'bottomLeft\'}).wink(3000);'; $icon = '<a id="jg-nametag-remove-icon-'.$row->nid.'" class="jg-nametag-remove-icon jg_displaynone" href="javascript:if(confirm(\''.JText::_('COM_JOOMGALLERY_DETAIL_NAMETAGS_ALERT_SURE_DELETE_OTHERS', true).'\')){ location.href=\''.JRoute::_('index.php?task=nametags.remove&id='.$row->npicid.'&nid='.$row->nid, false).'\';}">' .JHTML::_('joomgallery.icon', 'tag_delete.png', 'COM_JOOMGALLERY_DETAIL_NAMETAGS_DELETE_OTHERS_TIPCAPTION').'</a>'; } //} $html .= '">'; $html .= $name; $html .= '</div>'; $html .= $icon; $i++; } return $html; } /** * Returns the string of an anchor for a URL if using anchors is enabled * * @param string $name Name of the anchor * @return string The string of the anchor * @since 1.5.5 */ public static function anchor($name = 'joomimg') { $config = JoomConfig::getInstance(); $anchor = ''; if($name && $config->get('jg_anchors')) { $anchor = '#'.$name; } return $anchor; } /** * Returns the HTML output of a tooltip if showing tooltips is enabled * * @param string $text The text of the tooltip * @param string $title The title of the tooltip * @param boolean $addclass True, if the class attribute shall be added and false if it's already there * @param boolean $translate True, if the text and the title shall be translated * @param string $class The name of the class used by Mootools to detect the tooltips * @return string The HTML output created * @since 1.5.5 */ public static function tip($text = 'Tooltip', $title = null, $addclass = false, $translate = true, $class = 'hasHint') { $config = JoomConfig::getInstance(); $html = ''; if($config->get('jg_tooltips')) { static $loaded = false; if(!$loaded) { $params = array(); if($config->get('jg_tooltips') == 2) { $params['template'] = '<div class="jg-tooltip-wrap tooltip"><div class="tooltip-inner tip"></div></div>'; } JHtml::_('bootstrap.tooltip', '.'.$class, $params); $loaded = true; } if($config->get('jg_tooltips') == 2) { $tmp = ""; if($title) { $tmp = '<div class="tip-title">'; if($translate) { $title = JText::_($title); } $tmp .= $title . '</div>'; } $tmp .= '<div class="tip-text">' . ($translate ? JText::_($text) : $text) . '</div>'; $text = htmlspecialchars($tmp, ENT_QUOTES, 'UTF-8'); } else { $text = JHtml::tooltipText($title, $text, $translate); } if($addclass) { $html = ' class="'.$class.'" title="'.$text.'"'; } else { $html = ' '.$class.'" title="'.$text; } } return $html; } /** * Creates invisible links to images in order that * the popup boxes recognize them * * @param array $rows An array of image objects to use * @param int $start Index of the first image to use * @param int $end Index of the last image to use, if null we will use every image from $start to end * @param string $secondGroup Name of an optional second group, by specifying a second group all links will be duplicated with that group * @return string The HTML output * @since 1.5.5 */ public static function popup(&$rows, $start = 0, $end = null, $secondGroup = null) { $config = JoomConfig::getInstance(); $ambit = JoomAmbit::getInstance(); $user = JFactory::getUser(); $view = JRequest::getCmd('view'); $html = ''; if( ( $view == 'category' // 'jg_detailpic_open' is not numeric if an OpenImage plugin was selected, thus we handle it like > 4 && (!is_numeric($config->get('jg_detailpic_open')) || $config->get('jg_detailpic_open') > 4) && ( $config->get('jg_showdetailpage') == 1 || ($config->get('jg_showdetailpage') == 0 && $user->get('id')) ) ) || ( $view == 'detail' && ( ($config->get('jg_bigpic') == 1 && $user->get('id')) || ($config->get('jg_bigpic_unreg') == 1 && !$user->get('id')) ) // 'jg_bigpic_open' is not numeric if an OpenImage plugin was selected, thus we handle it like > 4 && (!is_numeric($config->get('jg_bigpic_open')) || $config->get('jg_bigpic_open') > 4) ) ) { if(is_null($end)) { $rows = array_slice($rows, (int)$start); } else { $rows = array_slice($rows, (int)$start, (int)$end); } $html = ' <div class="jg_displaynone">'; foreach($rows as $row) { if( ($view == 'detail' && is_file($ambit->getImg('orig_path', $row))) || $view == 'category' ) { if($view == 'detail') { $type = $config->get('jg_bigpic_open'); } else { $type = $config->get('jg_detailpic_open'); } // Set the title attribute in a tag with title and/or description of image // if a box is activated if(!is_numeric($type) || $type > 1) { $atagtitle = JHtml::_('joomgallery.getTitleforATag', $row); } else { $atagtitle = 'title="'.$row->imgtitle.'"'; } $link = self::openImage($type, $row); $html .= ' <a href="'.$link.'" '.$atagtitle.'>'.$row->id.'</a>'; if($secondGroup) { $link = self::openImage($type, $row, false, $secondGroup); $html .= ' <a href="'.$link.'" '.$atagtitle.'>'.$row->id.'</a>'; } } } $html .= ' </div>'; } return $html; } /** * Returns the title attribute of HTML a tag * * @param object $image The object which holds the image data * @param boolean $attr True if title attribute should be returned completely, * if false only the content is returned, defaults to true * @return string The title attribute of HTML a Tag * @since 2.0 */ public static function getTitleforATag($image, $attr = true) { $config = JoomConfig::getInstance(); $tagtitle = ''; $tagdesc = ''; if( $config->get('jg_show_title_in_popup') || $config->get('jg_show_description_in_popup')) { if($config->get('jg_show_title_in_popup')) { $tagtitle = $image->imgtitle; } if( $config->get('jg_show_description_in_popup') && !empty($image->imgtext)) { if($config->get('jg_show_description_in_popup') == 1) { // Show description without html tag modifications $tagdesc = htmlspecialchars($image->imgtext); } else { // Strip html tags of description before $tagdesc = strip_tags($image->imgtext); } } if(!empty($tagdesc)) { if(!empty($tagtitle)) { $tagtitle .= ' '.$tagdesc; } else { $tagtitle = $tagdesc; } } if(!empty($tagtitle) && $attr) { $tagtitle = 'title="'.$tagtitle.'"'; } } return $tagtitle; } /** * Returns the link to a given image, which opens the image in slimbox, for example * * @param int $open Use of lightbox, javascript window or DHTML container? * @param int/object $image The id of the image or an object which holds the image data * @param string $type The image type ('thumb', 'img', 'orig'), use 'false' for default value * @param string $group Name of a group to group images in the popups * @return string The link to the image * @since 1.0.0 */ public static function openImage($open, $image, $type = false, $group = null) { static $loaded = array(); $config = JoomConfig::getInstance(); $ambit = JoomAmbit::getInstance(); $user = JFactory::getUser(); // No detail view for guests if adjusted like that if(!$config->get('jg_showdetailpage') && !$user->get('id')) { return 'javascript:alert(\''.JText::_('COM_JOOMGALLERY_COMMON_ALERT_NO_DETAILVIEW_FOR_GUESTS', true).'\')'; } if(!is_object($image)) { $image = $ambit->getImgObject($image); } if(!$type) { // 'jg_detailpic_open' is not numeric if an OpenImage plugin was selected, thus we handle it like > 4 if( (!is_numeric($config->get('jg_detailpic_open')) || $config->get('jg_detailpic_open') > 4) && $config->get('jg_lightboxbigpic') ) { $type = 'orig'; } else { if(JRequest::getCmd('view') == 'detail') { $type = 'orig'; } else { $type = 'img'; } } } if(!$group) { $group = 'joomgallery'; } $img_url = $ambit->getImg($type.'_url', $image); $img_path = $ambit->getImg($type.'_path', $image); switch($open) { case '0': // Detail view $link = JRoute::_('index.php?view=detail&id='.$image->id); break; case 1: // New window $link = $img_url."\" target=\"_blank"; break; case 2: // JavaScript window $imginfo = getimagesize($img_path); $link = "javascript:joom_openjswindow('".$img_url."','".JoomHelper::fixForJS($image->imgtitle)."', '".$imginfo[0]."','".$imginfo[1]."')"; if(!isset($loaded[2])) { $doc = JFactory::getDocument(); $doc->addScript($ambit->getScript('jswindow.js')); $script = ' var resizeJsImage = '.$config->get('jg_resize_js_image').'; var jg_disableclick = '.$config->get('jg_disable_rightclick_original').';'; $doc->addScriptDeclaration($script); $loaded[2] = true; } break; case 3: // DHTML container $imginfo = getimagesize($img_path); $link = "javascript:joom_opendhtml('".$img_url."','"; if($config->get('jg_show_title_in_popup')) { $link .= JoomHelper::fixForJS($image->imgtitle)."','"; } else { $link .= "','"; } if($config->get('jg_show_description_in_popup')) { if($config->get('jg_show_description_in_popup') == 1) { $link .= JoomHelper::fixForJS($image->imgtext)."','"; } else { $link .= JoomHelper::fixForJS(strip_tags($image->imgtext))."','"; } } else { $link .= "','"; } $link .= $imginfo[0]."','".$imginfo[1]."','".JUri::root()."')"; if(!isset($loaded[3])) { $doc = JFactory::getDocument(); $doc->addScript($ambit->getScript('dhtml.js')); $script = ' var resizeJsImage = '.$config->get('jg_resize_js_image').'; var jg_padding = '.$config->jg_openjs_padding.'; var jg_dhtml_border = "'.$config->jg_dhtml_border.'"; var jg_openjs_background = "'.$config->jg_openjs_background.'"; var jg_disableclick = '.$config->jg_disable_rightclick_original.';'; $doc->addScriptDeclaration($script); $loaded[3] = true; } break; case 4: // Modalbox #$imginfo = getimagesize($img_path); $link = $img_url.'" class="modal" rel="'./*{handler: 'iframe', size: {x: ".$imginfo[0].", y: ".$imginfo[1]."}}*/'" title="'.$image->imgtitle; if(!isset($loaded[4])) { JHtml::_('behavior.framework'); // Loads mootools only, if it hasn't already been loaded JHTML::_('behavior.modal'); $loaded[4] = true; } break; case 5: // Thickbox3 $link = $img_url.'" rel="thickbox.'.$group; if(!isset($loaded[5])) { $doc = JFactory::getDocument(); JHtml::_('jquery.framework'); $doc->addScript($ambit->getScript('thickbox3/js/thickbox.js')); $doc->addStyleSheet($ambit->getScript('thickbox3/css/thickbox.css')); $script = ' var resizeJsImage = '.$config->get('jg_resize_js_image').'; var joomgallery_image = "'.JText::_('COM_JOOMGALLERY_COMMON_IMAGE', true).'"; var joomgallery_of = "'.JText::_('COM_JOOMGALLERY_POPUP_OF', true).'"; var joomgallery_close = "'.JText::_('COM_JOOMGALLERY_POPUP_CLOSE', true).'"; var joomgallery_prev = "'.JText::_('COM_JOOMGALLERY_POPUP_PREVIOUS', true).'"; var joomgallery_next = "'.JText::_('COM_JOOMGALLERY_POPUP_NEXT', true).'"; var joomgallery_press_esc = "'.JText::_('COM_JOOMGALLERY_POPUP_ESC', true).'"; var tb_pathToImage = "'.$ambit->getScript('thickbox3/images/loadingAnimation.gif').'";'; $doc->addScriptDeclaration($script); $loaded[5] = true; } break; case 6: // Slimbox $link = $img_url.'" rel="lightbox['.$group.']'; if(!isset($loaded[6])) { $doc = JFactory::getDocument(); JHtml::_('behavior.framework'); // Loads mootools only, if it hasn't already been loaded $doc->addScript($ambit->getScript('slimbox/js/slimbox.js')); $doc->addStyleSheet($ambit->getScript('slimbox/css/slimbox.css')); $script = ' var resizeJsImage = '.$config->get('jg_resize_js_image').'; var resizeSpeed = '.$config->get('jg_lightbox_speed').'; var joomgallery_image = "'.JText::_('COM_JOOMGALLERY_COMMON_IMAGE', true).'"; var joomgallery_of = "'.JText::_('COM_JOOMGALLERY_POPUP_OF', true).'";'; $doc->addScriptDeclaration($script); $loaded[6] = true; } break; default: // Plugins if(!isset($loaded[12])) { $loaded[12] = JDispatcher::getInstance(); } $link = ''; $loaded[12]->trigger('onJoomOpenImage', array(&$link, $image, $img_url, $group, $type, $open)); if(!$link) { // Fallback to new window $link = $img_url."\" target=\"_blank"; } break; } return $link; } /** * Creates a JavaScript tree with all sub-categories of a category * * @param int $rootcatid The category ID * @param string $align Alignment of the tree * @return void * @since 1.5.0 */ public static function categoryTree($rootcatid, $align) { $ambit = JoomAmbit::getInstance(); $config = JoomConfig::getInstance(); $user = JFactory::getUser(); $categories = $ambit->getCategoryStructure(true); // Check access rights settings $filter_cats = false; $restricted_hint = false; $restricted_cats = false; $root_access = false; if(!$config->get('jg_showrestrictedhint') && !$config->get('jg_showrestrictedcats')) { $filter_cats = true; } else { if($config->get('jg_showrestrictedhint')) { $restricted_hint = true; } if($config->get('jg_showrestrictedcats')) { $restricted_cats = true; } } // Array to hold the relevant sub-category objects $subcategories = array(); // Array to hold the valid parent categories $validParentCats = array(); $validParentCats[$rootcatid] = true; // Get all relevant subcategories $keys = array_keys($categories); $startindex = array_search($rootcatid, $keys); if($startindex !== false) { $stopindex = count($categories); $root_access = in_array($categories[$rootcatid]->access, $user->getAuthorisedViewLevels()) && !$categories[$rootcatid]->protected; for($j = $startindex + 1; $j < $stopindex; $j++) { $i = $keys[$j]; $parentcat = $categories[$i]->parent_id; if(isset($validParentCats[$parentcat])) { // Hide empty categories $empty = false; if($config->get('jg_hideemptycats')) { $subcatids = JoomHelper::getAllSubCategories($i, true, ($config->get('jg_hideemptycats') == 1), true); // If 'jg_hideemptycats' is set to 1 the root category will always be in $subcatids, so check whether there are images in it if( !count($subcatids) || (count($subcatids) == 1 && $config->get('jg_hideemptycats') == 1 && !$categories[$i]->piccount) ) { $empty = true; } } if( $categories[$i]->published && ($filter_cats == false || ( in_array($categories[$i]->access, $user->getAuthorisedViewLevels()) && (($parentcat == $rootcatid && $root_access) || ($parentcat != $rootcatid && $subcategories[$parentcat]->access)) ) ) && !$categories[$i]->hidden && (!$config->get('jg_hideemptycats') || !$empty) ) { $validParentCats[$i] = true; $subcategories[$i] = clone $categories[$i]; if( ( $parentcat == $rootcatid && !$root_access ) || ( $parentcat != $rootcatid && !$subcategories[$parentcat]->access ) || !in_array($categories[$i]->access, $user->getAuthorisedViewLevels()) || $categories[$i]->protected ) { $subcategories[$i]->access = false; if( ( $parentcat == $rootcatid && !$root_access ) || ( $parentcat != $rootcatid && !$subcategories[$parentcat]->access ) ) { $subcategories[$i]->protected = false; } } } } else { if($parentcat == 0) { // Branch has been processed completely break; } } } } // Show the treeview $count = count($subcategories); if(!$count) { return; } // If $align is 'jg_element_txt' we are displaying random thumbnails // or the thumbnail alignment is set to 'Use global'. In both cases // we have to take 'jg_ctalign' under consideration. if($align == 'jg_element_txt') { switch($config->get('jg_ctalign')) { case 0: // Changing: $align is only 'jg_element_txt' if the thumbnail is aligned left // Break omitted intentionally case 1: // Left $align = 'jg_element_txt_l'; break; case 2: // Right $align = 'jg_element_txt_r'; break; case 3: // Break omitted intentionally default: // Centered $align = 'jg_element_txt_c'; break; } } if($align == 'jg_element_txt_l') { ?> <div class="jg_treeview_l"> <?php } elseif($align == 'jg_element_txt_r') { ?> <div class="jg_treeview_r"> <?php } else { ?> <div class="jg_treeview_c"> <?php } ?> <table> <tr> <td> <script type="text/javascript" language="javascript"> <!-- // Create new dTree object var jg_TreeView<?php echo $rootcatid;?> = new jg_dTree( <?php echo "'"."jg_TreeView".$rootcatid."'"; ?>, <?php echo "'".$ambit->getScript('dTree/img/')."'"; ?>); // dTree configuration jg_TreeView<?php echo $rootcatid;?>.config.useCookies = true; jg_TreeView<?php echo $rootcatid;?>.config.inOrder = true; jg_TreeView<?php echo $rootcatid;?>.config.useSelection = false; // Add root node jg_TreeView<?php echo $rootcatid;?>.add( 0, -1, ' ', <?php echo "'".JRoute::_( 'index.php?view=gallery'.$rootcatid)."'"; ?>, false); // Add node to hold all subcategories jg_TreeView<?php echo $rootcatid;?>.add( <?php echo $rootcatid; ?>, 0, <?php echo "'".JText::_('COM_JOOMGALLERY_COMMON_SUBCATEGORIES', true)."(".$count.")"."'";?>, <?php echo $root_access ? "'".JRoute::_('index.php?view=category&catid='.$rootcatid)."'" : "''"; ?>, <?php echo $root_access ? 'false' :'true'; ?> ); <?php foreach($subcategories as $category) { // Create sub-category name and sub-category link if($filter_cats == false || $category->access || $category->protected) { // If the category is accessible create a link. // The link is also created if the category is password-protected, but only if its parent category is accessible. // The latter is ensured above by setting property 'protected' respectively. if($category->access || $category->protected) { $cat_name = addslashes(trim($category->name)); $cat_link = JRoute::_('index.php?view=category&catid='.$category->cid); } else { $cat_name = ($restricted_cats == true ? addslashes(trim($category->name)) : JText::_('COM_JOOMGALLERY_COMMON_NO_ACCESS', true)); $cat_link = ''; } } if($restricted_hint == true) { if(!$category->access) { if($category->protected) { $cat_name .= '<span class="jg_rm">'.self::icon('key.png', 'COM_JOOMGALLERY_COMMON_TIP_YOU_NOT_ACCESS_THIS_CATEGORY').'</span>'; } else { $cat_name .= '<span class="jg_rm">'.self::icon('group_key.png', 'COM_JOOMGALLERY_COMMON_TIP_YOU_NOT_ACCESS_THIS_CATEGORY').'</span>'; } } } if($config->get('jg_showcatasnew')) { $isnew = JoomHelper::checkNewCatg($category->cid); } else { $isnew = ''; } $cat_name .= $isnew; // Add node if($category->parent_id == $rootcatid) { ?> jg_TreeView<?php echo $rootcatid;?>.add(<?php echo $category->cid;?>, <?php echo $rootcatid;?>, <?php echo "'".$cat_name."'";?>, <?php echo "'".$cat_link."'"; ?>, <?php echo $category->access ? 'false' :'true'; ?> ); <?php } else { ?> jg_TreeView<?php echo $rootcatid;?>.add(<?php echo $category->cid;?>, <?php echo $category->parent_id;?>, <?php echo "'".$cat_name."'";?>, <?php echo "'".$cat_link."'"; ?>, <?php echo $category->access ? 'false' :'true'; ?> ); <?php } } ?> document.write(jg_TreeView<?php echo $rootcatid;?>); --> </script> </td> </tr> </table> </div> <?php } /** * Creates the HTML output to display the rating of an image * * @param object $image Image object holding the image data * @param boolean $shortText In case of text output return text without COM_JOOMGALLERY_COMMON_RATING_VAR * @param string $ratingclass CSS class name of rating div in case of displaying stars * @param string $tooltipclass CSS tooltip class of rating div in case of displaying stars * @return string The HTML output * @since 1.5.6 */ public static function rating($image, $shortText, $ratingclass, $tooltipclass = null) { $config = JoomConfig::getInstance(); $db = JFactory::getDBO(); $html = ''; $maxvoting = $config->get('jg_maxvoting'); // Standard rating output as text if($config->get('jg_ratingdisplaytype') == 0) { $rating = number_format((float) $image->rating, 2, JText::_('COM_JOOMGALLERY_COMMON_DECIMAL_SEPARATOR'), JText::_('COM_JOOMGALLERY_COMMON_THOUSANDS_SEPARATOR')); if($image->imgvotes > 0) { if($image->imgvotes == 1) { $html = $rating.' ('.$image->imgvotes.' '. JText::_('COM_JOOMGALLERY_COMMON_ONE_VOTE') . ')'; } else { $html = $rating.' ('.$image->imgvotes.' '. JText::_('COM_JOOMGALLERY_COMMON_VOTES') . ')'; } } else { $html = JText::_('COM_JOOMGALLERY_COMMON_NO_VOTES'); } if(!$shortText) { $html = JText::sprintf('COM_JOOMGALLERY_COMMON_RATING_VAR', $html); } // Same as &nbsp; but &#160; also works in XML $html .= '&#160;'; } // Rating output with star images if($config->get('jg_ratingdisplaytype') == 1) { $width = 0; if($config->get('jg_maxvoting') > 0 && $image->imgvotes > 0) { $width = (int) ($image->rating / (float) $config->get('jg_maxvoting') * 100.0); } if(isset($tooltipclass)) { $html .= '<div class="'.$ratingclass.' '.JHTML::_('joomgallery.tip', JText::sprintf('COM_JOOMGALLERY_COMMON_RATING_TIPTEXT_VAR', $image->rating, $image->imgvotes), JText::_('COM_JOOMGALLERY_COMMON_RATING_TIPCAPTION'), false, false, $tooltipclass).'">'; } else { $html .= '<div class="'.$ratingclass.' '.JHTML::_('joomgallery.tip', JText::sprintf('COM_JOOMGALLERY_COMMON_RATING_TIPTEXT_VAR', $image->rating, $image->imgvotes), JText::_('COM_JOOMGALLERY_COMMON_RATING_TIPCAPTION'), false, false).'">'; } $html .= ' <div style="width:'.$width.'%"></div>'; $html .= '</div>'; } return $html; } /** * Replace bbcode tags (b/u/i/url/email) with HTML tags * * @param string $text The text to be modified * @return string The modified text * @since 1.0.0 */ public static function BBDecode($text) { static $bbcode_tpl = array(); static $patterns = array(); static $replacements = array(); // First: If there isn't a "[" and a "]" in the message, don't bother. if((strpos($text, '[') === false || strpos($text, ']') === false)) { return $text; } // [b] and [/b] for bolding text. $text = str_replace('[b]', '<b>', $text); $text = str_replace('[/b]', '</b>', $text); // [u] and [/u] for underlining text. $text = str_replace('[u]', '<u>', $text); $text = str_replace('[/u]', '</u>', $text); // [i] and [/i] for italicizing text. $text = str_replace('[i]', '<i>', $text); $text = str_replace('[/i]', '</i>', $text); if(!count($bbcode_tpl)) { // We do URLs in several different ways.. $bbcode_tpl['url'] = '<span class="bblink"><a href="{URL}" target="_blank">{DESCRIPTION}</a></span>'; $bbcode_tpl['email'] = '<span class="bblink"><a href="mailto:{EMAIL}">{EMAIL}</a></span>'; $bbcode_tpl['url1'] = str_replace('{URL}', '\\1\\2', $bbcode_tpl['url']); $bbcode_tpl['url1'] = str_replace('{DESCRIPTION}', '\\1\\2', $bbcode_tpl['url1']); $bbcode_tpl['url2'] = str_replace('{URL}', 'http://\\1', $bbcode_tpl['url']); $bbcode_tpl['url2'] = str_replace('{DESCRIPTION}', '\\1', $bbcode_tpl['url2']); $bbcode_tpl['url3'] = str_replace('{URL}', '\\1\\2', $bbcode_tpl['url']); $bbcode_tpl['url3'] = str_replace('{DESCRIPTION}', '\\3', $bbcode_tpl['url3']); $bbcode_tpl['url4'] = str_replace('{URL}', 'http://\\1', $bbcode_tpl['url']); $bbcode_tpl['url4'] = str_replace('{DESCRIPTION}', '\\2', $bbcode_tpl['url4']); $bbcode_tpl['email'] = str_replace('{EMAIL}', '\\1', $bbcode_tpl['email']); // [url]xxxx://www.phpbb.com[/url] code.. $patterns[1] = '#\[url\]([a-z]+?://){1}([a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+\(\)]+)\[/url\]#si'; $replacements[1] = $bbcode_tpl['url1']; // [url]www.phpbb.com[/url] code.. (no xxxx:// prefix). $patterns[2] = '#\[url\]([a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+\(\)]+)\[/url\]#si'; $replacements[2] = $bbcode_tpl['url2']; // [url=xxxx://www.phpbb.com]phpBB[/url] code.. $patterns[3] = '#\[url=([a-z]+?://){1}([a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+\(\)]+)\](.*?)\[/url\]#si'; $replacements[3] = $bbcode_tpl['url3']; // [url=www.phpbb.com]phpBB[/url] code.. (no xxxx:// prefix). $patterns[4] = '#\[url=([a-z0-9\-\.,\?!%\*_\#:;~\\&$@\/=\+\(\)]+)\](.*?)\[/url\]#si'; $replacements[4] = $bbcode_tpl['url4']; //[email]user@domain.tld[/email] code.. $patterns[5] = '#\[email\]([a-z0-9\-_.]+?@[\w\-]+\.([\w\-\.]+\.)?[\w]+)\[/email\]#si'; $replacements[5] = $bbcode_tpl['email']; } $text = preg_replace($patterns, $replacements, $text); return $text; } /** * Displays the credits * * @return void * @since 1.5.5 */ public static function credits() { $ambit = JoomAmbit::getInstance(); ?> <div class="center"> <p> <br /> <a href="http://www.joomgallery.net" target="_blank"> <img src="<?php echo $ambit->getIcon('powered_by.gif'); ?>" class="jg-poweredby" alt="Powered by JoomGallery" /> </a> </p> By: <a href="mailto:team@joomgallery.net"> JoomGallery::ProjectTeam </a> <br /> <?php echo 'Version '.$ambit->get('version'); ?> </div> <?php } /** * Creates the path to a category which can be displayed * * @param int $catid The category ID * @param boolean $child True, if category itself shall also be included, defaults to true * @param string $separator The separator * @param boolean $linked True if elements shall be linked, defaults to false * @param boolean $with_home True if the home link shall be included, defaults to false * @param boolean $all True if all categories shall be shown defaults to false * @return string The HTML output * @since 1.5.5 */ public static function categoryPath(&$catid, $child = true, $separator = ' &raquo; ', &$linked = false, &$with_home = false, $all = false) { // Maybe this path was already generated static $catPaths = array(); if(isset($catPaths[$catid])) { return $catPaths[$catid]; } $path = ''; $catid = intval($catid); $user = JFactory::getUser(); $ambit = JoomAmbit::getInstance(); $allowed_categories = $ambit->getCategoryStructure(); // Get category and their parents $pathCats = JoomHelper::getAllParentCategories($catid, $child, $all); $count = count($pathCats); if(!$count) { return $path; } // Construct the HTML if($count == 1) { $category = reset($pathCats); // Link to category only if category published if($linked && isset($allowed_categories[$catid])) { $path = '<a href="'.JRoute::_('index.php?view=category&catid='.$catid).'" class="jg_pathitem">'.$category->name.'</a>'; } else { $path = $category->name; } } else { // Reindex the array with index from 0 to n $pathCatsidx = array_values($pathCats); // First element if($linked && isset($allowed_categories[$pathCatsidx[0]->cid])) { $path = '<a href="'.JRoute::_('index.php?view=category&catid='.$pathCatsidx[0]->cid).'" class="jg_pathitem">'.$pathCatsidx[0]->name.'</a>'; } else { $path = $pathCatsidx[0]->name; } for($i = 1; $i < $count; $i++) { if($linked && isset($allowed_categories[$pathCatsidx[$i]->cid])) { $path .= $separator.'<a href="'.JRoute::_('index.php?view=category&catid='.$pathCatsidx[$i]->cid).'" class="jg_pathitem">'.$pathCatsidx[$i]->name.'</a>'; } else { $path .= $separator.$pathCatsidx[$i]->name; } } } if($with_home) { $home = '<a href="'.JRoute::_('index.php?view=gallery').'" class="jg_pathitem">'.JText::_('COM_JOOMGALLERY_COMMON_HOME').'</a>'; $path = $home.$separator.$path.' '; } // Store it for later use $catPaths[$catid] = $path; return $path; } /** * Creates the HTML output to display a minithumb for an image * * @param object $img Image object holding the image data * @param string $class CSS class name for minithumb styling * @param boolean $linkattribs Link attributes for creating a link on the minithumb, if false no link will created * @param boolean $showtip Shows the thumbnail as tip on hoovering above minithumb * @return string The HTML output * @since 1.5.7 */ public static function minithumbimg($img, $class = null, $linkattribs = null, $showtip = true) { jimport('joomla.filesystem.file'); $ambit = JoomAmbit::getInstance(); $config = JoomConfig::getInstance(); $html = ''; $linked = $linkattribs ? true : false; $thumb = $ambit->getImg('thumb_path', $img); if(JFile::exists($thumb)) { $isSite = JFactory::getApplication()->isSite(); $imginfo = getimagesize($thumb); $url = $ambit->getImg('thumb_url', $img); if($showtip) { if($isSite) { $html .= '<span'.JHtml::_('joomgallery.tip', '<img src="'.$url.'" width="'.$imginfo[0].'" height="'.$imginfo[1].'" alt="'.$img->imgtitle.'" />', null, true, false).'>'; } else { $html .= '<span class="hasTooltip" title="'.htmlspecialchars('<img src="'.$url.'" width="'.$imginfo[0].'" height="'.$imginfo[1].'" alt="'.$img->imgtitle.'" />', ENT_QUOTES, 'UTF-8').'">'; } } if($linked) { if($isSite) { // Set the title attribute in a tag with title and/or // description of image if a box is activated if(!is_numeric($config->get('jg_detailpic_open')) || $config->get('jg_detailpic_open') > 1) { $atagtitle = JHtml::_('joomgallery.getTitleforATag', $img); } else { // Set the imgtitle by default $atagtitle = 'title="'.$img->imgtitle.'"'; } $html .= '<a '.$atagtitle.' href="'.JHtml::_('joomgallery.openImage', $config->get('jg_detailpic_open'), $img, false, 'jgminithumbs').'">'; } else { $html .= '<a '.$linkattribs.'">'; } } $html .= '<img src="'.$url.'" alt="'.htmlspecialchars($img->imgtitle, ENT_QUOTES, 'UTF-8').'"'; if($class !== null) { $html .= ' class="'.$class.'"'; } $html .= '>'; if($linked) { $html .= '</a>'; } if($showtip) { $html .= '</span>'; } } return $html; } /** * Creates the HTML output to display a minithumb for a category * * @param object $cat Category object holding the category data * @param string $class CSS class name for minithumb styling * @param boolean $linkattribs Link attributes for creating a link on the minithumb, if false no link will created * @param boolean $showtip Shows the thumbnail as tip on hoovering above minithumb * @return string The HTML output * @since 1.5.7 */ public static function minithumbcat($cat, $class = null, $linkattribs = null, $showtip = true) { $ambit = JoomAmbit::getInstance(); $config = JoomConfig::getInstance(); $html = ''; $linked = $linkattribs ? true : false; if(isset($cat->thumbnail) && !empty($cat->thumbnail)) { $thumb = $ambit->getImg('thumb_path', $cat->thumbnail, null, $cat->cid); jimport('joomla.filesystem.file'); if(JFile::exists($thumb)) { $isSite = JFactory::getApplication()->isSite(); $imginfo = getimagesize($thumb); $url = $ambit->getImg('thumb_url', $cat->thumbnail, null, $cat->cid); // Clean category name $catname = str_replace('&nbsp;', '', $cat->name); $catname = trim(str_replace('&raquo;', '', $catname)); if($showtip) { if($isSite) { $html .= '<span'.JHtml::_('joomgallery.tip', '<img src="'.$url.'" width="'.$imginfo[0].'" height="'.$imginfo[1].'" alt="'.$cat->name.'" />', null, true, false).'>'; } else { $html .= '<span class="hasTooltip" title="'.htmlspecialchars('<img src="'.$url.'" width="'.$imginfo[0].'" height="'.$imginfo[1].'" alt="'.$catname.'" />', ENT_QUOTES, 'UTF-8').'">'; } } if($linked) { if($isSite) { $html .= '<a href="'.JRoute::_('index.php?view=category&catid='.$cat->cid).'">'; } else { $html .= '<a '.$linkattribs.'">'; } } $html .= '<img src="'.$url.'" alt="'.htmlspecialchars($catname, ENT_QUOTES, 'UTF-8').'"'; if($class !== null) { $html .= ' class="'.$class.'"'; } $html .= '>'; if($linked) { $html .= '</a>'; } if($showtip) { $html .= '</span>'; } } } return $html; } /** * Creates the HTML output to display a input box and color picker field * * @param $key string the identifier of the configuration option, e.g. 'jg_pathimages' * @param $color string current color setting of the option * @param $style string colorpicker style, either 'hue', 'saturation', 'brightness' or 'wheel' * @param $postion string postion of the panel, right, left, top or bottom * @return string The HTML output * @since 2.1.0 */ public static function colorpicker($key, $color, $style = 'hue', $postion = 'right') { $color = strtolower($color); if(!$color || in_array($color, array('none', 'transparent'))) { $color = 'none'; } elseif($color['0'] != '#') { $color = '#' . $color; } $class = ' class="minicolors"'; $control = ' data-control="'.$style.'"'; $position = ' data-position="'.$postion.'"'; JHtml::_('behavior.colorpicker'); return '<input type="text" name="'.$key.'" id="'.$key.'"'.' value="' .htmlspecialchars($color, ENT_COMPAT, 'UTF-8').'"'.$class.$position.$control.'/>'; } /** * State buttons for approved/not yet approved/rejected state of images * * @param array $states Array of state information * @param int $value Current state of the image * @param int $i Number of the image in the current list * @param string $prefix Optional prefix for task name * @param boolean $enabled Indicates whether the buttons should be active * @param int $id ID of the image * @param int $owner ID of the owner of the image * @param boolean $translate Indicates whether the state names should be translated * @param string $checkbox Name prefix of the checkboxes in the current image list * @return string HTML of the state buttons * @since 3.1 */ public static function approved($states, $value, $i, $prefix = '', $enabled = true, $id = 0, $owner = 0, $translate = true, $checkbox = 'cb') { $state = JArrayHelper::getValue($states, (int) $value, $states[0]); $task = array_key_exists('task', $state) ? $state['task'] : $state[0]; $text = array_key_exists('text', $state) ? $state['text'] : (array_key_exists(1, $state) ? $state[1] : ''); $active_title = array_key_exists('active_title', $state) ? $state['active_title'] : (array_key_exists(2, $state) ? $state[2] : ''); $inactive_title = array_key_exists('inactive_title', $state) ? $state['inactive_title'] : (array_key_exists(3, $state) ? $state[3] : ''); $tip = array_key_exists('tip', $state) ? $state['tip'] : (array_key_exists(4, $state) ? $state[4] : false); $active_class = array_key_exists('active_class', $state) ? $state['active_class'] : (array_key_exists(5, $state) ? $state[5] : ''); $inactive_class = array_key_exists('inactive_class', $state) ? $state['inactive_class'] : (array_key_exists(6, $state) ? $state[6] : ''); if($enabled) { // Button group is only necessary for 'not yet approved' if($value == 0) { $html[] = '<span class="btn-group">'; } // Normal button for approving is necessary for states 'not yet approved' and 'rejected' if($value == 0 || $value == -1) { $html[] = '<a class="btn btn-micro ' . ($active_class == "publish" || $value == -1 ? 'active' : '') . '" ' . ($tip ? 'rel="tooltip"' : '') . ''; $html[] = ' href="javascript:void(0);" onclick="return listItemTask(\'' . $checkbox . $i . '\',\'' . $prefix . $task . '\')"'; $html[] = ' title="' . addslashes(htmlspecialchars($translate ? JText::_($active_title) : $active_title, ENT_COMPAT, 'UTF-8')) . '">'; $html[] = '<i class="icon-' . $active_class . '">'; $html[] = '</i>'; $html[] = '</a>'; } // Special rejecting button is necessary for states 'not yet approved' and 'approved' if($value == 0 || $value == 1) { if($owner) { $owner = htmlspecialchars(JHtml::_('joomgallery.displayname', $owner), ENT_COMPAT, 'UTF-8'); } else { $owner = ''; } JHtml::_('bootstrap.modal', 'jg-reject-popup'); $html[] = '<a class="btn btn-micro '.($active_class == "publish" ? 'active' : '').'" '.($tip ? 'rel="tooltip"' : '').''; $html[] = ' href="javascript:void(0);" onclick="joomRejectionWindow(this);" data-owner="'.$owner.'" data-image-id="'.$id.'"'; $html[] = ' title="'.addslashes(htmlspecialchars(JText::_('COM_JOOMGALLERY_IMGMAN_REJECT_IMAGE'), ENT_COMPAT, 'UTF-8')).'" data-toggle="modal" data-target="#jg-reject-popup">'; if($value == 0) { $html[] = '<i class="icon-minus" style="color:#BD362F;">'; } else { $html[] = '<i class="icon-'.$active_class.'">'; } $html[] = '</i>'; $html[] = '</a>'; if($value == 0) { $html[] = '</span>'; } $html[] = '<script type="text/javascript"> function joomRejectionWindow(button) { var owner = jQuery(button).attr(\'data-owner\'); var id = jQuery(button).attr(\'data-image-id\'); jQuery(\'#jg-reject-image\').attr(\'src\', \''.JRoute::_('index.php?option='._JOOM_OPTION.'&view=image', false).'&format=raw&type=img&cid=\' + id); jQuery(\'#jg-reject-cid\').val(id); if(owner) { jQuery(\'#jg-reject-no-owner\').addClass(\'hide\'); jQuery(\'#jg-reject-owner-name\').html(owner); jQuery(\'#jg-reject-owner\').removeClass(\'hide\'); } else { jQuery(\'#jg-reject-no-owner\').removeClass(\'hide\'); jQuery(\'#jg-reject-owner\').addClass(\'hide\'); } } </script>'; } } else { // Disabled button (usually used if the user doesn't have the permission to change the state) $html[] = '<a class="btn btn-micro disabled jgrid" '.($tip ? 'rel="tooltip"' : ''); $html[] = ' title="'.addslashes(htmlspecialchars($translate ? JText::_($inactive_title) : $inactive_title, ENT_COMPAT, 'UTF-8')).'">'; $html[] = '<i class="icon-'.$inactive_class.'"></i>'; $html[] = '</a>'; } return implode($html); } public static function special($value = 0, $i, $canChange = true) { JHtml::_('bootstrap.tooltip'); // Array of image, task, title, action $states = array( 0 => array('unpublish', 'special', 'Bỏ chọn', 'Chọn'), 1 => array('publish', 'unspecial', 'Chọn', 'Bỏ chọn'), ); $state = JArrayHelper::getValue($states, (int) $value, $states[1]); $icon = $state[0]; if ($canChange) { $html = '<a href="#" onclick="return listItemTask(\'cb' . $i . '\',\'' . $state[1] . '\')" class="btn btn-micro hasTooltip' . ($value == 1 ? ' active' : '') . '" title="' . JHtml::tooltipText($state[3]) . '"><span class="icon-' . $icon . '"></span></a>'; } else { $html = '<a class="btn btn-micro hasTooltip disabled' . ($value == 1 ? ' active' : '') . '" title="' . JHtml::tooltipText($state[2]) . '"><span class="icon-' . $icon . '"></span></a>'; } return $html; } }
naka211/kkvn
administrator/components/com_joomgallery/helpers/html/joomgallery.php
PHP
gpl-2.0
53,524
package edu.iris.Fissures.seismogramDC; import edu.iris.Fissures.Sampling; import edu.iris.Fissures.Time; import edu.iris.Fissures.Unit; import edu.iris.Fissures.IfNetwork.ChannelId; import edu.iris.Fissures.IfParameterMgr.ParameterRef; import edu.iris.Fissures.IfSeismogramDC.LocalMotionVector; import edu.iris.Fissures.IfSeismogramDC.Property; import edu.iris.Fissures.model.TimeInterval; /** * MotionVectorAttrImpl.java * * * Created: Thu Dec 6 22:00:42 2001 * The strange extends is to avoid diamond of death while still reusing this * class in LocalMotionVector. * * @author Philip Crotwell */ public class MotionVectorAttrImpl extends LocalMotionVector { protected MotionVectorAttrImpl() { } public MotionVectorAttrImpl(String id, Property[] properties, Time begin_time, int num_points, Sampling sampling_info, Unit y_unit, ChannelId[] channel_group, ParameterRef[] parm_ids, TimeInterval[] time_corrections, Sampling[] sample_rate_history) { this.id = id; this.properties = properties; this.begin_time = begin_time; this.num_points = num_points; this.sampling_info = sampling_info; this.y_unit = y_unit; this.channel_group = channel_group; this.parm_ids = parm_ids; this.time_corrections = time_corrections; this.sample_rate_history = sample_rate_history; } /** A factory method to create an empty LocalDataSetImpl. * This is to be used only by the ORB for unmarshelling * valuetypes that have been sent via IIOP. */ public static java.io.Serializable createEmpty() { return new MotionVectorAttrImpl(); } public String get_id() { return id; } }// MotionVectorAttrImpl
crotwell/fissuresImpl
src/main/java/edu/iris/Fissures/seismogramDC/MotionVectorAttrImpl.java
Java
gpl-2.0
1,733
<?php /** * @package WordPress * @subpackage Industrial * @since Industrial 1.0 * * Admin Panel Logo Options * Created by CMSMasters * */ function cmsms_options_logo_tabs() { $tabs = array(); $tabs['image'] = __('Image Logo', 'cmsmasters'); $tabs['text'] = __('Text Logo', 'cmsmasters'); $tabs['favicon'] = __('Favicon', 'cmsmasters'); return $tabs; } function cmsms_options_logo_sections() { $tab = cmsms_get_the_tab(); switch ($tab) { case 'image': $sections = array(); $sections['image_section'] = __('Image Logo Options', 'cmsmasters'); break; case 'text': $sections = array(); $sections['text_section'] = __('Text Logo Options', 'cmsmasters'); break; case 'favicon': $sections = array(); $sections['favicon_section'] = __('Favicon Options', 'cmsmasters'); break; } return $sections; } function cmsms_options_logo_fields($set_tab = false) { if ($set_tab) { $tab = $set_tab; } else { $tab = cmsms_get_the_tab(); } $options = array(); switch ($tab) { case 'image': $options[] = array( 'section' => 'image_section', 'id' => CMSMS_SHORTNAME . '_logo_url', 'title' => __('Custom Logo URL', 'cmsmasters'), 'desc' => __('Choose your custom website logo image url.', 'cmsmasters'), 'type' => 'upload', 'std' => get_template_directory_uri() . '/img/logo.png' ); $options[] = array( 'section' => 'image_section', 'id' => CMSMS_SHORTNAME . '_logo_width', 'title' => __('Logo Image Width', 'cmsmasters'), 'desc' => __('pixels', 'cmsmasters'), 'type' => 'number', 'std' => '120' ); $options[] = array( 'section' => 'image_section', 'id' => CMSMS_SHORTNAME . '_logo_height', 'title' => __('Logo Image Height', 'cmsmasters'), 'desc' => __('pixels', 'cmsmasters'), 'type' => 'number', 'std' => '70' ); $options[] = array( 'section' => 'image_section', 'id' => CMSMS_SHORTNAME . '_logo_top', 'title' => __('Logo Top Position', 'cmsmasters'), 'desc' => __('pixels', 'cmsmasters'), 'type' => 'number', 'std' => '35' ); $options[] = array( 'section' => 'image_section', 'id' => CMSMS_SHORTNAME . '_logo_left', 'title' => __('Logo Left Position', 'cmsmasters'), 'desc' => __('pixels', 'cmsmasters'), 'type' => 'number', 'std' => '0' ); break; case 'text': $options[] = array( 'section' => 'text_section', 'id' => CMSMS_SHORTNAME . '_text_logo', 'title' => __('Text Logo', 'cmsmasters'), 'desc' => __('show', 'cmsmasters'), 'type' => 'checkbox', 'std' => 0 ); $options[] = array( 'section' => 'text_section', 'id' => CMSMS_SHORTNAME . '_text_logo_title', 'title' => __('Custom Logo Title', 'cmsmasters'), 'desc' => '', 'type' => 'text', 'std' => ((get_bloginfo('name')) ? get_bloginfo('name') : 'Industrial'), 'class' => 'nohtml' ); $options[] = array( 'section' => 'text_section', 'id' => CMSMS_SHORTNAME . '_text_logo_subtitle', 'title' => __('Logo Subtitle', 'cmsmasters'), 'desc' => __('show', 'cmsmasters'), 'type' => 'checkbox', 'std' => 0 ); $options[] = array( 'section' => 'text_section', 'id' => CMSMS_SHORTNAME . '_text_logo_subtitle_text', 'title' => __('Custom Logo Subtitle', 'cmsmasters'), 'desc' => '', 'type' => 'text', 'std' => ((get_bloginfo('description')) ? get_bloginfo('description') : 'Corporate &amp; Business'), 'class' => 'nohtml' ); break; case 'favicon': $options[] = array( 'section' => 'favicon_section', 'id' => CMSMS_SHORTNAME . '_favicon', 'title' => __('Favicon', 'cmsmasters'), 'desc' => __('show', 'cmsmasters'), 'type' => 'checkbox', 'std' => 1 ); $options[] = array( 'section' => 'favicon_section', 'id' => CMSMS_SHORTNAME . '_favicon_url', 'title' => __('Custom Favicon URL', 'cmsmasters'), 'desc' => __('Choose your custom website favicon image url.', 'cmsmasters'), 'type' => 'upload', 'std' => get_template_directory_uri() . '/img/favicon.ico' ); break; } return $options; }
gx761/jhm
wp-content/themes/industrial/framework/admin/settings/cmsms-theme-settings-logo.php
PHP
gpl-2.0
4,162
<?php /* Plugin Name: Slate Admin Theme Plugin URI: http://sevenbold.com/wordpress/ Description: A clean, simplified WordPress Admin theme Author: Ryan Sommers Version: 1.1.4 Author URI: http://sevenbold.com/ */ function slate_files() { wp_enqueue_style( 'slate-admin-theme', plugins_url('css/slate.css', __FILE__), array(), '1.1.4' ); wp_enqueue_script( 'slate', plugins_url( "js/slate.js", __FILE__ ), array( 'jquery' ), '1.1.4', true ); } add_action( 'admin_enqueue_scripts', 'slate_files' ); add_action( 'login_enqueue_scripts', 'slate_files' ); function slate_add_editor_styles() { add_editor_style( plugins_url('css/editor-style.css', __FILE__ ) ); } add_action( 'after_setup_theme', 'slate_add_editor_styles' ); add_filter('admin_footer_text', 'slate_admin_footer_text_output'); function slate_admin_footer_text_output($text) { $text = 'WordPress Admin Theme <a href="http://wordpress.org/plugins/slate-admin-theme/" target="_blank">Slate</a> by <a href="http://sevenbold.com/wordpress/" target="_blank">Seven Bold</a>. Check out <a href="http://sevenbold.com/wordpress/slate-pro/" target="_blank">Slate Pro</a> for extra features + white label.'; return $text; } add_action( 'admin_head', 'slate_colors' ); add_action( 'login_head', 'slate_colors' ); function slate_colors() { include( 'css/dynamic.php' ); } function slate_get_user_admin_color(){ $user_id = get_current_user_id(); $user_info = get_userdata($user_id); if ( !( $user_info instanceof WP_User ) ) { return; } $user_admin_color = $user_info->admin_color; return $user_admin_color; } // Remove the hyphen before the post state add_filter( 'display_post_states', 'slate_post_state' ); function slate_post_state( $post_states ) { if ( !empty($post_states) ) { $state_count = count($post_states); $i = 0; foreach ( $post_states as $state ) { ++$i; ( $i == $state_count ) ? $sep = '' : $sep = ''; echo "<span class='post-state'>$state$sep</span>"; } } } ?>
od1n0chka/por.ru
wp-content/plugins/slate-admin-theme/slate-admin-theme.php
PHP
gpl-2.0
1,970
<?php /* * Template name: Shareable. */ $type = isset( $_GET[ 'type' ] ) ? $_GET[ 'type' ] : 'supporter'; $extn = ($type != 'supporter') ? 'jpg' : 'png'; $verbs = array( 'speaker' => "'m speaking at", 'attendee' => "'m attending", 'supporter' => " support", 'sponsor' => "'m sponsoring", 'volunteer' => "'m volunteering at", 'organiser' => "'m organising" ); $url = 'https://pune.wordcamp.org/2015/'; switch ( $type ) { case 'speaker': $url .= 'speakers/'; break; case 'organiser': $url .= 'organisers/'; break; case 'supporter': case 'attendee': case 'sponsor': default: $url .='tickets/'; break; } ?> <html> <head> <title>I<?php echo $verbs[ $type ]; ?> WordCamp Pune 2015 on 6th September 2015 at Modern College of Arts, Science and Commerce</title> <style> body{ width:660px; margin:0 auto; background:#f2f2f2; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; text-align:center; color: #555; } h1{ background: #fff; color:#555; padding: 20px; font-weight:bold; margin:0; padding:20px; } p{ background:#f2f2f2; color:#555; margin: 0; padding:20px; } p.notice{ background: #C0C4CB none; color:#555; } </style> </head> <body> <h1>I<?php echo $verbs[ $type ]; ?> WordCamp Pune 2015 on 6th September 2015 at Modern College of Arts, Science and Commerce</h1> <img src="https://pune.wordcamp.org/2015/files/2015/07/<?php echo $type; ?>-500x250.<?php echo $extn; ?>"> <p class="notice">I may see you at WordCamp Pune 2015, a one day long conference and unconference of WordPress lovers with loads of useful and interactive sessions, fun activities and lot of networking.</p> <p style="padding-bottom:0;"><img src="<?php echo get_stylesheet_directory_uri(); ?>/email/images/loading.gif"></p> <p style="padding-top:0;">Taking you to WordCamp Pune</p> <p style="padding-top:0;"><a style="color:#ef7c00; font-weight:bold; text-decoration:none;" href="<?php echo $url; ?>">[or click here]</a></p> </body> <script> setTimeout( function() { window.location.href = "<?php echo $url; ?>"; }, 5000 ); </script> </html>
yapapaya/Instamojo-Ticketer-for-WordCamp-Pune-2015
shareable-redirect.php
PHP
gpl-2.0
2,653
<?php /** * @copyright Incsub ( http://incsub.com/ ) * * @license http://opensource.org/licenses/GPL-2.0 GNU General Public License, version 2 ( GPL-2.0 ) * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License, version 2, as * published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, * MA 02110-1301 USA * */ if ( ! class_exists( 'CoursePress_Compatibility' ) ) { /** * CoursePress class for dealing with WordPress version compatibility * * @since 1.2.1 * */ class CoursePress_Compatibility { private $version; private $plugin_url; private $min_version = false; private $editor_options = array(); function __construct() { $this->plugin_url = $GLOBALS['coursepress_url']; $this->version = $GLOBALS['coursepress_version']; $this->editor_options = array( 'quicktags' => false, ); // Are we dealing with 3.9 and up? if ( self::is_3_9_up() ) { $this->min_version = 3.9; } else { $this->min_version = 3.8; } // Administration area if ( is_admin() ) { add_action( 'coursepress_editor_compatibility', array( &$this, 'coursepress_editor_compatibility' ) ); // Fix some anomalies on unit builder page add_action( 'admin_init', array( &$this, 'alter_unit_builder_editor' ) ); } add_action( 'coursepress_editor_compatibility', array( &$this, 'coursepress_editor_compatibility' ) ); // Public area /** * Admin header actions. * * Compatibility mode. * * @since 1.2.1 */ add_action( 'admin_enqueue_scripts', array( &$this, 'admin_header_actions' ) ); /** * Admin footer scripts. * * Load specific scripts in the footer. * * @since 1.2.1 */ add_action( 'admin_enqueue_scripts', array( &$this, 'admin_footer_scripts' ) ); } /** * Check for WordPress 3.9 and up * * @since 1.2.1 */ public static function is_3_9_up() { global $wp_version; if ( 3.9 <= (double) $wp_version ) { return true; } else { return false; } } /** * Alter editor for Unit pages. * * Because of the complexities of the unit builder we might need to suppress * or alter some editor options. * * @since 1.2.1 */ public function alter_unit_builder_editor() { if ( isset( $_GET['page'] ) && 'course_details' == $_GET['page'] && isset( $_GET['tab'] ) && 'units' == $_GET['tab'] ) { /* * Multiple editors on the same page is causing conflicts with Visual/Text tab selection * so we need to disabled it. */ if ( $this->is_3_9_up() ) { $this->editor_options['quicktags'] = false; } } } /** * Hook WordPress Editor filters and actions. * * @since 1.2.1 */ public function coursepress_editor_compatibility() { // Version Specific Hooks switch ( $this->min_version ) { // Do 3.9+ specific hooks for the editor case 3.9: add_filter( 'coursepress_element_editor_args', array( &$this, 'cp_element_editor_args_39plus' ), 10, 3 ); add_action( 'coursepress_editor_options', array( &$this, 'prepare_coursepress_editor_39plus' ) ); break; // Do 3.8 specific hooks for the editor case 3.8: // $this->editor_options['quicktags'] = true; add_filter( 'coursepress_element_editor_args', array( &$this, 'cp_element_editor_args_38' ), 10, 3 ); add_filter( 'coursepress_format_tinymce_plugins', array( &$this, 'cp_format_tinymce_plugins_38' ), 10, 1 ); add_action( 'coursepress_editor_options', array( &$this, 'prepare_coursepress_editor_38' ) ); break; } // Default Hooks /** * Apply some styles to the WordPress editor (AJAX). * * Keeps consistency across course setup and unit setup. * * @since 1.0.0 */ add_filter( 'mce_css', array( &$this, 'mce_editor_style' ) ); /** * Add keydown() event listener for WP Editor. * * @since 1.0.0 */ add_filter( 'tiny_mce_before_init', array( &$this, 'init_tiny_mce_listeners' ) ); /** * Listen to dynamic editor requests. * * Used on unit page in admin. * * @since 1.0.0 */ add_action( 'wp_ajax_dynamic_wp_editor', array( &$this, 'dynamic_wp_editor' ) ); } function admin_header_actions() { /* Adding menu icon font */ if ( $this->min_version >= 3.8 ) { wp_register_style( 'cp-38', CoursePress::instance()->plugin_url . 'css/admin-icon.css' ); wp_enqueue_style( 'cp-38' ); } if ( isset( $_GET['page'] ) ) { $page = isset( $_GET['page'] ); } else { $page = ''; } if ( $page == 'courses' || $page == 'course_details' || $page == 'instructors' || $page == 'students' || $page == 'assessment' || $page == 'reports' || $page == 'settings' || ( isset( $_GET['taxonomy'] ) && $_GET['taxonomy'] == 'course_category' ) ) { add_filter( 'tiny_mce_before_init', array( &$this, 'cp_format_TinyMCE' ) ); wp_enqueue_style( 'editor-buttons' ); } } public function admin_footer_scripts( $hook ) { // Address issue specifically caused by WPEngine and relative URLs if ( 'coursepress-pro_page_course_details' == $hook ) { wp_enqueue_script( 'coursepress_fix_editor', $this->plugin_url . 'js/footer-editor-fixes.js', array( 'jquery' ), $this->version, true ); } } /** * Create a listener for TinyMCE change event * */ function init_tiny_mce_listeners( $initArray ) { if ( is_admin() ) { $detect_pages = array( 'coursepress_page_course_details', 'coursepress-pro_page_course_details', ); $page = get_current_screen()->id; $tab = empty( $_GET['tab'] ) ? '' : $_GET['tab']; if ( in_array( $page, $detect_pages ) ) { $initArray['height'] = '360px'; $initArray['relative_urls'] = false; $initArray['url_converter'] = false; $initArray['url_converter_scope'] = false; if ( 3.8 < $this->min_version ) { $initArray['setup'] = 'function( ed ) { ed.on( \'keydown\', function( args ) { cp_editor_key_down( ed, \'' . $page . '\', \'' . $tab . '\' ); } ); }'; } else { $initArray['setup'] = 'function( ed ) { ed.onKeyDown.add(function(ed, evt) { cp_editor_key_down( ed, \'' . $page . '\', \'' . $tab . '\' ); }); }'; } } } return $initArray; } // CoursePress CSS styles for TinyMCE function mce_editor_style( $url ) { global $wp_version; // Only on these pages $detect_pages = array( 'coursepress_page_course_details', 'coursepress-pro_page_course_details', ); $page = get_current_screen()->id; $tab = empty( $_GET['tab'] ) ? '' : $_GET['tab']; if ( in_array( $page, $detect_pages ) ) { if ( ! empty( $url ) ) { $url .= ','; } $url .= CoursePress::instance()->plugin_url . 'css/editor_style_fix.css,'; if ( 3.9 <= (double) $wp_version ) { } else { $url .= CoursePress::instance()->plugin_url . 'css/editor_style_fix_38.css,'; } } return $url; } /* Retrieve wp_editor dynamically ( using in unit admin ) */ function dynamic_wp_editor() { $editor_name = ( isset( $_GET['module_name'] ) ? $_GET['module_name'] : '' ) . "_content[]"; $editor_id = ( ( isset( $_GET['rand_id'] ) ? $_GET['rand_id'] : rand( 1, 9999 ) ) ); $editor_content = htmlspecialchars_decode( ( isset( $_GET['editor_content'] ) ? $_GET['editor_content'] : '' ) ); $args = array( "textarea_name" => $editor_name, "textarea_rows" => 4, "teeny" => true, "editor_class" => 'cp-editor cp-dynamic-editor', ); if ( $this->editor_options['quicktags'] ) { $args['quicktags'] = $this->editor_options['quicktags']; } // Filter $args before showing editor $args = apply_filters( 'coursepress_element_editor_args', $args, $editor_name, $editor_id ); wp_editor( $editor_content, $editor_id, $args ); exit; } function cp_format_TinyMCE( $in ) { $plugins = apply_filters( 'coursepress_format_tinymce_plugins', $this->get_plugins() ); $plugins = implode( ',', $plugins ); $in['menubar'] = false; $in['plugins'] = $plugins; $in['toolbar1'] = implode( ',', $this->get_buttons() ); $in['toolbar2'] = ''; $in['toolbar3'] = ''; $in['toolbar4'] = ''; return $in; } // TinyMCE 4.0 function cp_element_editor_args_39plus( $args, $editor_name, $editor_id ) { $args['quicktags'] = $this->editor_options['quicktags']; return $args; } function prepare_coursepress_editor_39plus() { //array( 'inlinepopups', 'tabfocus', 'paste', 'media', 'fullscreen', 'wordpress', 'wpeditimage', 'wpgallery', 'wplink', 'wpdialogs', 'textcolor', 'hr' ) wp_localize_script( 'courses_bulk', 'coursepress_editor', array( 'plugins' => apply_filters( 'coursepress_format_tinymce_plugins', $this->get_plugins() ), 'toolbar' => $this->get_buttons(), 'theme' => apply_filters( 'coursepress_editor_theme', 'modern' ), // filter it for themers 'skin' => apply_filters( 'coursepress_editor_skin', 'wp_theme' ), // filter it for themers 'quicktags' => $this->editor_options['quicktags'], // are we using quicktags? ) ); } // TinyMCE 3.5.9 function cp_element_editor_args_38( $args, $editor_name, $editor_id ) { $args['quicktags'] = $this->editor_options['quicktags']; // unset( $args[ "quicktags" ] );//it doesn't work in 3.8 for some reason - should peform further checks return $args; } function prepare_coursepress_editor_38() { wp_localize_script( 'courses_bulk', 'coursepress_editor', array( 'plugins' => apply_filters( 'coursepress_format_tinymce_plugins', $this->get_plugins() ), 'toolbar' => $this->get_buttons(), 'theme' => apply_filters( 'coursepress_editor_theme', 'advanced' ), // filter it for themers 'skin' => apply_filters( 'coursepress_editor_skin', 'wp_theme' ), // filter it for themers 'quicktags' => false, // Always false for WP 3.8 dynamic editor ) ); } function get_plugins() { // WP default plugins // array( 'inlinepopups', 'tabfocus', 'paste', 'media', 'fullscreen', 'wordpress', 'wpeditimage', 'wpgallery', 'wplink', 'wpdialogs' ); // WP teeny plugins // array('inlinepopups', 'fullscreen', 'wordpress', 'wplink', 'wpdialogs' ) $plugins = array( // 'inlinepopups', // 'tabfocus', // 'paste', // 'media', // 'fullscreen', // 'wordpress', // 'wpeditimage', // 'wpgallery', 'wplink', // 'wpdialogs', 'textcolor', // not in 3.8 'hr' // not in 3.8 ); return $plugins; } function get_buttons() { $buttons = array( 'bold', 'italic', 'underline', 'blockquote', 'hr', 'strikethrough', 'bullist', 'numlist', 'subscript', 'superscript', 'alignleft', 'aligncenter', 'alignright', 'alignjustify', 'outdent', 'indent', 'link', 'unlink', 'forecolor', 'backcolor', 'undo', 'redo', 'removeformat', 'formatselect', 'fontselect', 'fontsizeselect' ); return $buttons; } function cp_format_tinymce_plugins_38( $plugins ) { $not_allowed = array( 'textcolor', 'hr' ); foreach ( $plugins as $key => $value ) { if ( in_array( $value, $not_allowed ) ) { unset( $plugins[ $key ] ); } } return $plugins; } } } $coursepress_compatibility = new CoursePress_Compatibility();
MujeresdelasAmericas/Sitio
wp-content/plugins/coursepress/includes/classes/class.coursepress-compatibility.php
PHP
gpl-2.0
11,959
package it.giacomos.android.wwwsapp.widgets.map.report.tutorialActivity; public interface ReportConditionsAcceptedListener { public void onReportConditionsAccepted(boolean accepted); }
delleceste/wwwsapp
src/it/giacomos/android/wwwsapp/widgets/map/report/tutorialActivity/ReportConditionsAcceptedListener.java
Java
gpl-2.0
188
<?php /** * Spring includes */ require_once locate_template('/lib/utils.php'); // Utility functions require_once locate_template('/lib/init.php'); // Initial theme setup and constants require_once locate_template('/lib/wrapper.php'); // Theme wrapper class require_once locate_template('/lib/sidebar.php'); // Sidebar class require_once locate_template('/lib/config.php'); // Configuration require_once locate_template('/lib/titles.php'); // Page titles require_once locate_template('/lib/cleanup.php'); // Cleanup require_once locate_template('/lib/comments.php'); // Custom comments modifications require_once locate_template('/lib/relative-urls.php'); // Root relative URLs require_once locate_template('/lib/widgets.php'); // Sidebars and widgets require_once locate_template('/lib/scripts.php'); // Scripts and stylesheets require_once locate_template('/lib/custom.php'); // Custom functions
3themes/spring-theme
functions.php
PHP
gpl-2.0
995
<?php /** * Network installation administration panel. * * A multi-step process allowing the user to enable a network of WordPress sites. * * @since 3.0.0 * * @package WordPress * @subpackage Administration */ define( 'WP_INSTALLING_NETWORK', true ); /** WordPress Administration Bootstrap */ require_once( './admin.php' ); if ( ! is_super_admin() ) wp_die( __( 'You do not have sufficient permissions to manage options for this site.' ) ); if ( is_multisite() ) { if ( ! is_network_admin() ) { wp_redirect( network_admin_url( 'setup.php' ) ); exit; } if ( ! defined( 'MULTISITE' ) ) wp_die( __( 'The Network creation panel is not for WordPress MU networks.' ) ); } // We need to create references to ms global tables to enable Network. foreach ( $wpdb->tables( 'ms_global' ) as $table => $prefixed_table ) $wpdb->$table = $prefixed_table; /** * Check for an existing network. * * @since 3.0.0 * @return Whether a network exists. */ function network_domain_check() { global $wpdb; if ( $wpdb->get_var( "SHOW TABLES LIKE '$wpdb->site'" ) ) return $wpdb->get_var( "SELECT domain FROM $wpdb->site ORDER BY id ASC LIMIT 1" ); return false; } /** * Allow subdomain install * * @since 3.0.0 * @return bool Whether subdomain install is allowed */ function allow_subdomain_install() { $domain = preg_replace( '|https?://([^/]+)|', '$1', get_option( 'home' ) ); if( parse_url( get_option( 'home' ), PHP_URL_PATH ) || 'mels11-n1bsql.hosting-services.net.au' == $domain || preg_match( '|^[0-9]+\.[0-9]+\.[0-9]+\.[0-9]+$|', $domain ) ) return false; return true; } /** * Allow subdirectory install * * @since 3.0.0 * @return bool Whether subdirectory install is allowed */ function allow_subdirectory_install() { global $wpdb; if ( apply_filters( 'allow_subdirectory_install', false ) ) return true; if ( defined( 'ALLOW_SUBDIRECTORY_INSTALL' ) && ALLOW_SUBDIRECTORY_INSTALL ) return true; $post = $wpdb->get_row( "SELECT ID FROM $wpdb->posts WHERE post_date < DATE_SUB(NOW(), INTERVAL 1 MONTH) AND post_status = 'publish'" ); if ( empty( $post ) ) return true; return false; } /** * Get base domain of network. * * @since 3.0.0 * @return string Base domain. */ function get_clean_basedomain() { if ( $existing_domain = network_domain_check() ) return $existing_domain; $domain = preg_replace( '|https?://|', '', get_option( 'siteurl' ) ); if ( $slash = strpos( $domain, '/' ) ) $domain = substr( $domain, 0, $slash ); return $domain; } if ( ! network_domain_check() && ( ! defined( 'WP_ALLOW_MULTISITE' ) || ! WP_ALLOW_MULTISITE ) ) wp_die( __( 'You must define the <code>WP_ALLOW_MULTISITE</code> constant as true in your wp-config.php file to allow creation of a Network.' ) ); if ( is_network_admin() ) { $title = __( 'Network Setup' ); $parent_file = 'settings.php'; } else { $title = __( 'Create a Network of WordPress Sites' ); $parent_file = 'tools.php'; } $network_help = '<p>' . __('This screen allows you to configure a network as having subdomains (<code>site1.example.com</code>) or subdirectories (<code>example.com/site1</code>). Subdomains require wildcard subdomains to be enabled in Apache and DNS records, if your host allows it.') . '</p>' . '<p>' . __('Choose subdomains or subdirectories; this can only be switched afterwards by reconfiguring your install. Fill out the network details, and click install. If this does not work, you may have to add a wildcard DNS record (for subdomains) or change to another setting in Permalinks (for subdirectories).') . '</p>' . '<p>' . __('The next screen for Network Setup will give you individually-generated lines of code to add to your wp-config.php and .htaccess files. Make sure the settings of your FTP client make files starting with a dot visible, so that you can find .htaccess; you may have to create this file if it really is not there. Make backup copies of those two files.') . '</p>' . '<p>' . __('Add the designated lines of code to wp-config.php (just before <code>/*...stop editing...*/</code>) and <code>.htaccess</code> (replacing the existing WordPress rules).') . '</p>' . '<p>' . __('Once you add this code and refresh your browser, multisite should be enabled. This screen, now in the Network Admin navigation menu, will keep an archive of the added code. You can toggle between Network Admin and Site Admin by clicking on the Network Admin or an individual site name under the My Sites dropdown in the Toolbar.') . '</p>' . '<p>' . __('The choice of subdirectory sites is disabled if this setup is more than a month old because of permalink problems with &#8220;/blog/&#8221; from the main site. This disabling will be addressed in a future version.') . '</p>' . '<p><strong>' . __('For more information:') . '</strong></p>' . '<p>' . __('<a href="http://codex.wordpress.org/Create_A_Network" target="_blank">Documentation on Creating a Network</a>') . '</p>' . '<p>' . __('<a href="http://codex.wordpress.org/Tools_Network_Screen" target="_blank">Documentation on the Network Screen</a>') . '</p>'; get_current_screen()->add_help_tab( array( 'id' => 'network', 'title' => __('Network'), 'content' => $network_help, ) ); get_current_screen()->set_help_sidebar( '<p><strong>' . __('For more information:') . '</strong></p>' . '<p>' . __('<a href="http://codex.wordpress.org/Create_A_Network" target="_blank">Documentation on Creating a Network</a>') . '</p>' . '<p>' . __('<a href="http://codex.wordpress.org/Tools_Network_Screen" target="_blank">Documentation on the Network Screen</a>') . '</p>' . '<p>' . __('<a href="http://wordpress.org/support/" target="_blank">Support Forums</a>') . '</p>' ); include( ABSPATH . 'wp-admin/admin-header.php' ); ?> <div class="wrap"> <?php screen_icon('tools'); ?> <h2><?php echo esc_html( $title ); ?></h2> <?php /** * Prints step 1 for Network installation process. * * @todo Realistically, step 1 should be a welcome screen explaining what a Network is and such. Navigating to Tools > Network * should not be a sudden "Welcome to a new install process! Fill this out and click here." See also contextual help todo. * * @since 3.0.0 */ function network_step1( $errors = false ) { global $is_apache; if ( defined('DO_NOT_UPGRADE_GLOBAL_TABLES') ) { echo '<div class="error"><p><strong>' . __('ERROR:') . '</strong> ' . __( 'The constant DO_NOT_UPGRADE_GLOBAL_TABLES cannot be defined when creating a network.' ) . '</p></div>'; echo '</div>'; include ( ABSPATH . 'wp-admin/admin-footer.php' ); die(); } $active_plugins = get_option( 'active_plugins' ); if ( ! empty( $active_plugins ) ) { echo '<div class="updated"><p><strong>' . __('Warning:') . '</strong> ' . sprintf( __( 'Please <a href="%s">deactivate your plugins</a> before enabling the Network feature.' ), admin_url( 'plugins.php?plugin_status=active' ) ) . '</p></div><p>' . __( 'Once the network is created, you may reactivate your plugins.' ) . '</p>'; echo '</div>'; include( ABSPATH . 'wp-admin/admin-footer.php' ); die(); } $hostname = get_clean_basedomain(); $has_ports = strstr( $hostname, ':' ); if ( ( false !== $has_ports && ! in_array( $has_ports, array( ':80', ':443' ) ) ) ) { echo '<div class="error"><p><strong>' . __( 'ERROR:') . '</strong> ' . __( 'You cannot install a network of sites with your server address.' ) . '</p></div>'; echo '<p>' . sprintf( __( 'You cannot use port numbers such as <code>%s</code>.' ), $has_ports ) . '</p>'; echo '<a href="' . esc_url( admin_url() ) . '">' . __( 'Return to Dashboard' ) . '</a>'; echo '</div>'; include( ABSPATH . 'wp-admin/admin-footer.php' ); die(); } echo '<form method="post" action="">'; wp_nonce_field( 'install-network-1' ); $error_codes = array(); if ( is_wp_error( $errors ) ) { echo '<div class="error"><p><strong>' . __( 'ERROR: The network could not be created.' ) . '</strong></p>'; foreach ( $errors->get_error_messages() as $error ) echo "<p>$error</p>"; echo '</div>'; $error_codes = $errors->get_error_codes(); } $site_name = ( ! empty( $_POST['sitename'] ) && ! in_array( 'empty_sitename', $error_codes ) ) ? $_POST['sitename'] : sprintf( _x('%s Sites', 'Default network name' ), get_option( 'blogname' ) ); $admin_email = ( ! empty( $_POST['email'] ) && ! in_array( 'invalid_email', $error_codes ) ) ? $_POST['email'] : get_option( 'admin_email' ); ?> <p><?php _e( 'Welcome to the Network installation process!' ); ?></p> <p><?php _e( 'Fill in the information below and you&#8217;ll be on your way to creating a network of WordPress sites. We will create configuration files in the next step.' ); ?></p> <?php if ( isset( $_POST['subdomain_install'] ) ) { $subdomain_install = (bool) $_POST['subdomain_install']; } elseif ( apache_mod_loaded('mod_rewrite') ) { // assume nothing $subdomain_install = true; } elseif ( !allow_subdirectory_install() ) { $subdomain_install = true; } else { $subdomain_install = false; if ( $got_mod_rewrite = got_mod_rewrite() ) // dangerous assumptions echo '<div class="updated inline"><p><strong>' . __( 'Note:' ) . '</strong> ' . __( 'Please make sure the Apache <code>mod_rewrite</code> module is installed as it will be used at the end of this installation.' ) . '</p>'; elseif ( $is_apache ) echo '<div class="error inline"><p><strong>' . __( 'Warning!' ) . '</strong> ' . __( 'It looks like the Apache <code>mod_rewrite</code> module is not installed.' ) . '</p>'; if ( $got_mod_rewrite || $is_apache ) // Protect against mod_rewrite mimicry (but ! Apache) echo '<p>' . __( 'If <code>mod_rewrite</code> is disabled, ask your administrator to enable that module, or look at the <a href="http://httpd.apache.org/docs/mod/mod_rewrite.html">Apache documentation</a> or <a href="http://www.google.com/search?q=apache+mod_rewrite">elsewhere</a> for help setting it up.' ) . '</p></div>'; } if ( allow_subdomain_install() && allow_subdirectory_install() ) : ?> <h3><?php esc_html_e( 'Addresses of Sites in your Network' ); ?></h3> <p><?php _e( 'Please choose whether you would like sites in your WordPress network to use sub-domains or sub-directories. <strong>You cannot change this later.</strong>' ); ?></p> <p><?php _e( 'You will need a wildcard DNS record if you are going to use the virtual host (sub-domain) functionality.' ); ?></p> <?php // @todo: Link to an MS readme? ?> <table class="form-table"> <tr> <th><label><input type='radio' name='subdomain_install' value='1'<?php checked( $subdomain_install ); ?> /> <?php _e( 'Sub-domains' ); ?></label></th> <td><?php printf( _x( 'like <code>site1.%1$s</code> and <code>site2.%1$s</code>', 'subdomain examples' ), $hostname ); ?></td> </tr> <tr> <th><label><input type='radio' name='subdomain_install' value='0'<?php checked( ! $subdomain_install ); ?> /> <?php _e( 'Sub-directories' ); ?></label></th> <td><?php printf( _x( 'like <code>%1$s/site1</code> and <code>%1$s/site2</code>', 'subdirectory examples' ), $hostname ); ?></td> </tr> </table> <?php endif; if ( WP_CONTENT_DIR != ABSPATH . 'wp-content' && ( allow_subdirectory_install() || ! allow_subdomain_install() ) ) echo '<div class="error inline"><p><strong>' . __('Warning!') . '</strong> ' . __( 'Subdirectory networks may not be fully compatible with custom wp-content directories.' ) . '</p></div>'; $is_www = ( 0 === strpos( $hostname, 'www.' ) ); if ( $is_www ) : ?> <h3><?php esc_html_e( 'Server Address' ); ?></h3> <p><?php printf( __( 'We recommend you change your siteurl to <code>%1$s</code> before enabling the network feature. It will still be possible to visit your site using the <code>www</code> prefix with an address like <code>%2$s</code> but any links will not have the <code>www</code> prefix.' ), substr( $hostname, 4 ), $hostname ); ?></p> <table class="form-table"> <tr> <th scope='row'><?php esc_html_e( 'Server Address' ); ?></th> <td> <?php printf( __( 'The internet address of your network will be <code>%s</code>.' ), $hostname ); ?> </td> </tr> </table> <?php endif; ?> <h3><?php esc_html_e( 'Network Details' ); ?></h3> <table class="form-table"> <?php if ( 'mels11-n1bsql.hosting-services.net.au' == $hostname ) : ?> <tr> <th scope="row"><?php esc_html_e( 'Sub-directory Install' ); ?></th> <td><?php _e( 'Because you are using <code>mels11-n1bsql.hosting-services.net.au</code>, the sites in your WordPress network must use sub-directories. Consider using <code>mels11-n1bsql.hosting-services.net.au.localdomain</code> if you wish to use sub-domains.' ); // Uh oh: if ( !allow_subdirectory_install() ) echo ' <strong>' . __( 'Warning!' ) . ' ' . __( 'The main site in a sub-directory install will need to use a modified permalink structure, potentially breaking existing links.' ) . '</strong>'; ?></td> </tr> <?php elseif ( !allow_subdomain_install() ) : ?> <tr> <th scope="row"><?php esc_html_e( 'Sub-directory Install' ); ?></th> <td><?php _e( 'Because your install is in a directory, the sites in your WordPress network must use sub-directories.' ); // Uh oh: if ( !allow_subdirectory_install() ) echo ' <strong>' . __( 'Warning!' ) . ' ' . __( 'The main site in a sub-directory install will need to use a modified permalink structure, potentially breaking existing links.' ) . '</strong>'; ?></td> </tr> <?php elseif ( !allow_subdirectory_install() ) : ?> <tr> <th scope="row"><?php esc_html_e( 'Sub-domain Install' ); ?></th> <td><?php _e( 'Because your install is not new, the sites in your WordPress network must use sub-domains.' ); echo ' <strong>' . __( 'The main site in a sub-directory install will need to use a modified permalink structure, potentially breaking existing links.' ) . '</strong>'; ?></td> </tr> <?php endif; ?> <?php if ( ! $is_www ) : ?> <tr> <th scope='row'><?php esc_html_e( 'Server Address' ); ?></th> <td> <?php printf( __( 'The internet address of your network will be <code>%s</code>.' ), $hostname ); ?> </td> </tr> <?php endif; ?> <tr> <th scope='row'><?php esc_html_e( 'Network Title' ); ?></th> <td> <input name='sitename' type='text' size='45' value='<?php echo esc_attr( $site_name ); ?>' /> <br /><?php _e( 'What would you like to call your network?' ); ?> </td> </tr> <tr> <th scope='row'><?php esc_html_e( 'Admin E-mail Address' ); ?></th> <td> <input name='email' type='text' size='45' value='<?php echo esc_attr( $admin_email ); ?>' /> <br /><?php _e( 'Your email address.' ); ?> </td> </tr> </table> <?php submit_button( __( 'Install' ), 'primary', 'submit' ); ?> </form> <?php } /** * Prints step 2 for Network installation process. * * @since 3.0.0 */ function network_step2( $errors = false ) { global $wpdb; $hostname = get_clean_basedomain(); $slashed_home = trailingslashit( get_option( 'home' ) ); $base = parse_url( $slashed_home, PHP_URL_PATH ); $document_root_fix = str_replace( '\\', '/', realpath( $_SERVER['DOCUMENT_ROOT'] ) ); $abspath_fix = str_replace( '\\', '/', ABSPATH ); $home_path = 0 === strpos( $abspath_fix, $document_root_fix ) ? $document_root_fix . $base : str_replace( '\\', '/', get_home_path() ); $wp_siteurl_subdir = preg_replace( '#^' . preg_quote( $home_path, '#' ) . '#', '', $abspath_fix ); $rewrite_base = ! empty( $wp_siteurl_subdir ) ? ltrim( trailingslashit( $wp_siteurl_subdir ), '/' ) : ''; $location_of_wp_config = ABSPATH; if ( ! file_exists( ABSPATH . 'wp-config.php' ) && file_exists( dirname( ABSPATH ) . '/wp-config.php' ) ) $location_of_wp_config = trailingslashit( dirname( ABSPATH ) ); // Wildcard DNS message. if ( is_wp_error( $errors ) ) echo '<div class="error">' . $errors->get_error_message() . '</div>'; if ( $_POST ) { if ( allow_subdomain_install() ) $subdomain_install = allow_subdirectory_install() ? ! empty( $_POST['subdomain_install'] ) : true; else $subdomain_install = false; } else { if ( is_multisite() ) { $subdomain_install = is_subdomain_install(); ?> <p><?php _e( 'The original configuration steps are shown here for reference.' ); ?></p> <?php } else { $subdomain_install = (bool) $wpdb->get_var( "SELECT meta_value FROM $wpdb->sitemeta WHERE site_id = 1 AND meta_key = 'subdomain_install'" ); ?> <div class="error"><p><strong><?php _e('Warning:'); ?></strong> <?php _e( 'An existing WordPress network was detected.' ); ?></p></div> <p><?php _e( 'Please complete the configuration steps. To create a new network, you will need to empty or remove the network database tables.' ); ?></p> <?php } } $subdir_match = $subdomain_install ? '' : '([_0-9a-zA-Z-]+/)?'; $subdir_replacement_01 = $subdomain_install ? '' : '$1'; $subdir_replacement_12 = $subdomain_install ? '$1' : '$2'; if ( $_POST || ! is_multisite() ) { ?> <h3><?php esc_html_e( 'Enabling the Network' ); ?></h3> <p><?php _e( 'Complete the following steps to enable the features for creating a network of sites.' ); ?></p> <div class="updated inline"><p><?php if ( file_exists( $home_path . '.htaccess' ) ) printf( __( '<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> and <code>%s</code> files.' ), '.htaccess' ); elseif ( file_exists( $home_path . 'web.config' ) ) printf( __( '<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> and <code>%s</code> files.' ), 'web.config' ); else _e( '<strong>Caution:</strong> We recommend you back up your existing <code>wp-config.php</code> file.' ); ?></p></div> <?php } ?> <ol> <li><p><?php printf( __( 'Add the following to your <code>wp-config.php</code> file in <code>%s</code> <strong>above</strong> the line reading <code>/* That&#8217;s all, stop editing! Happy blogging. */</code>:' ), $location_of_wp_config ); ?></p> <textarea class="code" readonly="readonly" cols="100" rows="6"> define('MULTISITE', true); define('SUBDOMAIN_INSTALL', <?php echo $subdomain_install ? 'true' : 'false'; ?>); define('DOMAIN_CURRENT_SITE', '<?php echo $hostname; ?>'); define('PATH_CURRENT_SITE', '<?php echo $base; ?>'); define('SITE_ID_CURRENT_SITE', 1); define('BLOG_ID_CURRENT_SITE', 1); </textarea> <?php $keys_salts = array( 'AUTH_KEY' => '', 'SECURE_AUTH_KEY' => '', 'LOGGED_IN_KEY' => '', 'NONCE_KEY' => '', 'AUTH_SALT' => '', 'SECURE_AUTH_SALT' => '', 'LOGGED_IN_SALT' => '', 'NONCE_SALT' => '' ); foreach ( $keys_salts as $c => $v ) { if ( defined( $c ) ) unset( $keys_salts[ $c ] ); } if ( ! empty( $keys_salts ) ) { $keys_salts_str = ''; $from_api = wp_remote_get( 'https://api.wordpress.org/secret-key/1.1/salt/' ); if ( is_wp_error( $from_api ) ) { foreach ( $keys_salts as $c => $v ) { $keys_salts_str .= "\ndefine( '$c', '" . wp_generate_password( 64, true, true ) . "' );"; } } else { $from_api = explode( "\n", wp_remote_retrieve_body( $from_api ) ); foreach ( $keys_salts as $c => $v ) { $keys_salts_str .= "\ndefine( '$c', '" . substr( array_shift( $from_api ), 28, 64 ) . "' );"; } } $num_keys_salts = count( $keys_salts ); ?> <p><?php echo _n( 'This unique authentication key is also missing from your <code>wp-config.php</code> file.', 'These unique authentication keys are also missing from your <code>wp-config.php</code> file.', $num_keys_salts ); ?> <?php _e( 'To make your installation more secure, you should also add:' ) ?></p> <textarea class="code" readonly="readonly" cols="100" rows="<?php echo $num_keys_salts; ?>"><?php echo esc_textarea( $keys_salts_str ); ?></textarea> <?php } ?> </li> <?php if ( iis7_supports_permalinks() ) : // IIS doesn't support RewriteBase, all your RewriteBase are belong to us $iis_subdir_match = ltrim( $base, '/' ) . $subdir_match; $iis_rewrite_base = ltrim( $base, '/' ) . $rewrite_base; $iis_subdir_replacement = $subdomain_install ? '' : '{R:1}'; $web_config_file = '<?xml version="1.0" encoding="UTF-8"?> <configuration> <system.webServer> <rewrite> <rules> <rule name="WordPress Rule 1" stopProcessing="true"> <match url="^index\.php$" ignoreCase="false" /> <action type="None" /> </rule>'; if ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) { $web_config_file .= ' <rule name="WordPress Rule for Files" stopProcessing="true"> <match url="^' . $iis_subdir_match . 'files/(.+)" ignoreCase="false" /> <action type="Rewrite" url="' . $iis_rewrite_base . 'wp-includes/ms-files.php?file={R:1}" appendQueryString="false" /> </rule>'; } $web_config_file .= ' <rule name="WordPress Rule 2" stopProcessing="true"> <match url="^' . $iis_subdir_match . 'wp-admin$" ignoreCase="false" /> <action type="Redirect" url="' . $iis_subdir_replacement . 'wp-admin/" redirectType="Permanent" /> </rule> <rule name="WordPress Rule 3" stopProcessing="true"> <match url="^" ignoreCase="false" /> <conditions logicalGrouping="MatchAny"> <add input="{REQUEST_FILENAME}" matchType="IsFile" ignoreCase="false" /> <add input="{REQUEST_FILENAME}" matchType="IsDirectory" ignoreCase="false" /> </conditions> <action type="None" /> </rule> <rule name="WordPress Rule 4" stopProcessing="true"> <match url="^' . $iis_subdir_match . '(wp-(content|admin|includes).*)" ignoreCase="false" /> <action type="Rewrite" url="' . $iis_rewrite_base . '{R:1}" /> </rule> <rule name="WordPress Rule 5" stopProcessing="true"> <match url="^' . $iis_subdir_match . '([_0-9a-zA-Z-]+/)?(.*\.php)$" ignoreCase="false" /> <action type="Rewrite" url="' . $iis_rewrite_base . '{R:2}" /> </rule> <rule name="WordPress Rule 6" stopProcessing="true"> <match url="." ignoreCase="false" /> <action type="Rewrite" url="index.php" /> </rule> </rules> </rewrite> </system.webServer> </configuration>'; ?> <li><p><?php printf( __( 'Add the following to your <code>web.config</code> file in <code>%s</code>, replacing other WordPress rules:' ), $home_path ); ?></p> <?php if ( ! $subdomain_install && WP_CONTENT_DIR != ABSPATH . 'wp-content' ) echo '<p><strong>' . __('Warning:') . ' ' . __( 'Subdirectory networks may not be fully compatible with custom wp-content directories.' ) . '</strong></p>'; ?> <textarea class="code" readonly="readonly" cols="100" rows="20"><?php echo esc_textarea( $web_config_file ); ?> </textarea></li> </ol> <?php else : // end iis7_supports_permalinks(). construct an htaccess file instead: $ms_files_rewriting = ''; if ( is_multisite() && get_site_option( 'ms_files_rewriting' ) ) { $ms_files_rewriting = "\n# uploaded files\nRewriteRule ^"; $ms_files_rewriting .= $subdir_match . "files/(.+) {$rewrite_base}wp-includes/ms-files.php?file={$subdir_replacement_12} [L]" . "\n"; } $htaccess_file = <<<EOF RewriteEngine On RewriteBase {$base} RewriteRule ^index\.php$ - [L] {$ms_files_rewriting} # add a trailing slash to /wp-admin RewriteRule ^{$subdir_match}wp-admin$ {$subdir_replacement_01}wp-admin/ [R=301,L] RewriteCond %{REQUEST_FILENAME} -f [OR] RewriteCond %{REQUEST_FILENAME} -d RewriteRule ^ - [L] RewriteRule ^{$subdir_match}(wp-(content|admin|includes).*) {$rewrite_base}{$subdir_replacement_12} [L] RewriteRule ^{$subdir_match}(.*\.php)$ {$rewrite_base}$subdir_replacement_12 [L] RewriteRule . index.php [L] EOF; ?> <li><p><?php printf( __( 'Add the following to your <code>.htaccess</code> file in <code>%s</code>, replacing other WordPress rules:' ), $home_path ); ?></p> <?php if ( ! $subdomain_install && WP_CONTENT_DIR != ABSPATH . 'wp-content' ) echo '<p><strong>' . __('Warning:') . ' ' . __( 'Subdirectory networks may not be fully compatible with custom wp-content directories.' ) . '</strong></p>'; ?> <textarea class="code" readonly="readonly" cols="100" rows="<?php echo substr_count( $htaccess_file, "\n" ) + 1; ?>"> <?php echo esc_textarea( $htaccess_file ); ?></textarea></li> </ol> <?php endif; // end IIS/Apache code branches. if ( !is_multisite() ) { ?> <p><?php printf( __( 'Once you complete these steps, your network is enabled and configured. You will have to log in again.') ); ?> <a href="<?php echo esc_url( site_url( 'wp-login.php' ) ); ?>"><?php _e( 'Log In' ); ?></a></p> <?php } } if ( $_POST ) { check_admin_referer( 'install-network-1' ); require_once( ABSPATH . 'wp-admin/includes/upgrade.php' ); // create network tables install_network(); $base = parse_url( trailingslashit( get_option( 'home' ) ), PHP_URL_PATH ); $subdomain_install = allow_subdomain_install() ? !empty( $_POST['subdomain_install'] ) : false; if ( ! network_domain_check() ) { $result = populate_network( 1, get_clean_basedomain(), sanitize_email( $_POST['email'] ), stripslashes( $_POST['sitename'] ), $base, $subdomain_install ); if ( is_wp_error( $result ) ) { if ( 1 == count( $result->get_error_codes() ) && 'no_wildcard_dns' == $result->get_error_code() ) network_step2( $result ); else network_step1( $result ); } else { network_step2(); } } else { network_step2(); } } elseif ( is_multisite() || network_domain_check() ) { network_step2(); } else { network_step1(); } ?> </div> <?php include( ABSPATH . 'wp-admin/admin-footer.php' ); ?>
wellswong/knowpathology
wp-admin/network.php
PHP
gpl-2.0
25,972
<?php /** * Review Order */ global $woocommerce; $checked = get_option('woocommerce_enable_guest_checkout'); //Add hook to show login form or not $show_login = apply_filters('paypal-for-woocommerce-show-login', !is_user_logged_in() && $checked==="no" && isset($_REQUEST['pp_action'])); ?> <style type="text/css"> #payment{ display:none; } </style> <form class="angelleye_checkout" method="POST" action="<?php echo add_query_arg( 'pp_action', 'payaction', add_query_arg( 'wc-api', 'WC_Gateway_PayPal_Express_AngellEYE', home_url( '/' ) ) );?>"> <div id="paypalexpress_order_review"> <?php woocommerce_order_review();?> </div> <?php if ( WC()->cart->needs_shipping() ) : ?> <div class="title"> <h2><?php _e( 'Customer details', 'woocommerce' ); ?></h2> </div> <div class="col2-set addresses"> <div class="col-1"> <div class="title"> <h3><?php _e( 'Shipping Address', 'woocommerce' ); ?></h3> </div> <div class="address"> <p> <?php // Formatted Addresses $address = array( 'first_name' => WC()->customer->shiptoname, 'last_name' => "", 'company' => "", 'address_1' => WC()->customer->get_address(), 'address_2' => "", 'city' => WC()->customer->get_city(), 'state' => WC()->customer->get_state(), 'postcode' => WC()->customer->get_postcode(), 'country' => WC()->customer->get_country() ) ; echo WC()->countries->get_formatted_address( $address ); ?> </p> </div> </div><!-- /.col-1 --> <div class="col-2"> </div><!-- /.col-2 --> </div><!-- /.col2-set --> <?php endif; ?> <?php if ( $show_login ): ?> </form> <style type="text/css"> .woocommerce #content p.form-row input.button, .woocommerce #respond p.form-row input#submit, .woocommerce p.form-row a.button, .woocommerce p.form-row button.button, .woocommerce p.form-row input.button, .woocommerce-page p.form-row #content input.button, .woocommerce-page p.form-row #respond input#submit, .woocommerce-page p.form-row a.button, .woocommerce-page p.form-row button.button, .woocommerce-page p.form-row input.button{ display: block !important; } </style> <div class="title"> <h2><?php _e( 'Login', 'woocommerce' ); ?></h2> </div> <form name="" action="" method="post"> <?php function curPageURL() { $pageURL = 'http'; if (@$_SERVER["HTTPS"] == "on") {$pageURL .= "s";} $pageURL .= "://"; if ($_SERVER["SERVER_PORT"] != "80") { $pageURL .= $_SERVER["SERVER_NAME"].":".$_SERVER["SERVER_PORT"].$_SERVER["REQUEST_URI"]; } else { $pageURL .= $_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"]; } return $pageURL; } woocommerce_login_form( array( 'message' => 'Please login or create an account to complete your order.', 'redirect' => curPageURL(), 'hidden' => true ) ); $result = unserialize(WC()->session->RESULT); $email = (!empty($_POST['email']))?$_POST['email']:$result['EMAIL']; ?> </form> <div class="title"> <h2><?php _e( 'Create A New Account', 'woocommerce' ); ?></h2> </div> <form action="" method="post"> <p class="form-row form-row-first"> <label for="paypalexpress_order_review_username">Username:<span class="required">*</span></label> <input style="width: 100%;" type="text" name="username" id="paypalexpress_order_review_username" value="" /> </p> <p class="form-row form-row-last"> <label for="paypalexpress_order_review_email">Email:<span class="required">*</span></label> <input style="width: 100%;" type="email" name="email" id="paypalexpress_order_review_email" value="<?php echo $email; ?>" /> </p> <div class="clear"></div> <p class="form-row form-row-first"> <label for="paypalexpress_order_review_password">Password:<span class="required">*</span></label> <input type="password" name="password" id="paypalexpress_order_review_password" class="input-text" /> </p> <p class="form-row form-row-last"> <label for="paypalexpress_order_review_repassword">Re Password:<span class="required">*</span></label> <input type="password" name="repassword" id="paypalexpress_order_review_repassword" class="input-text"/> </p> <div class="clear"></div> <p> <input class="button" type="submit" name="createaccount" value="Create Account" /> <input type="hidden" name="address" value="<?php echo WC()->customer->get_address(); ?>"> </p> </form> <?php else: echo '<div class="clear"></div>'; echo '<p><a class="button angelleye_cancel" href="' . $woocommerce->cart->get_cart_url() . '">'.__('Cancel order', 'paypal-for-woocommerce').'</a> '; echo '<input type="submit" onclick="jQuery(this).attr(\'disabled\', \'disabled\').val(\'Processing\'); jQuery(this).parents(\'form\').submit(); return false;" class="button" value="' . __( 'Place Order','paypal-for-woocommerce') . '" /></p>'; ?> </form><!--close the checkout form--> <?php endif; ?> <div class="clear"></div>
davidxcarroll/TATM
wp-content/plugins/paypal-for-woocommerce/template/paypal-review-order.php
PHP
gpl-2.0
5,955
<?php /** * @package HikaShop for Joomla! * @version 2.6.4 * @author hikashop.com * @copyright (C) 2010-2016 HIKARI SOFTWARE. All rights reserved. * @license GNU/GPLv3 http://www.gnu.org/licenses/gpl-3.0.html */ defined('_JEXEC') or die('Restricted access'); ?><?php $sort = JRequest::getString('sort_comment',''); $row = & $this->rows; $pagination = & $this->pagination; if($row->comment_enabled != 1) return; if(($row->hikashop_vote_con_req_list == 1 && hikashop_loadUser() != "") || $row->hikashop_vote_con_req_list == 0) { ?> <div class="hikashop_listing_comment"><?php echo JText::_('HIKASHOP_LISTING_COMMENT');?> <?php if($row->vote_comment_sort_frontend){ ?> <span style="float: right;" class="hikashop_sort_listing_comment"> <select name="sort_comment" onchange="refreshCommentSort(this.value); return false;"> <option <?php if($sort == 'date')echo "selected"; ?> value="date"><?php echo JText::_('HIKASHOP_COMMENT_ORDER_DATE');?></option> <option <?php if($sort == 'helpful')echo "selected"; ?> value="helpful"><?php echo JText::_('HIKASHOP_COMMENT_ORDER_HELPFUL');?></option> </select> </span> <?php } ?> </div> <?php $i = 0; foreach($this->elts as $elt) { if(empty($elt->vote_comment)) continue; ?> <table itemprop="review" itemscope itemtype="http://schema.org/Review" class="hika_comment_listing" style="width:100%;"> <tr> <td class="hika_comment_listing_name" itemprop="author" itemscope itemtype="http://schema.org/Person"> <?php if ($elt->vote_pseudo == '0') { ?> <span itemprop="name" class="hika_vote_listing_username"><?php echo $elt->username; ?> </span> <?php } else { ?> <span itemprop="name" class="hika_vote_listing_username" ><?php echo $elt->vote_pseudo; ?></span> <?php } ?> </td> <td class="hika_comment_listing_stars"><?php $nb_star_vote = $elt->vote_rating; JRequest::setVar("nb_star", $nb_star_vote); $nb_star_config = $row->vote_star_number; JRequest::setVar("nb_max_star", $nb_star_config); if($nb_star_vote != 0) { for($k=0; $k < $nb_star_vote; $k++ ){ ?><span class="hika_comment_listing_full_stars" ></span><?php } $nb_star_empty = $nb_star_config - $nb_star_vote; if($nb_star_empty != 0){ for($j=0; $j < $nb_star_empty; $j++ ){ ?><span class="hika_comment_listing_empty_stars" ></span><?php } } ?> <span style="display:none;" itemprop="reviewRating" itemscope itemtype="http://schema.org/Rating"> <span itemprop="bestRating"><?php echo $nb_star_config; ?></span> <span itemprop="worstRating">1</span> <span itemprop="ratingValue"><?php echo $nb_star_vote; ?></span> </span> <?php } ?> </td> <td> <div class="hika_comment_listing_notification" id="<?php echo $elt->vote_id; ?>"> <?php if($elt->total_vote_useful != 0){ if($elt->vote_useful == 0) { $hika_useful = $elt->total_vote_useful / 2; } else if($elt->total_vote_useful == $elt->vote_useful) { $hika_useful = $elt->vote_useful; } else if($elt->total_vote_useful == -$elt->vote_useful) { $hika_useful = 0; } else { $hika_useful = ($elt->total_vote_useful + $elt->vote_useful) /2; } $hika_useless = $elt->total_vote_useful - $hika_useful; if($row->useful_style == 'helpful'){ echo JText::sprintf('HIKA_FIND_IT_HELPFUL', $hika_useful, $elt->total_vote_useful); } } else { $hika_useless = 0; $hika_useful = 0; if($row->useful_style == 'helpful' && $row->useful_rating == 1 && $elt->vote_user_id != hikashop_loadUser() && $elt->vote_user_id != hikashop_getIP()) { echo JText::_('HIKASHOP_NO_USEFUL'); } } ?></div> </td> <?php if($row->useful_rating == 1) { if($row->hide == 0 && $elt->already_vote == 0 && $elt->vote_user_id != hikashop_loadUser() && $elt->vote_user_id != hikashop_getIP()){ if($row->useful_style == 'thumbs') { ?> <td class="hika_comment_listing_useful_p"><?php echo $hika_useful; ?></td> <?php } ?> <td class="hika_comment_listing_useful" title="<?php echo JText::_('HIKA_USEFUL'); ?>" onclick="hikashop_vote_useful(<?php echo $elt->vote_id;?>,1);"></td> <?php if($row->useful_style == 'thumbs'){?> <td class="hika_comment_listing_useful_p"><?php echo $hika_useless; ?></td> <?php } ?> <td class="hika_comment_listing_useless" title="Useless" onclick="hikashop_vote_useful(<?php echo $elt->vote_id;?>,2);"></td> <?php } else if($row->useful_style == "thumbs") { ?> <td class="hika_comment_listing_useful_p"><?php echo $hika_useful; ?></td> <td class="hika_comment_listing_useful locked"></td> <td class="hika_comment_listing_useless_p"><?php echo $hika_useless; ?></td> <td class="hika_comment_listing_useless locked"></td> <?php } else { ?> <td class="hika_comment_listing_useful_p hide"></td> <td class="hika_comment_listing_useful locked hide"></td> <td class="hika_comment_listing_useless_p hide"></td> <td class="hika_comment_listing_useless locked hide"></td> <?php } } ?> </tr> <?php if($row->show_comment_date) { ?> <tr> <td colspan="8"><?php $voteClass = hikashop_get('class.vote'); $vote = $voteClass->get($elt->vote_id); echo hikashop_getDate($vote->vote_date); ?></td> </tr> <?php } ?> <tr> <td colspan="8"> <div id="<?php echo $i++; ?>" itemprop="reviewBody" class="hika_comment_listing_content"><?php echo nl2br($elt->vote_comment); ?></div> </td> </tr> <tr> <td colspan="8" class="hika_comment_listing_bottom"> <?php if(!empty ($elt->purchased)) { ?> <span class="hikashop_vote_listing_useful_bought"><?php echo JText::_('HIKASHOP_VOTE_BOUGHT_COMMENT'); ?></span> <?php } ?> </td> </tr> </table> <?php } if(!count($this->elts)) { ?> <table class="hika_comment_listing"> <tr> <td class="hika_comment_listing_empty"><?php echo JText::_('HIKASHOP_NO_COMMENT_YET'); ?></td> </tr> </table> <?php } else { $this->pagination->form = '_hikashop_comment_form'; ?> <div class="pagination"><?php echo $this->pagination->getListFooter(); echo $this->pagination->getResultsCounter(); ?></div> <?php } } if($row->vote_comment_sort_frontend) { $jconfig = JFactory::getConfig(); $sef = (HIKASHOP_J30 ? $jconfig->get('sef') : $jconfig->getValue('config.sef')); $sortUrl = $sef ? '/sort_comment-' : '&sort_comment='; ?> <script type="text/javascript"> function refreshCommentSort(value){ var url = window.location.href; if(url.match(/sort_comment/g)){ url = url.replace(/\/sort_comment.?[a-z]*/g,'').replace(/&sort_comment.?[a-z]*/g,''); } url = url+'<?php echo $sortUrl; ?>'+value; document.location.href = url; } </script> <?php }
khuongdang/dongtrungtruongsinh
components/com_hikashop/views/vote/tmpl/listing.php
PHP
gpl-2.0
6,756
from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout, Submit, Button, Field, Hidden, HTML, Div from crispy_forms.bootstrap import FormActions, AppendedText, StrictButton, InlineField from django import forms from django.contrib.auth.decorators import login_required from django.core.urlresolvers import resolve, reverse from django.db import models from django.db.models import F, ExpressionWrapper, FloatField, IntegerField, CharField, Case, When, Sum, Func, Min, Q from django.shortcuts import render, redirect from django.utils.encoding import python_2_unicode_compatible from cooking.helpers import prepareContext from cooking.models import Ingredient from cooking.forms import ConfirmDeleteForm class IngredientForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(IngredientForm, self).__init__(*args, **kwargs) self.fields['cooked_weight'].required = False self.helper = FormHelper() self.helper.form_class = 'form-horizontal' self.helper.form_method = 'post' self.helper.form_action = '' self.helper.label_class = 'col-lg-2' self.helper.field_class = 'col-lg-4' self.helper.layout = Layout( Field('name'), Field('buying_quantity'), Field('buying_measurement'), Field('calculation_quantity'), Field('calculation_measurement'), AppendedText('cooked_weight', 'Gram'), AppendedText('price', '€'), Field('cheapest_store'), Field('remarks'), Field('allergens'), FormActions( Submit('save', 'Save changes'), HTML('<a href="' + reverse('cooking:ingredients') + '" class="btn btn-default" role="button">Cancel</a>'), ) ) #self.helper.add_input(Submit('submit', 'Save')) def clean_price(self): if(self.cleaned_data.get('price') < 0): raise forms.ValidationError("Price can't be negative") return self.cleaned_data.get('price') def clean_buying_quantity(self): if(self.cleaned_data.get('buying_quantity') == 0): raise forms.ValidationError("Buying Quantity can't be zero") return self.cleaned_data.get('buying_quantity') def clean_calculation_quantity(self): if(self.cleaned_data.get('calculation_quantity') != None and self.cleaned_data.get('calculation_quantity') == 0): raise forms.ValidationError("Calculation Quantity can not be zero, leave it out if you don't need it") return self.cleaned_data.get('calculation_quantity') def clean_calculation_measurement(self): if(self.cleaned_data.get('calculation_measurement') == None and self.cleaned_data.get('calculation_quantity') != None): raise forms.ValidationError('If calculation quantity is set, you also need to set the measurement') elif(self.cleaned_data.get('calculation_quantity') == None and self.cleaned_data.get('calculation_measurement') != None): raise forms.ValidationError('You can not set a measurement without a quantity') else: return self.cleaned_data.get('calculation_measurement') def clean_cooked_weight(self): if(self.cleaned_data.get('cooked_weight') == None): self.cleaned_data['cooked_weight'] = 0 return self.cleaned_data.get('cooked_weight') class Meta: model = Ingredient exclude = ['id'] @login_required def list_ingredients(request): context = prepareContext(request) context['ingredient_list'] = Ingredient.objects.all() context['pagetitle'] = 'Ingredients' return render(request, 'listings/ingredients.html', context) @login_required def edit_ingredient(request, ingredient): context = prepareContext(request) if(request.POST and 'id' in request.POST): ingredient = int(request.POST.get('id')) ing = Ingredient.objects.get(id=ingredient) form = IngredientForm(request.POST or None, instance=ing) if(form.is_valid()): form.save() context['submitted'] = True context['form'] = form context['name'] = ing.name context['pagetitle'] = 'Edit Ingredient' return render(request, 'single/defaultform.html', context) @login_required def del_ingredient(request, ingredient): context = prepareContext(request) ing = Ingredient.objects.get(id=ingredient) form = ConfirmDeleteForm(request.POST or None) if(form.is_valid()): ing.delete() return redirect('cooking:ingredients') context['object'] = ing context['noaction'] = reverse('cooking:ingredients') context['form'] = form context['pagetitle'] = 'Delete Ingredient' return render(request, 'single/confirmdelete.html', context) @login_required def new_ingredient(request): context = prepareContext(request) form = None if(request.POST): form = IngredientForm(data=request.POST or None) if(form.is_valid()): form.save() return redirect('cooking:ingredients') else: form = IngredientForm() context['form'] = form context['name'] = 'New Ingredient' context['pagetitle'] = 'New Ingredient' return render(request, 'single/defaultform.html', context) @login_required def ingredients_csv(request): response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="ingredients.csv"' writer = UnicodeWriter(response) writer.writerow(['Name', 'Buying unit', '', 'Calculation unit', '', 'Price', 'Remarks', 'Cheapest Store', 'Allergens']) ingredients = Ingredient.objects.all() for item in ingredients: writer.writerow([item.name, item.buying_quantity, conv_measurement(item.buying_measurement, item.buying_quantity), item.calculation_quantity, conv_measurement(item.calculation_measurement, item.calculation_quantity), item.price, item.remarks, item.cheapest_store, ', '.join([a.name for a in item.allergens.all()])]) return response
blacksph3re/alastair
cooking/ingredient/ingredient.py
Python
gpl-2.0
5,596
<?php /** * * @package Football * @version $Id: chart_hist.php 1 2010-05-17 22:09:43Z football $ * @copyright (c) 2010 football (http://football.bplaced.net) * @license http://opensource.org/licenses/gpl-license.php GNU Public License * */ if (!defined('IN_PHPBB')) { exit; } $values1 = ( isset($_GET['v1']) ) ? $_GET['v1'] : 0; $graphvalues1 = explode(",",$values1); $matchdays = sizeof($graphvalues1); // Define .PNG image header("Content-type: image/png"); $horz = 15; $vert = 9; $start = 25; $imgWidth= $matchdays * $vert + 20; $imgHeight=90; // Create image and define colors $image = imagecreate($imgWidth, $imgHeight); $colorBackground = imagecolorallocate($image, 236, 240, 246); $colorWhite = imagecolorallocate($image, 255, 255, 255); $colorBlack = imagecolorallocate($image, 0, 0, 0); $colorGrey = imagecolorallocate($image, 106, 106, 106); $colorBlue = imagecolorallocate($image, 0, 0, 255); $colorRed = imagecolorallocate($image, 176, 0, 0); $colorGreen = imagecolorallocate($image, 0, 176, 0); imagefill($image, 0, 0, $colorBackground); imageline($image, 0, 45, $imgWidth, 45, $colorGrey); imagestring($image,4, 5, 15, 'H', $colorBlack); imagestring($image,4, 5, 60, 'A', $colorBlack); imagesetthickness($image, 5); $count_values=count($graphvalues1); // Create line graph for ($i = 0; $i < $count_values; $i++) { if (substr($graphvalues1[$i],0,1) == '-') { imageline($image, $start + ($i * $vert), 45, $start + ($i * $vert), substr($graphvalues1[$i], 1, strlen($graphvalues1[$i]) - 1), $colorRed); } else { if (substr($graphvalues1[$i],0,1) == ' ') { imageline($image, $start + ($i * $vert), 45, $start + ($i * $vert), substr($graphvalues1[$i], 1, strlen($graphvalues1[$i]) - 1), $colorGreen); } else { imageline($image, $start + ($i * $vert), 45, $start + ($i * $vert), substr($graphvalues1[$i], 0, strlen($graphvalues1[$i])), $colorGrey); } } } // Output graph and clear image from memory imagepng($image); imagedestroy($image);
football/Prediction-League
includes/chart_hist.php
PHP
gpl-2.0
1,999
<?php /** * @version $Id: ie7splash.php 10172 2013-05-10 16:09:54Z kevin $ * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2014 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only * * Gantry uses the Joomla Framework (http://www.joomla.org), a GNU/GPLv2 content management system * */ defined('JPATH_BASE') or die(); gantry_import('core.gantryfeature'); /** * @package gantry * @subpackage features */ class GantryFeatureIE7Splash extends GantryFeature { var $_feature_name = 'ie7splash'; function isEnabled(){ if ($this->get('enabled')) { return true; } } function isInPosition($position) { return false; } function isOrderable(){ return true; } function init() { global $gantry; if (JFactory::getApplication()->input->getString('tmpl')!=='unsupported' && $gantry->browser->name == 'ie' && $gantry->browser->shortversion == '7') { header("Location: ".$gantry->baseUrl."?tmpl=unsupported"); } } }
onekweb/rhemawebb.se-in-joomla3
templates/rt_praxis/features/ie7splash.php
PHP
gpl-2.0
1,120
// tp2points.cc: test program for P2Point class ////////////////////////////////////////////////////////////////////////// // // Copyright 1990-2012 John Cremona // // This file is part of the eclib package. // // eclib is free software; you can redistribute it and/or modify it // under the terms of the GNU General Public License as published by the // Free Software Foundation; either version 2 of the License, or (at your // option) any later version. // // eclib is distributed in the hope that it will be useful, but WITHOUT // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or // FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License // for more details. // // You should have received a copy of the GNU General Public License // along with eclib; if not, write to the Free Software Foundation, // Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA // ////////////////////////////////////////////////////////////////////////// #include <eclib/p2points.h> int main() { cout << "Test program for P2Point class" << endl; P2Point P, Q, R; cout << "Point input formats are [x:y:z], [x,y], [x/z,y/z] with any type of brackets" << endl; cout << "Enter a point P: "; cin >> P; cout << "P="<<P<<endl; cout << "output_pari(P) = "; output_pari(cout,P); cout<<endl; cout << "P==P? "<< (P==P) <<endl; P=P2Point(2,4,-6); cout << "After P=P2Point(2,4,-6), P="<<P<<endl; Q=P; cout << "After Q=P, Q="<<Q<<endl; Q=transform(P,BIGINT(3),BIGINT(4),BIGINT(5),BIGINT(6),0); cout << "After Q=transform(P,3,4,5,6,0), Q="<<Q<<endl; R=transform(Q,BIGINT(3),BIGINT(4),BIGINT(5),BIGINT(6),1); cout << "After R=transform(Q,3,4,5,6,1), R="<<R<<endl; cout << "R==P? "<< (R==P) <<endl; bigint x,y,z; bigrational X,Y; bigfloat rx,ry; P.getcoordinates(x,y,z); cout<<"Projective coordinates of P are X="<<x<<", Y="<<y<<", Z="<<z<<endl; P.getaffinecoordinates(X,Y); cout<<"Affine coordinates of P are X="<<X<<", Y="<<Y<<endl; P.getrealcoordinates(rx,ry); cout<<"Real affine coordinates of P are X="<<rx<<", Y="<<ry<<endl; cout<<"P.isintegral()? "<<P.isintegral()<<endl; } // end of file: tp2points.cc
JohnCremona/eclib
tests/tp2points.cc
C++
gpl-2.0
2,181
package com.gorgo.pirates; import java.lang.ref.WeakReference; import android.app.Activity; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.util.Log; import android.view.SurfaceHolder; import android.view.View; import android.view.WindowManager; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.ListView; import com.gorgo.pirates.controller.GameEngine; import com.gorgo.pirates.controller.GuybrushController; import com.gorgo.pirates.controller.Turns; import com.gorgo.pirates.controller.WorldController; import com.gorgo.pirates.model.Guybrush; import com.gorgo.pirates.model.World; import com.gorgo.pirates.view.ListViewCustomAdapter; /** * @author Gorgo * * Activity del gioco. Inizializza il Layout, la SurfaceView che contiene la Canvas, il GameLoop e il GameEngine. * */ public class Pirates extends Activity implements SurfaceHolder.Callback { private GameThread gameThread; //GameLoop Thread private MainGamePanel surface; //SurfaceView per la Canvas private SurfaceHolder holder; //Abstract interface per gestire Destroy/Creation della View private ListView mlistView; //ListView contenente dialoghi e insulti private GameEngine gameEngine; //Controller inizializzatore private mHandler handler; //Handler per gestire eventi tra thread diversi private boolean lViewVisibility; private static final String TAG = Pirates.class.getSimpleName(); //Costanti Handler private static final int LVIEW_INVISIBLE = 0, LVIEW_VISIBLE = 1, INIT_INSULTS = 2, LISTVIEW_UPDATE = 3, INIT_CONTROINSULTS = 4, INIT_GUYBRUSH = 5, INIT_GUYBRUSH_CARLA = 6, MUSIC_PAUSE = 7, MUSIC_ON = 8; //Turni da Salvare private static final int INIT_SCABB_INTRO = -8, INIT_MAP = -3, OUTRO_FUOCO = 20; //Costanti Activity private static final int NO_PIRATE_SELECTED = 0, GAME_NOT_END = 0, GAME_END = 1; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_pirates); // Fullscreen getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); // Inizializzo SurfaceView surface = (MainGamePanel) findViewById(R.id.surface); holder = surface.getHolder(); holder.addCallback(this); // Handler per gestire i messaggi tra SurfaceView, GameThread e Listview handler = new mHandler(this); // Setting ListView mlistView = (ListView) findViewById(R.id.mylist); mlistView.setVisibility(View.GONE); // GameEngine si occupa di inizializzare classi, renderer e update gameEngine = new GameEngine(this, surface, mlistView); //ListView listener //Salva la selezione dell'utente in Guybrush via Controller mlistView.setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> a, View v, int position, long id) { GuybrushController controllerG = gameEngine.getControllerG(); String selectedFromList = (String) (mlistView.getItemAtPosition(position)); //Log.d("setOnItemClickListener", "Hai Selezionato "+ selectedFromList + " in posizione nella lView " + position); controllerG.getText().setString(selectedFromList); controllerG.setSpeech(selectedFromList, position); controllerG.setInputWaiting(false); //L'utente ha scelto gameThread.notifyMessage(LVIEW_INVISIBLE); //lView off } }); } //Metodi del SurfaceHolder @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {} @Override public void surfaceCreated(SurfaceHolder holder) { //Avvio il gameLoop Thread gameThread.setRunning(true); gameThread.start(); } @Override public void surfaceDestroyed(SurfaceHolder holder) { Log.d(TAG, "Surface is being destroyed"); // Segnala al Thread che deve arrestarsi e attende // Shutdown pulito del Thread boolean retry = true; if (this.gameThread.isAlive()) { this.gameThread.setRunning(false); while (retry) { try { gameThread.join(); retry = false; } catch (InterruptedException e) { } } this.gameThread.setRunning(false); Log.d(TAG, "Thread was shut down cleanly"); } } // Metodi dell'Activity protected void onSaveInstanceState(Bundle state) { super.onSaveInstanceState(state); Log.d(TAG, "App in background. Salvataggio informazioni utili al ripristino..."); handler.sendEmptyMessage(MUSIC_PAUSE); //Pause Music state.putSerializable("turnDialog", gameEngine.getTurnsInstance().getTurnDialog()); //Salvo turnDialog di Turns state.putSerializable("level", gameEngine.getWorldInstance().getLevel()); state.putSerializable("vittorie", gameEngine.getControllerG().getVittorie()); //Check Carla state.putSerializable("justSeenCarla", gameEngine.getTurnsInstance().getSeenCarla()); state.putSerializable("carlaInit", gameEngine.getTurnsInstance().getCarlaInit()); state.putSerializable("okCarla", gameEngine.getControllerW().getOkCarla()); //Se sono già stati fatti duelli salvo gli insulti/controInsulti imparati if (gameEngine.getTurnsInstance().getTurnDialog() >= INIT_MAP) { //Per salvare lo SparseArray<String> nel Bundle salvo solo le Key in un int[] //Nella onRestore verrà ricostruito lo SparseArray<String> int insultKeyArray[] = gameEngine.getDialogsInstance().DisassembleInsultKeyArray(); int controInsultKeyArray[] = gameEngine.getDialogsInstance().DisassembleControInsultKeyArray(); state.putIntArray("guybrushInsult", insultKeyArray); state.putIntArray("guybrushControInsult", controInsultKeyArray); } } @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); Log.d(TAG, "App in foreground. Ripristino informazioni salvate.."); int mTurnDialog = (Integer) savedInstanceState.getSerializable("turnDialog"); int mLevel = (Integer) savedInstanceState.getSerializable("level"); int mVittorie = (Integer) savedInstanceState.getSerializable("vittorie"); //Check Carla int mJustSeen = (Integer) savedInstanceState.getSerializable("justSeenCarla"); int mOkCarla = (Integer) savedInstanceState.getSerializable("okCarla"); int mCarlaInit = (Integer) savedInstanceState.getSerializable("carlaInit"); int insultKeyArray[] = savedInstanceState.getIntArray("guybrushInsult"); int controInsultKeyArray[] = savedInstanceState.getIntArray("guybrushControInsult"); Turns mTurns = gameEngine.getTurnsInstance(); World mWorld = gameEngine.getWorldInstance(); Dialogs mDialogs = gameEngine.getDialogsInstance(); GuybrushController mControllerG = gameEngine.getControllerG(); WorldController mControllerW = gameEngine.getControllerW(); if (mTurnDialog < INIT_MAP){ // Intro mTurns.setTurn(INIT_SCABB_INTRO); // Restart Game if(mWorld.getPlayer() != null) mWorld.getPlayer().release(); } else if (mTurnDialog == OUTRO_FUOCO) mTurns.setTurn(OUTRO_FUOCO); // Fine gioco else { mTurns.setTurn(INIT_MAP); // Mappa mTurns.setSeenCarla(mJustSeen); mTurns.setCarlaInit(mCarlaInit); mWorld.setPirate(NO_PIRATE_SELECTED); mWorld.setLevel(mLevel); mControllerG.setVittorie(mVittorie); mControllerW.setOkCarla(mOkCarla); // Ripristino insulti mDialogs.buildInsultArray(insultKeyArray, mLevel); mDialogs.buildControInsultArray(controInsultKeyArray, mLevel); } } @Override protected void onDestroy() { super.onDestroy(); System.runFinalizersOnExit(true); } @Override protected void onResume() { super.onResume(); //Re-inizializzo il GameThread gameThread = new GameThread(holder, gameEngine, handler); gameThread.setRunning(true); //Resume Music handler.sendEmptyMessage(MUSIC_ON); //lView on se visibile prima dello standby if (lViewVisibility) handler.sendEmptyMessage(LVIEW_VISIBLE); World mWorld = gameEngine.getWorldInstance(); //Se stai ripristinando un gioco concluso, ricarica dall'inizio if(mWorld.getEnd() == GAME_END){ mWorld.setEnd(GAME_NOT_END); mWorld.getPlayer().release(); gameEngine.getTurnsInstance().setTurn(INIT_SCABB_INTRO); } } @Override protected void onPause() { super.onPause(); //Pause Music handler.sendEmptyMessage(MUSIC_PAUSE); //Controllo se la lView è visibile e salvo boolean if (gameEngine.getControllerG().getInputWaiting()) lViewVisibility = true; else lViewVisibility = false; } @Override public void onBackPressed() { moveTaskToBack(true); } // Handler per gestire visibilità della ListView static class mHandler extends Handler { private final WeakReference<Pirates> mTarget; private ListViewCustomAdapter adapter; mHandler(Pirates target) { mTarget = new WeakReference<Pirates>(target); } @Override public void handleMessage(Message msg) { Pirates target = mTarget.get(); if (msg.what == INIT_INSULTS) { //Inserisco gli insulti nella ListView Guybrush guybrush = target.gameEngine.getGuybrush(); adapter = new ListViewCustomAdapter(target, guybrush.getInsulti()); target.mlistView.setAdapter(adapter); } if (msg.what == INIT_CONTROINSULTS) { //Inserisco i ControInsulti nella ListView Guybrush guybrush = target.gameEngine.getGuybrush(); adapter = new ListViewCustomAdapter(target, guybrush.getControInsulti()); target.mlistView.setAdapter(adapter); } if (msg.what == MUSIC_PAUSE) { //Metto in pausa la Musica World world = target.gameEngine.getWorldInstance(); Log.d(TAG, "PAUSE MUSIC " + world.getPlayer()); if (world.getPlayer() != null) world.getPlayer().pause(); } if (msg.what == MUSIC_ON) { //Metto in start la Musica World world = target.gameEngine.getWorldInstance(); Log.d(TAG, "MUSIC ON " + world.getPlayer()); if (world.getPlayer() != null) world.getPlayer().start(); } if (msg.what == INIT_GUYBRUSH) { //Inizializzo discorso Guybrush/Pirati listView Dialogs dialogs = target.gameEngine.getDialogsInstance(); adapter = new ListViewCustomAdapter(target, dialogs.getGuybrushIntro()); target.mlistView.setAdapter(adapter); } if (msg.what == INIT_GUYBRUSH_CARLA) { Dialogs dialogs = target.gameEngine.getDialogsInstance(); adapter = new ListViewCustomAdapter(target, dialogs.getGuybrushStartCarla()); target.mlistView.setAdapter(adapter); } if (msg.what == LISTVIEW_UPDATE) adapter.notifyDataSetChanged(); if (msg.what == LVIEW_VISIBLE) target.mlistView.setVisibility(View.VISIBLE); if (msg.what == LVIEW_INVISIBLE) target.mlistView.setVisibility(View.GONE); } }; }
gorghino/miswordfighting
src/com/gorgo/pirates/Pirates.java
Java
gpl-2.0
11,140
package fi.helsinki.cs.codebrowser.controller; import fi.helsinki.cs.codebrowser.app.App; import fi.helsinki.cs.codebrowser.model.Course; import fi.helsinki.cs.codebrowser.service.CourseService; import java.util.ArrayList; import java.util.List; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import org.springframework.boot.test.SpringApplicationConfiguration; import org.springframework.http.MediaType; import org.springframework.test.context.ActiveProfiles; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.setup.MockMvcBuilders; import static com.jayway.jsonassert.impl.matcher.IsCollectionWithSize.hasSize; import static org.hamcrest.CoreMatchers.is; import static org.mockito.Mockito.times; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.verifyNoMoreInteractions; import static org.mockito.Mockito.when; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.content; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; @RunWith(SpringJUnit4ClassRunner.class) @SpringApplicationConfiguration(classes = App.class) @WebAppConfiguration @ActiveProfiles("test") public final class CourseControllerTest { private static final String INSTANCE = "instance"; private static final String COURSE = "courseID"; private static final String USER = "userID"; private static final String COURSE_A_NAME = "Course A"; private static final String COURSE_B_NAME = "Course B"; @Mock private CourseService courseService; @InjectMocks private CourseController courseController; private MockMvc mockMvc; @Before public void setUp() { MockitoAnnotations.initMocks(this); mockMvc = MockMvcBuilders.standaloneSetup(courseController).build(); } private List<Course> buildCourseList() { final List<Course> courses = new ArrayList<>(); final Course courseA = new Course(); courseA.setName(COURSE_A_NAME); courses.add(courseA); final Course courseB = new Course(); courseB.setName(COURSE_B_NAME); courses.add(courseB); return courses; } @Test public void listShouldReturnAllCourses() throws Exception { final List<Course> courses = buildCourseList(); when(courseService.findAll(INSTANCE)).thenReturn(courses); mockMvc.perform(get("/" + INSTANCE + "/courses")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$", hasSize(2))) .andExpect(jsonPath("$[0].name", is(COURSE_A_NAME))) .andExpect(jsonPath("$[1].name", is(COURSE_B_NAME))); verify(courseService, times(1)).findAll(INSTANCE); verifyNoMoreInteractions(courseService); } @Test public void listByStudentShouldReturnAllCourses() throws Exception { final List<Course> courses = buildCourseList(); when(courseService.findAllBy(INSTANCE, USER)).thenReturn(courses); mockMvc.perform(get("/" + INSTANCE + "/students/" + USER + "/courses")) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$", hasSize(2))) .andExpect(jsonPath("$[0].name", is(COURSE_A_NAME))) .andExpect(jsonPath("$[1].name", is(COURSE_B_NAME))); verify(courseService, times(1)).findAllBy(INSTANCE, USER); verifyNoMoreInteractions(courseService); } @Test public void readShouldReturnCourse() throws Exception { final Course course = new Course(); course.setName(COURSE_A_NAME); when(courseService.findBy(INSTANCE, COURSE)).thenReturn(course); mockMvc.perform(get("/" + INSTANCE + "/courses/" + COURSE)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.name", is(COURSE_A_NAME))); verify(courseService, times(1)).findBy(INSTANCE, COURSE); verifyNoMoreInteractions(courseService); } @Test public void readByStudentShouldReturnCourse() throws Exception { final Course course = new Course(); course.setName(COURSE_A_NAME); when(courseService.findBy(INSTANCE, USER, COURSE)).thenReturn(course); mockMvc.perform(get("/" + INSTANCE + "/students/" + USER + "/courses/" + COURSE)) .andExpect(status().isOk()) .andExpect(content().contentType(MediaType.APPLICATION_JSON)) .andExpect(jsonPath("$.name", is(COURSE_A_NAME))); verify(courseService, times(1)).findBy(INSTANCE, USER, COURSE); verifyNoMoreInteractions(courseService); } }
rage/codebrowser-back-end
src/test/java/fi/helsinki/cs/codebrowser/controller/CourseControllerTest.java
Java
gpl-2.0
5,328
import org.civet.Civet; import org.civet.Civet.Compile; public class TestLiteral { @Compile void test1() { int x = 10; int i = 1; System.out.println(x + i); } @Compile void test2() { int x = 10; int i = Civet.CT(1); System.out.println(x + i); } @Compile void test3() { int x = 10; double i = Civet.CT(1.0); System.out.println(x + i); } }
w7cook/batch-javac
test/civet/TestLiteral.java
Java
gpl-2.0
407
<?php /** * * * Created on Sep 4, 2006 * * Copyright © 2006 Yuri Astrakhan "<Firstname><Lastname>@gmail.com" * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file * @defgroup API API */ /** * This is the main API class, used for both external and internal processing. * When executed, it will create the requested formatter object, * instantiate and execute an object associated with the needed action, * and use formatter to print results. * In case of an exception, an error message will be printed using the same formatter. * * To use API from another application, run it using FauxRequest object, in which * case any internal exceptions will not be handled but passed up to the caller. * After successful execution, use getResult() for the resulting data. * * @ingroup API */ class ApiMain extends ApiBase { /** * When no format parameter is given, this format will be used */ const API_DEFAULT_FORMAT = 'jsonfm'; /** * List of available modules: action name => module class */ private static $Modules = [ 'login' => 'ApiLogin', 'logout' => 'ApiLogout', 'createaccount' => 'ApiCreateAccount', 'query' => 'ApiQuery', 'expandtemplates' => 'ApiExpandTemplates', 'parse' => 'ApiParse', 'stashedit' => 'ApiStashEdit', 'opensearch' => 'ApiOpenSearch', 'feedcontributions' => 'ApiFeedContributions', 'feedrecentchanges' => 'ApiFeedRecentChanges', 'feedwatchlist' => 'ApiFeedWatchlist', 'help' => 'ApiHelp', 'paraminfo' => 'ApiParamInfo', 'rsd' => 'ApiRsd', 'compare' => 'ApiComparePages', 'tokens' => 'ApiTokens', 'checktoken' => 'ApiCheckToken', // Write modules 'purge' => 'ApiPurge', 'setnotificationtimestamp' => 'ApiSetNotificationTimestamp', 'rollback' => 'ApiRollback', 'delete' => 'ApiDelete', 'undelete' => 'ApiUndelete', 'protect' => 'ApiProtect', 'block' => 'ApiBlock', 'unblock' => 'ApiUnblock', 'move' => 'ApiMove', 'edit' => 'ApiEditPage', 'upload' => 'ApiUpload', 'filerevert' => 'ApiFileRevert', 'emailuser' => 'ApiEmailUser', 'watch' => 'ApiWatch', 'patrol' => 'ApiPatrol', 'import' => 'ApiImport', 'clearhasmsg' => 'ApiClearHasMsg', 'userrights' => 'ApiUserrights', 'options' => 'ApiOptions', 'imagerotate' => 'ApiImageRotate', 'revisiondelete' => 'ApiRevisionDelete', 'managetags' => 'ApiManageTags', 'tag' => 'ApiTag', 'mergehistory' => 'ApiMergeHistory', ]; /** * List of available formats: format name => format class */ private static $Formats = [ 'json' => 'ApiFormatJson', 'jsonfm' => 'ApiFormatJson', 'php' => 'ApiFormatPhp', 'phpfm' => 'ApiFormatPhp', 'xml' => 'ApiFormatXml', 'xmlfm' => 'ApiFormatXml', 'rawfm' => 'ApiFormatJson', 'none' => 'ApiFormatNone', ]; // @codingStandardsIgnoreStart String contenation on "msg" not allowed to break long line /** * List of user roles that are specifically relevant to the API. * array( 'right' => array ( 'msg' => 'Some message with a $1', * 'params' => array ( $someVarToSubst ) ), * ); */ private static $mRights = array( 'writeapi' => array( 'msg' => 'right-writeapi', 'params' => array() ), 'apihighlimits' => array( 'msg' => 'api-help-right-apihighlimits', 'params' => array( ApiBase::LIMIT_SML2, ApiBase::LIMIT_BIG2 ) ) ); // @codingStandardsIgnoreEnd /** * @var ApiFormatBase */ private $mPrinter; private $mModuleMgr, $mResult, $mErrorFormatter, $mContinuationManager; private $mAction; private $mEnableWrite; private $mInternalMode, $mSquidMaxage, $mModule; private $mCacheMode = 'private'; private $mCacheControl = []; private $mParamsUsed = []; /** * Constructs an instance of ApiMain that utilizes the module and format specified by $request. * * @param IContextSource|WebRequest $context If this is an instance of * FauxRequest, errors are thrown and no printing occurs * @param bool $enableWrite Should be set to true if the api may modify data */ public function __construct( $context = null, $enableWrite = false ) { if ( $context === null ) { $context = RequestContext::getMain(); } elseif ( $context instanceof WebRequest ) { // BC for pre-1.19 $request = $context; $context = RequestContext::getMain(); } // We set a derivative context so we can change stuff later $this->setContext( new DerivativeContext( $context ) ); if ( isset( $request ) ) { $this->getContext()->setRequest( $request ); } $this->mInternalMode = ( $this->getRequest() instanceof FauxRequest ); // Special handling for the main module: $parent === $this parent::__construct( $this, $this->mInternalMode ? 'main_int' : 'main' ); if ( !$this->mInternalMode ) { // Impose module restrictions. // If the current user cannot read, // Remove all modules other than login global $wgUser; if ( $this->lacksSameOriginSecurity() ) { // If we're in a mode that breaks the same-origin policy, strip // user credentials for security. wfDebug( "API: stripping user credentials when the same-origin policy is not applied\n" ); $wgUser = new User(); $this->getContext()->setUser( $wgUser ); } } $uselang = $this->getParameter( 'uselang' ); if ( $uselang === 'user' ) { // Assume the parent context is going to return the user language // for uselang=user (see T85635). } else { if ( $uselang === 'content' ) { global $wgContLang; $uselang = $wgContLang->getCode(); } $code = RequestContext::sanitizeLangCode( $uselang ); $this->getContext()->setLanguage( $code ); if ( !$this->mInternalMode ) { global $wgLang; $wgLang = $this->getContext()->getLanguage(); RequestContext::getMain()->setLanguage( $wgLang ); } } $config = $this->getConfig(); $this->mModuleMgr = new ApiModuleManager( $this ); $this->mModuleMgr->addModules( self::$Modules, 'action' ); $this->mModuleMgr->addModules( $config->get( 'APIModules' ), 'action' ); $this->mModuleMgr->addModules( self::$Formats, 'format' ); $this->mModuleMgr->addModules( $config->get( 'APIFormatModules' ), 'format' ); Hooks::run( 'ApiMain::moduleManager', [ $this->mModuleMgr ] ); $this->mResult = new ApiResult( $this->getConfig()->get( 'APIMaxResultSize' ) ); $this->mErrorFormatter = new ApiErrorFormatter_BackCompat( $this->mResult ); $this->mResult->setErrorFormatter( $this->mErrorFormatter ); $this->mResult->setMainForContinuation( $this ); $this->mContinuationManager = null; $this->mEnableWrite = $enableWrite; $this->mSquidMaxage = -1; // flag for executeActionWithErrorHandling() $this->mCommit = false; } /** * Return true if the API was started by other PHP code using FauxRequest * @return bool */ public function isInternalMode() { return $this->mInternalMode; } /** * Get the ApiResult object associated with current request * * @return ApiResult */ public function getResult() { return $this->mResult; } /** * Get the ApiErrorFormatter object associated with current request * @return ApiErrorFormatter */ public function getErrorFormatter() { return $this->mErrorFormatter; } /** * Get the continuation manager * @return ApiContinuationManager|null */ public function getContinuationManager() { return $this->mContinuationManager; } /** * Set the continuation manager * @param ApiContinuationManager|null */ public function setContinuationManager( $manager ) { if ( $manager !== null ) { if ( !$manager instanceof ApiContinuationManager ) { throw new InvalidArgumentException( __METHOD__ . ': Was passed ' . is_object( $manager ) ? get_class( $manager ) : gettype( $manager ) ); } if ( $this->mContinuationManager !== null ) { throw new UnexpectedValueException( __METHOD__ . ': tried to set manager from ' . $manager->getSource() . ' when a manager is already set from ' . $this->mContinuationManager->getSource() ); } } $this->mContinuationManager = $manager; } /** * Get the API module object. Only works after executeAction() * * @return ApiBase */ public function getModule() { return $this->mModule; } /** * Get the result formatter object. Only works after setupExecuteAction() * * @return ApiFormatBase */ public function getPrinter() { return $this->mPrinter; } /** * Set how long the response should be cached. * * @param int $maxage */ public function setCacheMaxAge( $maxage ) { $this->setCacheControl( [ 'max-age' => $maxage, 's-maxage' => $maxage ] ); } /** * Set the type of caching headers which will be sent. * * @param string $mode One of: * - 'public': Cache this object in public caches, if the maxage or smaxage * parameter is set, or if setCacheMaxAge() was called. If a maximum age is * not provided by any of these means, the object will be private. * - 'private': Cache this object only in private client-side caches. * - 'anon-public-user-private': Make this object cacheable for logged-out * users, but private for logged-in users. IMPORTANT: If this is set, it must be * set consistently for a given URL, it cannot be set differently depending on * things like the contents of the database, or whether the user is logged in. * * If the wiki does not allow anonymous users to read it, the mode set here * will be ignored, and private caching headers will always be sent. In other words, * the "public" mode is equivalent to saying that the data sent is as public as a page * view. * * For user-dependent data, the private mode should generally be used. The * anon-public-user-private mode should only be used where there is a particularly * good performance reason for caching the anonymous response, but where the * response to logged-in users may differ, or may contain private data. * * If this function is never called, then the default will be the private mode. */ public function setCacheMode( $mode ) { if ( !in_array( $mode, [ 'private', 'public', 'anon-public-user-private' ] ) ) { wfDebug( __METHOD__ . ": unrecognised cache mode \"$mode\"\n" ); // Ignore for forwards-compatibility return; } if ( !User::isEveryoneAllowed( 'read' ) ) { // Private wiki, only private headers if ( $mode !== 'private' ) { wfDebug( __METHOD__ . ": ignoring request for $mode cache mode, private wiki\n" ); return; } } if ( $mode === 'public' && $this->getParameter( 'uselang' ) === 'user' ) { // User language is used for i18n, so we don't want to publicly // cache. Anons are ok, because if they have non-default language // then there's an appropriate Vary header set by whatever set // their non-default language. wfDebug( __METHOD__ . ": downgrading cache mode 'public' to " . "'anon-public-user-private' due to uselang=user\n" ); $mode = 'anon-public-user-private'; } wfDebug( __METHOD__ . ": setting cache mode $mode\n" ); $this->mCacheMode = $mode; } /** * Set directives (key/value pairs) for the Cache-Control header. * Boolean values will be formatted as such, by including or omitting * without an equals sign. * * Cache control values set here will only be used if the cache mode is not * private, see setCacheMode(). * * @param array $directives */ public function setCacheControl( $directives ) { $this->mCacheControl = $directives + $this->mCacheControl; } /** * Create an instance of an output formatter by its name * * @param string $format * * @return ApiFormatBase */ public function createPrinterByName( $format ) { $printer = $this->mModuleMgr->getModule( $format, 'format' ); if ( $printer === null ) { $this->dieUsage( "Unrecognized format: {$format}", 'unknown_format' ); } return $printer; } /** * Execute api request. Any errors will be handled if the API was called by the remote client. */ public function execute() { if ( $this->mInternalMode ) { $this->executeAction(); } else { $this->executeActionWithErrorHandling(); } } /** * Execute an action, and in case of an error, erase whatever partial results * have been accumulated, and replace it with an error message and a help screen. */ protected function executeActionWithErrorHandling() { // Verify the CORS header before executing the action if ( !$this->handleCORS() ) { // handleCORS() has sent a 403, abort return; } // Exit here if the request method was OPTIONS // (assume there will be a followup GET or POST) if ( $this->getRequest()->getMethod() === 'OPTIONS' ) { return; } // In case an error occurs during data output, // clear the output buffer and print just the error information $obLevel = ob_get_level(); ob_start(); $t = microtime( true ); try { $this->executeAction(); $isError = false; } catch ( Exception $e ) { $this->handleException( $e ); $isError = true; } // Log the request whether or not there was an error $this->logRequest( microtime( true ) - $t ); // Commit DBs and send any related cookies and headers MediaWiki::preOutputCommit( $this->getContext() ); // Send cache headers after any code which might generate an error, to // avoid sending public cache headers for errors. $this->sendCacheHeaders( $isError ); // Executing the action might have already messed with the output // buffers. while ( ob_get_level() > $obLevel ) { ob_end_flush(); } } /** * Handle an exception as an API response * * @since 1.23 * @param Exception $e */ protected function handleException( Exception $e ) { // Bug 63145: Rollback any open database transactions if ( !( $e instanceof UsageException ) ) { // UsageExceptions are intentional, so don't rollback if that's the case try { MWExceptionHandler::rollbackMasterChangesAndLog( $e ); } catch ( DBError $e2 ) { // Rollback threw an exception too. Log it, but don't interrupt // our regularly scheduled exception handling. MWExceptionHandler::logException( $e2 ); } } // Allow extra cleanup and logging Hooks::run( 'ApiMain::onException', [ $this, $e ] ); // Log it if ( !( $e instanceof UsageException ) ) { MWExceptionHandler::logException( $e ); } // Handle any kind of exception by outputting properly formatted error message. // If this fails, an unhandled exception should be thrown so that global error // handler will process and log it. $errCode = $this->substituteResultWithError( $e ); // Error results should not be cached $this->setCacheMode( 'private' ); $response = $this->getRequest()->response(); $headerStr = 'MediaWiki-API-Error: ' . $errCode; if ( $e->getCode() === 0 ) { $response->header( $headerStr ); } else { $response->header( $headerStr, true, $e->getCode() ); } // Reset and print just the error message ob_clean(); // Printer may not be initialized if the extractRequestParams() fails for the main module $this->createErrorPrinter(); try { $this->printResult( true ); } catch ( UsageException $ex ) { // The error printer itself is failing. Try suppressing its request // parameters and redo. $this->setWarning( 'Error printer failed (will retry without params): ' . $ex->getMessage() ); $this->mPrinter = null; $this->createErrorPrinter(); $this->mPrinter->forceDefaultParams(); $this->printResult( true ); } } /** * Handle an exception from the ApiBeforeMain hook. * * This tries to print the exception as an API response, to be more * friendly to clients. If it fails, it will rethrow the exception. * * @since 1.23 * @param Exception $e * @throws Exception */ public static function handleApiBeforeMainException( Exception $e ) { ob_start(); try { $main = new self( RequestContext::getMain(), false ); $main->handleException( $e ); } catch ( Exception $e2 ) { // Nope, even that didn't work. Punt. throw $e; } // Log the request and reset cache headers $main->logRequest( 0 ); $main->sendCacheHeaders( true ); ob_end_flush(); } /** * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately. * * If no origin parameter is present, nothing happens. * If an origin parameter is present but doesn't match the Origin header, a 403 status code * is set and false is returned. * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS * headers are set. * http://www.w3.org/TR/cors/#resource-requests * http://www.w3.org/TR/cors/#resource-preflight-requests * * @return bool False if the caller should abort (403 case), true otherwise (all other cases) */ protected function handleCORS() { $originParam = $this->getParameter( 'origin' ); // defaults to null if ( $originParam === null ) { // No origin parameter, nothing to do return true; } $request = $this->getRequest(); $response = $request->response(); // Origin: header is a space-separated list of origins, check all of them $originHeader = $request->getHeader( 'Origin' ); if ( $originHeader === false ) { $origins = []; } else { $originHeader = trim( $originHeader ); $origins = preg_split( '/\s+/', $originHeader ); } if ( !in_array( $originParam, $origins ) ) { // origin parameter set but incorrect // Send a 403 response $response->statusHeader( 403 ); $response->header( 'Cache-Control: no-cache' ); echo "'origin' parameter does not match Origin header\n"; return false; } $config = $this->getConfig(); $matchOrigin = count( $origins ) === 1 && self::matchOrigin( $originParam, $config->get( 'CrossSiteAJAXdomains' ), $config->get( 'CrossSiteAJAXdomainExceptions' ) ); if ( $matchOrigin ) { $requestedMethod = $request->getHeader( 'Access-Control-Request-Method' ); $preflight = $request->getMethod() === 'OPTIONS' && $requestedMethod !== false; if ( $preflight ) { // This is a CORS preflight request if ( $requestedMethod !== 'POST' && $requestedMethod !== 'GET' ) { // If method is not a case-sensitive match, do not set any additional headers and terminate. return true; } // We allow the actual request to send the following headers $requestedHeaders = $request->getHeader( 'Access-Control-Request-Headers' ); if ( $requestedHeaders !== false ) { if ( !self::matchRequestedHeaders( $requestedHeaders ) ) { return true; } $response->header( 'Access-Control-Allow-Headers: ' . $requestedHeaders ); } // We only allow the actual request to be GET or POST $response->header( 'Access-Control-Allow-Methods: POST, GET' ); } $response->header( "Access-Control-Allow-Origin: $originHeader" ); $response->header( 'Access-Control-Allow-Credentials: true' ); // http://www.w3.org/TR/resource-timing/#timing-allow-origin $response->header( "Timing-Allow-Origin: $originHeader" ); if ( !$preflight ) { $response->header( 'Access-Control-Expose-Headers: MediaWiki-API-Error, Retry-After, X-Database-Lag' ); } } $this->getOutput()->addVaryHeader( 'Origin' ); return true; } /** * Attempt to match an Origin header against a set of rules and a set of exceptions * @param string $value Origin header * @param array $rules Set of wildcard rules * @param array $exceptions Set of wildcard rules * @return bool True if $value matches a rule in $rules and doesn't match * any rules in $exceptions, false otherwise */ protected static function matchOrigin( $value, $rules, $exceptions ) { foreach ( $rules as $rule ) { if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) { // Rule matches, check exceptions foreach ( $exceptions as $exc ) { if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) { return false; } } return true; } } return false; } /** * Attempt to validate the value of Access-Control-Request-Headers against a list * of headers that we allow the follow up request to send. * * @param string $requestedHeaders Comma seperated list of HTTP headers * @return bool True if all requested headers are in the list of allowed headers */ protected static function matchRequestedHeaders( $requestedHeaders ) { if ( trim( $requestedHeaders ) === '' ) { return true; } $requestedHeaders = explode( ',', $requestedHeaders ); $allowedAuthorHeaders = array_flip( [ /* simple headers (see spec) */ 'accept', 'accept-language', 'content-language', 'content-type', /* non-authorable headers in XHR, which are however requested by some UAs */ 'accept-encoding', 'dnt', 'origin', /* MediaWiki whitelist */ 'api-user-agent', ] ); foreach ( $requestedHeaders as $rHeader ) { $rHeader = strtolower( trim( $rHeader ) ); if ( !isset( $allowedAuthorHeaders[$rHeader] ) ) { wfDebugLog( 'api', 'CORS preflight failed on requested header: ' . $rHeader ); return false; } } return true; } /** * Helper function to convert wildcard string into a regex * '*' => '.*?' * '?' => '.' * * @param string $wildcard String with wildcards * @return string Regular expression */ protected static function wildcardToRegex( $wildcard ) { $wildcard = preg_quote( $wildcard, '/' ); $wildcard = str_replace( [ '\*', '\?' ], [ '.*?', '.' ], $wildcard ); return "/^https?:\/\/$wildcard$/"; } /** * Send caching headers * @param boolean $isError Whether an error response is being output * @since 1.26 added $isError parameter */ protected function sendCacheHeaders( $isError ) { $response = $this->getRequest()->response(); $out = $this->getOutput(); $config = $this->getConfig(); if ( $config->get( 'VaryOnXFP' ) ) { $out->addVaryHeader( 'X-Forwarded-Proto' ); } if ( !$isError && $this->mModule && ( $this->getRequest()->getMethod() === 'GET' || $this->getRequest()->getMethod() === 'HEAD' ) ) { $etag = $this->mModule->getConditionalRequestData( 'etag' ); if ( $etag !== null ) { $response->header( "ETag: $etag" ); } $lastMod = $this->mModule->getConditionalRequestData( 'last-modified' ); if ( $lastMod !== null ) { $response->header( 'Last-Modified: ' . wfTimestamp( TS_RFC2822, $lastMod ) ); } } // The logic should be: // $this->mCacheControl['max-age'] is set? // Use it, the module knows better than our guess. // !$this->mModule || $this->mModule->isWriteMode(), and mCacheMode is private? // Use 0 because we can guess caching is probably the wrong thing to do. // Use $this->getParameter( 'maxage' ), which already defaults to 0. $maxage = 0; if ( isset( $this->mCacheControl['max-age'] ) ) { $maxage = $this->mCacheControl['max-age']; } elseif ( ( $this->mModule && !$this->mModule->isWriteMode() ) || $this->mCacheMode !== 'private' ) { $maxage = $this->getParameter( 'maxage' ); } $privateCache = 'private, must-revalidate, max-age=' . $maxage; if ( $this->mCacheMode == 'private' ) { $response->header( "Cache-Control: $privateCache" ); return; } $useKeyHeader = $config->get( 'UseKeyHeader' ); if ( $this->mCacheMode == 'anon-public-user-private' ) { $out->addVaryHeader( 'Cookie' ); $response->header( $out->getVaryHeader() ); if ( $useKeyHeader ) { $response->header( $out->getKeyHeader() ); if ( $out->haveCacheVaryCookies() ) { // Logged in, mark this request private $response->header( "Cache-Control: $privateCache" ); return; } // Logged out, send normal public headers below } elseif ( MediaWiki\Session\SessionManager::getGlobalSession()->isPersistent() ) { // Logged in or otherwise has session (e.g. anonymous users who have edited) // Mark request private $response->header( "Cache-Control: $privateCache" ); return; } // else no Key and anonymous, send public headers below } // Send public headers $response->header( $out->getVaryHeader() ); if ( $useKeyHeader ) { $response->header( $out->getKeyHeader() ); } // If nobody called setCacheMaxAge(), use the (s)maxage parameters if ( !isset( $this->mCacheControl['s-maxage'] ) ) { $this->mCacheControl['s-maxage'] = $this->getParameter( 'smaxage' ); } if ( !isset( $this->mCacheControl['max-age'] ) ) { $this->mCacheControl['max-age'] = $this->getParameter( 'maxage' ); } if ( !$this->mCacheControl['s-maxage'] && !$this->mCacheControl['max-age'] ) { // Public cache not requested // Sending a Vary header in this case is harmless, and protects us // against conditional calls of setCacheMaxAge(). $response->header( "Cache-Control: $privateCache" ); return; } $this->mCacheControl['public'] = true; // Send an Expires header $maxAge = min( $this->mCacheControl['s-maxage'], $this->mCacheControl['max-age'] ); $expiryUnixTime = ( $maxAge == 0 ? 1 : time() + $maxAge ); $response->header( 'Expires: ' . wfTimestamp( TS_RFC2822, $expiryUnixTime ) ); // Construct the Cache-Control header $ccHeader = ''; $separator = ''; foreach ( $this->mCacheControl as $name => $value ) { if ( is_bool( $value ) ) { if ( $value ) { $ccHeader .= $separator . $name; $separator = ', '; } } else { $ccHeader .= $separator . "$name=$value"; $separator = ', '; } } $response->header( "Cache-Control: $ccHeader" ); } /** * Create the printer for error output */ private function createErrorPrinter() { if ( !isset( $this->mPrinter ) ) { $value = $this->getRequest()->getVal( 'format', self::API_DEFAULT_FORMAT ); if ( !$this->mModuleMgr->isDefined( $value, 'format' ) ) { $value = self::API_DEFAULT_FORMAT; } $this->mPrinter = $this->createPrinterByName( $value ); } // Printer may not be able to handle errors. This is particularly // likely if the module returns something for getCustomPrinter(). if ( !$this->mPrinter->canPrintErrors() ) { $this->mPrinter = $this->createPrinterByName( self::API_DEFAULT_FORMAT ); } } /** * Replace the result data with the information about an exception. * Returns the error code * @param Exception $e * @return string */ protected function substituteResultWithError( $e ) { $result = $this->getResult(); $config = $this->getConfig(); if ( $e instanceof UsageException ) { // User entered incorrect parameters - generate error response $errMessage = $e->getMessageArray(); $link = wfExpandUrl( wfScript( 'api' ) ); ApiResult::setContentValue( $errMessage, 'docref', "See $link for API usage" ); } else { // Something is seriously wrong if ( ( $e instanceof DBQueryError ) && !$config->get( 'ShowSQLErrors' ) ) { $info = 'Database query error'; } else { $info = "Exception Caught: {$e->getMessage()}"; } $errMessage = [ 'code' => 'internal_api_error_' . get_class( $e ), 'info' => '[' . MWExceptionHandler::getLogId( $e ) . '] ' . $info, ]; if ( $config->get( 'ShowExceptionDetails' ) ) { ApiResult::setContentValue( $errMessage, 'trace', MWExceptionHandler::getRedactedTraceAsString( $e ) ); } } // Remember all the warnings to re-add them later $warnings = $result->getResultData( [ 'warnings' ] ); $result->reset(); // Re-add the id $requestid = $this->getParameter( 'requestid' ); if ( !is_null( $requestid ) ) { $result->addValue( null, 'requestid', $requestid, ApiResult::NO_SIZE_CHECK ); } if ( $config->get( 'ShowHostnames' ) ) { // servedby is especially useful when debugging errors $result->addValue( null, 'servedby', wfHostname(), ApiResult::NO_SIZE_CHECK ); } if ( $warnings !== null ) { $result->addValue( null, 'warnings', $warnings, ApiResult::NO_SIZE_CHECK ); } $result->addValue( null, 'error', $errMessage, ApiResult::NO_SIZE_CHECK ); return $errMessage['code']; } /** * Set up for the execution. * @return array */ protected function setupExecuteAction() { // First add the id to the top element $result = $this->getResult(); $requestid = $this->getParameter( 'requestid' ); if ( !is_null( $requestid ) ) { $result->addValue( null, 'requestid', $requestid ); } if ( $this->getConfig()->get( 'ShowHostnames' ) ) { $servedby = $this->getParameter( 'servedby' ); if ( $servedby ) { $result->addValue( null, 'servedby', wfHostname() ); } } if ( $this->getParameter( 'curtimestamp' ) ) { $result->addValue( null, 'curtimestamp', wfTimestamp( TS_ISO_8601, time() ), ApiResult::NO_SIZE_CHECK ); } $params = $this->extractRequestParams(); $this->mAction = $params['action']; if ( !is_string( $this->mAction ) ) { $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' ); } return $params; } /** * Set up the module for response * @return ApiBase The module that will handle this action * @throws MWException * @throws UsageException */ protected function setupModule() { // Instantiate the module requested by the user $module = $this->mModuleMgr->getModule( $this->mAction, 'action' ); if ( $module === null ) { $this->dieUsage( 'The API requires a valid action parameter', 'unknown_action' ); } $moduleParams = $module->extractRequestParams(); // Check token, if necessary if ( $module->needsToken() === true ) { throw new MWException( "Module '{$module->getModuleName()}' must be updated for the new token handling. " . "See documentation for ApiBase::needsToken for details." ); } if ( $module->needsToken() ) { if ( !$module->mustBePosted() ) { throw new MWException( "Module '{$module->getModuleName()}' must require POST to use tokens." ); } if ( !isset( $moduleParams['token'] ) ) { $this->dieUsageMsg( [ 'missingparam', 'token' ] ); } if ( !$this->getConfig()->get( 'DebugAPI' ) && array_key_exists( $module->encodeParamName( 'token' ), $this->getRequest()->getQueryValues() ) ) { $this->dieUsage( "The '{$module->encodeParamName( 'token' )}' parameter was " . 'found in the query string, but must be in the POST body', 'mustposttoken' ); } if ( !$module->validateToken( $moduleParams['token'], $moduleParams ) ) { $this->dieUsageMsg( 'sessionfailure' ); } } return $module; } /** * Check the max lag if necessary * @param ApiBase $module Api module being used * @param array $params Array an array containing the request parameters. * @return bool True on success, false should exit immediately */ protected function checkMaxLag( $module, $params ) { if ( $module->shouldCheckMaxlag() && isset( $params['maxlag'] ) ) { $maxLag = $params['maxlag']; list( $host, $lag ) = wfGetLB()->getMaxLag(); if ( $lag > $maxLag ) { $response = $this->getRequest()->response(); $response->header( 'Retry-After: ' . max( intval( $maxLag ), 5 ) ); $response->header( 'X-Database-Lag: ' . intval( $lag ) ); if ( $this->getConfig()->get( 'ShowHostnames' ) ) { $this->dieUsage( "Waiting for $host: $lag seconds lagged", 'maxlag' ); } $this->dieUsage( "Waiting for a database server: $lag seconds lagged", 'maxlag' ); } } return true; } /** * Check selected RFC 7232 precondition headers * * RFC 7232 envisions a particular model where you send your request to "a * resource", and for write requests that you can read "the resource" by * changing the method to GET. When the API receives a GET request, it * works out even though "the resource" from RFC 7232's perspective might * be many resources from MediaWiki's perspective. But it totally fails for * a POST, since what HTTP sees as "the resource" is probably just * "/api.php" with all the interesting bits in the body. * * Therefore, we only support RFC 7232 precondition headers for GET (and * HEAD). That means we don't need to bother with If-Match and * If-Unmodified-Since since they only apply to modification requests. * * And since we don't support Range, If-Range is ignored too. * * @since 1.26 * @param ApiBase $module Api module being used * @return bool True on success, false should exit immediately */ protected function checkConditionalRequestHeaders( $module ) { if ( $this->mInternalMode ) { // No headers to check in internal mode return true; } if ( $this->getRequest()->getMethod() !== 'GET' && $this->getRequest()->getMethod() !== 'HEAD' ) { // Don't check POSTs return true; } $return304 = false; $ifNoneMatch = array_diff( $this->getRequest()->getHeader( 'If-None-Match', WebRequest::GETHEADER_LIST ) ?: [], [ '' ] ); if ( $ifNoneMatch ) { if ( $ifNoneMatch === [ '*' ] ) { // API responses always "exist" $etag = '*'; } else { $etag = $module->getConditionalRequestData( 'etag' ); } } if ( $ifNoneMatch && $etag !== null ) { $test = substr( $etag, 0, 2 ) === 'W/' ? substr( $etag, 2 ) : $etag; $match = array_map( function ( $s ) { return substr( $s, 0, 2 ) === 'W/' ? substr( $s, 2 ) : $s; }, $ifNoneMatch ); $return304 = in_array( $test, $match, true ); } else { $value = trim( $this->getRequest()->getHeader( 'If-Modified-Since' ) ); // Some old browsers sends sizes after the date, like this: // Wed, 20 Aug 2003 06:51:19 GMT; length=5202 // Ignore that. $i = strpos( $value, ';' ); if ( $i !== false ) { $value = trim( substr( $value, 0, $i ) ); } if ( $value !== '' ) { try { $ts = new MWTimestamp( $value ); if ( // RFC 7231 IMF-fixdate $ts->getTimestamp( TS_RFC2822 ) === $value || // RFC 850 $ts->format( 'l, d-M-y H:i:s' ) . ' GMT' === $value || // asctime (with and without space-padded day) $ts->format( 'D M j H:i:s Y' ) === $value || $ts->format( 'D M j H:i:s Y' ) === $value ) { $lastMod = $module->getConditionalRequestData( 'last-modified' ); if ( $lastMod !== null ) { // Mix in some MediaWiki modification times $modifiedTimes = [ 'page' => $lastMod, 'user' => $this->getUser()->getTouched(), 'epoch' => $this->getConfig()->get( 'CacheEpoch' ), ]; if ( $this->getConfig()->get( 'UseSquid' ) ) { // T46570: the core page itself may not change, but resources might $modifiedTimes['sepoch'] = wfTimestamp( TS_MW, time() - $this->getConfig()->get( 'SquidMaxage' ) ); } Hooks::run( 'OutputPageCheckLastModified', [ &$modifiedTimes ] ); $lastMod = max( $modifiedTimes ); $return304 = wfTimestamp( TS_MW, $lastMod ) <= $ts->getTimestamp( TS_MW ); } } } catch ( TimestampException $e ) { // Invalid timestamp, ignore it } } } if ( $return304 ) { $this->getRequest()->response()->statusHeader( 304 ); // Avoid outputting the compressed representation of a zero-length body MediaWiki\suppressWarnings(); ini_set( 'zlib.output_compression', 0 ); MediaWiki\restoreWarnings(); wfClearOutputBuffers(); return false; } return true; } /** * Check for sufficient permissions to execute * @param ApiBase $module An Api module */ protected function checkExecutePermissions( $module ) { $user = $this->getUser(); if ( $module->isReadMode() && !User::isEveryoneAllowed( 'read' ) && !$user->isAllowed( 'read' ) ) { $this->dieUsageMsg( 'readrequired' ); } if ( $module->isWriteMode() ) { if ( !$this->mEnableWrite ) { $this->dieUsageMsg( 'writedisabled' ); } elseif ( !$user->isAllowed( 'writeapi' ) ) { $this->dieUsageMsg( 'writerequired' ); } elseif ( $this->getRequest()->getHeader( 'Promise-Non-Write-API-Action' ) ) { $this->dieUsage( "Promise-Non-Write-API-Action HTTP header cannot be sent to write API modules", 'promised-nonwrite-api' ); } $this->checkReadOnly( $module ); } // Allow extensions to stop execution for arbitrary reasons. $message = false; if ( !Hooks::run( 'ApiCheckCanExecute', [ $module, $user, &$message ] ) ) { $this->dieUsageMsg( $message ); } } /** * Check if the DB is read-only for this user * @param ApiBase $module An Api module */ protected function checkReadOnly( $module ) { if ( wfReadOnly() ) { $this->dieReadOnly(); } if ( $module->isWriteMode() && in_array( 'bot', $this->getUser()->getGroups() ) && wfGetLB()->getServerCount() > 1 ) { $this->checkBotReadOnly(); } } /** * Check whether we are readonly for bots */ private function checkBotReadOnly() { // Figure out how many servers have passed the lag threshold $numLagged = 0; $lagLimit = $this->getConfig()->get( 'APIMaxLagThreshold' ); $laggedServers = []; $loadBalancer = wfGetLB(); foreach ( $loadBalancer->getLagTimes() as $serverIndex => $lag ) { if ( $lag > $lagLimit ) { ++$numLagged; $laggedServers[] = $loadBalancer->getServerName( $serverIndex ) . " ({$lag}s)"; } } // If a majority of slaves are too lagged then disallow writes $slaveCount = wfGetLB()->getServerCount() - 1; if ( $numLagged >= ceil( $slaveCount / 2 ) ) { $laggedServers = join( ', ', $laggedServers ); wfDebugLog( 'api-readonly', "Api request failed as read only because the following DBs are lagged: $laggedServers" ); $parsed = $this->parseMsg( [ 'readonlytext' ] ); $this->dieUsage( $parsed['info'], $parsed['code'], /* http error */ 0, [ 'readonlyreason' => "Waiting for $numLagged lagged database(s)" ] ); } } /** * Check asserts of the user's rights * @param array $params */ protected function checkAsserts( $params ) { if ( isset( $params['assert'] ) ) { $user = $this->getUser(); switch ( $params['assert'] ) { case 'user': if ( $user->isAnon() ) { $this->dieUsage( 'Assertion that the user is logged in failed', 'assertuserfailed' ); } break; case 'bot': if ( !$user->isAllowed( 'bot' ) ) { $this->dieUsage( 'Assertion that the user has the bot right failed', 'assertbotfailed' ); } break; } } } /** * Check POST for external response and setup result printer * @param ApiBase $module An Api module * @param array $params An array with the request parameters */ protected function setupExternalResponse( $module, $params ) { $request = $this->getRequest(); if ( !$request->wasPosted() && $module->mustBePosted() ) { // Module requires POST. GET request might still be allowed // if $wgDebugApi is true, otherwise fail. $this->dieUsageMsgOrDebug( [ 'mustbeposted', $this->mAction ] ); } // See if custom printer is used $this->mPrinter = $module->getCustomPrinter(); if ( is_null( $this->mPrinter ) ) { // Create an appropriate printer $this->mPrinter = $this->createPrinterByName( $params['format'] ); } if ( $request->getProtocol() === 'http' && ( $request->getSession()->shouldForceHTTPS() || ( $this->getUser()->isLoggedIn() && $this->getUser()->requiresHTTPS() ) ) ) { $this->logFeatureUsage( 'https-expected' ); $this->setWarning( 'HTTP used when HTTPS was expected' ); } } /** * Execute the actual module, without any error handling */ protected function executeAction() { $params = $this->setupExecuteAction(); $module = $this->setupModule(); $this->mModule = $module; if ( !$this->mInternalMode ) { $this->setRequestExpectations( $module ); } $this->checkExecutePermissions( $module ); if ( !$this->checkMaxLag( $module, $params ) ) { return; } if ( !$this->checkConditionalRequestHeaders( $module ) ) { return; } if ( !$this->mInternalMode ) { $this->setupExternalResponse( $module, $params ); } $this->checkAsserts( $params ); // Execute $module->execute(); Hooks::run( 'APIAfterExecute', [ &$module ] ); $this->reportUnusedParams(); if ( !$this->mInternalMode ) { // append Debug information MWDebug::appendDebugInfoToApiResult( $this->getContext(), $this->getResult() ); // Print result data $this->printResult( false ); } } /** * Set database connection, query, and write expectations given this module request * @param ApiBase $module */ protected function setRequestExpectations( ApiBase $module ) { $limits = $this->getConfig()->get( 'TrxProfilerLimits' ); $trxProfiler = Profiler::instance()->getTransactionProfiler(); if ( $this->getRequest()->wasPosted() ) { if ( $module->isWriteMode() ) { $trxProfiler->setExpectations( $limits['POST'], __METHOD__ ); } else { $trxProfiler->setExpectations( $limits['POST-nonwrite'], __METHOD__ ); } } else { $trxProfiler->setExpectations( $limits['GET'], __METHOD__ ); } } /** * Log the preceding request * @param float $time Time in seconds */ protected function logRequest( $time ) { $request = $this->getRequest(); $logCtx = [ 'dt' => date( 'c' ), 'client_ip' => $request->getIP(), 'user_agent' => $this->getUserAgent(), 'wiki' => wfWikiID(), 'time_backend_ms' => round( $time * 1000 ), 'params' => [], ]; // Construct space separated message for 'api' log channel $msg = "API {$request->getMethod()} " . wfUrlencode( str_replace( ' ', '_', $this->getUser()->getName() ) ) . " {$logCtx['client_ip']} " . "T={$logCtx['time_backend_ms']}ms"; foreach ( $this->getParamsUsed() as $name ) { $value = $request->getVal( $name ); if ( $value === null ) { continue; } if ( strlen( $value ) > 256 ) { $value = substr( $value, 0, 256 ); $encValue = $this->encodeRequestLogValue( $value ) . '[...]'; } else { $encValue = $this->encodeRequestLogValue( $value ); } $logCtx['params'][$name] = $value; $msg .= " {$name}={$encValue}"; } wfDebugLog( 'api', $msg, 'private' ); // ApiRequest channel is for structured data consumers wfDebugLog( 'ApiRequest', '', 'private', $logCtx ); } /** * Encode a value in a format suitable for a space-separated log line. * @param string $s * @return string */ protected function encodeRequestLogValue( $s ) { static $table; if ( !$table ) { $chars = ';@$!*(),/:'; $numChars = strlen( $chars ); for ( $i = 0; $i < $numChars; $i++ ) { $table[rawurlencode( $chars[$i] )] = $chars[$i]; } } return strtr( rawurlencode( $s ), $table ); } /** * Get the request parameters used in the course of the preceding execute() request * @return array */ protected function getParamsUsed() { return array_keys( $this->mParamsUsed ); } /** * Get a request value, and register the fact that it was used, for logging. * @param string $name * @param mixed $default * @return mixed */ public function getVal( $name, $default = null ) { $this->mParamsUsed[$name] = true; $ret = $this->getRequest()->getVal( $name ); if ( $ret === null ) { if ( $this->getRequest()->getArray( $name ) !== null ) { // See bug 10262 for why we don't just join( '|', ... ) the // array. $this->setWarning( "Parameter '$name' uses unsupported PHP array syntax" ); } $ret = $default; } return $ret; } /** * Get a boolean request value, and register the fact that the parameter * was used, for logging. * @param string $name * @return bool */ public function getCheck( $name ) { return $this->getVal( $name, null ) !== null; } /** * Get a request upload, and register the fact that it was used, for logging. * * @since 1.21 * @param string $name Parameter name * @return WebRequestUpload */ public function getUpload( $name ) { $this->mParamsUsed[$name] = true; return $this->getRequest()->getUpload( $name ); } /** * Report unused parameters, so the client gets a hint in case it gave us parameters we don't know, * for example in case of spelling mistakes or a missing 'g' prefix for generators. */ protected function reportUnusedParams() { $paramsUsed = $this->getParamsUsed(); $allParams = $this->getRequest()->getValueNames(); if ( !$this->mInternalMode ) { // Printer has not yet executed; don't warn that its parameters are unused $printerParams = array_map( [ $this->mPrinter, 'encodeParamName' ], array_keys( $this->mPrinter->getFinalParams() ?: [] ) ); $unusedParams = array_diff( $allParams, $paramsUsed, $printerParams ); } else { $unusedParams = array_diff( $allParams, $paramsUsed ); } if ( count( $unusedParams ) ) { $s = count( $unusedParams ) > 1 ? 's' : ''; $this->setWarning( "Unrecognized parameter$s: '" . implode( $unusedParams, "', '" ) . "'" ); } } /** * Print results using the current printer * * @param bool $isError */ protected function printResult( $isError ) { if ( $this->getConfig()->get( 'DebugAPI' ) !== false ) { $this->setWarning( 'SECURITY WARNING: $wgDebugAPI is enabled' ); } $printer = $this->mPrinter; $printer->initPrinter( false ); $printer->execute(); $printer->closePrinter(); } /** * @return bool */ public function isReadMode() { return false; } /** * See ApiBase for description. * * @return array */ public function getAllowedParams() { return [ 'action' => [ ApiBase::PARAM_DFLT => 'help', ApiBase::PARAM_TYPE => 'submodule', ], 'format' => [ ApiBase::PARAM_DFLT => ApiMain::API_DEFAULT_FORMAT, ApiBase::PARAM_TYPE => 'submodule', ], 'maxlag' => [ ApiBase::PARAM_TYPE => 'integer' ], 'smaxage' => [ ApiBase::PARAM_TYPE => 'integer', ApiBase::PARAM_DFLT => 0 ], 'maxage' => [ ApiBase::PARAM_TYPE => 'integer', ApiBase::PARAM_DFLT => 0 ], 'assert' => [ ApiBase::PARAM_TYPE => [ 'user', 'bot' ] ], 'requestid' => null, 'servedby' => false, 'curtimestamp' => false, 'origin' => null, 'uselang' => [ ApiBase::PARAM_DFLT => 'user', ], ]; } /** @see ApiBase::getExamplesMessages() */ protected function getExamplesMessages() { return [ 'action=help' => 'apihelp-help-example-main', 'action=help&recursivesubmodules=1' => 'apihelp-help-example-recursive', ]; } public function modifyHelp( array &$help, array $options, array &$tocData ) { // Wish PHP had an "array_insert_before". Instead, we have to manually // reindex the array to get 'permissions' in the right place. $oldHelp = $help; $help = []; foreach ( $oldHelp as $k => $v ) { if ( $k === 'submodules' ) { $help['permissions'] = ''; } $help[$k] = $v; } $help['datatypes'] = ''; $help['credits'] = ''; // Fill 'permissions' $help['permissions'] .= Html::openElement( 'div', [ 'class' => 'apihelp-block apihelp-permissions' ] ); $m = $this->msg( 'api-help-permissions' ); if ( !$m->isDisabled() ) { $help['permissions'] .= Html::rawElement( 'div', [ 'class' => 'apihelp-block-head' ], $m->numParams( count( self::$mRights ) )->parse() ); } $help['permissions'] .= Html::openElement( 'dl' ); foreach ( self::$mRights as $right => $rightMsg ) { $help['permissions'] .= Html::element( 'dt', null, $right ); $rightMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] )->parse(); $help['permissions'] .= Html::rawElement( 'dd', null, $rightMsg ); $groups = array_map( function ( $group ) { return $group == '*' ? 'all' : $group; }, User::getGroupsWithPermission( $right ) ); $help['permissions'] .= Html::rawElement( 'dd', null, $this->msg( 'api-help-permissions-granted-to' ) ->numParams( count( $groups ) ) ->params( $this->getLanguage()->commaList( $groups ) ) ->parse() ); } $help['permissions'] .= Html::closeElement( 'dl' ); $help['permissions'] .= Html::closeElement( 'div' ); // Fill 'datatypes' and 'credits', if applicable if ( empty( $options['nolead'] ) ) { $level = $options['headerlevel']; $tocnumber = &$options['tocnumber']; $header = $this->msg( 'api-help-datatypes-header' )->parse(); $help['datatypes'] .= Html::rawElement( 'h' . min( 6, $level ), [ 'id' => 'main/datatypes', 'class' => 'apihelp-header' ], Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/datatypes' ) ] ) . $header ); $help['datatypes'] .= $this->msg( 'api-help-datatypes' )->parseAsBlock(); if ( !isset( $tocData['main/datatypes'] ) ) { $tocnumber[$level]++; $tocData['main/datatypes'] = [ 'toclevel' => count( $tocnumber ), 'level' => $level, 'anchor' => 'main/datatypes', 'line' => $header, 'number' => join( '.', $tocnumber ), 'index' => false, ]; } $header = $this->msg( 'api-credits-header' )->parse(); $help['credits'] .= Html::rawElement( 'h' . min( 6, $level ), [ 'id' => 'main/credits', 'class' => 'apihelp-header' ], Html::element( 'span', [ 'id' => Sanitizer::escapeId( 'main/credits' ) ] ) . $header ); $help['credits'] .= $this->msg( 'api-credits' )->useDatabase( false )->parseAsBlock(); if ( !isset( $tocData['main/credits'] ) ) { $tocnumber[$level]++; $tocData['main/credits'] = [ 'toclevel' => count( $tocnumber ), 'level' => $level, 'anchor' => 'main/credits', 'line' => $header, 'number' => join( '.', $tocnumber ), 'index' => false, ]; } } } private $mCanApiHighLimits = null; /** * Check whether the current user is allowed to use high limits * @return bool */ public function canApiHighLimits() { if ( !isset( $this->mCanApiHighLimits ) ) { $this->mCanApiHighLimits = $this->getUser()->isAllowed( 'apihighlimits' ); } return $this->mCanApiHighLimits; } /** * Overrides to return this instance's module manager. * @return ApiModuleManager */ public function getModuleManager() { return $this->mModuleMgr; } /** * Fetches the user agent used for this request * * The value will be the combination of the 'Api-User-Agent' header (if * any) and the standard User-Agent header (if any). * * @return string */ public function getUserAgent() { return trim( $this->getRequest()->getHeader( 'Api-user-agent' ) . ' ' . $this->getRequest()->getHeader( 'User-agent' ) ); } /************************************************************************//** * @name Deprecated * @{ */ /** * Sets whether the pretty-printer should format *bold* and $italics$ * * @deprecated since 1.25 * @param bool $help */ public function setHelp( $help = true ) { wfDeprecated( __METHOD__, '1.25' ); $this->mPrinter->setHelp( $help ); } /** * Override the parent to generate help messages for all available modules. * * @deprecated since 1.25 * @return string */ public function makeHelpMsg() { wfDeprecated( __METHOD__, '1.25' ); $this->setHelp(); $cacheHelpTimeout = $this->getConfig()->get( 'APICacheHelpTimeout' ); return ObjectCache::getMainWANInstance()->getWithSetCallback( wfMemcKey( 'apihelp', $this->getModuleName(), str_replace( ' ', '_', SpecialVersion::getVersion( 'nodb' ) ) ), $cacheHelpTimeout > 0 ? $cacheHelpTimeout : WANObjectCache::TTL_UNCACHEABLE, [ $this, 'reallyMakeHelpMsg' ] ); } /** * @deprecated since 1.25 * @return mixed|string */ public function reallyMakeHelpMsg() { wfDeprecated( __METHOD__, '1.25' ); $this->setHelp(); // Use parent to make default message for the main module $msg = parent::makeHelpMsg(); $astriks = str_repeat( '*** ', 14 ); $msg .= "\n\n$astriks Modules $astriks\n\n"; foreach ( $this->mModuleMgr->getNames( 'action' ) as $name ) { $module = $this->mModuleMgr->getModule( $name ); $msg .= self::makeHelpMsgHeader( $module, 'action' ); $msg2 = $module->makeHelpMsg(); if ( $msg2 !== false ) { $msg .= $msg2; } $msg .= "\n"; } $msg .= "\n$astriks Permissions $astriks\n\n"; foreach ( self::$mRights as $right => $rightMsg ) { $rightsMsg = $this->msg( $rightMsg['msg'], $rightMsg['params'] ) ->useDatabase( false ) ->inLanguage( 'en' ) ->text(); $groups = User::getGroupsWithPermission( $right ); $msg .= "* " . $right . " *\n $rightsMsg" . "\nGranted to:\n " . str_replace( '*', 'all', implode( ', ', $groups ) ) . "\n\n"; } $msg .= "\n$astriks Formats $astriks\n\n"; foreach ( $this->mModuleMgr->getNames( 'format' ) as $name ) { $module = $this->mModuleMgr->getModule( $name ); $msg .= self::makeHelpMsgHeader( $module, 'format' ); $msg2 = $module->makeHelpMsg(); if ( $msg2 !== false ) { $msg .= $msg2; } $msg .= "\n"; } $credits = $this->msg( 'api-credits' )->useDatabase( 'false' )->inLanguage( 'en' )->text(); $credits = str_replace( "\n", "\n ", $credits ); $msg .= "\n*** Credits: ***\n $credits\n"; return $msg; } /** * @deprecated since 1.25 * @param ApiBase $module * @param string $paramName What type of request is this? e.g. action, * query, list, prop, meta, format * @return string */ public static function makeHelpMsgHeader( $module, $paramName ) { wfDeprecated( __METHOD__, '1.25' ); $modulePrefix = $module->getModulePrefix(); if ( strval( $modulePrefix ) !== '' ) { $modulePrefix = "($modulePrefix) "; } return "* $paramName={$module->getModuleName()} $modulePrefix*"; } /** * Check whether the user wants us to show version information in the API help * @return bool * @deprecated since 1.21, always returns false */ public function getShowVersions() { wfDeprecated( __METHOD__, '1.21' ); return false; } /** * Add or overwrite a module in this ApiMain instance. Intended for use by extending * classes who wish to add their own modules to their lexicon or override the * behavior of inherent ones. * * @deprecated since 1.21, Use getModuleManager()->addModule() instead. * @param string $name The identifier for this module. * @param ApiBase $class The class where this module is implemented. */ protected function addModule( $name, $class ) { $this->getModuleManager()->addModule( $name, 'action', $class ); } /** * Add or overwrite an output format for this ApiMain. Intended for use by extending * classes who wish to add to or modify current formatters. * * @deprecated since 1.21, Use getModuleManager()->addModule() instead. * @param string $name The identifier for this format. * @param ApiFormatBase $class The class implementing this format. */ protected function addFormat( $name, $class ) { $this->getModuleManager()->addModule( $name, 'format', $class ); } /** * Returns the list of supported formats in form ( 'format' => 'ClassName' ) * * @since 1.18 * @deprecated since 1.21, Use getModuleManager()'s methods instead. * @return array */ public function getFormats() { return $this->getModuleManager()->getNamesWithClasses( 'format' ); } /**@}*/ } /** * This exception will be thrown when dieUsage is called to stop module execution. * * @ingroup API */ class UsageException extends MWException { private $mCodestr; /** * @var null|array */ private $mExtraData; /** * @param string $message * @param string $codestr * @param int $code * @param array|null $extradata */ public function __construct( $message, $codestr, $code = 0, $extradata = null ) { parent::__construct( $message, $code ); $this->mCodestr = $codestr; $this->mExtraData = $extradata; } /** * @return string */ public function getCodeString() { return $this->mCodestr; } /** * @return array */ public function getMessageArray() { $result = [ 'code' => $this->mCodestr, 'info' => $this->getMessage() ]; if ( is_array( $this->mExtraData ) ) { $result = array_merge( $result, $this->mExtraData ); } return $result; } /** * @return string */ public function __toString() { return "{$this->getCodeString()}: {$this->getMessage()}"; } } /** * For really cool vim folding this needs to be at the end: * vim: foldmarker=@{,@} foldmethod=marker */
Sensatus/mediawiki-core
includes/api/ApiMain.php
PHP
gpl-2.0
56,908
#include <cstdio> #include <algorithm> using namespace std; #define K(x) key[x] #define S(x) size[x] #define C(x, d) ch[x][d] #define F(x) fa[x] #define L(x) ch[x][0] #define R(x) ch[x][1] #define keytree L(R(root)) #define LL long long const int maxn = 222222; int size[maxn], key[maxn], fa[maxn], ch[maxn][2], add[maxn], val[maxn]; LL sum[maxn]; int tot, root; int arr[maxn]; void newnode(int& x, int k, int f) { x = ++tot; F(x) = f; S(x) = 1; //K(x) = k; val[x] = sum[x] = k; } void pushup(int x) { S(x) = S(R(x)) + S(L(x)) + 1; sum[x] = sum[R(x)] + sum[L(x)] + val[x] + add[x]; } void pushdown(int x) { if(add[x]) { val[x] += add[x]; add[R(x)] += add[x]; add[L(x)] += add[x]; sum[R(x)] += (LL)add[x] * (LL)S(R(x)); sum[L(x)] += (LL)add[x] * (LL)S(L(x)); add[x] = 0; } } void rot(int x, int c) { int y = F(x); pushdown(y); pushdown(x); C(y, !c) = C(x, c); F(C(x, c)) = y; C(x, c) = y; F(x) = F(y); F(y) = x; if(F(x)) C(F(x), R(F(x)) == y) = x; pushup(y); } void splay(int x, int y) { if(!x) return; pushdown(x); while(F(x) != y) { if(F(F(x)) == y) rot(x, L(F(x)) == x); else { int d1 = L(F(F(x))) == F(x); int d2 = L(F(x)) == x; if(d1 == d2) { rot(F(x), d1); rot(x, d2); } else { rot(x, d2); rot(x, d1); } } } pushup(x); if(!y) root = x; } void insert(int k) { int x = root; while(C(x, k > K(x))) x = C(x, k > K(x)); newnode(C(x, k > K(x)), k, x); splay(C(x, k > K(x)), 0); } int sel(int k, int x) { if(!x || k > S(x) || k < 0) return 0; pushdown(x); int s = S(L(x)) + 1; if(s == k) return x; if(k < s) return sel(k, L(x)); return sel(k-s, R(x)); } void build(int l, int r, int& rt, int f) { if(l > r) return; int mid = (l+r) >> 1; newnode(rt, arr[mid], f); build(l, mid-1, L(rt), rt); build(mid+1, r, R(rt), rt); pushup(rt); } inline void RotateTo(int k,int goal) {//把第k位的数转到goal下边 int x = root; pushdown(x); while(S(L(x)) != k) { if(k < S(L(x))) { x = L(x); } else { k -= (S(L(x)) + 1); x = R(x); } pushdown(x); } splay(x, goal); } LL query(int l, int r) { RotateTo(l-1, 0); RotateTo(r+1, root); return sum[keytree]; } void updata(int l, int r, int _add) { RotateTo(l-1, 0); RotateTo(r+1, root); sum[keytree] += (LL)_add * (LL)S(keytree); add[keytree] += (LL)_add; } inline void init(int n) {/*这是题目特定函数*/ ch[0][0] = ch[0][1] = fa[0] = size[0] = 0; add[0] = sum[0] = 0; root = 0; //为了方便处理边界,加两个边界顶点 newnode(root, -1, 0); newnode(R(root) , -1, root); size[root] = 2; for (int i = 0 ; i < n ; i ++) scanf("%d",&arr[i]); build(0 , n-1, keytree, R(root)); pushup(ch[root][1]); pushup(root); } int n, q, t, a, b, c; int main() { scanf("%d", &n); init(n); //for(int i = 1; i <= n; ++i) scanf("%d", &arr[i]); //newnode(root, -1, 0); //newnode(R(root), -1, root); //S(root) = 2; //build(1, n, keytree, R(root)); //build(1, n, root, 0); scanf("%d", &q); while(q--) { scanf("%d", &t); if(t == 1) { scanf("%d%d%d", &a, &b, &c); updata(a, b, c); } else { scanf("%d%d", &a, &b); printf("%lld\n", query(a, b)); } } return 0; }
iwtwiioi/OnlineJudge
wikioi/Run_574615_Score_100_Date_2014-05-03.cpp
C++
gpl-2.0
3,324
class Solution: # @param haystack, a string # @param needle, a string # @return an integer def strStr(self, haystack, needle): lenH = len(haystack) lenN = len(needle) if lenN == 0: return 0 for i in range(lenH-lenN+1): p = i q = 0 while q < lenN and haystack[p] == needle[q]: p += 1 q += 1 if q == lenN: return i return -1 if __name__ == '__main__': sol = Solution() haystack = 'a' needle = 'a' print sol.strStr(haystack, needle)
Dectinc/leetcode
python/28 - Implement strStr().py
Python
gpl-2.0
612
/* * Copyright 2006-2012 The MZmine 2 Development Team * * This file is part of MZmine 2. * * MZmine 2 is free software; you can redistribute it and/or modify it under the * terms of the GNU General Public License as published by the Free Software * Foundation; either version 2 of the License, or (at your option) any later * version. * * MZmine 2 is distributed in the hope that it will be useful, but WITHOUT ANY * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR * A PARTICULAR PURPOSE. See the GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along with * MZmine 2; if not, write to the Free Software Foundation, Inc., 51 Franklin St, * Fifth Floor, Boston, MA 02110-1301 USA */ package net.sf.mzmine.modules.peaklistmethods.identification.custom; import net.sf.mzmine.parameters.Parameter; import net.sf.mzmine.parameters.impl.SimpleParameterSet; import net.sf.mzmine.parameters.parametertypes.BooleanParameter; import net.sf.mzmine.parameters.parametertypes.FileNameParameter; import net.sf.mzmine.parameters.parametertypes.MZToleranceParameter; import net.sf.mzmine.parameters.parametertypes.OrderParameter; import net.sf.mzmine.parameters.parametertypes.PeakListsParameter; import net.sf.mzmine.parameters.parametertypes.RTToleranceParameter; import net.sf.mzmine.parameters.parametertypes.StringParameter; /** * */ public class CustomDBSearchParameters extends SimpleParameterSet { public static final PeakListsParameter peakLists = new PeakListsParameter(); public static final FileNameParameter dataBaseFile = new FileNameParameter( "Database file", "Name of file that contains information for peak identification"); public static final StringParameter fieldSeparator = new StringParameter( "Field separator", "Character(s) used to separate fields in the database file", ","); public static final OrderParameter<FieldItem> fieldOrder = new OrderParameter<FieldItem>( "Field order", "Order of items in which they are read from database file", FieldItem.values()); public static final BooleanParameter ignoreFirstLine = new BooleanParameter( "Ignore first line", "Ignore the first line of database file"); public static final MZToleranceParameter mzTolerance = new MZToleranceParameter(); public static final RTToleranceParameter rtTolerance = new RTToleranceParameter(); public CustomDBSearchParameters() { super(new Parameter[]{peakLists, dataBaseFile, fieldSeparator, fieldOrder, ignoreFirstLine, mzTolerance, rtTolerance}); } }
berlinguyinca/mzmine-fork
src/main/java/net/sf/mzmine/modules/peaklistmethods/identification/custom/CustomDBSearchParameters.java
Java
gpl-2.0
2,612
/* * FSMorphSolidLine.cpp * Transform SWF * * Created by smackay on Sun Mar 30 2003. * Copyright (c) 2001-2003 Flagstone Software Ltd. All rights reserved. * * This file is part of the Transform SWF library. You may not use this file except in * compliance with the terms of the license (the 'License') that accompanied this file. * * The Original Code and all software distributed under the License are distributed on an * 'AS IS' basis, WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESS OR IMPLIED, AND Flagstone * HEREBY DISCLAIMS ALL SUCH WARRANTIES, INCLUDING WITHOUT LIMITATION, ANY WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, AND NONINFRINGEMENT OF THIRD PARTY * RIGHTS. Please see the License for the specific language governing rights and limitations * under the License. */ #include "FSMorphSolidLine.h" #include "FSInputStream.h" #include "FSOutputStream.h" using namespace transform; namespace transform { FSMorphSolidLine::FSMorphSolidLine(FSInputStream* aStream) : startWidth(0), endWidth(0), startColor(), endColor() { decodeFromStream(aStream); } const char* FSMorphSolidLine::className() const { static char* _name = "FSMorphSolidLine"; return _name; } int FSMorphSolidLine::lengthInStream(FSOutputStream* aStream) { int tagLength = 4; tagLength += startColor.lengthInStream(aStream); tagLength += endColor.lengthInStream(aStream); return tagLength; } void FSMorphSolidLine::encodeToStream(FSOutputStream* aStream) { #ifdef _DEBUG aStream->startEncoding(className()); #endif /* * The parent object decides whether to perform validation. */ aStream->write(startWidth, FSStream::UnsignedWord, 16); aStream->write(endWidth, FSStream::UnsignedWord, 16); startColor.encodeToStream(aStream); endColor.encodeToStream(aStream); #ifdef _DEBUG aStream->endEncoding(className()); #endif } void FSMorphSolidLine::decodeFromStream(FSInputStream* aStream) { #ifdef _DEBUG aStream->startDecoding(className()); #endif startWidth = aStream->read(FSStream::UnsignedWord, 16); endWidth = aStream->read(FSStream::UnsignedWord, 16); startColor.decodeFromStream(aStream); endColor.decodeFromStream(aStream); #ifdef _DEBUG aStream->endDecoding(className()); #endif } }
ozkanpakdil/f4l
src/flagStonePort/transform-cxx-bsd/transform/FSMorphSolidLine.cpp
C++
gpl-2.0
2,493
# # $Id: index_rebuild.rb 539 2010-09-05 15:53:58Z nicb $ # module SearchEngine module Test module Utilities module IndexRebuild def rebuild_search_index(filter = []) return SearchEngine::IndexBuilder::Builder.build(filter) end def rebuild_search_index_if_needed(filter = []) sz = SearchEngine::SearchIndex.all.size rebuild_search_index(filter) unless sz > 0 end def rebuild_search_index_without_mocks_if_needed sz = SearchEngine::SearchIndex.all.size msic = SearchEngine::SearchIndexClass.all.map { |sic| sic.class_name }.grep(/Mock/) other = SearchEngine::SearchIndexClass.all.delete(msic) rebuild_search_index unless (sz > 0 && msic.size == 0) end end end end end
nicb/fishrdb
vendor/plugins/search_engine/test/utilities/index_rebuild.rb
Ruby
gpl-2.0
810
/* $Id: UIGlobalSettingsInput.cpp 56153 2015-05-29 14:00:35Z vboxsync $ */ /** @file * VBox Qt GUI - UIGlobalSettingsInput class implementation. */ /* * Copyright (C) 2006-2013 Oracle Corporation * * This file is part of VirtualBox Open Source Edition (OSE), as * available from http://www.virtualbox.org. This file is free software; * you can redistribute it and/or modify it under the terms of the GNU * General Public License (GPL) as published by the Free Software * Foundation, in version 2 as it comes in the "COPYING" file of the * VirtualBox OSE distribution. VirtualBox OSE is distributed in the * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind. */ #ifdef VBOX_WITH_PRECOMPILED_HEADERS # include <precomp.h> #else /* !VBOX_WITH_PRECOMPILED_HEADERS */ /* Qt includes: */ # include <QHeaderView> # include <QAbstractItemDelegate> # include <QItemEditorFactory> # include <QTabWidget> /* GUI includes: */ # include "QIWidgetValidator.h" # include "QIStyledItemDelegate.h" # include "UIGlobalSettingsInput.h" # include "UIShortcutPool.h" # include "UIHotKeyEditor.h" # include "UIHostComboEditor.h" # include "VBoxGlobalSettings.h" #endif /* !VBOX_WITH_PRECOMPILED_HEADERS */ #include <QShortcut> /* Namespaces: */ using namespace UIExtraDataDefs; /* Input page constructor: */ UIGlobalSettingsInput::UIGlobalSettingsInput() : m_pTabWidget(0) , m_pSelectorFilterEditor(0), m_pSelectorModel(0), m_pSelectorTable(0) , m_pMachineFilterEditor(0), m_pMachineModel(0), m_pMachineTable(0) { /* Apply UI decorations: */ Ui::UIGlobalSettingsInput::setupUi(this); /* Create tab widget: */ m_pTabWidget = new QTabWidget(this); m_pTabWidget->setMinimumWidth(400); m_pMainLayout->addWidget(m_pTabWidget, 0, 0, 1, 2); /* Create selector tab: */ QWidget *pSelectorTab = new QWidget; m_pTabWidget->insertTab(UIHotKeyTableIndex_Selector, pSelectorTab, QString()); m_pSelectorFilterEditor = new QLineEdit(pSelectorTab); m_pSelectorModel = new UIHotKeyTableModel(this, UIActionPoolType_Selector); m_pSelectorTable = new UIHotKeyTable(pSelectorTab, m_pSelectorModel, "m_pSelectorTable"); connect(m_pSelectorFilterEditor, SIGNAL(textChanged(const QString &)), m_pSelectorModel, SLOT(sltHandleFilterTextChange(const QString &))); QVBoxLayout *pSelectorLayout = new QVBoxLayout(pSelectorTab); #ifndef Q_WS_WIN /* On Windows host that looks ugly, but * On Mac OS X and X11 that deserves it's place. */ pSelectorLayout->setContentsMargins(0, 0, 0, 0); #endif /* !Q_WS_WIN */ pSelectorLayout->setSpacing(1); pSelectorLayout->addWidget(m_pSelectorFilterEditor); pSelectorLayout->addWidget(m_pSelectorTable); setTabOrder(m_pTabWidget, m_pSelectorFilterEditor); setTabOrder(m_pSelectorFilterEditor, m_pSelectorTable); /* Create machine tab: */ QWidget *pMachineTab = new QWidget; m_pTabWidget->insertTab(UIHotKeyTableIndex_Machine, pMachineTab, QString()); m_pMachineFilterEditor = new QLineEdit(pMachineTab); m_pMachineModel = new UIHotKeyTableModel(this, UIActionPoolType_Runtime); m_pMachineTable = new UIHotKeyTable(pMachineTab, m_pMachineModel, "m_pMachineTable"); connect(m_pMachineFilterEditor, SIGNAL(textChanged(const QString &)), m_pMachineModel, SLOT(sltHandleFilterTextChange(const QString &))); QVBoxLayout *pMachineLayout = new QVBoxLayout(pMachineTab); #ifndef Q_WS_WIN /* On Windows host that looks ugly, but * On Mac OS X and X11 that deserves it's place. */ pMachineLayout->setContentsMargins(0, 0, 0, 0); #endif /* !Q_WS_WIN */ pMachineLayout->setSpacing(1); pMachineLayout->addWidget(m_pMachineFilterEditor); pMachineLayout->addWidget(m_pMachineTable); setTabOrder(m_pSelectorTable, m_pMachineFilterEditor); setTabOrder(m_pMachineFilterEditor, m_pMachineTable); /* Prepare validation: */ prepareValidation(); /* Apply language settings: */ retranslateUi(); } /* Load data to cache from corresponding external object(s), * this task COULD be performed in other than GUI thread: */ void UIGlobalSettingsInput::loadToCacheFrom(QVariant &data) { /* Fetch data to properties & settings: */ UISettingsPageGlobal::fetchData(data); /* Load host-combo shortcut to cache: */ m_cache.m_shortcuts << UIShortcutCacheItem(UIHostCombo::hostComboCacheKey(), tr("Host Key Combination"), m_settings.hostCombo(), QString()); /* Load all other shortcuts to cache: */ const QMap<QString, UIShortcut>& shortcuts = gShortcutPool->shortcuts(); const QList<QString> shortcutKeys = shortcuts.keys(); foreach (const QString &strShortcutKey, shortcutKeys) { const UIShortcut &shortcut = shortcuts[strShortcutKey]; m_cache.m_shortcuts << UIShortcutCacheItem(strShortcutKey, VBoxGlobal::removeAccelMark(shortcut.description()), shortcut.sequence().toString(QKeySequence::NativeText), shortcut.defaultSequence().toString(QKeySequence::NativeText)); } /* Load other things to cache: */ m_cache.m_fAutoCapture = m_settings.autoCapture(); /* Upload properties & settings to data: */ UISettingsPageGlobal::uploadData(data); } /* Load data to corresponding widgets from cache, * this task SHOULD be performed in GUI thread only: */ void UIGlobalSettingsInput::getFromCache() { /* Fetch from cache: */ m_pSelectorModel->load(m_cache.m_shortcuts); m_pMachineModel->load(m_cache.m_shortcuts); m_pEnableAutoGrabCheckbox->setChecked(m_cache.m_fAutoCapture); /* Revalidate: */ revalidate(); } /* Save data from corresponding widgets to cache, * this task SHOULD be performed in GUI thread only: */ void UIGlobalSettingsInput::putToCache() { /* Upload to cache: */ m_pSelectorModel->save(m_cache.m_shortcuts); m_pMachineModel->save(m_cache.m_shortcuts); m_cache.m_fAutoCapture = m_pEnableAutoGrabCheckbox->isChecked(); } /* Save data from cache to corresponding external object(s), * this task COULD be performed in other than GUI thread: */ void UIGlobalSettingsInput::saveFromCacheTo(QVariant &data) { /* Fetch data to properties & settings: */ UISettingsPageGlobal::fetchData(data); /* Save host-combo shortcut from cache: */ UIShortcutCacheItem fakeHostComboItem(UIHostCombo::hostComboCacheKey(), QString(), QString(), QString()); int iIndexOfHostComboItem = m_cache.m_shortcuts.indexOf(fakeHostComboItem); if (iIndexOfHostComboItem != -1) m_settings.setHostCombo(m_cache.m_shortcuts[iIndexOfHostComboItem].currentSequence); /* Iterate over cached shortcuts: */ QMap<QString, QString> sequences; foreach (const UIShortcutCacheItem &item, m_cache.m_shortcuts) sequences.insert(item.key, item.currentSequence); /* Save shortcut sequences from cache: */ gShortcutPool->setOverrides(sequences); /* Save other things from cache: */ m_settings.setAutoCapture(m_cache.m_fAutoCapture); /* Upload properties & settings to data: */ UISettingsPageGlobal::uploadData(data); } bool UIGlobalSettingsInput::validate(QList<UIValidationMessage> &messages) { /* Pass by default: */ bool fPass = true; /* Check VirtualBox Manager page for unique shortcuts: */ if (!m_pSelectorModel->isAllShortcutsUnique()) { UIValidationMessage message; message.first = VBoxGlobal::removeAccelMark(m_pTabWidget->tabText(UIHotKeyTableIndex_Selector)); message.second << tr("Some items have the same shortcuts assigned."); messages << message; fPass = false; } /* Check Virtual Machine page for unique shortcuts: */ if (!m_pMachineModel->isAllShortcutsUnique()) { UIValidationMessage message; message.first = VBoxGlobal::removeAccelMark(m_pTabWidget->tabText(UIHotKeyTableIndex_Machine)); message.second << tr("Some items have the same shortcuts assigned."); messages << message; fPass = false; } /* Return result: */ return fPass; } /* Navigation stuff: */ void UIGlobalSettingsInput::setOrderAfter(QWidget *pWidget) { setTabOrder(pWidget, m_pTabWidget); setTabOrder(m_pMachineTable, m_pEnableAutoGrabCheckbox); } /* Translation stuff: */ void UIGlobalSettingsInput::retranslateUi() { /* Translate uic generated strings: */ Ui::UIGlobalSettingsInput::retranslateUi(this); /* Translate tab-widget labels: */ m_pTabWidget->setTabText(UIHotKeyTableIndex_Selector, tr("&VirtualBox Manager")); m_pTabWidget->setTabText(UIHotKeyTableIndex_Machine, tr("Virtual &Machine")); m_pSelectorTable->setWhatsThis(tr("Lists all available shortcuts which can be configured.")); m_pMachineTable->setWhatsThis(tr("Lists all available shortcuts which can be configured.")); m_pSelectorFilterEditor->setWhatsThis(tr("Holds a sequence to filter the shortcut list.")); m_pMachineFilterEditor->setWhatsThis(tr("Holds a sequence to filter the shortcut list.")); } void UIGlobalSettingsInput::prepareValidation() { /* Prepare validation: */ connect(m_pSelectorModel, SIGNAL(sigRevalidationRequired()), this, SLOT(revalidate())); connect(m_pMachineModel, SIGNAL(sigRevalidationRequired()), this, SLOT(revalidate())); } UIHotKeyTableModel::UIHotKeyTableModel(QObject *pParent, UIActionPoolType type) : QAbstractTableModel(pParent) , m_type(type) { } void UIHotKeyTableModel::load(const UIShortcutCache &shortcuts) { /* Load shortcuts: */ foreach (const UIShortcutCacheItem &item, shortcuts) { /* Filter out unnecessary shortcuts: */ if ((m_type == UIActionPoolType_Selector && item.key.startsWith(GUI_Input_MachineShortcuts)) || (m_type == UIActionPoolType_Runtime && item.key.startsWith(GUI_Input_SelectorShortcuts))) continue; /* Load shortcut cache item into model: */ m_shortcuts << item; } /* Apply filter: */ applyFilter(); /* Notify table: */ emit sigShortcutsLoaded(); } void UIHotKeyTableModel::save(UIShortcutCache &shortcuts) { /* Save model items: */ foreach (const UIShortcutCacheItem &item, m_shortcuts) { /* Search for corresponding cache item index: */ int iIndexOfCacheItem = shortcuts.indexOf(item); /* Make sure index is valid: */ if (iIndexOfCacheItem == -1) continue; /* Save model item into the cache: */ shortcuts[iIndexOfCacheItem] = item; } } bool UIHotKeyTableModel::isAllShortcutsUnique() { /* Enumerate all the sequences: */ QMap<QString, QString> usedSequences; foreach (const UIShortcutCacheItem &item, m_shortcuts) if (!item.currentSequence.isEmpty()) usedSequences.insertMulti(item.currentSequence, item.key); /* Enumerate all the duplicated sequences: */ QSet<QString> duplicatedSequences; foreach (const QString &strKey, usedSequences.keys()) if (usedSequences.count(strKey) > 1) duplicatedSequences.unite(usedSequences.values(strKey).toSet()); /* Is there something changed? */ if (m_duplicatedSequences != duplicatedSequences) { m_duplicatedSequences = duplicatedSequences; emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1)); } /* Are there duplicated shortcuts? */ if (!m_duplicatedSequences.isEmpty()) return false; /* True by default: */ return true; } void UIHotKeyTableModel::sltHandleFilterTextChange(const QString &strText) { m_strFilter = strText; applyFilter(); } int UIHotKeyTableModel::rowCount(const QModelIndex& /*parent = QModelIndex()*/) const { return m_filteredShortcuts.size(); } int UIHotKeyTableModel::columnCount(const QModelIndex& /*parent = QModelIndex()*/) const { return 2; } Qt::ItemFlags UIHotKeyTableModel::flags(const QModelIndex &index) const { /* No flags for invalid index: */ if (!index.isValid()) return Qt::NoItemFlags; /* Switch for different columns: */ switch (index.column()) { case UIHotKeyTableSection_Name: return Qt::ItemIsEnabled | Qt::ItemIsSelectable; case UIHotKeyTableSection_Value: return Qt::ItemIsEnabled | Qt::ItemIsSelectable | Qt::ItemIsEditable; default: break; } /* No flags by default: */ return Qt::NoItemFlags; } QVariant UIHotKeyTableModel::headerData(int iSection, Qt::Orientation orientation, int iRole /* = Qt::DisplayRole*/) const { /* Switch for different roles: */ switch (iRole) { case Qt::DisplayRole: { /* Invalid for vertical header: */ if (orientation == Qt::Vertical) return QString(); /* Switch for different columns: */ switch (iSection) { case UIHotKeyTableSection_Name: return tr("Name"); case UIHotKeyTableSection_Value: return tr("Shortcut"); default: break; } /* Invalid for other cases: */ return QString(); } default: break; } /* Invalid by default: */ return QVariant(); } QVariant UIHotKeyTableModel::data(const QModelIndex &index, int iRole /* = Qt::DisplayRole*/) const { /* No data for invalid index: */ if (!index.isValid()) return QVariant(); int iIndex = index.row(); /* Switch for different roles: */ switch (iRole) { case Qt::DisplayRole: { /* Switch for different columns: */ switch (index.column()) { case UIHotKeyTableSection_Name: { /* Return shortcut description: */ return m_filteredShortcuts[iIndex].description; } case UIHotKeyTableSection_Value: { /* If that is host-combo cell: */ if (m_filteredShortcuts[iIndex].key == UIHostCombo::hostComboCacheKey()) /* We should return host-combo: */ return UIHostCombo::toReadableString(m_filteredShortcuts[iIndex].currentSequence); /* In other cases we should return hot-combo: */ QString strHotCombo = m_filteredShortcuts[iIndex].currentSequence; /* But if that is machine table and hot-combo is not empty: */ if (m_type == UIActionPoolType_Runtime && !strHotCombo.isEmpty()) /* We should prepend it with Host+ prefix: */ strHotCombo.prepend(UIHostCombo::hostComboModifierName()); /* Return what we've got: */ return strHotCombo; } default: break; } /* Invalid for other cases: */ return QString(); } case Qt::EditRole: { /* Switch for different columns: */ switch (index.column()) { case UIHotKeyTableSection_Value: return m_filteredShortcuts[iIndex].key == UIHostCombo::hostComboCacheKey() ? QVariant::fromValue(UIHostComboWrapper(m_filteredShortcuts[iIndex].currentSequence)) : QVariant::fromValue(UIHotKey(m_type == UIActionPoolType_Runtime ? UIHotKeyType_Simple : UIHotKeyType_WithModifiers, m_filteredShortcuts[iIndex].currentSequence, m_filteredShortcuts[iIndex].defaultSequence)); default: break; } /* Invalid for other cases: */ return QString(); } case Qt::FontRole: { /* Do we have a default font? */ QFont font(QApplication::font()); /* Switch for different columns: */ switch (index.column()) { case UIHotKeyTableSection_Value: { if (m_filteredShortcuts[iIndex].key != UIHostCombo::hostComboCacheKey() && m_filteredShortcuts[iIndex].currentSequence != m_filteredShortcuts[iIndex].defaultSequence) font.setBold(true); break; } default: break; } /* Return resulting font: */ return font; } case Qt::ForegroundRole: { /* Switch for different columns: */ switch (index.column()) { case UIHotKeyTableSection_Value: { if (m_duplicatedSequences.contains(m_filteredShortcuts[iIndex].key)) return QBrush(Qt::red); break; } default: break; } /* Default for other cases: */ return QString(); } default: break; } /* Invalid by default: */ return QVariant(); } bool UIHotKeyTableModel::setData(const QModelIndex &index, const QVariant &value, int iRole /* = Qt::EditRole*/) { /* Nothing to set for invalid index: */ if (!index.isValid()) return false; /* Switch for different roles: */ switch (iRole) { case Qt::EditRole: { /* Switch for different columns: */ switch (index.column()) { case UIHotKeyTableSection_Value: { /* Get index: */ int iIndex = index.row(); /* Set sequence to shortcut: */ UIShortcutCacheItem &filteredShortcut = m_filteredShortcuts[iIndex]; int iShortcutIndex = m_shortcuts.indexOf(filteredShortcut); if (iShortcutIndex != -1) { filteredShortcut.currentSequence = filteredShortcut.key == UIHostCombo::hostComboCacheKey() ? value.value<UIHostComboWrapper>().toString() : value.value<UIHotKey>().sequence(); m_shortcuts[iShortcutIndex] = filteredShortcut; emit sigRevalidationRequired(); return true; } break; } default: break; } break; } default: break; } /* Nothing to set by default: */ return false; } void UIHotKeyTableModel::sort(int iColumn, Qt::SortOrder order /* = Qt::AscendingOrder*/) { /* Sort whole the list: */ qStableSort(m_shortcuts.begin(), m_shortcuts.end(), UIShortcutCacheItemFunctor(iColumn, order)); /* Make sure host-combo item is always the first one: */ UIShortcutCacheItem fakeHostComboItem(UIHostCombo::hostComboCacheKey(), QString(), QString(), QString()); int iIndexOfHostComboItem = m_shortcuts.indexOf(fakeHostComboItem); if (iIndexOfHostComboItem != -1) { UIShortcutCacheItem hostComboItem = m_shortcuts.takeAt(iIndexOfHostComboItem); m_shortcuts.prepend(hostComboItem); } /* Apply the filter: */ applyFilter(); /* Notify the model: */ emit dataChanged(index(0, 0), index(rowCount() - 1, columnCount() - 1)); } void UIHotKeyTableModel::applyFilter() { /* Erase items first if necessary: */ if (!m_filteredShortcuts.isEmpty()) { beginRemoveRows(QModelIndex(), 0, m_filteredShortcuts.size() - 1); m_filteredShortcuts.clear(); endRemoveRows(); } /* If filter is empty: */ if (m_strFilter.isEmpty()) { /* Just add all the items: */ m_filteredShortcuts = m_shortcuts; } else { /* Check if the description matches the filter: */ foreach (const UIShortcutCacheItem &item, m_shortcuts) { /* If neither description nor sequence matches the filter, skip item: */ if (!item.description.contains(m_strFilter, Qt::CaseInsensitive) && !item.currentSequence.contains(m_strFilter, Qt::CaseInsensitive)) continue; /* Add that item: */ m_filteredShortcuts << item; } } /* Add items finally if necessary: */ if (!m_filteredShortcuts.isEmpty()) { beginInsertRows(QModelIndex(), 0, m_filteredShortcuts.size() - 1); endInsertRows(); } } UIHotKeyTable::UIHotKeyTable(QWidget *pParent, UIHotKeyTableModel *pModel, const QString &strObjectName) : QTableView(pParent) { /* Set object name: */ setObjectName(strObjectName); /* Connect model: */ setModel(pModel); connect(pModel, SIGNAL(sigShortcutsLoaded()), this, SLOT(sltHandleShortcutsLoaded())); /* Configure self: */ setTabKeyNavigation(false); setContextMenuPolicy(Qt::CustomContextMenu); setSelectionBehavior(QAbstractItemView::SelectRows); setSelectionMode(QAbstractItemView::SingleSelection); setEditTriggers(QAbstractItemView::CurrentChanged | QAbstractItemView::SelectedClicked); /* Configure headers: */ verticalHeader()->hide(); verticalHeader()->setDefaultSectionSize((int)(verticalHeader()->minimumSectionSize() * 1.33)); horizontalHeader()->setStretchLastSection(false); horizontalHeader()->setResizeMode(UIHotKeyTableSection_Name, QHeaderView::Interactive); horizontalHeader()->setResizeMode(UIHotKeyTableSection_Value, QHeaderView::Stretch); /* Reinstall delegate: */ delete itemDelegate(); QIStyledItemDelegate *pStyledItemDelegate = new QIStyledItemDelegate(this); setItemDelegate(pStyledItemDelegate); /* Create new item editor factory: */ QItemEditorFactory *pNewItemEditorFactory = new QItemEditorFactory; /* Register UIHotKeyEditor as the UIHotKey editor: */ int iHotKeyTypeId = qRegisterMetaType<UIHotKey>(); QStandardItemEditorCreator<UIHotKeyEditor> *pHotKeyItemEditorCreator = new QStandardItemEditorCreator<UIHotKeyEditor>(); pNewItemEditorFactory->registerEditor((QVariant::Type)iHotKeyTypeId, pHotKeyItemEditorCreator); /* Register UIHostComboEditor as the UIHostComboWrapper: */ int iHostComboTypeId = qRegisterMetaType<UIHostComboWrapper>(); QStandardItemEditorCreator<UIHostComboEditor> *pHostComboItemEditorCreator = new QStandardItemEditorCreator<UIHostComboEditor>(); pNewItemEditorFactory->registerEditor((QVariant::Type)iHostComboTypeId, pHostComboItemEditorCreator); /* Set configured item editor factory for table delegate: */ pStyledItemDelegate->setItemEditorFactory(pNewItemEditorFactory); } void UIHotKeyTable::sltHandleShortcutsLoaded() { /* Resize columns to feat contents: */ resizeColumnsToContents(); /* Configure sorting: */ sortByColumn(UIHotKeyTableSection_Name, Qt::AscendingOrder); setSortingEnabled(true); }
carmark/vbox
src/VBox/Frontends/VirtualBox/src/settings/global/UIGlobalSettingsInput.cpp
C++
gpl-2.0
23,244
from os import environ from os import path from time import sleep from selenium import webdriver from selenium.webdriver.common.by import By from selenium.common.exceptions import NoSuchElementException from selenium.webdriver.support.ui import WebDriverWait, Select from selenium.webdriver.support import expected_conditions as EC from selenium.webdriver.common.action_chains import ActionChains import atexit class WDriverBase(): DEFAULT_TIMEOUT = 1 def __init__(self): try: self.base_url = environ['BASE_URL'] except KeyError: raise BaseException('No BASE_URL environment variable') self.implicitly_wait(WDriverBase.DEFAULT_TIMEOUT) def module(self, name): package = __import__('zentyal.' + name) return getattr(package, name).WDriverModule() def var(self, name, mandatory=False): if not environ.has_key(name): if mandatory: raise Exception('Missing mandatory variable :' + name) return None return environ[name] def var_as_list(self, name): if not environ.has_key(name): return [] return environ[name].split() def open(self, url): self.get(self.base_url + url) def click(self, name=None, id=None, xpath=None, link=None, css=None): if name: print "CLICK name = " + name self._wait_for_element_clickable(name, By.NAME) self.find_element_by_name(name).click() elif id: print "CLICK id = " + id self._wait_for_element_clickable(id, By.ID) self.find_element_by_id(id).click() elif xpath: print "CLICK xpath = " + xpath self._wait_for_element_clickable(xpath, By.XPATH) self.find_element_by_xpath(xpath).click() elif link: print "CLICK link = " + link self._wait_for_element_clickable(link, By.LINK_TEXT) self.find_element_by_link_text(link).click() elif css: print "CLICK css = " + css self._wait_for_element_clickable(css, By.CSS_SELECTOR) self.find_element_by_css_selector(css).click() else: raise ValueError("No valid selector passed (name, id, xpath, link or css)") def click_radio(self, name, value): self.click(xpath=".//input[@type='radio' and @name='" + name + "' and contains(@value, '" + value + "')]") def type(self, text, name=None, id=None, xpath=None, css=None): text = str(text) if name: print "TYPE " + text + " IN name = " + name self._type_text_in_element(text, name, By.NAME) elif id: print "TYPE " + text + " IN id = " + id self._type_text_in_element(text, id, By.ID) elif xpath: print "TYPE " + text + " IN xpath = " + xpath self._type_text_in_element(text, xpath, By.XPATH) elif css: print "TYPE " + text + " IN css = " + css self._type_text_in_element(text, css, By.CSS_SELECTOR) else: raise ValueError("No valid selector passed (name, id, xpath or css)") def type_var(self, var, name=None, id=None, xpath=None, css=None): self.type(environ[var], name, id, xpath, css) def select(self, option=None, value=None, name=None, id=None, xpath=None, css=None): how = None what = None selector = None if name: what = name how = By.NAME selector = 'name' elif id: what = id how = By.ID selector = 'id' elif xpath: what = xpath how = By.XPATH selector = 'xpath' elif css: what = css how = By.CSS_SELECTOR selector = 'css' else: raise ValueError("No valid selector passed (name, id, xpath or css)") elem = self.find_element(by=how, value=what) select = Select(elem) if value: print "SELECT value = " + value + " IN " + selector + " = " + what select.select_by_value(value) elif option: print "SELECT option = " + str(option) + " IN " + selector + " = " + what select.select_by_visible_text(option) else: raise ValueError("No option or value passed") def check(self, name, how=By.NAME): elem = self.find_element(by=how, value=name) if not elem.is_selected(): elem.click() def uncheck(self, name, how=By.NAME): elem = self.find_element(by=how, value=name) if elem.is_selected(): elem.click() def assert_true(self, expr, msg='assertion failed'): if not expr: raise Exception("Failed in driver assertion with error: " + msg) def assert_present(self, name=None, id=None, xpath=None, text=None, css=None, timeout=10, msg='not present'): self.assert_true(self.wait_for(name, id, xpath, text, css, timeout), msg) def assert_value(self, value, name=None, id=None, xpath=None, css=None, timeout=10, msg='not present'): self.assert_true(self.wait_for_value(value, name, id, xpath, css, timeout), msg) def wait_for(self, name=None, id=None, xpath=None, text=None, css=None, timeout=10): if name: print "WAIT FOR name = " + name return self._wait_for_element_present(name, By.NAME, timeout_in_seconds=timeout) elif id: print "WAIT FOR id = " + id return self._wait_for_element_present(id, By.ID, timeout_in_seconds=timeout) elif xpath: print "WAIT FOR xpath = " + xpath return self._wait_for_element_present(xpath, By.XPATH, timeout_in_seconds=timeout) elif text: print "WAIT FOR text = " + text for i in range(timeout): if self.find_element_by_tag_name('body').text.find(text) != -1: return True sleep(1) return False elif css: print "WAIT FOR css = " + css return self._wait_for_element_present(css, By.CSS_SELECTOR, timeout_in_seconds=timeout) else: raise ValueError("No valid selector passed (name, id, xpath or css)") def wait_for_value(self, value, name=None, id=None, xpath=None, css=None, timeout=10): if name: print "WAIT FOR VALUE " + value + " IN name = " + name return self._wait_for_value(name, value, By.NAME, timeout_in_seconds=timeout) elif id: print "WAIT FOR VALUE " + value + " IN id = " + id return self._wait_for_value(id, value, By.ID, timeout_in_seconds=timeout) elif xpath: print "WAIT FOR VALUE " + value + " IN xpath = " + xpath return self._wait_for_value(xpath, value, By.XPATH, timeout_in_seconds=timeout) elif css: print "WAIT FOR VALUE " + value + " IN css = " + css return self._wait_for_value(css, value, By.CSS_SELECTOR, timeout_in_seconds=timeout) else: raise ValueError("No valid selector passed (name, id, xpath or css)") def is_present(self, name=None, id=None, xpath=None, text=None, css=None): if name: print "IS PRESENT? name = " + name return self._is_element_present(By.NAME, name) elif id: print "IS PRESENT? id = " + id return self._is_element_present(By.ID, id) elif xpath: print "IS PRESENT? xpath = " + xpath return self._is_element_present(By.XPATH, xpath) elif text: print "IS PRESENT? text = " + text return self.find_element_by_tag_name('body').text.find(text) != -1 elif css: print "IS PRESENT? css = " + css return self._is_element_present(By.CSS, css) else: raise ValueError("No valid selector passed (name, id, xpath, text or css)") def drag_and_drop(self, xpath_drag, id_drop): drag = driver.find_element_by_xpath(xpath_drag) drop = driver.find_element_by_id(id_drop) ActionChains(self).drag_and_drop(drag, drop).perform() def _is_element_present(self, how, what): self.implicitly_wait(WDriverBase.DEFAULT_TIMEOUT) try: return self.find_element(by=how, value=what).is_displayed() except NoSuchElementException: return False def _wait_for_value(self, name, value, how=By.NAME, timeout_in_seconds=10): for i in range(timeout_in_seconds): if self._is_element_present(how, name): if self.find_element(by=how, value=name).get_attribute("value") == value: return True sleep(1) return False def _wait_for_element_present(self, element, how=By.NAME, timeout_in_seconds=10): for i in range(timeout_in_seconds): if self._is_element_present(how, element): return True sleep(1) print "Timeout after " + str(timeout_in_seconds) + " seconds." return False def _type_text_in_element(self, text, element, how=By.NAME): self._wait_for_element_present(element, how) elem = self.find_element(how, element) elem.click() elem.clear() elem.send_keys(text.decode('utf-8')) def _wait_for_element_clickable(self, element, how=By.NAME, timeout_in_seconds=10): wait = WebDriverWait(self, timeout_in_seconds) element = wait.until(EC.element_to_be_clickable((how,element))) return element class WDriverFirefox(webdriver.Firefox, WDriverBase): init_done = False instance = None def __new__(cls, *args, **kargs): if cls.instance is None: cls.instance = object.__new__(cls, *args, **kargs) return cls.instance def __init__(self): if not WDriverFirefox.init_done: webdriver.Firefox.__init__(self) WDriverBase.__init__(self) WDriverFirefox.init_done = True atexit.register(self.quit) class WDriverChrome(webdriver.Chrome, WDriverBase): init_done = False instance = None default_ubuntu_path = '/usr/lib/chromium-browser/chromedriver' def __new__(cls, *args, **kargs): if cls.instance is None: cls.instance = object.__new__(cls, *args, **kargs) return cls.instance def __init__(self): if not WDriverChrome.init_done: if (self.exists()): webdriver.Chrome.__init__( self, executable_path=self.default_ubuntu_path) else: webdriver.Chrome.__init__(self) WDriverBase.__init__(self) WDriverChrome.init_done = True atexit.register(self.quit) @classmethod def exists(cls): return path.exists(cls.default_ubuntu_path) class WDriverPhantomJS(webdriver.PhantomJS, WDriverBase): init_done = False instance = None def __new__(cls, *args, **kargs): if cls.instance is None: cls.instance = object.__new__(cls, *args, **kargs) return cls.instance def __init__(self): if not WDriverPhantomJS.init_done: webdriver.PhantomJS.__init__(self, service_args=['--ignore-ssl-errors=true']) WDriverBase.__init__(self) WDriverPhantomJS.init_done = True atexit.register(self.quit) @classmethod def exists(cls): default_phantomjs_path = '/usr/bin/phantomjs' return path.exists(default_phantomjs_path) def instance(): if environ.has_key("GLOBAL_browser"): if environ["GLOBAL_browser"] == "Chrome": return WDriverChrome() elif environ["GLOBAL_browser"] == "Firefox": return WDriverFirefox() if WDriverPhantomJS.exists(): return WDriverPhantomJS(client_base) elif WDriverChrome.exists(): return WDriverChrome(client_base) return WDriverPhantomJS()
Zentyal/anste
lib/anste/wdriver.py
Python
gpl-2.0
12,084
<?php function getInstagram(){ $json = file_get_contents('https://api.instagram.com/v1/users/1167443738/media/recent?access_token=1167443738.5b9e1e6.5cb9e88dbfa5493e9c2648e489ece7da'); $obj = json_decode($json); return $obj->data; } ?>
MESH-Dev/MESH
wp-content/themes/MESH/assets/api/instagram.php
PHP
gpl-2.0
246
<?php define('DRUPAL_ROOT', getcwd()); require_once DRUPAL_ROOT.'/includes/bootstrap.inc'; drupal_bootstrap(DRUPAL_BOOTSTRAP_FULL); $Directory = "./sites/default/files/maps"; // $existing_pagenode = node_load(139); // print_r($existing_pagenode); // open the Directory $dhandle = dir($Directory); // define an array to hold the files $files = array(); if ($dhandle) { // loop through all of the files while (false !== ($fname = $dhandle->read())) { // if the file is not this file, and does not start with a '.' or '..', // then store it for later display if (($fname != '.') && ($fname != '..') && ($fname != basename($_SERVER['PHP_SELF']))) { $file = $Directory."/".$fname; // Get the town name out of file name $fname = substr($fname, 9); $fname = substr($fname, 0,-19); $fname = str_ireplace("_", " ", $fname); $fname = ucwords($fname); $PlaceName = $fname; // check if term already in: $suburb = taxonomy_get_term_by_name($PlaceName); if (empty($suburb)) { $suburb = new stdClass(); $suburb->name= $PlaceName; $suburb->vid = 3; taxonomy_term_save($suburb); $suburb = taxonomy_get_term_by_name($PlaceName); } else { continue; } $numb = array_keys($suburb); $suburbTermID = $numb[0]; // Create the node: $newnode = new stdClass(); // Set the Title $newnode->title = "Flood Flag Map - ".$PlaceName; $newnode->body = ""; $newnode->uid = 3; // Nicks user; $newnode->type = 'article'; $newnode->status = 1; $newnode->promote = 0; $newnode->field_tags['und'][0]['tid']= 36; $newnode->field_suburb['und'][0]['tid'] = $suburbTermID; // have to add in a suburb first?? // Get the file size $details = stat($file); $filesize = $details['size']; $dest = 'public://user_files/'; // Copy the file to the Drupal files directory $name = basename($file); // Build the file object $file_obj = new stdClass(); $file_obj->filename = $name; $file_obj->uri = $file; $file_obj->filemime = file_get_mimetype($name); $file_obj->filesize = $filesize; $file_obj->filesource = $name; $file_obj->uid = 3; // Nick $file_obj->status = FILE_STATUS_PERMANENT; $file_obj->timestamp = time(); $file_obj->list = 1; $file_obj->new = true; // TODO do a file move $file_obj = file_copy($file_obj,$dest); // Attach the file object to your node $newnode->field_file['und'][0]['fid'] = $file_obj->fid; $newnode->field_file['und'][0]['display'] = 1; node_save($newnode); $newpath = strtolower($newnode->title); $newpath = str_replace(" - ", "-", $newpath); $newpath = str_replace(" ", "-", $newpath); $path = array(); $path['source']=$newnode->uri['path']; $path['alias'] = "article/".$newpath; path_save($path); //content_insert($newnode); unset($newnode); unset($file_obj); } } }
rcross/qldfloods
newfiles.php
PHP
gpl-2.0
2,719
/* Copyright (c) 2000, 2013, Oracle and/or its affiliates. Copyright (c) 2008, 2013, Monty Program Ab This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ #define MYSQL_LEX 1 #include "my_global.h" #include "sql_priv.h" #include "unireg.h" // REQUIRED: for other includes #include "sql_parse.h" // sql_kill, *_precheck, *_prepare #include "lock.h" // try_transactional_lock, // check_transactional_lock, // set_handler_table_locks, // lock_global_read_lock, // make_global_read_lock_block_commit #include "sql_base.h" // find_temporary_table #include "sql_cache.h" // QUERY_CACHE_FLAGS_SIZE, query_cache_* #include "sql_show.h" // mysqld_list_*, mysqld_show_*, // calc_sum_of_all_status #include "mysqld.h" #include "sql_locale.h" // my_locale_en_US #include "log.h" // flush_error_log #include "sql_view.h" // mysql_create_view, mysql_drop_view #include "sql_delete.h" // mysql_delete #include "sql_insert.h" // mysql_insert #include "sql_update.h" // mysql_update, mysql_multi_update #include "sql_partition.h" // struct partition_info #include "sql_db.h" // mysql_change_db, mysql_create_db, // mysql_rm_db, mysql_upgrade_db, // mysql_alter_db, // check_db_dir_existence, // my_dbopt_cleanup #include "sql_table.h" // mysql_create_like_table, // mysql_create_table, // mysql_alter_table, // mysql_backup_table, // mysql_restore_table #include "sql_reload.h" // reload_acl_and_cache #include "sql_admin.h" // mysql_assign_to_keycache #include "sql_connect.h" // decrease_user_connections, // check_mqh, // reset_mqh #include "sql_rename.h" // mysql_rename_table #include "sql_tablespace.h" // mysql_alter_tablespace #include "hostname.h" // hostname_cache_refresh #include "sql_acl.h" // *_ACL, check_grant, is_acl_user, // has_any_table_level_privileges, // mysql_drop_user, mysql_rename_user, // check_grant_routine, // mysql_routine_grant, // mysql_show_grants, // sp_grant_privileges, ... #include "sql_test.h" // mysql_print_status #include "sql_select.h" // handle_select, mysql_select, // mysql_explain_union #include "sql_load.h" // mysql_load #include "sql_servers.h" // create_servers, alter_servers, // drop_servers, servers_reload #include "sql_handler.h" // mysql_ha_open, mysql_ha_close, // mysql_ha_read #include "sql_binlog.h" // mysql_client_binlog_statement #include "sql_do.h" // mysql_do #include "sql_help.h" // mysqld_help #include "rpl_constants.h" // Incident, INCIDENT_LOST_EVENTS #include "log_event.h" #include "sql_repl.h" #include "rpl_filter.h" #include "repl_failsafe.h" #include <m_ctype.h> #include <myisam.h> #include <my_dir.h> #include "rpl_handler.h" #include "rpl_mi.h" #include "sp_head.h" #include "sp.h" #include "sp_cache.h" #include "events.h" #include "sql_trigger.h" #include "transaction.h" #include "sql_audit.h" #include "sql_prepare.h" #include "debug_sync.h" #include "probes_mysql.h" #include "set_var.h" #include "log_slow.h" #include "sql_bootstrap.h" #define FLAGSTR(V,F) ((V)&(F)?#F" ":"") #ifdef WITH_ARIA_STORAGE_ENGINE #include "../storage/maria/ha_maria.h" #endif /** @defgroup Runtime_Environment Runtime Environment @{ */ /* Used in error handling only */ #define SP_TYPE_STRING(LP) \ ((LP)->sphead->m_type == TYPE_ENUM_FUNCTION ? "FUNCTION" : "PROCEDURE") #define SP_COM_STRING(LP) \ ((LP)->sql_command == SQLCOM_CREATE_SPFUNCTION || \ (LP)->sql_command == SQLCOM_ALTER_FUNCTION || \ (LP)->sql_command == SQLCOM_SHOW_CREATE_FUNC || \ (LP)->sql_command == SQLCOM_DROP_FUNCTION ? \ "FUNCTION" : "PROCEDURE") static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables); static void sql_kill(THD *thd, longlong id, killed_state state, killed_type type); static void sql_kill_user(THD *thd, LEX_USER *user, killed_state state); static bool lock_tables_precheck(THD *thd, TABLE_LIST *tables); static bool execute_show_status(THD *, TABLE_LIST *); static bool execute_rename_table(THD *, TABLE_LIST *, TABLE_LIST *); const char *any_db="*any*"; // Special symbol for check_access const LEX_STRING command_name[]={ { C_STRING_WITH_LEN("Sleep") }, { C_STRING_WITH_LEN("Quit") }, { C_STRING_WITH_LEN("Init DB") }, { C_STRING_WITH_LEN("Query") }, { C_STRING_WITH_LEN("Field List") }, { C_STRING_WITH_LEN("Create DB") }, { C_STRING_WITH_LEN("Drop DB") }, { C_STRING_WITH_LEN("Refresh") }, { C_STRING_WITH_LEN("Shutdown") }, { C_STRING_WITH_LEN("Statistics") }, { C_STRING_WITH_LEN("Processlist") }, { C_STRING_WITH_LEN("Connect") }, { C_STRING_WITH_LEN("Kill") }, { C_STRING_WITH_LEN("Debug") }, { C_STRING_WITH_LEN("Ping") }, { C_STRING_WITH_LEN("Time") }, { C_STRING_WITH_LEN("Delayed insert") }, { C_STRING_WITH_LEN("Change user") }, { C_STRING_WITH_LEN("Binlog Dump") }, { C_STRING_WITH_LEN("Table Dump") }, { C_STRING_WITH_LEN("Connect Out") }, { C_STRING_WITH_LEN("Register Slave") }, { C_STRING_WITH_LEN("Prepare") }, { C_STRING_WITH_LEN("Execute") }, { C_STRING_WITH_LEN("Long Data") }, { C_STRING_WITH_LEN("Close stmt") }, { C_STRING_WITH_LEN("Reset stmt") }, { C_STRING_WITH_LEN("Set option") }, { C_STRING_WITH_LEN("Fetch") }, { C_STRING_WITH_LEN("Daemon") }, { C_STRING_WITH_LEN("Error") } // Last command number }; const char *xa_state_names[]={ "NON-EXISTING", "ACTIVE", "IDLE", "PREPARED", "ROLLBACK ONLY" }; #ifdef HAVE_REPLICATION /** Returns true if all tables should be ignored. */ inline bool all_tables_not_ok(THD *thd, TABLE_LIST *tables) { return thd->rpl_filter->is_on() && tables && !thd->spcont && !thd->rpl_filter->tables_ok(thd->db, tables); } #endif static bool some_non_temp_table_to_be_updated(THD *thd, TABLE_LIST *tables) { for (TABLE_LIST *table= tables; table; table= table->next_global) { DBUG_ASSERT(table->db && table->table_name); if (table->updating && !find_temporary_table(thd, table)) return 1; } return 0; } /* Implicitly commit a active transaction if statement requires so. @param thd Thread handle. @param mask Bitmask used for the SQL command match. @return 0 No implicit commit @return 1 Do a commit */ static bool stmt_causes_implicit_commit(THD *thd, uint mask) { LEX *lex= thd->lex; bool skip= FALSE; DBUG_ENTER("stmt_causes_implicit_commit"); if (!(sql_command_flags[lex->sql_command] & mask)) DBUG_RETURN(FALSE); switch (lex->sql_command) { case SQLCOM_DROP_TABLE: skip= (lex->drop_temporary || (thd->variables.option_bits & OPTION_GTID_BEGIN)); break; case SQLCOM_ALTER_TABLE: /* If ALTER TABLE of non-temporary table, do implicit commit */ skip= (lex->create_info.tmp_table()); break; case SQLCOM_CREATE_TABLE: /* If CREATE TABLE of non-temporary table and the table is not part if a BEGIN GTID ... COMMIT group, do a implicit commit. This ensures that CREATE ... SELECT will in the same GTID group on the master and slave. */ skip= (lex->create_info.tmp_table() || (thd->variables.option_bits & OPTION_GTID_BEGIN)); break; case SQLCOM_SET_OPTION: skip= lex->autocommit ? FALSE : TRUE; break; default: break; } DBUG_RETURN(!skip); } /** Mark all commands that somehow changes a table. This is used to check number of updates / hour. sql_command is actually set to SQLCOM_END sometimes so we need the +1 to include it in the array. See COMMAND_FLAG_xxx for different type of commands 2 - query that returns meaningful ROW_COUNT() - a number of modified rows */ uint sql_command_flags[SQLCOM_END+1]; uint server_command_flags[COM_END+1]; void init_update_queries(void) { /* Initialize the server command flags array. */ memset(server_command_flags, 0, sizeof(server_command_flags)); server_command_flags[COM_STATISTICS]= CF_SKIP_QUERY_ID | CF_SKIP_QUESTIONS; server_command_flags[COM_PING]= CF_SKIP_QUERY_ID | CF_SKIP_QUESTIONS; server_command_flags[COM_STMT_PREPARE]= CF_SKIP_QUESTIONS; server_command_flags[COM_STMT_CLOSE]= CF_SKIP_QUESTIONS; server_command_flags[COM_STMT_RESET]= CF_SKIP_QUESTIONS; /* Initialize the sql command flags array. */ memset(sql_command_flags, 0, sizeof(sql_command_flags)); /* In general, DDL statements do not generate row events and do not go through a cache before being written to the binary log. However, the CREATE TABLE...SELECT is an exception because it may generate row events. For that reason, the SQLCOM_CREATE_TABLE which represents a CREATE TABLE, including the CREATE TABLE...SELECT, has the CF_CAN_GENERATE_ROW_EVENTS flag. The distinction between a regular CREATE TABLE and the CREATE TABLE...SELECT is made in other parts of the code, in particular in the Query_log_event's constructor. */ sql_command_flags[SQLCOM_CREATE_TABLE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE | CF_AUTO_COMMIT_TRANS | CF_REPORT_PROGRESS | CF_CAN_GENERATE_ROW_EVENTS; sql_command_flags[SQLCOM_CREATE_INDEX]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_ALTER_TABLE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS | CF_REPORT_PROGRESS | CF_INSERTS_DATA; sql_command_flags[SQLCOM_TRUNCATE]= CF_CHANGES_DATA | CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_DROP_TABLE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_LOAD]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_REPORT_PROGRESS | CF_INSERTS_DATA; sql_command_flags[SQLCOM_CREATE_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_DROP_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_ALTER_DB_UPGRADE]= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_ALTER_DB]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_RENAME_TABLE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_DROP_INDEX]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS | CF_REPORT_PROGRESS; sql_command_flags[SQLCOM_CREATE_VIEW]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_DROP_VIEW]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_CREATE_TRIGGER]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_DROP_TRIGGER]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_CREATE_EVENT]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_ALTER_EVENT]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_DROP_EVENT]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_UPDATE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_OPTIMIZER_TRACE | CF_CAN_BE_EXPLAINED | CF_UPDATES_DATA; sql_command_flags[SQLCOM_UPDATE_MULTI]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_OPTIMIZER_TRACE | CF_CAN_BE_EXPLAINED | CF_UPDATES_DATA; sql_command_flags[SQLCOM_INSERT]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_OPTIMIZER_TRACE | CF_CAN_BE_EXPLAINED | CF_INSERTS_DATA; sql_command_flags[SQLCOM_INSERT_SELECT]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_OPTIMIZER_TRACE | CF_CAN_BE_EXPLAINED | CF_INSERTS_DATA; sql_command_flags[SQLCOM_DELETE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_OPTIMIZER_TRACE | CF_CAN_BE_EXPLAINED; sql_command_flags[SQLCOM_DELETE_MULTI]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_OPTIMIZER_TRACE | CF_CAN_BE_EXPLAINED;; sql_command_flags[SQLCOM_REPLACE]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_OPTIMIZER_TRACE | CF_CAN_BE_EXPLAINED | CF_INSERTS_DATA;; sql_command_flags[SQLCOM_REPLACE_SELECT]= CF_CHANGES_DATA | CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_OPTIMIZER_TRACE | CF_CAN_BE_EXPLAINED | CF_INSERTS_DATA; sql_command_flags[SQLCOM_SELECT]= CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_OPTIMIZER_TRACE | CF_CAN_BE_EXPLAINED; // (1) so that subquery is traced when doing "SET @var = (subquery)" /* @todo SQLCOM_SET_OPTION should have CF_CAN_GENERATE_ROW_EVENTS set, because it may invoke a stored function that generates row events. /Sven */ sql_command_flags[SQLCOM_SET_OPTION]= CF_REEXECUTION_FRAGILE | CF_AUTO_COMMIT_TRANS | CF_OPTIMIZER_TRACE; // (1) // (1) so that subquery is traced when doing "DO @var := (subquery)" sql_command_flags[SQLCOM_DO]= CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_OPTIMIZER_TRACE; // (1) sql_command_flags[SQLCOM_SHOW_STATUS_PROC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_STATUS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_DATABASES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_TRIGGERS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_EVENTS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_OPEN_TABLES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_PLUGINS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_FIELDS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_KEYS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_VARIABLES]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_CHARSETS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_COLLATIONS]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_BINLOGS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_SLAVE_HOSTS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_BINLOG_EVENTS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_STORAGE_ENGINES]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_AUTHORS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_CONTRIBUTORS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_PRIVILEGES]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_WARNS]= CF_STATUS_COMMAND | CF_DIAGNOSTIC_STMT; sql_command_flags[SQLCOM_SHOW_ERRORS]= CF_STATUS_COMMAND | CF_DIAGNOSTIC_STMT; sql_command_flags[SQLCOM_SHOW_ENGINE_STATUS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_ENGINE_MUTEX]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_ENGINE_LOGS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_EXPLAIN]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_PROCESSLIST]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_GRANTS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_CREATE_DB]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_CREATE]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_MASTER_STAT]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_SLAVE_STAT]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_CREATE_PROC]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_CREATE_FUNC]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_CREATE_TRIGGER]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_STATUS_FUNC]= CF_STATUS_COMMAND | CF_REEXECUTION_FRAGILE; sql_command_flags[SQLCOM_SHOW_PROC_CODE]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_FUNC_CODE]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_CREATE_EVENT]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_PROFILES]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_PROFILE]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_BINLOG_BASE64_EVENT]= CF_STATUS_COMMAND | CF_CAN_GENERATE_ROW_EVENTS; sql_command_flags[SQLCOM_SHOW_CLIENT_STATS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_USER_STATS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_TABLE_STATS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_INDEX_STATS]= CF_STATUS_COMMAND; sql_command_flags[SQLCOM_SHOW_TABLES]= (CF_STATUS_COMMAND | CF_SHOW_TABLE_COMMAND | CF_REEXECUTION_FRAGILE); sql_command_flags[SQLCOM_SHOW_TABLE_STATUS]= (CF_STATUS_COMMAND | CF_SHOW_TABLE_COMMAND | CF_REEXECUTION_FRAGILE); sql_command_flags[SQLCOM_CREATE_USER]= CF_CHANGES_DATA; sql_command_flags[SQLCOM_RENAME_USER]= CF_CHANGES_DATA; sql_command_flags[SQLCOM_DROP_USER]= CF_CHANGES_DATA; sql_command_flags[SQLCOM_CREATE_ROLE]= CF_CHANGES_DATA; sql_command_flags[SQLCOM_GRANT]= CF_CHANGES_DATA; sql_command_flags[SQLCOM_GRANT_ROLE]= CF_CHANGES_DATA; sql_command_flags[SQLCOM_REVOKE]= CF_CHANGES_DATA; sql_command_flags[SQLCOM_REVOKE_ROLE]= CF_CHANGES_DATA; sql_command_flags[SQLCOM_OPTIMIZE]= CF_CHANGES_DATA; /* @todo SQLCOM_CREATE_FUNCTION should have CF_AUTO_COMMIT_TRANS set. this currently is binlogged *before* the transaction if executed inside a transaction because it does not have an implicit pre-commit and is written to the statement cache. /Sven */ sql_command_flags[SQLCOM_CREATE_FUNCTION]= CF_CHANGES_DATA; sql_command_flags[SQLCOM_CREATE_PROCEDURE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_CREATE_SPFUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_DROP_PROCEDURE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_DROP_FUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_ALTER_PROCEDURE]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_ALTER_FUNCTION]= CF_CHANGES_DATA | CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_INSTALL_PLUGIN]= CF_CHANGES_DATA; sql_command_flags[SQLCOM_UNINSTALL_PLUGIN]= CF_CHANGES_DATA; /* The following is used to preserver CF_ROW_COUNT during the a CALL or EXECUTE statement, so the value generated by the last called (or executed) statement is preserved. See mysql_execute_command() for how CF_ROW_COUNT is used. */ /* (1): without it, in "CALL some_proc((subq))", subquery would not be traced. */ sql_command_flags[SQLCOM_CALL]= CF_REEXECUTION_FRAGILE | CF_CAN_GENERATE_ROW_EVENTS | CF_OPTIMIZER_TRACE; // (1) sql_command_flags[SQLCOM_EXECUTE]= CF_CAN_GENERATE_ROW_EVENTS; /* We don't want to change to statement based replication for these commands */ sql_command_flags[SQLCOM_ROLLBACK]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT; /* We don't want to replicate ALTER TABLE for temp tables in row format */ sql_command_flags[SQLCOM_ALTER_TABLE]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT; /* We don't want to replicate TRUNCATE for temp tables in row format */ sql_command_flags[SQLCOM_TRUNCATE]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT; /* We don't want to replicate DROP for temp tables in row format */ sql_command_flags[SQLCOM_DROP_TABLE]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT; /* One can change replication mode with SET */ sql_command_flags[SQLCOM_SET_OPTION]|= CF_FORCE_ORIGINAL_BINLOG_FORMAT; /* The following admin table operations are allowed on log tables. */ sql_command_flags[SQLCOM_REPAIR]= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS | CF_REPORT_PROGRESS; sql_command_flags[SQLCOM_OPTIMIZE]|= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS | CF_REPORT_PROGRESS; sql_command_flags[SQLCOM_ANALYZE]= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS | CF_REPORT_PROGRESS; sql_command_flags[SQLCOM_CHECK]= CF_WRITE_LOGS_COMMAND | CF_AUTO_COMMIT_TRANS | CF_REPORT_PROGRESS; sql_command_flags[SQLCOM_CHECKSUM]= CF_REPORT_PROGRESS; sql_command_flags[SQLCOM_CREATE_USER]|= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_DROP_USER]|= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_RENAME_USER]|= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_CREATE_ROLE]|= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_DROP_ROLE]|= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_REVOKE_ALL]= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_REVOKE]|= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_REVOKE_ROLE]|= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_GRANT]|= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_GRANT_ROLE]|= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_ASSIGN_TO_KEYCACHE]= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_PRELOAD_KEYS]= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_FLUSH]= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_RESET]= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_CREATE_SERVER]= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_ALTER_SERVER]= CF_AUTO_COMMIT_TRANS; sql_command_flags[SQLCOM_DROP_SERVER]= CF_AUTO_COMMIT_TRANS; /* The following statements can deal with temporary tables, so temporary tables should be pre-opened for those statements to simplify privilege checking. There are other statements that deal with temporary tables and open them, but which are not listed here. The thing is that the order of pre-opening temporary tables for those statements is somewhat custom. */ sql_command_flags[SQLCOM_CREATE_TABLE]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_DROP_TABLE]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_CREATE_INDEX]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_ALTER_TABLE]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_TRUNCATE]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_LOAD]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_DROP_INDEX]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_UPDATE]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_UPDATE_MULTI]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_INSERT_SELECT]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_DELETE]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_DELETE_MULTI]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_REPLACE_SELECT]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_SELECT]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_SET_OPTION]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_DO]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_HA_OPEN]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_CALL]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_CHECKSUM]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_ANALYZE]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_CHECK]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_OPTIMIZE]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_REPAIR]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_PRELOAD_KEYS]|= CF_PREOPEN_TMP_TABLES; sql_command_flags[SQLCOM_ASSIGN_TO_KEYCACHE]|= CF_PREOPEN_TMP_TABLES; /* DDL statements that should start with closing opened handlers. We use this flag only for statements for which open HANDLERs have to be closed before temporary tables are pre-opened. */ sql_command_flags[SQLCOM_CREATE_TABLE]|= CF_HA_CLOSE; sql_command_flags[SQLCOM_DROP_TABLE]|= CF_HA_CLOSE; sql_command_flags[SQLCOM_ALTER_TABLE]|= CF_HA_CLOSE; sql_command_flags[SQLCOM_TRUNCATE]|= CF_HA_CLOSE; sql_command_flags[SQLCOM_REPAIR]|= CF_HA_CLOSE; sql_command_flags[SQLCOM_OPTIMIZE]|= CF_HA_CLOSE; sql_command_flags[SQLCOM_ANALYZE]|= CF_HA_CLOSE; sql_command_flags[SQLCOM_CHECK]|= CF_HA_CLOSE; sql_command_flags[SQLCOM_CREATE_INDEX]|= CF_HA_CLOSE; sql_command_flags[SQLCOM_DROP_INDEX]|= CF_HA_CLOSE; sql_command_flags[SQLCOM_PRELOAD_KEYS]|= CF_HA_CLOSE; sql_command_flags[SQLCOM_ASSIGN_TO_KEYCACHE]|= CF_HA_CLOSE; /* Mark statements that always are disallowed in read-only transactions. Note that according to the SQL standard, even temporary table DDL should be disallowed. */ sql_command_flags[SQLCOM_CREATE_TABLE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_ALTER_TABLE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_DROP_TABLE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_RENAME_TABLE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_CREATE_INDEX]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_DROP_INDEX]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_CREATE_DB]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_DROP_DB]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_ALTER_DB_UPGRADE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_ALTER_DB]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_CREATE_VIEW]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_DROP_VIEW]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_CREATE_TRIGGER]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_DROP_TRIGGER]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_CREATE_EVENT]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_ALTER_EVENT]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_DROP_EVENT]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_CREATE_USER]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_RENAME_USER]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_DROP_USER]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_CREATE_SERVER]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_ALTER_SERVER]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_DROP_SERVER]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_CREATE_FUNCTION]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_CREATE_PROCEDURE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_CREATE_SPFUNCTION]|=CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_DROP_PROCEDURE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_DROP_FUNCTION]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_ALTER_PROCEDURE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_ALTER_FUNCTION]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_TRUNCATE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_ALTER_TABLESPACE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_REPAIR]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_OPTIMIZE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_GRANT]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_REVOKE]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_REVOKE_ALL]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_INSTALL_PLUGIN]|= CF_DISALLOW_IN_RO_TRANS; sql_command_flags[SQLCOM_UNINSTALL_PLUGIN]|= CF_DISALLOW_IN_RO_TRANS; } bool sqlcom_can_generate_row_events(const THD *thd) { return (sql_command_flags[thd->lex->sql_command] & CF_CAN_GENERATE_ROW_EVENTS); } bool is_update_query(enum enum_sql_command command) { DBUG_ASSERT(command <= SQLCOM_END); return (sql_command_flags[command] & CF_CHANGES_DATA) != 0; } /** Check if a sql command is allowed to write to log tables. @param command The SQL command @return true if writing is allowed */ bool is_log_table_write_query(enum enum_sql_command command) { DBUG_ASSERT(command <= SQLCOM_END); return (sql_command_flags[command] & CF_WRITE_LOGS_COMMAND) != 0; } void execute_init_command(THD *thd, LEX_STRING *init_command, mysql_rwlock_t *var_lock) { Vio* save_vio; ulong save_client_capabilities; mysql_rwlock_rdlock(var_lock); if (!init_command->length) { mysql_rwlock_unlock(var_lock); return; } /* copy the value under a lock, and release the lock. init_command has to be executed without a lock held, as it may try to change itself */ size_t len= init_command->length; char *buf= thd->strmake(init_command->str, len); mysql_rwlock_unlock(var_lock); #if defined(ENABLED_PROFILING) thd->profiling.start_new_query(); thd->profiling.set_query_source(buf, len); #endif THD_STAGE_INFO(thd, stage_execution_of_init_command); save_client_capabilities= thd->client_capabilities; thd->client_capabilities|= CLIENT_MULTI_QUERIES; /* We don't need return result of execution to client side. To forbid this we should set thd->net.vio to 0. */ save_vio= thd->net.vio; thd->net.vio= 0; dispatch_command(COM_QUERY, thd, buf, len); thd->client_capabilities= save_client_capabilities; thd->net.vio= save_vio; #if defined(ENABLED_PROFILING) thd->profiling.finish_current_query(); #endif } static char *fgets_fn(char *buffer, size_t size, fgets_input_t input, int *error) { MYSQL_FILE *in= static_cast<MYSQL_FILE*> (input); char *line= mysql_file_fgets(buffer, size, in); if (error) *error= (line == NULL) ? ferror(in->m_file) : 0; return line; } static void handle_bootstrap_impl(THD *thd) { MYSQL_FILE *file= bootstrap_file; DBUG_ENTER("handle_bootstrap"); #ifndef EMBEDDED_LIBRARY pthread_detach_this_thread(); thd->thread_stack= (char*) &thd; #endif /* EMBEDDED_LIBRARY */ thd->security_ctx->user= (char*) my_strdup("boot", MYF(MY_WME)); thd->security_ctx->priv_user[0]= thd->security_ctx->priv_host[0]= thd->security_ctx->priv_role[0]= 0; /* Make the "client" handle multiple results. This is necessary to enable stored procedures with SELECTs and Dynamic SQL in init-file. */ thd->client_capabilities|= CLIENT_MULTI_RESULTS; thd->init_for_queries(); for ( ; ; ) { char buffer[MAX_BOOTSTRAP_QUERY_SIZE] = ""; int rc, length; char *query; int error= 0; rc= read_bootstrap_query(buffer, &length, file, fgets_fn, &error); if (rc == READ_BOOTSTRAP_EOF) break; /* Check for bootstrap file errors. SQL syntax errors will be caught below. */ if (rc != READ_BOOTSTRAP_SUCCESS) { /* mysql_parse() may have set a successful error status for the previous query. We must clear the error status to report the bootstrap error. */ thd->get_stmt_da()->reset_diagnostics_area(); /* Get the nearest query text for reference. */ char *err_ptr= buffer + (length <= MAX_BOOTSTRAP_ERROR_LEN ? 0 : (length - MAX_BOOTSTRAP_ERROR_LEN)); switch (rc) { case READ_BOOTSTRAP_ERROR: my_printf_error(ER_UNKNOWN_ERROR, "Bootstrap file error, return code (%d). " "Nearest query: '%s'", MYF(0), error, err_ptr); break; case READ_BOOTSTRAP_QUERY_SIZE: my_printf_error(ER_UNKNOWN_ERROR, "Boostrap file error. Query size " "exceeded %d bytes near '%s'.", MYF(0), MAX_BOOTSTRAP_LINE_SIZE, err_ptr); break; default: DBUG_ASSERT(false); break; } thd->protocol->end_statement(); bootstrap_error= 1; break; } query= (char *) thd->memdup_w_gap(buffer, length + 1, thd->db_length + 1 + QUERY_CACHE_DB_LENGTH_SIZE + QUERY_CACHE_FLAGS_SIZE); size_t db_len= 0; memcpy(query + length + 1, (char *) &db_len, sizeof(size_t)); thd->set_query_and_id(query, length, thd->charset(), next_query_id()); int2store(query + length + 1, 0); // No db in bootstrap DBUG_PRINT("query",("%-.4096s",thd->query())); #if defined(ENABLED_PROFILING) thd->profiling.start_new_query(); thd->profiling.set_query_source(thd->query(), length); #endif /* We don't need to obtain LOCK_thread_count here because in bootstrap mode we have only one thread. */ thd->set_time(); Parser_state parser_state; if (parser_state.init(thd, thd->query(), length)) { thd->protocol->end_statement(); bootstrap_error= 1; break; } mysql_parse(thd, thd->query(), length, &parser_state); bootstrap_error= thd->is_error(); thd->protocol->end_statement(); #if defined(ENABLED_PROFILING) thd->profiling.finish_current_query(); #endif delete_explain_query(thd->lex); if (bootstrap_error) break; free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC)); free_root(&thd->transaction.mem_root,MYF(MY_KEEP_PREALLOC)); } DBUG_VOID_RETURN; } /** Execute commands from bootstrap_file. Used when creating the initial grant tables. */ pthread_handler_t handle_bootstrap(void *arg) { THD *thd=(THD*) arg; mysql_thread_set_psi_id(thd->thread_id); do_handle_bootstrap(thd); return 0; } void do_handle_bootstrap(THD *thd) { /* The following must be called before DBUG_ENTER */ thd->thread_stack= (char*) &thd; if (my_thread_init() || thd->store_globals()) { #ifndef EMBEDDED_LIBRARY close_connection(thd, ER_OUT_OF_RESOURCES); #endif thd->fatal_error(); goto end; } handle_bootstrap_impl(thd); end: delete thd; #ifndef EMBEDDED_LIBRARY thread_safe_decrement32(&thread_count, &thread_count_lock); in_bootstrap= FALSE; mysql_mutex_lock(&LOCK_thread_count); mysql_cond_broadcast(&COND_thread_count); mysql_mutex_unlock(&LOCK_thread_count); my_thread_end(); pthread_exit(0); #endif return; } /* This works because items are allocated with sql_alloc() */ void free_items(Item *item) { Item *next; DBUG_ENTER("free_items"); for (; item ; item=next) { next=item->next; item->delete_self(); } DBUG_VOID_RETURN; } /** This works because items are allocated with sql_alloc(). @note The function also handles null pointers (empty list). */ void cleanup_items(Item *item) { DBUG_ENTER("cleanup_items"); for (; item ; item=item->next) item->cleanup(); DBUG_VOID_RETURN; } #ifndef EMBEDDED_LIBRARY /** Read one command from connection and execute it (query or simple command). This function is called in loop from thread function. For profiling to work, it must never be called recursively. @retval 0 success @retval 1 request of thread shutdown (see dispatch_command() description) */ bool do_command(THD *thd) { bool return_value; char *packet= 0; ulong packet_length; NET *net= &thd->net; enum enum_server_command command; DBUG_ENTER("do_command"); /* indicator of uninitialized lex => normal flow of errors handling (see my_message_sql) */ thd->lex->current_select= 0; /* This thread will do a blocking read from the client which will be interrupted when the next command is received from the client, the connection is closed or "net_wait_timeout" number of seconds has passed. */ if(!thd->skip_wait_timeout) my_net_set_read_timeout(net, thd->variables.net_wait_timeout); /* XXX: this code is here only to clear possible errors of init_connect. Consider moving to init_connect() instead. */ thd->clear_error(); // Clear error message thd->get_stmt_da()->reset_diagnostics_area(); net_new_transaction(net); /* Save for user statistics */ thd->start_bytes_received= thd->status_var.bytes_received; /* Synchronization point for testing of KILL_CONNECTION. This sync point can wait here, to simulate slow code execution between the last test of thd->killed and blocking in read(). The goal of this test is to verify that a connection does not hang, if it is killed at this point of execution. (Bug#37780 - main.kill fails randomly) Note that the sync point wait itself will be terminated by a kill. In this case it consumes a condition broadcast, but does not change anything else. The consumed broadcast should not matter here, because the read/recv() below doesn't use it. */ DEBUG_SYNC(thd, "before_do_command_net_read"); thd->m_server_idle= TRUE; packet_length= my_net_read(net); thd->m_server_idle= FALSE; if (packet_length == packet_error) { DBUG_PRINT("info",("Got error %d reading command from socket %s", net->error, vio_description(net->vio))); /* Instrument this broken statement as "statement/com/error" */ thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi, com_statement_info[COM_END]. m_key); /* Check if we can continue without closing the connection */ /* The error must be set. */ DBUG_ASSERT(thd->is_error()); thd->protocol->end_statement(); /* Mark the statement completed. */ MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da()); thd->m_statement_psi= NULL; if (net->error != 3) { return_value= TRUE; // We have to close it. goto out; } net->error= 0; return_value= FALSE; goto out; } packet= (char*) net->read_pos; /* 'packet_length' contains length of data, as it was stored in packet header. In case of malformed header, my_net_read returns zero. If packet_length is not zero, my_net_read ensures that the returned number of bytes was actually read from network. There is also an extra safety measure in my_net_read: it sets packet[packet_length]= 0, but only for non-zero packets. */ if (packet_length == 0) /* safety */ { /* Initialize with COM_SLEEP packet */ packet[0]= (uchar) COM_SLEEP; packet_length= 1; } /* Do not rely on my_net_read, extra safety against programming errors. */ packet[packet_length]= '\0'; /* safety */ command= (enum enum_server_command) (uchar) packet[0]; if (command >= COM_END) command= COM_END; // Wrong command DBUG_PRINT("info",("Command on %s = %d (%s)", vio_description(net->vio), command, command_name[command].str)); /* Restore read timeout value */ my_net_set_read_timeout(net, thd->variables.net_read_timeout); DBUG_ASSERT(packet_length); DBUG_ASSERT(!thd->apc_target.is_enabled()); return_value= dispatch_command(command, thd, packet+1, (uint) (packet_length-1)); DBUG_ASSERT(!thd->apc_target.is_enabled()); out: /* The statement instrumentation must be closed in all cases. */ DBUG_ASSERT(thd->m_statement_psi == NULL); DBUG_RETURN(return_value); } #endif /* EMBEDDED_LIBRARY */ /** @brief Determine if an attempt to update a non-temporary table while the read-only option was enabled has been made. This is a helper function to mysql_execute_command. @note SQLCOM_MULTI_UPDATE is an exception and delt with elsewhere. @see mysql_execute_command @returns Status code @retval TRUE The statement should be denied. @retval FALSE The statement isn't updating any relevant tables. */ static my_bool deny_updates_if_read_only_option(THD *thd, TABLE_LIST *all_tables) { DBUG_ENTER("deny_updates_if_read_only_option"); if (!opt_readonly) DBUG_RETURN(FALSE); LEX *lex= thd->lex; const my_bool user_is_super= ((ulong)(thd->security_ctx->master_access & SUPER_ACL) == (ulong)SUPER_ACL); if (user_is_super) DBUG_RETURN(FALSE); if (!(sql_command_flags[lex->sql_command] & CF_CHANGES_DATA)) DBUG_RETURN(FALSE); /* Multi update is an exception and is dealt with later. */ if (lex->sql_command == SQLCOM_UPDATE_MULTI) DBUG_RETURN(FALSE); const my_bool create_temp_tables= (lex->sql_command == SQLCOM_CREATE_TABLE) && lex->create_info.tmp_table(); const my_bool drop_temp_tables= (lex->sql_command == SQLCOM_DROP_TABLE) && lex->drop_temporary; const my_bool update_real_tables= some_non_temp_table_to_be_updated(thd, all_tables) && !(create_temp_tables || drop_temp_tables); const my_bool create_or_drop_databases= (lex->sql_command == SQLCOM_CREATE_DB) || (lex->sql_command == SQLCOM_DROP_DB); if (update_real_tables || create_or_drop_databases) { /* An attempt was made to modify one or more non-temporary tables. */ DBUG_RETURN(TRUE); } /* Assuming that only temporary tables are modified. */ DBUG_RETURN(FALSE); } /** Perform one connection-level (COM_XXXX) command. @param command type of command to perform @param thd connection handle @param packet data for the command, packet is always null-terminated @param packet_length length of packet + 1 (to show that data is null-terminated) except for COM_SLEEP, where it can be zero. @todo set thd->lex->sql_command to SQLCOM_END here. @todo The following has to be changed to an 8 byte integer @retval 0 ok @retval 1 request of thread shutdown, i. e. if command is COM_QUIT/COM_SHUTDOWN */ bool dispatch_command(enum enum_server_command command, THD *thd, char* packet, uint packet_length) { NET *net= &thd->net; bool error= 0; DBUG_ENTER("dispatch_command"); DBUG_PRINT("info", ("command: %d", command)); #if defined(ENABLED_PROFILING) thd->profiling.start_new_query(); #endif MYSQL_COMMAND_START(thd->thread_id, command, &thd->security_ctx->priv_user[0], (char *) thd->security_ctx->host_or_ip); DBUG_EXECUTE_IF("crash_dispatch_command_before", { DBUG_PRINT("crash_dispatch_command_before", ("now")); DBUG_ABORT(); }); /* Performance Schema Interface instrumentation, begin */ thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi, com_statement_info[command]. m_key); thd->set_command(command); /* Commands which always take a long time are logged into the slow log only if opt_log_slow_admin_statements is set. */ thd->enable_slow_log= TRUE; thd->query_plan_flags= QPLAN_INIT; thd->lex->sql_command= SQLCOM_END; /* to avoid confusing VIEW detectors */ DEBUG_SYNC(thd,"dispatch_command_before_set_time"); thd->set_time(); if (!(server_command_flags[command] & CF_SKIP_QUERY_ID)) thd->set_query_id(next_query_id()); else { /* ping, get statistics or similar stateless command. No reason to increase query id here. */ thd->set_query_id(get_query_id()); } inc_thread_running(); if (!(server_command_flags[command] & CF_SKIP_QUESTIONS)) statistic_increment(thd->status_var.questions, &LOCK_status); /* Copy data for user stats */ if ((thd->userstat_running= opt_userstat_running)) { thd->start_cpu_time= my_getcputime(); memcpy(&thd->org_status_var, &thd->status_var, sizeof(thd->status_var)); thd->select_commands= thd->update_commands= thd->other_commands= 0; } /** Clear the set of flags that are expected to be cleared at the beginning of each command. */ thd->server_status&= ~SERVER_STATUS_CLEAR_SET; switch (command) { case COM_INIT_DB: { LEX_STRING tmp; status_var_increment(thd->status_var.com_stat[SQLCOM_CHANGE_DB]); thd->convert_string(&tmp, system_charset_info, packet, packet_length, thd->charset()); if (!mysql_change_db(thd, &tmp, FALSE)) { general_log_write(thd, command, thd->db, thd->db_length); my_ok(thd); } break; } #ifdef HAVE_REPLICATION case COM_REGISTER_SLAVE: { if (!register_slave(thd, (uchar*)packet, packet_length)) my_ok(thd); break; } #endif case COM_CHANGE_USER: { int auth_rc; status_var_increment(thd->status_var.com_other); thd->change_user(); thd->clear_error(); // if errors from rollback /* acl_authenticate() takes the data from net->read_pos */ net->read_pos= (uchar*)packet; uint save_db_length= thd->db_length; char *save_db= thd->db; USER_CONN *save_user_connect= thd->user_connect; Security_context save_security_ctx= *thd->security_ctx; CHARSET_INFO *save_character_set_client= thd->variables.character_set_client; CHARSET_INFO *save_collation_connection= thd->variables.collation_connection; CHARSET_INFO *save_character_set_results= thd->variables.character_set_results; /* Ensure we don't free security_ctx->user in case we have to revert */ thd->security_ctx->user= 0; thd->user_connect= 0; /* to limit COM_CHANGE_USER ability to brute-force passwords, we only allow three unsuccessful COM_CHANGE_USER per connection. */ if (thd->failed_com_change_user >= 3) { my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); auth_rc= 1; } else auth_rc= acl_authenticate(thd, 0, packet_length); mysql_audit_notify_connection_change_user(thd); if (auth_rc) { /* Free user if allocated by acl_authenticate */ my_free(thd->security_ctx->user); *thd->security_ctx= save_security_ctx; if (thd->user_connect) decrease_user_connections(thd->user_connect); thd->user_connect= save_user_connect; thd->reset_db(save_db, save_db_length); thd->variables.character_set_client= save_character_set_client; thd->variables.collation_connection= save_collation_connection; thd->variables.character_set_results= save_character_set_results; thd->update_charset(); thd->failed_com_change_user++; my_sleep(1000000); } else { #ifndef NO_EMBEDDED_ACCESS_CHECKS /* we've authenticated new user */ if (save_user_connect) decrease_user_connections(save_user_connect); #endif /* NO_EMBEDDED_ACCESS_CHECKS */ my_free(save_db); my_free(save_security_ctx.user); } break; } case COM_STMT_EXECUTE: { mysqld_stmt_execute(thd, packet, packet_length); break; } case COM_STMT_FETCH: { mysqld_stmt_fetch(thd, packet, packet_length); break; } case COM_STMT_SEND_LONG_DATA: { mysql_stmt_get_longdata(thd, packet, packet_length); break; } case COM_STMT_PREPARE: { mysqld_stmt_prepare(thd, packet, packet_length); break; } case COM_STMT_CLOSE: { mysqld_stmt_close(thd, packet); break; } case COM_STMT_RESET: { mysqld_stmt_reset(thd, packet); break; } case COM_QUERY: { if (alloc_query(thd, packet, packet_length)) break; // fatal error is set MYSQL_QUERY_START(thd->query(), thd->thread_id, (char *) (thd->db ? thd->db : ""), &thd->security_ctx->priv_user[0], (char *) thd->security_ctx->host_or_ip); char *packet_end= thd->query() + thd->query_length(); general_log_write(thd, command, thd->query(), thd->query_length()); DBUG_PRINT("query",("%-.4096s",thd->query())); #if defined(ENABLED_PROFILING) thd->profiling.set_query_source(thd->query(), thd->query_length()); #endif MYSQL_SET_STATEMENT_TEXT(thd->m_statement_psi, thd->query(), thd->query_length()); Parser_state parser_state; if (parser_state.init(thd, thd->query(), thd->query_length())) break; mysql_parse(thd, thd->query(), thd->query_length(), &parser_state); while (!thd->killed && (parser_state.m_lip.found_semicolon != NULL) && ! thd->is_error()) { /* Multiple queries exist, execute them individually */ char *beginning_of_next_stmt= (char*) parser_state.m_lip.found_semicolon; #ifdef WITH_ARIA_STORAGE_ENGINE ha_maria::implicit_commit(thd, FALSE); #endif /* Finalize server status flags after executing a statement. */ thd->update_server_status(); thd->protocol->end_statement(); query_cache_end_of_result(thd); mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_STATUS, thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->sql_errno() : 0, command_name[command].str); ulong length= (ulong)(packet_end - beginning_of_next_stmt); log_slow_statement(thd); DBUG_ASSERT(!thd->apc_target.is_enabled()); /* Remove garbage at start of query */ while (length > 0 && my_isspace(thd->charset(), *beginning_of_next_stmt)) { beginning_of_next_stmt++; length--; } /* PSI end */ MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da()); thd->m_statement_psi= NULL; /* DTRACE end */ if (MYSQL_QUERY_DONE_ENABLED()) { MYSQL_QUERY_DONE(thd->is_error()); } #if defined(ENABLED_PROFILING) thd->profiling.finish_current_query(); thd->profiling.start_new_query("continuing"); thd->profiling.set_query_source(beginning_of_next_stmt, length); #endif /* DTRACE begin */ MYSQL_QUERY_START(beginning_of_next_stmt, thd->thread_id, (char *) (thd->db ? thd->db : ""), &thd->security_ctx->priv_user[0], (char *) thd->security_ctx->host_or_ip); /* PSI begin */ thd->m_statement_psi= MYSQL_START_STATEMENT(&thd->m_statement_state, com_statement_info[command].m_key, thd->db, thd->db_length, thd->charset()); THD_STAGE_INFO(thd, stage_init); MYSQL_SET_STATEMENT_TEXT(thd->m_statement_psi, beginning_of_next_stmt, length); thd->set_query_and_id(beginning_of_next_stmt, length, thd->charset(), next_query_id()); /* Count each statement from the client. */ statistic_increment(thd->status_var.questions, &LOCK_status); thd->set_time(); /* Reset the query start time. */ parser_state.reset(beginning_of_next_stmt, length); /* TODO: set thd->lex->sql_command to SQLCOM_END here */ mysql_parse(thd, beginning_of_next_stmt, length, &parser_state); } DBUG_PRINT("info",("query ready")); break; } case COM_FIELD_LIST: // This isn't actually needed #ifdef DONT_ALLOW_SHOW_COMMANDS my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */ break; #else { char *fields, *packet_end= packet + packet_length, *arg_end; /* Locked closure of all tables */ TABLE_LIST table_list; LEX_STRING table_name; LEX_STRING db; /* SHOW statements should not add the used tables to the list of tables used in a transaction. */ MDL_savepoint mdl_savepoint= thd->mdl_context.mdl_savepoint(); status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_FIELDS]); if (thd->copy_db_to(&db.str, &db.length)) break; /* We have name + wildcard in packet, separated by endzero (The packet is guaranteed to end with an end zero) */ arg_end= strend(packet); uint arg_length= arg_end - packet; /* Check given table name length. */ if (packet_length - arg_length > NAME_LEN + 1 || arg_length > SAFE_NAME_LEN) { my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); break; } thd->convert_string(&table_name, system_charset_info, packet, arg_length, thd->charset()); if (check_table_name(table_name.str, table_name.length, FALSE)) { /* this is OK due to convert_string() null-terminating the string */ my_error(ER_WRONG_TABLE_NAME, MYF(0), table_name.str); break; } packet= arg_end + 1; mysql_reset_thd_for_next_command(thd); lex_start(thd); /* Must be before we init the table list. */ if (lower_case_table_names) { table_name.length= my_casedn_str(files_charset_info, table_name.str); db.length= my_casedn_str(files_charset_info, db.str); } table_list.init_one_table(db.str, db.length, table_name.str, table_name.length, table_name.str, TL_READ); /* Init TABLE_LIST members necessary when the undelrying table is view. */ table_list.select_lex= &(thd->lex->select_lex); thd->lex-> select_lex.table_list.link_in_list(&table_list, &table_list.next_local); thd->lex->add_to_query_tables(&table_list); if (is_infoschema_db(table_list.db, table_list.db_length)) { ST_SCHEMA_TABLE *schema_table= find_schema_table(thd, table_list.alias); if (schema_table) table_list.schema_table= schema_table; } uint query_length= (uint) (packet_end - packet); // Don't count end \0 if (!(fields= (char *) thd->memdup(packet, query_length + 1))) break; thd->set_query(fields, query_length); general_log_print(thd, command, "%s %s", table_list.table_name, fields); if (open_temporary_tables(thd, &table_list)) break; if (check_table_access(thd, SELECT_ACL, &table_list, TRUE, UINT_MAX, FALSE)) break; /* Turn on an optimization relevant if the underlying table is a view: do not fill derived tables. */ thd->lex->sql_command= SQLCOM_SHOW_FIELDS; mysqld_list_fields(thd,&table_list,fields); thd->lex->unit.cleanup(); /* No need to rollback statement transaction, it's not started. */ DBUG_ASSERT(thd->transaction.stmt.is_empty()); close_thread_tables(thd); thd->mdl_context.rollback_to_savepoint(mdl_savepoint); if (thd->transaction_rollback_request) { /* Transaction rollback was requested since MDL deadlock was discovered while trying to open tables. Rollback transaction in all storage engines including binary log and release all locks. */ trans_rollback_implicit(thd); thd->mdl_context.release_transactional_locks(); } thd->cleanup_after_query(); break; } #endif case COM_QUIT: /* We don't calculate statistics for this command */ general_log_print(thd, command, NullS); net->error=0; // Don't give 'abort' message thd->get_stmt_da()->disable_status(); // Don't send anything back error=TRUE; // End server break; #ifndef EMBEDDED_LIBRARY case COM_BINLOG_DUMP: { ulong pos; ushort flags; uint32 slave_server_id; status_var_increment(thd->status_var.com_other); thd->enable_slow_log= opt_log_slow_admin_statements; thd->query_plan_flags|= QPLAN_ADMIN; if (check_global_access(thd, REPL_SLAVE_ACL)) break; /* TODO: The following has to be changed to an 8 byte integer */ pos = uint4korr(packet); flags = uint2korr(packet + 4); thd->variables.server_id=0; /* avoid suicide */ if ((slave_server_id= uint4korr(packet+6))) // mysqlbinlog.server_id==0 kill_zombie_dump_threads(slave_server_id); thd->variables.server_id = slave_server_id; general_log_print(thd, command, "Log: '%s' Pos: %ld", packet+10, (long) pos); mysql_binlog_send(thd, thd->strdup(packet + 10), (my_off_t) pos, flags); unregister_slave(thd,1,1); /* fake COM_QUIT -- if we get here, the thread needs to terminate */ error = TRUE; break; } #endif case COM_REFRESH: { int not_used; /* Initialize thd->lex since it's used in many base functions, such as open_tables(). Otherwise, it remains unitialized and may cause crash during execution of COM_REFRESH. */ lex_start(thd); status_var_increment(thd->status_var.com_stat[SQLCOM_FLUSH]); ulonglong options= (ulonglong) (uchar) packet[0]; if (trans_commit_implicit(thd)) break; thd->mdl_context.release_transactional_locks(); if (check_global_access(thd,RELOAD_ACL)) break; general_log_print(thd, command, NullS); #ifndef DBUG_OFF bool debug_simulate= FALSE; DBUG_EXECUTE_IF("simulate_detached_thread_refresh", debug_simulate= TRUE;); if (debug_simulate) { /* Simulate a reload without a attached thread session. Provides a environment similar to that of when the server receives a SIGHUP signal and reloads caches and flushes tables. */ bool res; set_current_thd(0); res= reload_acl_and_cache(NULL, options | REFRESH_FAST, NULL, &not_used); set_current_thd(thd); if (res) break; } else #endif { thd->lex->relay_log_connection_name.str= (char*) ""; thd->lex->relay_log_connection_name.length= 0; if (reload_acl_and_cache(thd, options, (TABLE_LIST*) 0, &not_used)) break; } if (trans_commit_implicit(thd)) break; close_thread_tables(thd); thd->mdl_context.release_transactional_locks(); my_ok(thd); break; } #ifndef EMBEDDED_LIBRARY case COM_SHUTDOWN: { status_var_increment(thd->status_var.com_other); if (check_global_access(thd,SHUTDOWN_ACL)) break; /* purecov: inspected */ /* If the client is < 4.1.3, it is going to send us no argument; then packet_length is 0, packet[0] is the end 0 of the packet. Note that SHUTDOWN_DEFAULT is 0. If client is >= 4.1.3, the shutdown level is in packet[0]. */ enum mysql_enum_shutdown_level level; level= (enum mysql_enum_shutdown_level) (uchar) packet[0]; if (level == SHUTDOWN_DEFAULT) level= SHUTDOWN_WAIT_ALL_BUFFERS; // soon default will be configurable else if (level != SHUTDOWN_WAIT_ALL_BUFFERS) { my_error(ER_NOT_SUPPORTED_YET, MYF(0), "this shutdown level"); break; } DBUG_PRINT("quit",("Got shutdown command for level %u", level)); general_log_print(thd, command, NullS); my_eof(thd); kill_mysql(); error=TRUE; break; } #endif case COM_STATISTICS: { STATUS_VAR *current_global_status_var; // Big; Don't allocate on stack ulong uptime; uint length __attribute__((unused)); ulonglong queries_per_second1000; char buff[250]; uint buff_len= sizeof(buff); if (!(current_global_status_var= (STATUS_VAR*) thd->alloc(sizeof(STATUS_VAR)))) break; general_log_print(thd, command, NullS); status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_STATUS]); calc_sum_of_all_status(current_global_status_var); if (!(uptime= (ulong) (thd->start_time - server_start_time))) queries_per_second1000= 0; else queries_per_second1000= thd->query_id * 1000 / uptime; length= my_snprintf(buff, buff_len - 1, "Uptime: %lu Threads: %d Questions: %lu " "Slow queries: %lu Opens: %lu Flush tables: %lu " "Open tables: %u Queries per second avg: %u.%03u", uptime, (int) thread_count, (ulong) thd->query_id, current_global_status_var->long_query_count, current_global_status_var->opened_tables, tdc_refresh_version(), tc_records(), (uint) (queries_per_second1000 / 1000), (uint) (queries_per_second1000 % 1000)); #ifdef EMBEDDED_LIBRARY /* Store the buffer in permanent memory */ my_ok(thd, 0, 0, buff); #else (void) my_net_write(net, (uchar*) buff, length); (void) net_flush(net); thd->get_stmt_da()->disable_status(); #endif break; } case COM_PING: status_var_increment(thd->status_var.com_other); my_ok(thd); // Tell client we are alive break; case COM_PROCESS_INFO: status_var_increment(thd->status_var.com_stat[SQLCOM_SHOW_PROCESSLIST]); if (!thd->security_ctx->priv_user[0] && check_global_access(thd, PROCESS_ACL)) break; general_log_print(thd, command, NullS); mysqld_list_processes(thd, thd->security_ctx->master_access & PROCESS_ACL ? NullS : thd->security_ctx->priv_user, 0); break; case COM_PROCESS_KILL: { status_var_increment(thd->status_var.com_stat[SQLCOM_KILL]); ulong id=(ulong) uint4korr(packet); sql_kill(thd, id, KILL_CONNECTION_HARD, KILL_TYPE_ID); break; } case COM_SET_OPTION: { status_var_increment(thd->status_var.com_stat[SQLCOM_SET_OPTION]); uint opt_command= uint2korr(packet); switch (opt_command) { case (int) MYSQL_OPTION_MULTI_STATEMENTS_ON: thd->client_capabilities|= CLIENT_MULTI_STATEMENTS; my_eof(thd); break; case (int) MYSQL_OPTION_MULTI_STATEMENTS_OFF: thd->client_capabilities&= ~CLIENT_MULTI_STATEMENTS; my_eof(thd); break; default: my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); break; } break; } case COM_DEBUG: status_var_increment(thd->status_var.com_other); if (check_global_access(thd, SUPER_ACL)) break; /* purecov: inspected */ mysql_print_status(); general_log_print(thd, command, NullS); my_eof(thd); break; case COM_SLEEP: case COM_CONNECT: // Impossible here case COM_TIME: // Impossible from client case COM_DELAYED_INSERT: case COM_END: default: my_message(ER_UNKNOWN_COM_ERROR, ER(ER_UNKNOWN_COM_ERROR), MYF(0)); break; } DBUG_ASSERT(thd->derived_tables == NULL && (thd->open_tables == NULL || (thd->locked_tables_mode == LTM_LOCK_TABLES))); thd_proc_info(thd, "updating status"); /* Finalize server status flags after executing a command. */ thd->update_server_status(); thd->protocol->end_statement(); query_cache_end_of_result(thd); if (!thd->is_error() && !thd->killed_errno()) mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_RESULT, 0, 0); mysql_audit_general(thd, MYSQL_AUDIT_GENERAL_STATUS, thd->get_stmt_da()->is_error() ? thd->get_stmt_da()->sql_errno() : 0, command_name[command].str); thd->update_all_stats(); log_slow_statement(thd); THD_STAGE_INFO(thd, stage_cleaning_up); thd->reset_query(); thd->set_examined_row_count(0); // For processlist thd->set_command(COM_SLEEP); /* Performance Schema Interface instrumentation, end */ MYSQL_END_STATEMENT(thd->m_statement_psi, thd->get_stmt_da()); thd->m_statement_psi= NULL; thd->set_time(); dec_thread_running(); thd->packet.shrink(thd->variables.net_buffer_length); // Reclaim some memory free_root(thd->mem_root,MYF(MY_KEEP_PREALLOC)); #if defined(ENABLED_PROFILING) thd->profiling.finish_current_query(); #endif if (MYSQL_QUERY_DONE_ENABLED() || MYSQL_COMMAND_DONE_ENABLED()) { int res __attribute__((unused)); res= (int) thd->is_error(); if (command == COM_QUERY) { MYSQL_QUERY_DONE(res); } MYSQL_COMMAND_DONE(res); } /* Check that some variables are reset properly */ DBUG_ASSERT(thd->abort_on_warning == 0); DBUG_RETURN(error); } /* @note This function must call delete_explain_query(). */ void log_slow_statement(THD *thd) { DBUG_ENTER("log_slow_statement"); /* The following should never be true with our current code base, but better to keep this here so we don't accidently try to log a statement in a trigger or stored function */ if (unlikely(thd->in_sub_stmt)) goto end; // Don't set time for sub stmt /* Follow the slow log filter configuration. */ if (!thd->enable_slow_log || (thd->variables.log_slow_filter && !(thd->variables.log_slow_filter & thd->query_plan_flags))) { goto end; } if (((thd->server_status & SERVER_QUERY_WAS_SLOW) || ((thd->server_status & (SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED)) && opt_log_queries_not_using_indexes && !(sql_command_flags[thd->lex->sql_command] & CF_STATUS_COMMAND))) && thd->get_examined_row_count() >= thd->variables.min_examined_row_limit) { thd->status_var.long_query_count++; /* If rate limiting of slow log writes is enabled, decide whether to log this query to the log or not. */ if (thd->variables.log_slow_rate_limit > 1 && (global_query_id % thd->variables.log_slow_rate_limit) != 0) goto end; THD_STAGE_INFO(thd, stage_logging_slow_query); slow_log_print(thd, thd->query(), thd->query_length(), thd->utime_after_query); } end: delete_explain_query(thd->lex); DBUG_VOID_RETURN; } /** Create a TABLE_LIST object for an INFORMATION_SCHEMA table. This function is used in the parser to convert a SHOW or DESCRIBE table_name command to a SELECT from INFORMATION_SCHEMA. It prepares a SELECT_LEX and a TABLE_LIST object to represent the given command as a SELECT parse tree. @param thd thread handle @param lex current lex @param table_ident table alias if it's used @param schema_table_idx the type of the INFORMATION_SCHEMA table to be created @note Due to the way this function works with memory and LEX it cannot be used outside the parser (parse tree transformations outside the parser break PS and SP). @retval 0 success @retval 1 out of memory or SHOW commands are not allowed in this version of the server. */ int prepare_schema_table(THD *thd, LEX *lex, Table_ident *table_ident, enum enum_schema_tables schema_table_idx) { SELECT_LEX *schema_select_lex= NULL; DBUG_ENTER("prepare_schema_table"); switch (schema_table_idx) { case SCH_SCHEMATA: #if defined(DONT_ALLOW_SHOW_COMMANDS) my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */ DBUG_RETURN(1); #else break; #endif case SCH_TABLE_NAMES: case SCH_TABLES: case SCH_VIEWS: case SCH_TRIGGERS: case SCH_EVENTS: #ifdef DONT_ALLOW_SHOW_COMMANDS my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */ DBUG_RETURN(1); #else { LEX_STRING db; size_t dummy; if (lex->select_lex.db == NULL && lex->copy_db_to(&lex->select_lex.db, &dummy)) { DBUG_RETURN(1); } schema_select_lex= new SELECT_LEX(); db.str= schema_select_lex->db= lex->select_lex.db; schema_select_lex->table_list.first= NULL; db.length= strlen(db.str); if (check_db_name(&db)) { my_error(ER_WRONG_DB_NAME, MYF(0), db.str); DBUG_RETURN(1); } break; } #endif case SCH_COLUMNS: case SCH_STATISTICS: { #ifdef DONT_ALLOW_SHOW_COMMANDS my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */ DBUG_RETURN(1); #else DBUG_ASSERT(table_ident); TABLE_LIST **query_tables_last= lex->query_tables_last; schema_select_lex= new SELECT_LEX(); /* 'parent_lex' is used in init_query() so it must be before it. */ schema_select_lex->parent_lex= lex; schema_select_lex->init_query(); if (!schema_select_lex->add_table_to_list(thd, table_ident, 0, 0, TL_READ, MDL_SHARED_READ)) DBUG_RETURN(1); lex->query_tables_last= query_tables_last; break; #endif } case SCH_PROFILES: /* Mark this current profiling record to be discarded. We don't wish to have SHOW commands show up in profiling. */ #if defined(ENABLED_PROFILING) thd->profiling.discard_current_query(); #endif break; case SCH_USER_STATS: case SCH_CLIENT_STATS: if (check_global_access(thd, SUPER_ACL | PROCESS_ACL, true)) DBUG_RETURN(1); case SCH_TABLE_STATS: case SCH_INDEX_STATS: case SCH_OPEN_TABLES: case SCH_VARIABLES: case SCH_STATUS: case SCH_PROCEDURES: case SCH_CHARSETS: case SCH_ENGINES: case SCH_COLLATIONS: case SCH_COLLATION_CHARACTER_SET_APPLICABILITY: case SCH_USER_PRIVILEGES: case SCH_SCHEMA_PRIVILEGES: case SCH_TABLE_PRIVILEGES: case SCH_COLUMN_PRIVILEGES: case SCH_TABLE_CONSTRAINTS: case SCH_KEY_COLUMN_USAGE: default: break; } SELECT_LEX *select_lex= lex->current_select; if (make_schema_select(thd, select_lex, schema_table_idx)) { DBUG_RETURN(1); } TABLE_LIST *table_list= select_lex->table_list.first; table_list->schema_select_lex= schema_select_lex; table_list->schema_table_reformed= 1; DBUG_RETURN(0); } /** Read query from packet and store in thd->query. Used in COM_QUERY and COM_STMT_PREPARE. Sets the following THD variables: - query - query_length @retval FALSE ok @retval TRUE error; In this case thd->fatal_error is set */ bool alloc_query(THD *thd, const char *packet, uint packet_length) { char *query; /* Remove garbage at start and end of query */ while (packet_length > 0 && my_isspace(thd->charset(), packet[0])) { packet++; packet_length--; } const char *pos= packet + packet_length; // Point at end null while (packet_length > 0 && (pos[-1] == ';' || my_isspace(thd->charset() ,pos[-1]))) { pos--; packet_length--; } /* We must allocate some extra memory for query cache The query buffer layout is: buffer :== <statement> The input statement(s) '\0' Terminating null char (1 byte) <length> Length of following current database name (size_t) <db_name> Name of current database <flags> Flags struct */ if (! (query= (char*) thd->memdup_w_gap(packet, packet_length, 1 + thd->db_length + QUERY_CACHE_DB_LENGTH_SIZE + QUERY_CACHE_FLAGS_SIZE))) return TRUE; query[packet_length]= '\0'; /* Space to hold the name of the current database is allocated. We also store this length, in case current database is changed during execution. We might need to reallocate the 'query' buffer */ int2store(query + packet_length + 1, thd->db_length); thd->set_query(query, packet_length); /* Reclaim some memory */ thd->packet.shrink(thd->variables.net_buffer_length); thd->convert_buffer.shrink(thd->variables.net_buffer_length); return FALSE; } static void reset_one_shot_variables(THD *thd) { thd->variables.character_set_client= global_system_variables.character_set_client; thd->variables.collation_connection= global_system_variables.collation_connection; thd->variables.collation_database= global_system_variables.collation_database; thd->variables.collation_server= global_system_variables.collation_server; thd->update_charset(); thd->variables.time_zone= global_system_variables.time_zone; thd->variables.lc_time_names= &my_locale_en_US; thd->one_shot_set= 0; } bool sp_process_definer(THD *thd) { DBUG_ENTER("sp_process_definer"); LEX *lex= thd->lex; /* If the definer is not specified, this means that CREATE-statement missed DEFINER-clause. DEFINER-clause can be missed in two cases: - The user submitted a statement w/o the clause. This is a normal case, we should assign CURRENT_USER as definer. - Our slave received an updated from the master, that does not replicate definer for stored rountines. We should also assign CURRENT_USER as definer here, but also we should mark this routine as NON-SUID. This is essential for the sake of backward compatibility. The problem is the slave thread is running under "special" user (@), that actually does not exist. In the older versions we do not fail execution of a stored routine if its definer does not exist and continue the execution under the authorization of the invoker (BUG#13198). And now if we try to switch to slave-current-user (@), we will fail. Actually, this leads to the inconsistent state of master and slave (different definers, different SUID behaviour), but it seems, this is the best we can do. */ if (!lex->definer) { Query_arena original_arena; Query_arena *ps_arena= thd->activate_stmt_arena_if_needed(&original_arena); lex->definer= create_default_definer(thd, false); if (ps_arena) thd->restore_active_arena(ps_arena, &original_arena); /* Error has been already reported. */ if (lex->definer == NULL) DBUG_RETURN(TRUE); if (thd->slave_thread && lex->sphead) lex->sphead->m_chistics->suid= SP_IS_NOT_SUID; } else { LEX_USER *d= lex->definer= get_current_user(thd, lex->definer); if (!d) DBUG_RETURN(TRUE); /* If the specified definer differs from the current user or role, we should check that the current user has SUPER privilege (in order to create a stored routine under another user one must have SUPER privilege). */ bool curuser= !strcmp(d->user.str, thd->security_ctx->priv_user); bool currole= !curuser && !strcmp(d->user.str, thd->security_ctx->priv_role); bool curuserhost= curuser && d->host.str && !my_strcasecmp(system_charset_info, d->host.str, thd->security_ctx->priv_host); if (!curuserhost && !currole && check_global_access(thd, SUPER_ACL, false)) DBUG_RETURN(TRUE); } /* Check that the specified definer exists. Emit a warning if not. */ #ifndef NO_EMBEDDED_ACCESS_CHECKS if (!is_acl_user(lex->definer->host.str, lex->definer->user.str)) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_NO_SUCH_USER, ER(ER_NO_SUCH_USER), lex->definer->user.str, lex->definer->host.str); } #endif /* NO_EMBEDDED_ACCESS_CHECKS */ DBUG_RETURN(FALSE); } /** Auxiliary call that opens and locks tables for LOCK TABLES statement and initializes the list of locked tables. @param thd Thread context. @param tables List of tables to be locked. @return FALSE in case of success, TRUE in case of error. */ static bool lock_tables_open_and_lock_tables(THD *thd, TABLE_LIST *tables) { Lock_tables_prelocking_strategy lock_tables_prelocking_strategy; uint counter; TABLE_LIST *table; thd->in_lock_tables= 1; if (open_tables(thd, &tables, &counter, 0, &lock_tables_prelocking_strategy)) goto err; /* We allow to change temporary tables even if they were locked for read by LOCK TABLES. To avoid a discrepancy between lock acquired at LOCK TABLES time and by the statement which is later executed under LOCK TABLES we ensure that for temporary tables we always request a write lock (such discrepancy can cause problems for the storage engine). We don't set TABLE_LIST::lock_type in this case as this might result in extra warnings from THD::decide_logging_format() even though binary logging is totally irrelevant for LOCK TABLES. */ for (table= tables; table; table= table->next_global) if (!table->placeholder() && table->table->s->tmp_table) table->table->reginfo.lock_type= TL_WRITE; if (lock_tables(thd, tables, counter, 0) || thd->locked_tables_list.init_locked_tables(thd)) goto err; thd->in_lock_tables= 0; return FALSE; err: thd->in_lock_tables= 0; trans_rollback_stmt(thd); /* Need to end the current transaction, so the storage engine (InnoDB) can free its locks if LOCK TABLES locked some tables before finding that it can't lock a table in its list */ trans_rollback(thd); /* Close tables and release metadata locks. */ close_thread_tables(thd); DBUG_ASSERT(!thd->locked_tables_mode); thd->mdl_context.release_transactional_locks(); return TRUE; } /** Execute command saved in thd and lex->sql_command. @param thd Thread handle @todo - Invalidate the table in the query cache if something changed after unlocking when changes become visible. TODO: this is workaround. right way will be move invalidating in the unlock procedure. - TODO: use check_change_password() @retval FALSE OK @retval TRUE Error */ int mysql_execute_command(THD *thd) { int res= FALSE; int up_result= 0; LEX *lex= thd->lex; /* first SELECT_LEX (have special meaning for many of non-SELECTcommands) */ SELECT_LEX *select_lex= &lex->select_lex; /* first table of first SELECT_LEX */ TABLE_LIST *first_table= select_lex->table_list.first; /* list of all tables in query */ TABLE_LIST *all_tables; /* most outer SELECT_LEX_UNIT of query */ SELECT_LEX_UNIT *unit= &lex->unit; #ifdef HAVE_REPLICATION /* have table map for update for multi-update statement (BUG#37051) */ bool have_table_map_for_update= FALSE; /* */ Rpl_filter *rpl_filter= thd->rpl_filter; #endif DBUG_ENTER("mysql_execute_command"); #ifdef WITH_PARTITION_STORAGE_ENGINE thd->work_part_info= 0; #endif DBUG_ASSERT(thd->transaction.stmt.is_empty() || thd->in_sub_stmt); /* Each statement or replication event which might produce deadlock should handle transaction rollback on its own. So by the start of the next statement transaction rollback request should be fulfilled already. */ DBUG_ASSERT(! thd->transaction_rollback_request || thd->in_sub_stmt); /* In many cases first table of main SELECT_LEX have special meaning => check that it is first table in global list and relink it first in queries_tables list if it is necessary (we need such relinking only for queries with subqueries in select list, in this case tables of subqueries will go to global list first) all_tables will differ from first_table only if most upper SELECT_LEX do not contain tables. Because of above in place where should be at least one table in most outer SELECT_LEX we have following check: DBUG_ASSERT(first_table == all_tables); DBUG_ASSERT(first_table == all_tables && first_table != 0); */ lex->first_lists_tables_same(); /* should be assigned after making first tables same */ all_tables= lex->query_tables; /* set context for commands which do not use setup_tables */ select_lex-> context.resolve_in_table_list_only(select_lex-> table_list.first); /* Reset warning count for each query that uses tables A better approach would be to reset this for any commands that is not a SHOW command or a select that only access local variables, but for now this is probably good enough. */ if ((sql_command_flags[lex->sql_command] & CF_DIAGNOSTIC_STMT) != 0) thd->get_stmt_da()->set_warning_info_read_only(TRUE); else { thd->get_stmt_da()->set_warning_info_read_only(FALSE); if (all_tables) thd->get_stmt_da()->opt_clear_warning_info(thd->query_id); } #ifdef HAVE_REPLICATION if (unlikely(thd->slave_thread)) { if (lex->sql_command == SQLCOM_DROP_TRIGGER) { /* When dropping a trigger, we need to load its table name before checking slave filter rules. */ add_table_for_trigger(thd, thd->lex->spname, 1, &all_tables); if (!all_tables) { /* If table name cannot be loaded, it means the trigger does not exists possibly because CREATE TRIGGER was previously skipped for this trigger according to slave filtering rules. Returning success without producing any errors in this case. */ DBUG_RETURN(0); } // force searching in slave.cc:tables_ok() all_tables->updating= 1; } /* For fix of BUG#37051, the master stores the table map for update in the Query_log_event, and the value is assigned to thd->variables.table_map_for_update before executing the update query. If thd->variables.table_map_for_update is set, then we are replicating from a new master, we can use this value to apply filter rules without opening all the tables. However If thd->variables.table_map_for_update is not set, then we are replicating from an old master, so we just skip this and continue with the old method. And of course, the bug would still exist for old masters. */ if (lex->sql_command == SQLCOM_UPDATE_MULTI && thd->table_map_for_update) { have_table_map_for_update= TRUE; table_map table_map_for_update= thd->table_map_for_update; uint nr= 0; TABLE_LIST *table; for (table=all_tables; table; table=table->next_global, nr++) { if (table_map_for_update & ((table_map)1 << nr)) table->updating= TRUE; else table->updating= FALSE; } if (all_tables_not_ok(thd, all_tables)) { /* we warn the slave SQL thread */ my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); if (thd->one_shot_set) reset_one_shot_variables(thd); DBUG_RETURN(0); } for (table=all_tables; table; table=table->next_global) table->updating= TRUE; } /* Check if statment should be skipped because of slave filtering rules Exceptions are: - UPDATE MULTI: For this statement, we want to check the filtering rules later in the code - SET: we always execute it (Not that many SET commands exists in the binary log anyway -- only 4.1 masters write SET statements, in 5.0 there are no SET statements in the binary log) - DROP TEMPORARY TABLE IF EXISTS: we always execute it (otherwise we have stale files on slave caused by exclusion of one tmp table). */ if (!(lex->sql_command == SQLCOM_UPDATE_MULTI) && !(lex->sql_command == SQLCOM_SET_OPTION) && !(lex->sql_command == SQLCOM_DROP_TABLE && lex->drop_temporary && lex->check_exists) && all_tables_not_ok(thd, all_tables)) { /* we warn the slave SQL thread */ my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); if (thd->one_shot_set) { /* It's ok to check thd->one_shot_set here: The charsets in a MySQL 5.0 slave can change by both a binlogged SET ONE_SHOT statement and the event-internal charset setting, and these two ways to change charsets do not seems to work together. At least there seems to be problems in the rli cache for charsets if we are using ONE_SHOT. Note that this is normally no problem because either the >= 5.0 slave reads a 4.1 binlog (with ONE_SHOT) *or* or 5.0 binlog (without ONE_SHOT) but never both." */ reset_one_shot_variables(thd); } DBUG_RETURN(0); } /* Execute deferred events first */ if (slave_execute_deferred_events(thd)) DBUG_RETURN(-1); } else { #endif /* HAVE_REPLICATION */ /* When option readonly is set deny operations which change non-temporary tables. Except for the replication thread and the 'super' users. */ if (deny_updates_if_read_only_option(thd, all_tables)) { my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only"); DBUG_RETURN(-1); } #ifdef HAVE_REPLICATION } /* endif unlikely slave */ #endif status_var_increment(thd->status_var.com_stat[lex->sql_command]); thd->progress.report_to_client= MY_TEST(sql_command_flags[lex->sql_command] & CF_REPORT_PROGRESS); DBUG_ASSERT(thd->transaction.stmt.modified_non_trans_table == FALSE); /* store old value of binlog format */ enum_binlog_format orig_binlog_format,orig_current_stmt_binlog_format; thd->get_binlog_format(&orig_binlog_format, &orig_current_stmt_binlog_format); /* Force statement logging for DDL commands to allow us to update privilege, system or statistic tables directly without the updates getting logged. */ if (!(sql_command_flags[lex->sql_command] & (CF_CAN_GENERATE_ROW_EVENTS | CF_FORCE_ORIGINAL_BINLOG_FORMAT | CF_STATUS_COMMAND))) thd->set_binlog_format_stmt(); /* End a active transaction so that this command will have it's own transaction and will also sync the binary log. If a DDL is not run in it's own transaction it may simply never appear on the slave in case the outside transaction rolls back. */ if (stmt_causes_implicit_commit(thd, CF_IMPLICT_COMMIT_BEGIN)) { /* Note that this should never happen inside of stored functions or triggers as all such statements prohibited there. */ DBUG_ASSERT(! thd->in_sub_stmt); /* Statement transaction still should not be started. */ DBUG_ASSERT(thd->transaction.stmt.is_empty()); if (!(thd->variables.option_bits & OPTION_GTID_BEGIN)) { /* Commit the normal transaction if one is active. */ if (trans_commit_implicit(thd)) goto error; /* Release metadata locks acquired in this transaction. */ thd->mdl_context.release_transactional_locks(); } } #ifndef DBUG_OFF if (lex->sql_command != SQLCOM_SET_OPTION) DEBUG_SYNC(thd,"before_execute_sql_command"); #endif /* Check if we are in a read-only transaction and we're trying to execute a statement which should always be disallowed in such cases. Note that this check is done after any implicit commits. */ if (thd->tx_read_only && (sql_command_flags[lex->sql_command] & CF_DISALLOW_IN_RO_TRANS)) { my_error(ER_CANT_EXECUTE_IN_READ_ONLY_TRANSACTION, MYF(0)); goto error; } /* Close tables open by HANDLERs before executing DDL statement which is going to affect those tables. This should happen before temporary tables are pre-opened as otherwise we will get errors about attempt to re-open tables if table to be changed is open through HANDLER. Note that even although this is done before any privilege checks there is no security problem here as closing open HANDLER doesn't require any privileges anyway. */ if (sql_command_flags[lex->sql_command] & CF_HA_CLOSE) mysql_ha_rm_tables(thd, all_tables); /* Pre-open temporary tables to simplify privilege checking for statements which need this. */ if (sql_command_flags[lex->sql_command] & CF_PREOPEN_TMP_TABLES) { if (open_temporary_tables(thd, all_tables)) goto error; } switch (lex->sql_command) { case SQLCOM_SHOW_EVENTS: #ifndef HAVE_EVENT_SCHEDULER my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server"); break; #endif case SQLCOM_SHOW_STATUS: { execute_show_status(thd, all_tables); break; } case SQLCOM_SHOW_EXPLAIN: { if (!thd->security_ctx->priv_user[0] && check_global_access(thd,PROCESS_ACL)) break; /* The select should use only one table, it's the SHOW EXPLAIN pseudo-table */ if (lex->sroutines.records || lex->query_tables->next_global) { my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY), MYF(0)); goto error; } Item **it= lex->value_list.head_ref(); if (!(*it)->basic_const_item() || (!(*it)->fixed && (*it)->fix_fields(lex->thd, it)) || (*it)->check_cols(1)) { my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY), MYF(0)); goto error; } /* no break; fall through */ } case SQLCOM_SHOW_STATUS_PROC: case SQLCOM_SHOW_STATUS_FUNC: case SQLCOM_SHOW_DATABASES: case SQLCOM_SHOW_TABLES: case SQLCOM_SHOW_TRIGGERS: case SQLCOM_SHOW_TABLE_STATUS: case SQLCOM_SHOW_OPEN_TABLES: case SQLCOM_SHOW_PLUGINS: case SQLCOM_SHOW_FIELDS: case SQLCOM_SHOW_KEYS: case SQLCOM_SHOW_VARIABLES: case SQLCOM_SHOW_CHARSETS: case SQLCOM_SHOW_COLLATIONS: case SQLCOM_SHOW_STORAGE_ENGINES: case SQLCOM_SHOW_PROFILE: case SQLCOM_SHOW_CLIENT_STATS: case SQLCOM_SHOW_USER_STATS: case SQLCOM_SHOW_TABLE_STATS: case SQLCOM_SHOW_INDEX_STATS: case SQLCOM_SELECT: { thd->status_var.last_query_cost= 0.0; /* lex->exchange != NULL implies SELECT .. INTO OUTFILE and this requires FILE_ACL access. */ ulong privileges_requested= lex->exchange ? SELECT_ACL | FILE_ACL : SELECT_ACL; if (all_tables) res= check_table_access(thd, privileges_requested, all_tables, FALSE, UINT_MAX, FALSE); else res= check_access(thd, privileges_requested, any_db, NULL, NULL, 0, 0); if (res) break; res= execute_sqlcom_select(thd, all_tables); break; } case SQLCOM_PREPARE: { mysql_sql_stmt_prepare(thd); break; } case SQLCOM_EXECUTE: { mysql_sql_stmt_execute(thd); break; } case SQLCOM_DEALLOCATE_PREPARE: { mysql_sql_stmt_close(thd); break; } case SQLCOM_DO: if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE) || open_and_lock_tables(thd, all_tables, TRUE, 0)) goto error; res= mysql_do(thd, *lex->insert_list); break; case SQLCOM_EMPTY_QUERY: my_ok(thd); break; case SQLCOM_HELP: res= mysqld_help(thd,lex->help_arg); break; #ifndef EMBEDDED_LIBRARY case SQLCOM_PURGE: { if (check_global_access(thd, SUPER_ACL)) goto error; /* PURGE MASTER LOGS TO 'file' */ res = purge_master_logs(thd, lex->to_log); break; } case SQLCOM_PURGE_BEFORE: { Item *it; if (check_global_access(thd, SUPER_ACL)) goto error; /* PURGE MASTER LOGS BEFORE 'data' */ it= (Item *)lex->value_list.head(); if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1)) { my_error(ER_WRONG_ARGUMENTS, MYF(0), "PURGE LOGS BEFORE"); goto error; } it= new Item_func_unix_timestamp(it); it->fix_fields(thd, &it); res = purge_master_logs_before_date(thd, (ulong)it->val_int()); break; } #endif case SQLCOM_SHOW_WARNS: { res= mysqld_show_warnings(thd, (ulong) ((1L << (uint) Sql_condition::WARN_LEVEL_NOTE) | (1L << (uint) Sql_condition::WARN_LEVEL_WARN) | (1L << (uint) Sql_condition::WARN_LEVEL_ERROR) )); break; } case SQLCOM_SHOW_ERRORS: { res= mysqld_show_warnings(thd, (ulong) (1L << (uint) Sql_condition::WARN_LEVEL_ERROR)); break; } case SQLCOM_SHOW_PROFILES: { #if defined(ENABLED_PROFILING) thd->profiling.discard_current_query(); res= thd->profiling.show_profiles(); if (res) goto error; #else my_error(ER_FEATURE_DISABLED, MYF(0), "SHOW PROFILES", "enable-profiling"); goto error; #endif break; } #ifdef HAVE_REPLICATION case SQLCOM_SHOW_SLAVE_HOSTS: { if (check_global_access(thd, REPL_SLAVE_ACL)) goto error; res = show_slave_hosts(thd); break; } case SQLCOM_SHOW_RELAYLOG_EVENTS: /* fall through */ case SQLCOM_SHOW_BINLOG_EVENTS: { if (check_global_access(thd, REPL_SLAVE_ACL)) goto error; res = mysql_show_binlog_events(thd); break; } #endif case SQLCOM_ASSIGN_TO_KEYCACHE: { DBUG_ASSERT(first_table == all_tables && first_table != 0); if (check_access(thd, INDEX_ACL, first_table->db, &first_table->grant.privilege, &first_table->grant.m_internal, 0, 0)) goto error; res= mysql_assign_to_keycache(thd, first_table, &lex->ident); break; } case SQLCOM_PRELOAD_KEYS: { DBUG_ASSERT(first_table == all_tables && first_table != 0); if (check_access(thd, INDEX_ACL, first_table->db, &first_table->grant.privilege, &first_table->grant.m_internal, 0, 0)) goto error; res = mysql_preload_keys(thd, first_table); break; } #ifdef HAVE_REPLICATION case SQLCOM_CHANGE_MASTER: { LEX_MASTER_INFO *lex_mi= &thd->lex->mi; Master_info *mi; bool new_master= 0; bool master_info_added; if (check_global_access(thd, SUPER_ACL)) goto error; mysql_mutex_lock(&LOCK_active_mi); mi= master_info_index->get_master_info(&lex_mi->connection_name, Sql_condition::WARN_LEVEL_NOTE); if (mi == NULL) { /* New replication created */ mi= new Master_info(&lex_mi->connection_name, relay_log_recovery); if (!mi || mi->error()) { delete mi; res= 1; mysql_mutex_unlock(&LOCK_active_mi); break; } new_master= 1; } res= change_master(thd, mi, &master_info_added); if (res && new_master) { /* If the new master was added by change_master(), remove it as it didn't work (this will free mi as well). If new master was not added, we still need to free mi. */ if (master_info_added) master_info_index->remove_master_info(&lex_mi->connection_name); else delete mi; } else { mi->rpl_filter= get_or_create_rpl_filter(lex_mi->connection_name.str, lex_mi->connection_name.length); } mysql_mutex_unlock(&LOCK_active_mi); break; } case SQLCOM_SHOW_SLAVE_STAT: { /* Accept one of two privileges */ if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL)) goto error; mysql_mutex_lock(&LOCK_active_mi); if (lex->verbose) res= show_all_master_info(thd); else { LEX_MASTER_INFO *lex_mi= &thd->lex->mi; Master_info *mi; mi= master_info_index->get_master_info(&lex_mi->connection_name, Sql_condition::WARN_LEVEL_ERROR); if (mi != NULL) { res= show_master_info(thd, mi, 0); } } mysql_mutex_unlock(&LOCK_active_mi); break; } case SQLCOM_SHOW_MASTER_STAT: { /* Accept one of two privileges */ if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL)) goto error; res = show_binlog_info(thd); break; } #endif /* HAVE_REPLICATION */ case SQLCOM_SHOW_ENGINE_STATUS: { if (check_global_access(thd, PROCESS_ACL)) goto error; res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_STATUS); break; } case SQLCOM_SHOW_ENGINE_MUTEX: { if (check_global_access(thd, PROCESS_ACL)) goto error; res = ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_MUTEX); break; } case SQLCOM_CREATE_TABLE: { DBUG_ASSERT(first_table == all_tables && first_table != 0); bool link_to_local; TABLE_LIST *create_table= first_table; TABLE_LIST *select_tables= lex->create_last_non_select_table->next_global; /* Code below (especially in mysql_create_table() and select_create methods) may modify HA_CREATE_INFO structure in LEX, so we have to use a copy of this structure to make execution prepared statement- safe. A shallow copy is enough as this code won't modify any memory referenced from this structure. */ HA_CREATE_INFO create_info(lex->create_info); /* We need to copy alter_info for the same reasons of re-execution safety, only in case of Alter_info we have to do (almost) a deep copy. */ Alter_info alter_info(lex->alter_info, thd->mem_root); if (thd->is_fatal_error) { /* If out of memory when creating a copy of alter_info. */ res= 1; goto end_with_restore_list; } /* Check privileges */ if ((res= create_table_precheck(thd, select_tables, create_table))) goto end_with_restore_list; /* Might have been updated in create_table_precheck */ create_info.alias= create_table->alias; /* Fix names if symlinked or relocated tables */ if (append_file_to_dir(thd, &create_info.data_file_name, create_table->table_name) || append_file_to_dir(thd, &create_info.index_file_name, create_table->table_name)) goto end_with_restore_list; /* If no engine type was given, work out the default now rather than at parse-time. */ if (!(create_info.used_fields & HA_CREATE_USED_ENGINE)) create_info.db_type= ha_default_handlerton(thd); /* If we are using SET CHARSET without DEFAULT, add an implicit DEFAULT to not confuse old users. (This may change). */ if ((create_info.used_fields & (HA_CREATE_USED_DEFAULT_CHARSET | HA_CREATE_USED_CHARSET)) == HA_CREATE_USED_CHARSET) { create_info.used_fields&= ~HA_CREATE_USED_CHARSET; create_info.used_fields|= HA_CREATE_USED_DEFAULT_CHARSET; create_info.default_table_charset= create_info.table_charset; create_info.table_charset= 0; } /* For CREATE TABLE we should not open the table even if it exists. If the table exists, we should either not create it or replace it */ lex->query_tables->open_strategy= TABLE_LIST::OPEN_STUB; /* If we are a slave, we should add OR REPLACE if we don't have IF EXISTS. This will help a slave to recover from CREATE TABLE OR EXISTS failures by dropping the table and retrying the create. */ create_info.org_options= create_info.options; if (thd->slave_thread && slave_ddl_exec_mode_options == SLAVE_EXEC_MODE_IDEMPOTENT && !(lex->create_info.options & HA_LEX_CREATE_IF_NOT_EXISTS)) create_info.options|= HA_LEX_CREATE_REPLACE; #ifdef WITH_PARTITION_STORAGE_ENGINE { partition_info *part_info= thd->lex->part_info; if (part_info && !(part_info= thd->lex->part_info->get_clone())) { res= -1; goto end_with_restore_list; } thd->work_part_info= part_info; } #endif if (select_lex->item_list.elements) // With select { select_result *result; /* CREATE TABLE...IGNORE/REPLACE SELECT... can be unsafe, unless ORDER BY PRIMARY KEY clause is used in SELECT statement. We therefore use row based logging if mixed or row based logging is available. TODO: Check if the order of the output of the select statement is deterministic. Waiting for BUG#42415 */ if(lex->ignore) lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_CREATE_IGNORE_SELECT); if(lex->duplicates == DUP_REPLACE) lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_CREATE_REPLACE_SELECT); /* If: a) we inside an SP and there was NAME_CONST substitution, b) binlogging is on (STMT mode), c) we log the SP as separate statements raise a warning, as it may cause problems (see 'NAME_CONST issues' in 'Binary Logging of Stored Programs') */ if (thd->query_name_consts && mysql_bin_log.is_open() && thd->variables.binlog_format == BINLOG_FORMAT_STMT && !mysql_bin_log.is_query_in_union(thd, thd->query_id)) { List_iterator_fast<Item> it(select_lex->item_list); Item *item; uint splocal_refs= 0; /* Count SP local vars in the top-level SELECT list */ while ((item= it++)) { if (item->is_splocal()) splocal_refs++; } /* If it differs from number of NAME_CONST substitution applied, we may have a SOME_FUNC(NAME_CONST()) in the SELECT list, that may cause a problem with binary log (see BUG#35383), raise a warning. */ if (splocal_refs != thd->query_name_consts) push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_UNKNOWN_ERROR, "Invoked routine ran a statement that may cause problems with " "binary log, see 'NAME_CONST issues' in 'Binary Logging of Stored Programs' " "section of the manual."); } select_lex->options|= SELECT_NO_UNLOCK; unit->set_limit(select_lex); /* Disable non-empty MERGE tables with CREATE...SELECT. Too complicated. See Bug #26379. Empty MERGE tables are read-only and don't allow CREATE...SELECT anyway. */ if (create_info.used_fields & HA_CREATE_USED_UNION) { my_error(ER_WRONG_OBJECT, MYF(0), create_table->db, create_table->table_name, "BASE TABLE"); res= 1; goto end_with_restore_list; } res= open_and_lock_tables(thd, lex->query_tables, TRUE, 0); if (res) { /* Got error or warning. Set res to 1 if error */ if (!(res= thd->is_error())) my_ok(thd); // CREATE ... IF NOT EXISTS goto end_with_restore_list; } /* Ensure we don't try to create something from which we select from */ if ((create_info.options & HA_LEX_CREATE_REPLACE) && !create_info.tmp_table()) { TABLE_LIST *duplicate; if ((duplicate= unique_table(thd, lex->query_tables, lex->query_tables->next_global, 0))) { update_non_unique_table_error(lex->query_tables, "CREATE", duplicate); res= TRUE; goto end_with_restore_list; } } { /* Remove target table from main select and name resolution context. This can't be done earlier as it will break view merging in statements like "CREATE TABLE IF NOT EXISTS existing_view SELECT". */ lex->unlink_first_table(&link_to_local); /* Store reference to table in case of LOCK TABLES */ create_info.table= create_table->table; /* select_create is currently not re-execution friendly and needs to be created for every execution of a PS/SP. */ if ((result= new select_create(create_table, &create_info, &alter_info, select_lex->item_list, lex->duplicates, lex->ignore, select_tables))) { /* CREATE from SELECT give its SELECT_LEX for SELECT, and item_list belong to SELECT */ if (!(res= handle_select(thd, lex, result, 0))) { if (create_info.tmp_table()) thd->variables.option_bits|= OPTION_KEEP_LOG; } delete result; } lex->link_first_table_back(create_table, link_to_local); } } else { /* regular create */ if (create_info.options & HA_LEX_CREATE_TABLE_LIKE) { /* CREATE TABLE ... LIKE ... */ res= mysql_create_like_table(thd, create_table, select_tables, &create_info); } else { /* Regular CREATE TABLE */ res= mysql_create_table(thd, create_table, &create_info, &alter_info); } if (!res) { /* So that CREATE TEMPORARY TABLE gets to binlog at commit/rollback */ if (create_info.tmp_table()) thd->variables.option_bits|= OPTION_KEEP_LOG; my_ok(thd); } } end_with_restore_list: break; } case SQLCOM_CREATE_INDEX: /* Fall through */ case SQLCOM_DROP_INDEX: /* CREATE INDEX and DROP INDEX are implemented by calling ALTER TABLE with proper arguments. In the future ALTER TABLE will notice that the request is to only add indexes and create these one by one for the existing table without having to do a full rebuild. */ { /* Prepare stack copies to be re-execution safe */ HA_CREATE_INFO create_info; Alter_info alter_info(lex->alter_info, thd->mem_root); if (thd->is_fatal_error) /* out of memory creating a copy of alter_info */ goto error; DBUG_ASSERT(first_table == all_tables && first_table != 0); if (check_one_table_access(thd, INDEX_ACL, all_tables)) goto error; /* purecov: inspected */ /* Currently CREATE INDEX or DROP INDEX cause a full table rebuild and thus classify as slow administrative statements just like ALTER TABLE. */ thd->enable_slow_log= opt_log_slow_admin_statements; thd->query_plan_flags|= QPLAN_ADMIN; bzero((char*) &create_info, sizeof(create_info)); create_info.db_type= 0; create_info.row_type= ROW_TYPE_NOT_USED; create_info.default_table_charset= thd->variables.collation_database; res= mysql_alter_table(thd, first_table->db, first_table->table_name, &create_info, first_table, &alter_info, 0, (ORDER*) 0, 0); break; } #ifdef HAVE_REPLICATION case SQLCOM_SLAVE_START: { LEX_MASTER_INFO* lex_mi= &thd->lex->mi; Master_info *mi; int load_error; load_error= rpl_load_gtid_slave_state(thd); mysql_mutex_lock(&LOCK_active_mi); if ((mi= (master_info_index-> get_master_info(&lex_mi->connection_name, Sql_condition::WARN_LEVEL_ERROR)))) { if (load_error) { /* We cannot start a slave using GTID if we cannot load the GTID position from the mysql.gtid_slave_pos table. But we can allow non-GTID replication (useful eg. during upgrade). */ if (mi->using_gtid != Master_info::USE_GTID_NO) { mysql_mutex_unlock(&LOCK_active_mi); break; } else thd->clear_error(); } if (!start_slave(thd, mi, 1 /* net report*/)) my_ok(thd); } mysql_mutex_unlock(&LOCK_active_mi); break; } case SQLCOM_SLAVE_STOP: { LEX_MASTER_INFO *lex_mi; Master_info *mi; /* If the client thread has locked tables, a deadlock is possible. Assume that - the client thread does LOCK TABLE t READ. - then the master updates t. - then the SQL slave thread wants to update t, so it waits for the client thread because t is locked by it. - then the client thread does SLAVE STOP. SLAVE STOP waits for the SQL slave thread to terminate its update t, which waits for the client thread because t is locked by it. To prevent that, refuse SLAVE STOP if the client thread has locked tables */ if (thd->locked_tables_mode || thd->in_active_multi_stmt_transaction() || thd->global_read_lock.is_acquired()) { my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0)); goto error; } lex_mi= &thd->lex->mi; mysql_mutex_lock(&LOCK_active_mi); if ((mi= (master_info_index-> get_master_info(&lex_mi->connection_name, Sql_condition::WARN_LEVEL_ERROR)))) if (!stop_slave(thd, mi, 1/* net report*/)) my_ok(thd); mysql_mutex_unlock(&LOCK_active_mi); break; } case SQLCOM_SLAVE_ALL_START: { mysql_mutex_lock(&LOCK_active_mi); if (!master_info_index->start_all_slaves(thd)) my_ok(thd); mysql_mutex_unlock(&LOCK_active_mi); break; } case SQLCOM_SLAVE_ALL_STOP: { if (thd->locked_tables_mode || thd->in_active_multi_stmt_transaction() || thd->global_read_lock.is_acquired()) { my_message(ER_LOCK_OR_ACTIVE_TRANSACTION, ER(ER_LOCK_OR_ACTIVE_TRANSACTION), MYF(0)); goto error; } mysql_mutex_lock(&LOCK_active_mi); if (!master_info_index->stop_all_slaves(thd)) my_ok(thd); mysql_mutex_unlock(&LOCK_active_mi); break; } #endif /* HAVE_REPLICATION */ case SQLCOM_RENAME_TABLE: { if (execute_rename_table(thd, first_table, all_tables)) goto error; break; } #ifndef EMBEDDED_LIBRARY case SQLCOM_SHOW_BINLOGS: #ifdef DONT_ALLOW_SHOW_COMMANDS my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */ goto error; #else { if (check_global_access(thd, SUPER_ACL | REPL_CLIENT_ACL)) goto error; res = show_binlogs(thd); break; } #endif #endif /* EMBEDDED_LIBRARY */ case SQLCOM_SHOW_CREATE: DBUG_ASSERT(first_table == all_tables && first_table != 0); #ifdef DONT_ALLOW_SHOW_COMMANDS my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */ goto error; #else { /* Access check: SHOW CREATE TABLE require any privileges on the table level (ie effecting all columns in the table). SHOW CREATE VIEW require the SHOW_VIEW and SELECT ACLs on the table level. NOTE: SHOW_VIEW ACL is checked when the view is created. */ DBUG_PRINT("debug", ("lex->only_view: %d, table: %s.%s", lex->only_view, first_table->db, first_table->table_name)); if (lex->only_view) { if (check_table_access(thd, SELECT_ACL, first_table, FALSE, 1, FALSE)) { DBUG_PRINT("debug", ("check_table_access failed")); my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0), "SHOW", thd->security_ctx->priv_user, thd->security_ctx->host_or_ip, first_table->alias); goto error; } DBUG_PRINT("debug", ("check_table_access succeeded")); /* Ignore temporary tables if this is "SHOW CREATE VIEW" */ first_table->open_type= OT_BASE_ONLY; } else { /* Temporary tables should be opened for SHOW CREATE TABLE, but not for SHOW CREATE VIEW. */ if (open_temporary_tables(thd, all_tables)) goto error; /* The fact that check_some_access() returned FALSE does not mean that access is granted. We need to check if first_table->grant.privilege contains any table-specific privilege. */ DBUG_PRINT("debug", ("first_table->grant.privilege: %lx", first_table->grant.privilege)); if (check_some_access(thd, SHOW_CREATE_TABLE_ACLS, first_table) || (first_table->grant.privilege & SHOW_CREATE_TABLE_ACLS) == 0) { my_error(ER_TABLEACCESS_DENIED_ERROR, MYF(0), "SHOW", thd->security_ctx->priv_user, thd->security_ctx->host_or_ip, first_table->alias); goto error; } } /* Access is granted. Execute the command. */ res= mysqld_show_create(thd, first_table); break; } #endif case SQLCOM_CHECKSUM: { DBUG_ASSERT(first_table == all_tables && first_table != 0); if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)) goto error; /* purecov: inspected */ res = mysql_checksum_table(thd, first_table, &lex->check_opt); break; } case SQLCOM_UPDATE: { ha_rows found= 0, updated= 0; DBUG_ASSERT(first_table == all_tables && first_table != 0); if (update_precheck(thd, all_tables)) break; /* UPDATE IGNORE can be unsafe. We therefore use row based logging if mixed or row based logging is available. TODO: Check if the order of the output of the select statement is deterministic. Waiting for BUG#42415 */ if (lex->ignore) lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_UPDATE_IGNORE); DBUG_ASSERT(select_lex->offset_limit == 0); unit->set_limit(select_lex); MYSQL_UPDATE_START(thd->query()); res= (up_result= mysql_update(thd, all_tables, select_lex->item_list, lex->value_list, select_lex->where, select_lex->order_list.elements, select_lex->order_list.first, unit->select_limit_cnt, lex->duplicates, lex->ignore, &found, &updated)); MYSQL_UPDATE_DONE(res, found, updated); /* mysql_update return 2 if we need to switch to multi-update */ if (up_result != 2) break; /* Fall through */ } case SQLCOM_UPDATE_MULTI: { DBUG_ASSERT(first_table == all_tables && first_table != 0); /* if we switched from normal update, rights are checked */ if (up_result != 2) { if ((res= multi_update_precheck(thd, all_tables))) break; } else res= 0; res= mysql_multi_update_prepare(thd); #ifdef HAVE_REPLICATION /* Check slave filtering rules */ if (unlikely(thd->slave_thread && !have_table_map_for_update)) { if (all_tables_not_ok(thd, all_tables)) { if (res!= 0) { res= 0; /* don't care of prev failure */ thd->clear_error(); /* filters are of highest prior */ } /* we warn the slave SQL thread */ my_error(ER_SLAVE_IGNORED_TABLE, MYF(0)); break; } if (res) break; } else { #endif /* HAVE_REPLICATION */ if (res) break; if (opt_readonly && !(thd->security_ctx->master_access & SUPER_ACL) && some_non_temp_table_to_be_updated(thd, all_tables)) { my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "--read-only"); break; } #ifdef HAVE_REPLICATION } /* unlikely */ #endif { multi_update *result_obj; MYSQL_MULTI_UPDATE_START(thd->query()); res= mysql_multi_update(thd, all_tables, &select_lex->item_list, &lex->value_list, select_lex->where, select_lex->options, lex->duplicates, lex->ignore, unit, select_lex, &result_obj); if (result_obj) { MYSQL_MULTI_UPDATE_DONE(res, result_obj->num_found(), result_obj->num_updated()); res= FALSE; /* Ignore errors here */ delete result_obj; } else { MYSQL_MULTI_UPDATE_DONE(1, 0, 0); } } break; } case SQLCOM_REPLACE: #ifndef DBUG_OFF if (mysql_bin_log.is_open()) { /* Generate an incident log event before writing the real event to the binary log. We put this event is before the statement since that makes it simpler to check that the statement was not executed on the slave (since incidents usually stop the slave). Observe that any row events that are generated will be generated before. This is only for testing purposes and will not be present in a release build. */ Incident incident= INCIDENT_NONE; DBUG_PRINT("debug", ("Just before generate_incident()")); DBUG_EXECUTE_IF("incident_database_resync_on_replace", incident= INCIDENT_LOST_EVENTS;); if (incident) { Incident_log_event ev(thd, incident); (void) mysql_bin_log.write(&ev); /* error is ignored */ if (mysql_bin_log.rotate_and_purge(true)) { res= 1; break; } } DBUG_PRINT("debug", ("Just after generate_incident()")); } #endif case SQLCOM_INSERT: { DBUG_ASSERT(first_table == all_tables && first_table != 0); /* Since INSERT DELAYED doesn't support temporary tables, we could not pre-open temporary tables for SQLCOM_INSERT / SQLCOM_REPLACE. Open them here instead. */ if (first_table->lock_type != TL_WRITE_DELAYED) { if ((res= open_temporary_tables(thd, all_tables))) break; } if ((res= insert_precheck(thd, all_tables))) break; MYSQL_INSERT_START(thd->query()); res= mysql_insert(thd, all_tables, lex->field_list, lex->many_values, lex->update_list, lex->value_list, lex->duplicates, lex->ignore); MYSQL_INSERT_DONE(res, (ulong) thd->get_row_count_func()); /* If we have inserted into a VIEW, and the base table has AUTO_INCREMENT column, but this column is not accessible through a view, then we should restore LAST_INSERT_ID to the value it had before the statement. */ if (first_table->view && !first_table->contain_auto_increment) thd->first_successful_insert_id_in_cur_stmt= thd->first_successful_insert_id_in_prev_stmt; #ifdef ENABLED_DEBUG_SYNC DBUG_EXECUTE_IF("after_mysql_insert", { const char act1[]= "now " "wait_for signal.continue"; const char act2[]= "now " "signal signal.continued"; DBUG_ASSERT(debug_sync_service); DBUG_ASSERT(!debug_sync_set_action(thd, STRING_WITH_LEN(act1))); DBUG_ASSERT(!debug_sync_set_action(thd, STRING_WITH_LEN(act2))); };); DEBUG_SYNC(thd, "after_mysql_insert"); #endif break; } case SQLCOM_REPLACE_SELECT: case SQLCOM_INSERT_SELECT: { select_result *sel_result; bool explain= MY_TEST(lex->describe); DBUG_ASSERT(first_table == all_tables && first_table != 0); if ((res= insert_precheck(thd, all_tables))) break; /* INSERT...SELECT...ON DUPLICATE KEY UPDATE/REPLACE SELECT/ INSERT...IGNORE...SELECT can be unsafe, unless ORDER BY PRIMARY KEY clause is used in SELECT statement. We therefore use row based logging if mixed or row based logging is available. TODO: Check if the order of the output of the select statement is deterministic. Waiting for BUG#42415 */ if (lex->sql_command == SQLCOM_INSERT_SELECT && lex->duplicates == DUP_UPDATE) lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_SELECT_UPDATE); if (lex->sql_command == SQLCOM_INSERT_SELECT && lex->ignore) lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_INSERT_IGNORE_SELECT); if (lex->sql_command == SQLCOM_REPLACE_SELECT) lex->set_stmt_unsafe(LEX::BINLOG_STMT_UNSAFE_REPLACE_SELECT); /* Fix lock for first table */ if (first_table->lock_type == TL_WRITE_DELAYED) first_table->lock_type= TL_WRITE; /* Don't unlock tables until command is written to binary log */ select_lex->options|= SELECT_NO_UNLOCK; unit->set_limit(select_lex); if (!(res= open_and_lock_tables(thd, all_tables, TRUE, 0))) { MYSQL_INSERT_SELECT_START(thd->query()); /* Only the INSERT table should be merged. Other will be handled by select. */ /* Skip first table, which is the table we are inserting in */ TABLE_LIST *second_table= first_table->next_local; select_lex->table_list.first= second_table; select_lex->context.table_list= select_lex->context.first_name_resolution_table= second_table; res= mysql_insert_select_prepare(thd); if (!res && (sel_result= new select_insert(first_table, first_table->table, &lex->field_list, &lex->update_list, &lex->value_list, lex->duplicates, lex->ignore))) { res= handle_select(thd, lex, sel_result, OPTION_SETUP_TABLES_DONE); /* Invalidate the table in the query cache if something changed after unlocking when changes become visible. TODO: this is workaround. right way will be move invalidating in the unlock procedure. */ if (!res && first_table->lock_type == TL_WRITE_CONCURRENT_INSERT && thd->lock) { /* INSERT ... SELECT should invalidate only the very first table */ TABLE_LIST *save_table= first_table->next_local; first_table->next_local= 0; query_cache_invalidate3(thd, first_table, 1); first_table->next_local= save_table; } delete sel_result; } if (!res && explain) res= thd->lex->explain->send_explain(thd); /* revert changes for SP */ MYSQL_INSERT_SELECT_DONE(res, (ulong) thd->get_row_count_func()); select_lex->table_list.first= first_table; } /* If we have inserted into a VIEW, and the base table has AUTO_INCREMENT column, but this column is not accessible through a view, then we should restore LAST_INSERT_ID to the value it had before the statement. */ if (first_table->view && !first_table->contain_auto_increment) thd->first_successful_insert_id_in_cur_stmt= thd->first_successful_insert_id_in_prev_stmt; break; } case SQLCOM_DELETE: { select_result *sel_result=lex->result; DBUG_ASSERT(first_table == all_tables && first_table != 0); if ((res= delete_precheck(thd, all_tables))) break; DBUG_ASSERT(select_lex->offset_limit == 0); unit->set_limit(select_lex); MYSQL_DELETE_START(thd->query()); if (!(sel_result= lex->result) && !(sel_result= new select_send())) return 1; res = mysql_delete(thd, all_tables, select_lex->where, &select_lex->order_list, unit->select_limit_cnt, select_lex->options, sel_result); delete sel_result; MYSQL_DELETE_DONE(res, (ulong) thd->get_row_count_func()); break; } case SQLCOM_DELETE_MULTI: { DBUG_ASSERT(first_table == all_tables && first_table != 0); TABLE_LIST *aux_tables= thd->lex->auxiliary_table_list.first; bool explain= MY_TEST(lex->describe); multi_delete *result; if ((res= multi_delete_precheck(thd, all_tables))) break; /* condition will be TRUE on SP re-excuting */ if (select_lex->item_list.elements != 0) select_lex->item_list.empty(); if (add_item_to_list(thd, new Item_null())) goto error; THD_STAGE_INFO(thd, stage_init); if ((res= open_and_lock_tables(thd, all_tables, TRUE, 0))) break; MYSQL_MULTI_DELETE_START(thd->query()); if ((res= mysql_multi_delete_prepare(thd))) { MYSQL_MULTI_DELETE_DONE(1, 0); goto error; } if (!thd->is_fatal_error) { result= new multi_delete(aux_tables, lex->table_count); if (result) { res= mysql_select(thd, &select_lex->ref_pointer_array, select_lex->get_table_list(), select_lex->with_wild, select_lex->item_list, select_lex->where, 0, (ORDER *)NULL, (ORDER *)NULL, (Item *)NULL, (ORDER *)NULL, (select_lex->options | thd->variables.option_bits | SELECT_NO_JOIN_CACHE | SELECT_NO_UNLOCK | OPTION_SETUP_TABLES_DONE) & ~OPTION_BUFFER_RESULT, result, unit, select_lex); res|= thd->is_error(); MYSQL_MULTI_DELETE_DONE(res, result->num_deleted()); if (res) result->abort_result_set(); /* for both DELETE and EXPLAIN DELETE */ else { if (explain) res= thd->lex->explain->send_explain(thd); } delete result; } } else { res= TRUE; // Error MYSQL_MULTI_DELETE_DONE(1, 0); } break; } case SQLCOM_DROP_TABLE: { DBUG_ASSERT(first_table == all_tables && first_table != 0); if (!lex->drop_temporary) { if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE)) goto error; /* purecov: inspected */ } else { /* So that DROP TEMPORARY TABLE gets to binlog at commit/rollback */ thd->variables.option_bits|= OPTION_KEEP_LOG; } /* If we are a slave, we should add IF EXISTS if the query executed on the master without an error. This will help a slave to recover from multi-table DROP TABLE that was aborted in the middle. */ if (thd->slave_thread && !thd->slave_expected_error && slave_ddl_exec_mode_options == SLAVE_EXEC_MODE_IDEMPOTENT) lex->check_exists= 1; /* DDL and binlog write order are protected by metadata locks. */ res= mysql_rm_table(thd, first_table, lex->check_exists, lex->drop_temporary); } break; case SQLCOM_SHOW_PROCESSLIST: if (!thd->security_ctx->priv_user[0] && check_global_access(thd,PROCESS_ACL)) break; mysqld_list_processes(thd, (thd->security_ctx->master_access & PROCESS_ACL ? NullS : thd->security_ctx->priv_user), lex->verbose); break; case SQLCOM_SHOW_AUTHORS: res= mysqld_show_authors(thd); break; case SQLCOM_SHOW_CONTRIBUTORS: res= mysqld_show_contributors(thd); break; case SQLCOM_SHOW_PRIVILEGES: res= mysqld_show_privileges(thd); break; case SQLCOM_SHOW_ENGINE_LOGS: #ifdef DONT_ALLOW_SHOW_COMMANDS my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); /* purecov: inspected */ goto error; #else { if (check_access(thd, FILE_ACL, any_db, NULL, NULL, 0, 0)) goto error; res= ha_show_status(thd, lex->create_info.db_type, HA_ENGINE_LOGS); break; } #endif case SQLCOM_CHANGE_DB: { LEX_STRING db_str= { (char *) select_lex->db, strlen(select_lex->db) }; if (!mysql_change_db(thd, &db_str, FALSE)) my_ok(thd); break; } case SQLCOM_LOAD: { DBUG_ASSERT(first_table == all_tables && first_table != 0); uint privilege= (lex->duplicates == DUP_REPLACE ? INSERT_ACL | DELETE_ACL : INSERT_ACL) | (lex->local_file ? 0 : FILE_ACL); if (lex->local_file) { if (!(thd->client_capabilities & CLIENT_LOCAL_FILES) || !opt_local_infile) { my_message(ER_NOT_ALLOWED_COMMAND, ER(ER_NOT_ALLOWED_COMMAND), MYF(0)); goto error; } } if (check_one_table_access(thd, privilege, all_tables)) goto error; res= mysql_load(thd, lex->exchange, first_table, lex->field_list, lex->update_list, lex->value_list, lex->duplicates, lex->ignore, (bool) lex->local_file); break; } case SQLCOM_SET_OPTION: { List<set_var_base> *lex_var_list= &lex->var_list; if ((check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE) || open_and_lock_tables(thd, all_tables, TRUE, 0))) goto error; if (!(res= sql_set_variables(thd, lex_var_list))) { /* If the previous command was a SET ONE_SHOT, we don't want to forget about the ONE_SHOT property of that SET. So we use a |= instead of = . */ thd->one_shot_set|= lex->one_shot_set; my_ok(thd); } else { /* We encountered some sort of error, but no message was sent. Send something semi-generic here since we don't know which assignment in the list caused the error. */ if (!thd->is_error()) my_error(ER_WRONG_ARGUMENTS,MYF(0),"SET"); goto error; } break; } case SQLCOM_UNLOCK_TABLES: /* It is critical for mysqldump --single-transaction --master-data that UNLOCK TABLES does not implicitely commit a connection which has only done FLUSH TABLES WITH READ LOCK + BEGIN. If this assumption becomes false, mysqldump will not work. */ if (thd->variables.option_bits & OPTION_TABLE_LOCK) { res= trans_commit_implicit(thd); thd->locked_tables_list.unlock_locked_tables(thd); thd->mdl_context.release_transactional_locks(); thd->variables.option_bits&= ~(OPTION_TABLE_LOCK); } if (thd->global_read_lock.is_acquired()) thd->global_read_lock.unlock_global_read_lock(thd); if (res) goto error; my_ok(thd); break; case SQLCOM_LOCK_TABLES: /* We must end the transaction first, regardless of anything */ res= trans_commit_implicit(thd); thd->locked_tables_list.unlock_locked_tables(thd); /* Release transactional metadata locks. */ thd->mdl_context.release_transactional_locks(); if (res) goto error; /* Here we have to pre-open temporary tables for LOCK TABLES. CF_PREOPEN_TMP_TABLES is not set for this SQL statement simply because LOCK TABLES calls close_thread_tables() as a first thing (it's called from unlock_locked_tables() above). So even if CF_PREOPEN_TMP_TABLES was set and the tables would be pre-opened in a usual way, they would have been closed. */ if (open_temporary_tables(thd, all_tables)) goto error; if (lock_tables_precheck(thd, all_tables)) goto error; thd->variables.option_bits|= OPTION_TABLE_LOCK; res= lock_tables_open_and_lock_tables(thd, all_tables); if (res) { thd->variables.option_bits&= ~(OPTION_TABLE_LOCK); } else { #ifdef HAVE_QUERY_CACHE if (thd->variables.query_cache_wlock_invalidate) query_cache.invalidate_locked_for_write(thd, first_table); #endif /*HAVE_QUERY_CACHE*/ my_ok(thd); } break; case SQLCOM_CREATE_DB: { /* As mysql_create_db() may modify HA_CREATE_INFO structure passed to it, we need to use a copy of LEX::create_info to make execution prepared statement- safe. */ HA_CREATE_INFO create_info(lex->create_info); if (check_db_name(&lex->name)) { my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str); break; } /* If in a slave thread : CREATE DATABASE DB was certainly not preceded by USE DB. For that reason, db_ok() in sql/slave.cc did not check the do_db/ignore_db. And as this query involves no tables, tables_ok() above was not called. So we have to check rules again here. */ #ifdef HAVE_REPLICATION if (thd->slave_thread && (!rpl_filter->db_ok(lex->name.str) || !rpl_filter->db_ok_with_wild_table(lex->name.str))) { my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); break; } #endif if (check_access(thd, CREATE_ACL, lex->name.str, NULL, NULL, 1, 0)) break; res= mysql_create_db(thd, lex->name.str, &create_info, 0); break; } case SQLCOM_DROP_DB: { if (check_db_name(&lex->name)) { my_error(ER_WRONG_DB_NAME, MYF(0), lex->name.str); break; } /* If in a slave thread : DROP DATABASE DB may not be preceded by USE DB. For that reason, maybe db_ok() in sql/slave.cc did not check the do_db/ignore_db. And as this query involves no tables, tables_ok() above was not called. So we have to check rules again here. */ #ifdef HAVE_REPLICATION if (thd->slave_thread && (!rpl_filter->db_ok(lex->name.str) || !rpl_filter->db_ok_with_wild_table(lex->name.str))) { my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); break; } #endif if (check_access(thd, DROP_ACL, lex->name.str, NULL, NULL, 1, 0)) break; res= mysql_rm_db(thd, lex->name.str, lex->check_exists, 0); break; } case SQLCOM_ALTER_DB_UPGRADE: { LEX_STRING *db= & lex->name; #ifdef HAVE_REPLICATION if (thd->slave_thread && (!rpl_filter->db_ok(db->str) || !rpl_filter->db_ok_with_wild_table(db->str))) { res= 1; my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); break; } #endif if (check_db_name(db)) { my_error(ER_WRONG_DB_NAME, MYF(0), db->str); break; } if (check_access(thd, ALTER_ACL, db->str, NULL, NULL, 1, 0) || check_access(thd, DROP_ACL, db->str, NULL, NULL, 1, 0) || check_access(thd, CREATE_ACL, db->str, NULL, NULL, 1, 0)) { res= 1; break; } res= mysql_upgrade_db(thd, db); if (!res) my_ok(thd); break; } case SQLCOM_ALTER_DB: { LEX_STRING *db= &lex->name; HA_CREATE_INFO create_info(lex->create_info); if (check_db_name(db)) { my_error(ER_WRONG_DB_NAME, MYF(0), db->str); break; } /* If in a slave thread : ALTER DATABASE DB may not be preceded by USE DB. For that reason, maybe db_ok() in sql/slave.cc did not check the do_db/ignore_db. And as this query involves no tables, tables_ok() above was not called. So we have to check rules again here. */ #ifdef HAVE_REPLICATION if (thd->slave_thread && (!rpl_filter->db_ok(db->str) || !rpl_filter->db_ok_with_wild_table(db->str))) { my_message(ER_SLAVE_IGNORED_TABLE, ER(ER_SLAVE_IGNORED_TABLE), MYF(0)); break; } #endif if (check_access(thd, ALTER_ACL, db->str, NULL, NULL, 1, 0)) break; res= mysql_alter_db(thd, db->str, &create_info); break; } case SQLCOM_SHOW_CREATE_DB: { char db_name_buff[NAME_LEN+1]; LEX_STRING db_name; DBUG_EXECUTE_IF("4x_server_emul", my_error(ER_UNKNOWN_ERROR, MYF(0)); goto error;); db_name.str= db_name_buff; db_name.length= lex->name.length; strmov(db_name.str, lex->name.str); if (check_db_name(&db_name)) { my_error(ER_WRONG_DB_NAME, MYF(0), db_name.str); break; } res= mysqld_show_create_db(thd, &db_name, &lex->name, &lex->create_info); break; } case SQLCOM_CREATE_EVENT: case SQLCOM_ALTER_EVENT: #ifdef HAVE_EVENT_SCHEDULER do { DBUG_ASSERT(lex->event_parse_data); if (lex->table_or_sp_used()) { my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Usage of subqueries or stored " "function calls as part of this statement"); break; } res= sp_process_definer(thd); if (res) break; switch (lex->sql_command) { case SQLCOM_CREATE_EVENT: { bool if_not_exists= (lex->create_info.options & HA_LEX_CREATE_IF_NOT_EXISTS); res= Events::create_event(thd, lex->event_parse_data, if_not_exists); break; } case SQLCOM_ALTER_EVENT: res= Events::update_event(thd, lex->event_parse_data, lex->spname ? &lex->spname->m_db : NULL, lex->spname ? &lex->spname->m_name : NULL); break; default: DBUG_ASSERT(0); } DBUG_PRINT("info",("DDL error code=%d", res)); if (!res) my_ok(thd); } while (0); /* Don't do it, if we are inside a SP */ if (!thd->spcont) { delete lex->sphead; lex->sphead= NULL; } /* lex->unit.cleanup() is called outside, no need to call it here */ break; case SQLCOM_SHOW_CREATE_EVENT: res= Events::show_create_event(thd, lex->spname->m_db, lex->spname->m_name); break; case SQLCOM_DROP_EVENT: if (!(res= Events::drop_event(thd, lex->spname->m_db, lex->spname->m_name, lex->check_exists))) my_ok(thd); break; #else my_error(ER_NOT_SUPPORTED_YET,MYF(0),"embedded server"); break; #endif case SQLCOM_CREATE_FUNCTION: // UDF function { if (check_access(thd, INSERT_ACL, "mysql", NULL, NULL, 1, 0)) break; #ifdef HAVE_DLOPEN if (!(res = mysql_create_function(thd, &lex->udf))) my_ok(thd); #else my_error(ER_CANT_OPEN_LIBRARY, MYF(0), lex->udf.dl, 0, "feature disabled"); res= TRUE; #endif break; } #ifndef NO_EMBEDDED_ACCESS_CHECKS case SQLCOM_CREATE_USER: case SQLCOM_CREATE_ROLE: { if (check_access(thd, INSERT_ACL, "mysql", NULL, NULL, 1, 1) && check_global_access(thd,CREATE_USER_ACL)) break; /* Conditionally writes to binlog */ if (!(res= mysql_create_user(thd, lex->users_list, lex->sql_command == SQLCOM_CREATE_ROLE))) my_ok(thd); break; } case SQLCOM_DROP_USER: case SQLCOM_DROP_ROLE: { if (check_access(thd, DELETE_ACL, "mysql", NULL, NULL, 1, 1) && check_global_access(thd,CREATE_USER_ACL)) break; /* Conditionally writes to binlog */ if (!(res= mysql_drop_user(thd, lex->users_list, lex->sql_command == SQLCOM_DROP_ROLE))) my_ok(thd); break; } case SQLCOM_RENAME_USER: { if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) && check_global_access(thd,CREATE_USER_ACL)) break; /* Conditionally writes to binlog */ if (!(res= mysql_rename_user(thd, lex->users_list))) my_ok(thd); break; } case SQLCOM_REVOKE_ALL: { if (check_access(thd, UPDATE_ACL, "mysql", NULL, NULL, 1, 1) && check_global_access(thd,CREATE_USER_ACL)) break; /* Conditionally writes to binlog */ if (!(res = mysql_revoke_all(thd, lex->users_list))) my_ok(thd); break; } case SQLCOM_REVOKE: case SQLCOM_GRANT: { if (lex->type != TYPE_ENUM_PROXY && check_access(thd, lex->grant | lex->grant_tot_col | GRANT_ACL, first_table ? first_table->db : select_lex->db, first_table ? &first_table->grant.privilege : NULL, first_table ? &first_table->grant.m_internal : NULL, first_table ? 0 : 1, 0)) goto error; /* Replicate current user as grantor */ thd->binlog_invoker(false); if (thd->security_ctx->user) // If not replication { LEX_USER *user; bool first_user= TRUE; List_iterator <LEX_USER> user_list(lex->users_list); while ((user= user_list++)) { if (specialflag & SPECIAL_NO_RESOLVE && hostname_requires_resolving(user->host.str)) push_warning_printf(thd, Sql_condition::WARN_LEVEL_WARN, ER_WARN_HOSTNAME_WONT_WORK, ER(ER_WARN_HOSTNAME_WONT_WORK)); /* GRANT/REVOKE PROXY has the target user as a first entry in the list. */ if (lex->type == TYPE_ENUM_PROXY && first_user) { if (!(user= get_current_user(thd, user)) || !user->host.str) goto error; first_user= FALSE; if (acl_check_proxy_grant_access (thd, user->host.str, user->user.str, lex->grant & GRANT_ACL)) goto error; } else if (user->password.str) { // Are we trying to change a password of another user? const char *hostname= user->host.str, *username=user->user.str; bool userok; if (username == current_user.str) { username= thd->security_ctx->priv_user; hostname= thd->security_ctx->priv_host; userok= true; } else { if (!hostname) hostname= host_not_specified.str; userok= is_acl_user(hostname, username); } if (userok && check_change_password (thd, hostname, username, user->password.str, user->password.length)) goto error; } } } if (first_table) { if (lex->type == TYPE_ENUM_PROCEDURE || lex->type == TYPE_ENUM_FUNCTION) { uint grants= lex->all_privileges ? (PROC_ACLS & ~GRANT_ACL) | (lex->grant & GRANT_ACL) : lex->grant; if (check_grant_routine(thd, grants | GRANT_ACL, all_tables, lex->type == TYPE_ENUM_PROCEDURE, 0)) goto error; /* Conditionally writes to binlog */ res= mysql_routine_grant(thd, all_tables, lex->type == TYPE_ENUM_PROCEDURE, lex->users_list, grants, lex->sql_command == SQLCOM_REVOKE, TRUE); if (!res) my_ok(thd); } else { if (check_grant(thd,(lex->grant | lex->grant_tot_col | GRANT_ACL), all_tables, FALSE, UINT_MAX, FALSE)) goto error; /* Conditionally writes to binlog */ res= mysql_table_grant(thd, all_tables, lex->users_list, lex->columns, lex->grant, lex->sql_command == SQLCOM_REVOKE); } } else { if (lex->columns.elements || (lex->type && lex->type != TYPE_ENUM_PROXY)) { my_message(ER_ILLEGAL_GRANT_FOR_TABLE, ER(ER_ILLEGAL_GRANT_FOR_TABLE), MYF(0)); goto error; } else { /* Conditionally writes to binlog */ res= mysql_grant(thd, select_lex->db, lex->users_list, lex->grant, lex->sql_command == SQLCOM_REVOKE, lex->type == TYPE_ENUM_PROXY); } if (!res) { if (lex->sql_command == SQLCOM_GRANT) { List_iterator <LEX_USER> str_list(lex->users_list); LEX_USER *user, *tmp_user; while ((tmp_user=str_list++)) { if (!(user= get_current_user(thd, tmp_user))) goto error; reset_mqh(user, 0); } } } } break; } case SQLCOM_REVOKE_ROLE: case SQLCOM_GRANT_ROLE: { if (!(res= mysql_grant_role(thd, lex->users_list, lex->sql_command != SQLCOM_GRANT_ROLE))) my_ok(thd); break; } #endif /*!NO_EMBEDDED_ACCESS_CHECKS*/ case SQLCOM_RESET: /* RESET commands are never written to the binary log, so we have to initialize this variable because RESET shares the same code as FLUSH */ lex->no_write_to_binlog= 1; case SQLCOM_FLUSH: { int write_to_binlog; if (check_global_access(thd,RELOAD_ACL)) goto error; if (first_table && lex->type & (REFRESH_READ_LOCK|REFRESH_FOR_EXPORT)) { /* Check table-level privileges. */ if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)) goto error; if (flush_tables_with_read_lock(thd, all_tables)) goto error; my_ok(thd); break; } /* reload_acl_and_cache() will tell us if we are allowed to write to the binlog or not. */ if (!reload_acl_and_cache(thd, lex->type, first_table, &write_to_binlog)) { /* We WANT to write and we CAN write. ! we write after unlocking the table. */ /* Presumably, RESET and binlog writing doesn't require synchronization */ if (write_to_binlog > 0) // we should write { if (!lex->no_write_to_binlog) res= write_bin_log(thd, FALSE, thd->query(), thd->query_length()); } else if (write_to_binlog < 0) { /* We should not write, but rather report error because reload_acl_and_cache binlog interactions failed */ res= 1; } if (!res) my_ok(thd); } break; } case SQLCOM_KILL: { if (lex->table_or_sp_used()) { my_error(ER_NOT_SUPPORTED_YET, MYF(0), "Usage of subqueries or stored " "function calls as part of this statement"); break; } if (lex->kill_type == KILL_TYPE_ID || lex->kill_type == KILL_TYPE_QUERY) { Item *it= (Item *)lex->value_list.head(); if ((!it->fixed && it->fix_fields(lex->thd, &it)) || it->check_cols(1)) { my_message(ER_SET_CONSTANTS_ONLY, ER(ER_SET_CONSTANTS_ONLY), MYF(0)); goto error; } sql_kill(thd, it->val_int(), lex->kill_signal, lex->kill_type); } else sql_kill_user(thd, get_current_user(thd, lex->users_list.head()), lex->kill_signal); break; } case SQLCOM_SHUTDOWN: #ifndef EMBEDDED_LIBRARY if (check_global_access(thd,SHUTDOWN_ACL)) goto error; kill_mysql(); my_ok(thd); #else my_error(ER_NOT_SUPPORTED_YET, MYF(0), "embedded server"); #endif break; #ifndef NO_EMBEDDED_ACCESS_CHECKS case SQLCOM_SHOW_GRANTS: { LEX_USER *grant_user= lex->grant_user; if (!grant_user) goto error; if (grant_user->user.str && !strcmp(thd->security_ctx->priv_user, grant_user->user.str)) grant_user->user= current_user; if (grant_user->user.str == current_user.str || grant_user->user.str == current_role.str || grant_user->user.str == current_user_and_current_role.str || !check_access(thd, SELECT_ACL, "mysql", NULL, NULL, 1, 0)) { res = mysql_show_grants(thd, grant_user); } break; } #endif case SQLCOM_HA_OPEN: DBUG_ASSERT(first_table == all_tables && first_table != 0); if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE)) goto error; /* Close temporary tables which were pre-opened for privilege checking. */ close_thread_tables(thd); all_tables->table= NULL; res= mysql_ha_open(thd, first_table, 0); break; case SQLCOM_HA_CLOSE: DBUG_ASSERT(first_table == all_tables && first_table != 0); res= mysql_ha_close(thd, first_table); break; case SQLCOM_HA_READ: DBUG_ASSERT(first_table == all_tables && first_table != 0); /* There is no need to check for table permissions here, because if a user has no permissions to read a table, he won't be able to open it (with SQLCOM_HA_OPEN) in the first place. */ unit->set_limit(select_lex); res= mysql_ha_read(thd, first_table, lex->ha_read_mode, lex->ident.str, lex->insert_list, lex->ha_rkey_mode, select_lex->where, unit->select_limit_cnt, unit->offset_limit_cnt); break; case SQLCOM_BEGIN: DBUG_PRINT("info", ("Executing SQLCOM_BEGIN thd: %p", thd)); if (trans_begin(thd, lex->start_transaction_opt)) goto error; my_ok(thd); break; case SQLCOM_COMMIT: { DBUG_ASSERT(thd->lock == NULL || thd->locked_tables_mode == LTM_LOCK_TABLES); bool tx_chain= (lex->tx_chain == TVL_YES || (thd->variables.completion_type == 1 && lex->tx_chain != TVL_NO)); bool tx_release= (lex->tx_release == TVL_YES || (thd->variables.completion_type == 2 && lex->tx_release != TVL_NO)); if (trans_commit(thd)) goto error; thd->mdl_context.release_transactional_locks(); /* Begin transaction with the same isolation level. */ if (tx_chain) { if (trans_begin(thd)) goto error; } else { /* Reset the isolation level and access mode if no chaining transaction.*/ thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation; thd->tx_read_only= thd->variables.tx_read_only; } /* Disconnect the current client connection. */ if (tx_release) { thd->killed= KILL_CONNECTION; thd->print_aborted_warning(3, "RELEASE"); } my_ok(thd); break; } case SQLCOM_ROLLBACK: { DBUG_ASSERT(thd->lock == NULL || thd->locked_tables_mode == LTM_LOCK_TABLES); bool tx_chain= (lex->tx_chain == TVL_YES || (thd->variables.completion_type == 1 && lex->tx_chain != TVL_NO)); bool tx_release= (lex->tx_release == TVL_YES || (thd->variables.completion_type == 2 && lex->tx_release != TVL_NO)); if (trans_rollback(thd)) goto error; thd->mdl_context.release_transactional_locks(); /* Begin transaction with the same isolation level. */ if (tx_chain) { if (trans_begin(thd)) goto error; } else { /* Reset the isolation level and access mode if no chaining transaction.*/ thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation; thd->tx_read_only= thd->variables.tx_read_only; } /* Disconnect the current client connection. */ if (tx_release) thd->killed= KILL_CONNECTION; my_ok(thd); break; } case SQLCOM_RELEASE_SAVEPOINT: if (trans_release_savepoint(thd, lex->ident)) goto error; my_ok(thd); break; case SQLCOM_ROLLBACK_TO_SAVEPOINT: if (trans_rollback_to_savepoint(thd, lex->ident)) goto error; my_ok(thd); break; case SQLCOM_SAVEPOINT: if (trans_savepoint(thd, lex->ident)) goto error; my_ok(thd); break; case SQLCOM_CREATE_PROCEDURE: case SQLCOM_CREATE_SPFUNCTION: { uint namelen; char *name; int sp_result= SP_INTERNAL_ERROR; DBUG_ASSERT(lex->sphead != 0); DBUG_ASSERT(lex->sphead->m_db.str); /* Must be initialized in the parser */ /* Verify that the database name is allowed, optionally lowercase it. */ if (check_db_name(&lex->sphead->m_db)) { my_error(ER_WRONG_DB_NAME, MYF(0), lex->sphead->m_db.str); goto create_sp_error; } /* Check that a database directory with this name exists. Design note: This won't work on virtual databases like information_schema. */ if (check_db_dir_existence(lex->sphead->m_db.str)) { my_error(ER_BAD_DB_ERROR, MYF(0), lex->sphead->m_db.str); goto create_sp_error; } if (check_access(thd, CREATE_PROC_ACL, lex->sphead->m_db.str, NULL, NULL, 0, 0)) goto create_sp_error; name= lex->sphead->name(&namelen); #ifdef HAVE_DLOPEN if (lex->sphead->m_type == TYPE_ENUM_FUNCTION) { udf_func *udf = find_udf(name, namelen); if (udf) { my_error(ER_UDF_EXISTS, MYF(0), name); goto create_sp_error; } } #endif if (sp_process_definer(thd)) goto create_sp_error; res= (sp_result= sp_create_routine(thd, lex->sphead->m_type, lex->sphead)); switch (sp_result) { case SP_OK: { #ifndef NO_EMBEDDED_ACCESS_CHECKS /* only add privileges if really neccessary */ Security_context security_context; bool restore_backup_context= false; Security_context *backup= NULL; LEX_USER *definer= thd->lex->definer; /* We're going to issue an implicit GRANT statement so we close all open tables. We have to keep metadata locks as this ensures that this statement is atomic against concurent FLUSH TABLES WITH READ LOCK. Deadlocks which can arise due to fact that this implicit statement takes metadata locks should be detected by a deadlock detector in MDL subsystem and reported as errors. No need to commit/rollback statement transaction, it's not started. TODO: Long-term we should either ensure that implicit GRANT statement is written into binary log as a separate statement or make both creation of routine and implicit GRANT parts of one fully atomic statement. */ DBUG_ASSERT(thd->transaction.stmt.is_empty()); close_thread_tables(thd); /* Check if the definer exists on slave, then use definer privilege to insert routine privileges to mysql.procs_priv. For current user of SQL thread has GLOBAL_ACL privilege, which doesn't any check routine privileges, so no routine privilege record will insert into mysql.procs_priv. */ if (thd->slave_thread && is_acl_user(definer->host.str, definer->user.str)) { security_context.change_security_context(thd, &thd->lex->definer->user, &thd->lex->definer->host, &thd->lex->sphead->m_db, &backup); restore_backup_context= true; } if (sp_automatic_privileges && !opt_noacl && check_routine_access(thd, DEFAULT_CREATE_PROC_ACLS, lex->sphead->m_db.str, name, lex->sql_command == SQLCOM_CREATE_PROCEDURE, 1)) { if (sp_grant_privileges(thd, lex->sphead->m_db.str, name, lex->sql_command == SQLCOM_CREATE_PROCEDURE)) push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_PROC_AUTO_GRANT_FAIL, ER(ER_PROC_AUTO_GRANT_FAIL)); thd->clear_error(); } /* Restore current user with GLOBAL_ACL privilege of SQL thread */ if (restore_backup_context) { DBUG_ASSERT(thd->slave_thread == 1); thd->security_ctx->restore_security_context(thd, backup); } #endif break; } case SP_WRITE_ROW_FAILED: my_error(ER_SP_ALREADY_EXISTS, MYF(0), SP_TYPE_STRING(lex), name); break; case SP_BAD_IDENTIFIER: my_error(ER_TOO_LONG_IDENT, MYF(0), name); break; case SP_BODY_TOO_LONG: my_error(ER_TOO_LONG_BODY, MYF(0), name); break; case SP_FLD_STORE_FAILED: my_error(ER_CANT_CREATE_SROUTINE, MYF(0), name); break; default: my_error(ER_SP_STORE_FAILED, MYF(0), SP_TYPE_STRING(lex), name); break; } /* end switch */ /* Capture all errors within this CASE and clean up the environment. */ create_sp_error: if (sp_result != SP_OK ) goto error; my_ok(thd); break; /* break super switch */ } /* end case group bracket */ case SQLCOM_CALL: { sp_head *sp; /* This will cache all SP and SF and open and lock all tables required for execution. */ if (check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE) || open_and_lock_tables(thd, all_tables, TRUE, 0)) goto error; if (check_routine_access(thd, EXECUTE_ACL, lex->spname->m_db.str, lex->spname->m_name.str, TRUE, FALSE)) goto error; /* By this moment all needed SPs should be in cache so no need to look into DB. */ if (!(sp= sp_find_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname, &thd->sp_proc_cache, TRUE))) { my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "PROCEDURE", lex->spname->m_qname.str); goto error; } else { ha_rows select_limit; /* bits that should be cleared in thd->server_status */ uint bits_to_be_cleared= 0; /* Check that the stored procedure doesn't contain Dynamic SQL and doesn't return result sets: such stored procedures can't be called from a function or trigger. */ if (thd->in_sub_stmt) { const char *where= (thd->in_sub_stmt & SUB_STMT_TRIGGER ? "trigger" : "function"); if (sp->is_not_allowed_in_function(where)) goto error; } if (sp->m_flags & sp_head::MULTI_RESULTS) { if (! (thd->client_capabilities & CLIENT_MULTI_RESULTS)) { /* The client does not support multiple result sets being sent back */ my_error(ER_SP_BADSELECT, MYF(0), sp->m_qname.str); goto error; } /* If SERVER_MORE_RESULTS_EXISTS is not set, then remember that it should be cleared */ bits_to_be_cleared= (~thd->server_status & SERVER_MORE_RESULTS_EXISTS); thd->server_status|= SERVER_MORE_RESULTS_EXISTS; } select_limit= thd->variables.select_limit; thd->variables.select_limit= HA_POS_ERROR; /* We never write CALL statements into binlog: - If the mode is non-prelocked, each statement will be logged separately. - If the mode is prelocked, the invoking statement will care about writing into binlog. So just execute the statement. */ res= sp->execute_procedure(thd, &lex->value_list); thd->variables.select_limit= select_limit; thd->server_status&= ~bits_to_be_cleared; if (!res) { my_ok(thd, (thd->get_row_count_func() < 0) ? 0 : thd->get_row_count_func()); } else { DBUG_ASSERT(thd->is_error() || thd->killed); goto error; // Substatement should already have sent error } } break; } case SQLCOM_ALTER_PROCEDURE: case SQLCOM_ALTER_FUNCTION: { int sp_result; enum stored_procedure_type type; type= (lex->sql_command == SQLCOM_ALTER_PROCEDURE ? TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION); if (check_routine_access(thd, ALTER_PROC_ACL, lex->spname->m_db.str, lex->spname->m_name.str, lex->sql_command == SQLCOM_ALTER_PROCEDURE, 0)) goto error; /* Note that if you implement the capability of ALTER FUNCTION to alter the body of the function, this command should be made to follow the restrictions that log-bin-trust-function-creators=0 already puts on CREATE FUNCTION. */ /* Conditionally writes to binlog */ sp_result= sp_update_routine(thd, type, lex->spname, &lex->sp_chistics); switch (sp_result) { case SP_OK: my_ok(thd); break; case SP_KEY_NOT_FOUND: my_error(ER_SP_DOES_NOT_EXIST, MYF(0), SP_COM_STRING(lex), lex->spname->m_qname.str); goto error; default: my_error(ER_SP_CANT_ALTER, MYF(0), SP_COM_STRING(lex), lex->spname->m_qname.str); goto error; } break; } case SQLCOM_DROP_PROCEDURE: case SQLCOM_DROP_FUNCTION: { #ifdef HAVE_DLOPEN if (lex->sql_command == SQLCOM_DROP_FUNCTION && ! lex->spname->m_explicit_name) { /* DROP FUNCTION <non qualified name> */ udf_func *udf = find_udf(lex->spname->m_name.str, lex->spname->m_name.length); if (udf) { if (check_access(thd, DELETE_ACL, "mysql", NULL, NULL, 1, 0)) goto error; if (!(res = mysql_drop_function(thd, &lex->spname->m_name))) { my_ok(thd); break; } my_error(ER_SP_DROP_FAILED, MYF(0), "FUNCTION (UDF)", lex->spname->m_name.str); goto error; } if (lex->spname->m_db.str == NULL) { if (lex->check_exists) { push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST), "FUNCTION (UDF)", lex->spname->m_name.str); res= FALSE; my_ok(thd); break; } my_error(ER_SP_DOES_NOT_EXIST, MYF(0), "FUNCTION (UDF)", lex->spname->m_name.str); goto error; } /* Fall thought to test for a stored function */ } #endif int sp_result; enum stored_procedure_type type; type= (lex->sql_command == SQLCOM_DROP_PROCEDURE ? TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION); char *db= lex->spname->m_db.str; char *name= lex->spname->m_name.str; if (check_routine_access(thd, ALTER_PROC_ACL, db, name, lex->sql_command == SQLCOM_DROP_PROCEDURE, 0)) goto error; /* Conditionally writes to binlog */ sp_result= sp_drop_routine(thd, type, lex->spname); #ifndef NO_EMBEDDED_ACCESS_CHECKS /* We're going to issue an implicit REVOKE statement so we close all open tables. We have to keep metadata locks as this ensures that this statement is atomic against concurent FLUSH TABLES WITH READ LOCK. Deadlocks which can arise due to fact that this implicit statement takes metadata locks should be detected by a deadlock detector in MDL subsystem and reported as errors. No need to commit/rollback statement transaction, it's not started. TODO: Long-term we should either ensure that implicit REVOKE statement is written into binary log as a separate statement or make both dropping of routine and implicit REVOKE parts of one fully atomic statement. */ DBUG_ASSERT(thd->transaction.stmt.is_empty()); close_thread_tables(thd); if (sp_result != SP_KEY_NOT_FOUND && sp_automatic_privileges && !opt_noacl && sp_revoke_privileges(thd, db, name, lex->sql_command == SQLCOM_DROP_PROCEDURE)) { push_warning(thd, Sql_condition::WARN_LEVEL_WARN, ER_PROC_AUTO_REVOKE_FAIL, ER(ER_PROC_AUTO_REVOKE_FAIL)); /* If this happens, an error should have been reported. */ goto error; } #endif res= sp_result; switch (sp_result) { case SP_OK: my_ok(thd); break; case SP_KEY_NOT_FOUND: if (lex->check_exists) { res= write_bin_log(thd, TRUE, thd->query(), thd->query_length()); push_warning_printf(thd, Sql_condition::WARN_LEVEL_NOTE, ER_SP_DOES_NOT_EXIST, ER(ER_SP_DOES_NOT_EXIST), SP_COM_STRING(lex), lex->spname->m_qname.str); if (!res) my_ok(thd); break; } my_error(ER_SP_DOES_NOT_EXIST, MYF(0), SP_COM_STRING(lex), lex->spname->m_qname.str); goto error; default: my_error(ER_SP_DROP_FAILED, MYF(0), SP_COM_STRING(lex), lex->spname->m_qname.str); goto error; } break; } case SQLCOM_SHOW_CREATE_PROC: { if (sp_show_create_routine(thd, TYPE_ENUM_PROCEDURE, lex->spname)) goto error; break; } case SQLCOM_SHOW_CREATE_FUNC: { if (sp_show_create_routine(thd, TYPE_ENUM_FUNCTION, lex->spname)) goto error; break; } case SQLCOM_SHOW_PROC_CODE: case SQLCOM_SHOW_FUNC_CODE: { #ifndef DBUG_OFF sp_head *sp; stored_procedure_type type= (lex->sql_command == SQLCOM_SHOW_PROC_CODE ? TYPE_ENUM_PROCEDURE : TYPE_ENUM_FUNCTION); if (sp_cache_routine(thd, type, lex->spname, FALSE, &sp)) goto error; if (!sp || sp->show_routine_code(thd)) { /* We don't distinguish between errors for now */ my_error(ER_SP_DOES_NOT_EXIST, MYF(0), SP_COM_STRING(lex), lex->spname->m_name.str); goto error; } break; #else my_error(ER_FEATURE_DISABLED, MYF(0), "SHOW PROCEDURE|FUNCTION CODE", "--with-debug"); goto error; #endif // ifndef DBUG_OFF } case SQLCOM_SHOW_CREATE_TRIGGER: { if (lex->spname->m_name.length > NAME_LEN) { my_error(ER_TOO_LONG_IDENT, MYF(0), lex->spname->m_name.str); goto error; } if (show_create_trigger(thd, lex->spname)) goto error; /* Error has been already logged. */ break; } case SQLCOM_CREATE_VIEW: { /* Note: SQLCOM_CREATE_VIEW also handles 'ALTER VIEW' commands as specified through the thd->lex->create_view_mode flag. */ res= mysql_create_view(thd, first_table, thd->lex->create_view_mode); break; } case SQLCOM_DROP_VIEW: { if (check_table_access(thd, DROP_ACL, all_tables, FALSE, UINT_MAX, FALSE)) goto error; /* Conditionally writes to binlog. */ res= mysql_drop_view(thd, first_table, thd->lex->drop_mode); break; } case SQLCOM_CREATE_TRIGGER: { /* Conditionally writes to binlog. */ res= mysql_create_or_drop_trigger(thd, all_tables, 1); break; } case SQLCOM_DROP_TRIGGER: { /* Conditionally writes to binlog. */ res= mysql_create_or_drop_trigger(thd, all_tables, 0); break; } case SQLCOM_XA_START: if (trans_xa_start(thd)) goto error; my_ok(thd); break; case SQLCOM_XA_END: if (trans_xa_end(thd)) goto error; my_ok(thd); break; case SQLCOM_XA_PREPARE: if (trans_xa_prepare(thd)) goto error; my_ok(thd); break; case SQLCOM_XA_COMMIT: if (trans_xa_commit(thd)) goto error; thd->mdl_context.release_transactional_locks(); /* We've just done a commit, reset transaction isolation level and access mode to the session default. */ thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation; thd->tx_read_only= thd->variables.tx_read_only; my_ok(thd); break; case SQLCOM_XA_ROLLBACK: if (trans_xa_rollback(thd)) goto error; thd->mdl_context.release_transactional_locks(); /* We've just done a rollback, reset transaction isolation level and access mode to the session default. */ thd->tx_isolation= (enum_tx_isolation) thd->variables.tx_isolation; thd->tx_read_only= thd->variables.tx_read_only; my_ok(thd); break; case SQLCOM_XA_RECOVER: res= mysql_xa_recover(thd); break; case SQLCOM_ALTER_TABLESPACE: if (check_global_access(thd, CREATE_TABLESPACE_ACL)) break; if (!(res= mysql_alter_tablespace(thd, lex->alter_tablespace_info))) my_ok(thd); break; case SQLCOM_INSTALL_PLUGIN: if (! (res= mysql_install_plugin(thd, &thd->lex->comment, &thd->lex->ident))) my_ok(thd); break; case SQLCOM_UNINSTALL_PLUGIN: if (! (res= mysql_uninstall_plugin(thd, &thd->lex->comment, &thd->lex->ident))) my_ok(thd); break; case SQLCOM_BINLOG_BASE64_EVENT: { #ifndef EMBEDDED_LIBRARY mysql_client_binlog_statement(thd); #else /* EMBEDDED_LIBRARY */ my_error(ER_OPTION_PREVENTS_STATEMENT, MYF(0), "embedded"); #endif /* EMBEDDED_LIBRARY */ break; } case SQLCOM_CREATE_SERVER: { int error; LEX *lex= thd->lex; DBUG_PRINT("info", ("case SQLCOM_CREATE_SERVER")); if (check_global_access(thd, SUPER_ACL)) break; if ((error= create_server(thd, &lex->server_options))) { DBUG_PRINT("info", ("problem creating server <%s>", lex->server_options.server_name)); my_error(error, MYF(0), lex->server_options.server_name); break; } my_ok(thd, 1); break; } case SQLCOM_ALTER_SERVER: { int error; LEX *lex= thd->lex; DBUG_PRINT("info", ("case SQLCOM_ALTER_SERVER")); if (check_global_access(thd, SUPER_ACL)) break; if ((error= alter_server(thd, &lex->server_options))) { DBUG_PRINT("info", ("problem altering server <%s>", lex->server_options.server_name)); my_error(error, MYF(0), lex->server_options.server_name); break; } my_ok(thd, 1); break; } case SQLCOM_DROP_SERVER: { int err_code; LEX *lex= thd->lex; DBUG_PRINT("info", ("case SQLCOM_DROP_SERVER")); if (check_global_access(thd, SUPER_ACL)) break; if ((err_code= drop_server(thd, &lex->server_options))) { if (! lex->check_exists && err_code == ER_FOREIGN_SERVER_DOESNT_EXIST) { DBUG_PRINT("info", ("problem dropping server %s", lex->server_options.server_name)); my_error(err_code, MYF(0), lex->server_options.server_name); } else { my_ok(thd, 0); } break; } my_ok(thd, 1); break; } case SQLCOM_ANALYZE: case SQLCOM_CHECK: case SQLCOM_OPTIMIZE: case SQLCOM_REPAIR: case SQLCOM_TRUNCATE: case SQLCOM_ALTER_TABLE: thd->query_plan_flags|= QPLAN_ADMIN; DBUG_ASSERT(first_table == all_tables && first_table != 0); /* fall through */ case SQLCOM_SIGNAL: case SQLCOM_RESIGNAL: case SQLCOM_GET_DIAGNOSTICS: DBUG_ASSERT(lex->m_sql_cmd != NULL); res= lex->m_sql_cmd->execute(thd); break; default: #ifndef EMBEDDED_LIBRARY DBUG_ASSERT(0); /* Impossible */ #endif my_ok(thd); break; } THD_STAGE_INFO(thd, stage_query_end); thd->update_stats(); /* Binlog-related cleanup: Reset system variables temporarily modified by SET ONE SHOT. Exception: If this is a SET, do nothing. This is to allow mysqlbinlog to print many SET commands (in this case we want the charset temp setting to live until the real query). This is also needed so that SET CHARACTER_SET_CLIENT... does not cancel itself immediately. */ if (thd->one_shot_set && lex->sql_command != SQLCOM_SET_OPTION) reset_one_shot_variables(thd); goto finish; error: res= TRUE; finish: DBUG_ASSERT(!thd->in_active_multi_stmt_transaction() || thd->in_multi_stmt_transaction_mode()); lex->unit.cleanup(); if (! thd->in_sub_stmt) { if (thd->killed != NOT_KILLED) { /* report error issued during command execution */ if (thd->killed_errno()) { /* If we already sent 'ok', we can ignore any kill query statements */ if (! thd->get_stmt_da()->is_set()) thd->send_kill_message(); } if (thd->killed < KILL_CONNECTION) { thd->reset_killed(); thd->mysys_var->abort= 0; } } if (thd->is_error() || (thd->variables.option_bits & OPTION_MASTER_SQL_ERROR)) trans_rollback_stmt(thd); else { /* If commit fails, we should be able to reset the OK status. */ thd->get_stmt_da()->set_overwrite_status(true); trans_commit_stmt(thd); thd->get_stmt_da()->set_overwrite_status(false); } #ifdef WITH_ARIA_STORAGE_ENGINE ha_maria::implicit_commit(thd, FALSE); #endif } /* Free tables */ THD_STAGE_INFO(thd, stage_closing_tables); close_thread_tables(thd); #ifndef DBUG_OFF if (lex->sql_command != SQLCOM_SET_OPTION && ! thd->in_sub_stmt) DEBUG_SYNC(thd, "execute_command_after_close_tables"); #endif if (!(sql_command_flags[lex->sql_command] & (CF_CAN_GENERATE_ROW_EVENTS | CF_FORCE_ORIGINAL_BINLOG_FORMAT | CF_STATUS_COMMAND))) thd->set_binlog_format(orig_binlog_format, orig_current_stmt_binlog_format); if (! thd->in_sub_stmt && thd->transaction_rollback_request) { /* We are not in sub-statement and transaction rollback was requested by one of storage engines (e.g. due to deadlock). Rollback transaction in all storage engines including binary log. */ trans_rollback_implicit(thd); thd->mdl_context.release_transactional_locks(); } else if (stmt_causes_implicit_commit(thd, CF_IMPLICIT_COMMIT_END)) { /* No transaction control allowed in sub-statements. */ DBUG_ASSERT(! thd->in_sub_stmt); if (!(thd->variables.option_bits & OPTION_GTID_BEGIN)) { /* If commit fails, we should be able to reset the OK status. */ thd->get_stmt_da()->set_overwrite_status(true); /* Commit the normal transaction if one is active. */ trans_commit_implicit(thd); thd->get_stmt_da()->set_overwrite_status(false); thd->mdl_context.release_transactional_locks(); } } else if (! thd->in_sub_stmt && ! thd->in_multi_stmt_transaction_mode()) { /* - If inside a multi-statement transaction, defer the release of metadata locks until the current transaction is either committed or rolled back. This prevents other statements from modifying the table for the entire duration of this transaction. This provides commit ordering and guarantees serializability across multiple transactions. - If in autocommit mode, or outside a transactional context, automatically release metadata locks of the current statement. */ thd->mdl_context.release_transactional_locks(); } else if (! thd->in_sub_stmt) { thd->mdl_context.release_statement_locks(); } DBUG_RETURN(res || thd->is_error()); } static bool execute_sqlcom_select(THD *thd, TABLE_LIST *all_tables) { LEX *lex= thd->lex; select_result *result=lex->result; bool res; /* assign global limit variable if limit is not given */ { SELECT_LEX *param= lex->unit.global_parameters; if (!param->explicit_limit) param->select_limit= new Item_int((ulonglong) thd->variables.select_limit); } if (!(res= open_and_lock_tables(thd, all_tables, TRUE, 0))) { if (lex->describe) { /* We always use select_send for EXPLAIN, even if it's an EXPLAIN for SELECT ... INTO OUTFILE: a user application should be able to prepend EXPLAIN to any query and receive output for it, even if the query itself redirects the output. */ if (!(result= new select_send())) return 1; /* purecov: inspected */ thd->send_explain_fields(result); /* This will call optimize() for all parts of query. The query plan is printed out below. */ res= mysql_explain_union(thd, &thd->lex->unit, result); /* Print EXPLAIN only if we don't have an error */ if (!res) { /* Do like the original select_describe did: remove OFFSET from the top-level LIMIT */ result->reset_offset_limit(); thd->lex->explain->print_explain(result, thd->lex->describe); if (lex->describe & DESCRIBE_EXTENDED) { char buff[1024]; String str(buff,(uint32) sizeof(buff), system_charset_info); str.length(0); /* The warnings system requires input in utf8, @see mysqld_show_warnings(). */ thd->lex->unit.print(&str, QT_TO_SYSTEM_CHARSET); push_warning(thd, Sql_condition::WARN_LEVEL_NOTE, ER_YES, str.c_ptr_safe()); } } if (res) result->abort_result_set(); else result->send_eof(); delete result; } else { if (!result && !(result= new select_send())) return 1; /* purecov: inspected */ query_cache_store_query(thd, all_tables); res= handle_select(thd, lex, result, 0); if (result != lex->result) delete result; } } /* Count number of empty select queries */ if (!thd->get_sent_row_count()) status_var_increment(thd->status_var.empty_queries); else status_var_add(thd->status_var.rows_sent, thd->get_sent_row_count()); return res; } static bool execute_show_status(THD *thd, TABLE_LIST *all_tables) { bool res; system_status_var old_status_var= thd->status_var; thd->initial_status_var= &old_status_var; if (!(res= check_table_access(thd, SELECT_ACL, all_tables, FALSE, UINT_MAX, FALSE))) res= execute_sqlcom_select(thd, all_tables); /* Don't log SHOW STATUS commands to slow query log */ thd->server_status&= ~(SERVER_QUERY_NO_INDEX_USED | SERVER_QUERY_NO_GOOD_INDEX_USED); /* restore status variables, as we don't want 'show status' to cause changes */ mysql_mutex_lock(&LOCK_status); add_diff_to_status(&global_status_var, &thd->status_var, &old_status_var); memcpy(&thd->status_var, &old_status_var, offsetof(STATUS_VAR, last_cleared_system_status_var)); mysql_mutex_unlock(&LOCK_status); return res; } static bool execute_rename_table(THD *thd, TABLE_LIST *first_table, TABLE_LIST *all_tables) { DBUG_ASSERT(first_table == all_tables && first_table != 0); TABLE_LIST *table; for (table= first_table; table; table= table->next_local->next_local) { if (check_access(thd, ALTER_ACL | DROP_ACL, table->db, &table->grant.privilege, &table->grant.m_internal, 0, 0) || check_access(thd, INSERT_ACL | CREATE_ACL, table->next_local->db, &table->next_local->grant.privilege, &table->next_local->grant.m_internal, 0, 0)) return 1; TABLE_LIST old_list, new_list; /* we do not need initialize old_list and new_list because we will come table[0] and table->next[0] there */ old_list= table[0]; new_list= table->next_local[0]; if (check_grant(thd, ALTER_ACL | DROP_ACL, &old_list, FALSE, 1, FALSE) || (!test_all_bits(table->next_local->grant.privilege, INSERT_ACL | CREATE_ACL) && check_grant(thd, INSERT_ACL | CREATE_ACL, &new_list, FALSE, 1, FALSE))) return 1; } return mysql_rename_tables(thd, first_table, 0); } /** @brief Compare requested privileges with the privileges acquired from the User- and Db-tables. @param thd Thread handler @param want_access The requested access privileges. @param db A pointer to the Db name. @param[out] save_priv A pointer to the granted privileges will be stored. @param grant_internal_info A pointer to the internal grant cache. @param dont_check_global_grants True if no global grants are checked. @param no_error True if no errors should be sent to the client. 'save_priv' is used to save the User-table (global) and Db-table grants for the supplied db name. Note that we don't store db level grants if the global grants is enough to satisfy the request AND the global grants contains a SELECT grant. For internal databases (INFORMATION_SCHEMA, PERFORMANCE_SCHEMA), additional rules apply, see ACL_internal_schema_access. @see check_grant @return Status of denial of access by exclusive ACLs. @retval FALSE Access can't exclusively be denied by Db- and User-table access unless Column- and Table-grants are checked too. @retval TRUE Access denied. */ bool check_access(THD *thd, ulong want_access, const char *db, ulong *save_priv, GRANT_INTERNAL_INFO *grant_internal_info, bool dont_check_global_grants, bool no_errors) { #ifdef NO_EMBEDDED_ACCESS_CHECKS if (save_priv) *save_priv= GLOBAL_ACLS; return false; #else Security_context *sctx= thd->security_ctx; ulong db_access; /* GRANT command: In case of database level grant the database name may be a pattern, in case of table|column level grant the database name can not be a pattern. We use 'dont_check_global_grants' as a flag to determine if it's database level grant command (see SQLCOM_GRANT case, mysql_execute_command() function) and set db_is_pattern according to 'dont_check_global_grants' value. */ bool db_is_pattern= ((want_access & GRANT_ACL) && dont_check_global_grants); ulong dummy; DBUG_ENTER("check_access"); DBUG_PRINT("enter",("db: %s want_access: %lu master_access: %lu", db ? db : "", want_access, sctx->master_access)); if (save_priv) *save_priv=0; else { save_priv= &dummy; dummy= 0; } THD_STAGE_INFO(thd, stage_checking_permissions); if ((!db || !db[0]) && !thd->db && !dont_check_global_grants) { DBUG_PRINT("error",("No database")); if (!no_errors) my_message(ER_NO_DB_ERROR, ER(ER_NO_DB_ERROR), MYF(0)); /* purecov: tested */ DBUG_RETURN(TRUE); /* purecov: tested */ } if ((db != NULL) && (db != any_db)) { /* Check if this is reserved database, like information schema or performance schema */ const ACL_internal_schema_access *access; access= get_cached_schema_access(grant_internal_info, db); if (access) { switch (access->check(want_access, save_priv)) { case ACL_INTERNAL_ACCESS_GRANTED: /* All the privileges requested have been granted internally. [out] *save_privileges= Internal privileges. */ DBUG_RETURN(FALSE); case ACL_INTERNAL_ACCESS_DENIED: if (! no_errors) { status_var_increment(thd->status_var.access_denied_errors); my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), sctx->priv_user, sctx->priv_host, db); } DBUG_RETURN(TRUE); case ACL_INTERNAL_ACCESS_CHECK_GRANT: /* Only some of the privilege requested have been granted internally, proceed with the remaining bits of the request (want_access). */ want_access&= ~(*save_priv); break; } } } if ((sctx->master_access & want_access) == want_access) { /* 1. If we don't have a global SELECT privilege, we have to get the database specific access rights to be able to handle queries of type UPDATE t1 SET a=1 WHERE b > 0 2. Change db access if it isn't current db which is being addressed */ if (!(sctx->master_access & SELECT_ACL)) { if (db && (!thd->db || db_is_pattern || strcmp(db, thd->db))) { db_access= acl_get(sctx->host, sctx->ip, sctx->priv_user, db, db_is_pattern); if (sctx->priv_role[0]) db_access|= acl_get("", "", sctx->priv_role, db, db_is_pattern); } else { /* get access for current db */ db_access= sctx->db_access; } /* The effective privileges are the union of the global privileges and the intersection of db- and host-privileges, plus the internal privileges. */ *save_priv|= sctx->master_access | db_access; } else *save_priv|= sctx->master_access; DBUG_RETURN(FALSE); } if (((want_access & ~sctx->master_access) & ~DB_ACLS) || (! db && dont_check_global_grants)) { // We can never grant this DBUG_PRINT("error",("No possible access")); if (!no_errors) { status_var_increment(thd->status_var.access_denied_errors); my_error(access_denied_error_code(thd->password), MYF(0), sctx->priv_user, sctx->priv_host, (thd->password ? ER(ER_YES) : ER(ER_NO))); /* purecov: tested */ } DBUG_RETURN(TRUE); /* purecov: tested */ } if (db == any_db) { /* Access granted; Allow select on *any* db. [out] *save_privileges= 0 */ DBUG_RETURN(FALSE); } if (db && (!thd->db || db_is_pattern || strcmp(db,thd->db))) { db_access= acl_get(sctx->host, sctx->ip, sctx->priv_user, db, db_is_pattern); if (sctx->priv_role[0]) { db_access|= acl_get("", "", sctx->priv_role, db, db_is_pattern); } } else db_access= sctx->db_access; DBUG_PRINT("info",("db_access: %lu want_access: %lu", db_access, want_access)); /* Save the union of User-table and the intersection between Db-table and Host-table privileges, with the already saved internal privileges. */ db_access= (db_access | sctx->master_access); *save_priv|= db_access; /* We need to investigate column- and table access if all requested privileges belongs to the bit set of . */ bool need_table_or_column_check= (want_access & (TABLE_ACLS | PROC_ACLS | db_access)) == want_access; /* Grant access if the requested access is in the intersection of host- and db-privileges (as retrieved from the acl cache), also grant access if all the requested privileges are in the union of TABLES_ACLS and PROC_ACLS; see check_grant. */ if ( (db_access & want_access) == want_access || (!dont_check_global_grants && need_table_or_column_check)) { /* Ok; but need to check table- and column privileges. [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv) */ DBUG_RETURN(FALSE); } /* Access is denied; [out] *save_privileges is (User-priv | (Db-priv & Host-priv) | Internal-priv) */ DBUG_PRINT("error",("Access denied")); if (!no_errors) { status_var_increment(thd->status_var.access_denied_errors); my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), sctx->priv_user, sctx->priv_host, (db ? db : (thd->db ? thd->db : "unknown"))); } DBUG_RETURN(TRUE); #endif // NO_EMBEDDED_ACCESS_CHECKS } #ifndef NO_EMBEDDED_ACCESS_CHECKS /** Check grants for commands which work only with one table. @param thd Thread handler @param privilege requested privilege @param all_tables global table list of query @param no_errors FALSE/TRUE - report/don't report error to the client (using my_error() call). @retval 0 OK @retval 1 access denied, error is sent to client */ bool check_single_table_access(THD *thd, ulong privilege, TABLE_LIST *all_tables, bool no_errors) { Security_context * backup_ctx= thd->security_ctx; /* we need to switch to the saved context (if any) */ if (all_tables->security_ctx) thd->security_ctx= all_tables->security_ctx; const char *db_name; if ((all_tables->view || all_tables->field_translation) && !all_tables->schema_table) db_name= all_tables->view_db.str; else db_name= all_tables->db; if (check_access(thd, privilege, db_name, &all_tables->grant.privilege, &all_tables->grant.m_internal, 0, no_errors)) goto deny; /* Show only 1 table for check_grant */ if (!(all_tables->belong_to_view && (thd->lex->sql_command == SQLCOM_SHOW_FIELDS)) && check_grant(thd, privilege, all_tables, FALSE, 1, no_errors)) goto deny; thd->security_ctx= backup_ctx; return 0; deny: thd->security_ctx= backup_ctx; return 1; } /** Check grants for commands which work only with one table and all other tables belonging to subselects or implicitly opened tables. @param thd Thread handler @param privilege requested privilege @param all_tables global table list of query @retval 0 OK @retval 1 access denied, error is sent to client */ bool check_one_table_access(THD *thd, ulong privilege, TABLE_LIST *all_tables) { if (check_single_table_access (thd,privilege,all_tables, FALSE)) return 1; /* Check rights on tables of subselects and implictly opened tables */ TABLE_LIST *subselects_tables, *view= all_tables->view ? all_tables : 0; if ((subselects_tables= all_tables->next_global)) { /* Access rights asked for the first table of a view should be the same as for the view */ if (view && subselects_tables->belong_to_view == view) { if (check_single_table_access (thd, privilege, subselects_tables, FALSE)) return 1; subselects_tables= subselects_tables->next_global; } if (subselects_tables && (check_table_access(thd, SELECT_ACL, subselects_tables, FALSE, UINT_MAX, FALSE))) return 1; } return 0; } static bool check_show_access(THD *thd, TABLE_LIST *table) { /* This is a SHOW command using an INFORMATION_SCHEMA table. check_access() has not been called for 'table', and SELECT is currently always granted on the I_S, so we automatically grant SELECT on table here, to bypass a call to check_access(). Note that not calling check_access(table) is an optimization, which needs to be revisited if the INFORMATION_SCHEMA does not always automatically grant SELECT but use the grant tables. See Bug#38837 need a way to disable information_schema for security */ table->grant.privilege= SELECT_ACL; switch (get_schema_table_idx(table->schema_table)) { case SCH_SCHEMATA: return (specialflag & SPECIAL_SKIP_SHOW_DB) && check_global_access(thd, SHOW_DB_ACL); case SCH_TABLE_NAMES: case SCH_TABLES: case SCH_VIEWS: case SCH_TRIGGERS: case SCH_EVENTS: { const char *dst_db_name= table->schema_select_lex->db; DBUG_ASSERT(dst_db_name); if (check_access(thd, SELECT_ACL, dst_db_name, &thd->col_access, NULL, FALSE, FALSE)) return TRUE; if (!thd->col_access && check_grant_db(thd, dst_db_name)) { status_var_increment(thd->status_var.access_denied_errors); my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), thd->security_ctx->priv_user, thd->security_ctx->priv_host, dst_db_name); return TRUE; } return FALSE; } case SCH_COLUMNS: case SCH_STATISTICS: { TABLE_LIST *dst_table; dst_table= table->schema_select_lex->table_list.first; DBUG_ASSERT(dst_table); /* Open temporary tables to be able to detect them during privilege check. */ if (open_temporary_tables(thd, dst_table)) return TRUE; if (check_access(thd, SELECT_ACL, dst_table->db, &dst_table->grant.privilege, &dst_table->grant.m_internal, FALSE, FALSE)) return TRUE; /* Access denied */ /* Check_grant will grant access if there is any column privileges on all of the tables thanks to the fourth parameter (bool show_table). */ if (check_grant(thd, SELECT_ACL, dst_table, TRUE, UINT_MAX, FALSE)) return TRUE; /* Access denied */ close_thread_tables(thd); dst_table->table= NULL; /* Access granted */ return FALSE; } default: break; } return FALSE; } /** @brief Check if the requested privileges exists in either User-, Host- or Db-tables. @param thd Thread context @param want_access Privileges requested @param tables List of tables to be compared against @param no_errors Don't report error to the client (using my_error() call). @param any_combination_of_privileges_will_do TRUE if any privileges on any column combination is enough. @param number Only the first 'number' tables in the linked list are relevant. The suppled table list contains cached privileges. This functions calls the help functions check_access and check_grant to verify the first three steps in the privileges check queue: 1. Global privileges 2. OR (db privileges AND host privileges) 3. OR table privileges 4. OR column privileges (not checked by this function!) 5. OR routine privileges (not checked by this function!) @see check_access @see check_grant @note This functions assumes that table list used and thd->lex->query_tables_own_last value correspond to each other (the latter should be either 0 or point to next_global member of one of elements of this table list). @return @retval FALSE OK @retval TRUE Access denied; But column or routine privileges might need to be checked also. */ bool check_table_access(THD *thd, ulong requirements,TABLE_LIST *tables, bool any_combination_of_privileges_will_do, uint number, bool no_errors) { TABLE_LIST *org_tables= tables; TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table(); Security_context *sctx= thd->security_ctx, *backup_ctx= thd->security_ctx; uint i= 0; /* The check that first_not_own_table is not reached is for the case when the given table list refers to the list for prelocking (contains tables of other queries). For simple queries first_not_own_table is 0. */ for (; i < number && tables != first_not_own_table && tables; tables= tables->next_global, i++) { ulong want_access= requirements; if (tables->security_ctx) sctx= tables->security_ctx; else sctx= backup_ctx; /* Register access for view underlying table. Remove SHOW_VIEW_ACL, because it will be checked during making view */ tables->grant.orig_want_privilege= (want_access & ~SHOW_VIEW_ACL); if (tables->schema_table_reformed) { if (check_show_access(thd, tables)) goto deny; continue; } DBUG_PRINT("info", ("derived: %d view: %d", tables->derived != 0, tables->view != 0)); if (tables->is_anonymous_derived_table()) continue; thd->security_ctx= sctx; if (check_access(thd, want_access, tables->get_db_name(), &tables->grant.privilege, &tables->grant.m_internal, 0, no_errors)) goto deny; } thd->security_ctx= backup_ctx; return check_grant(thd,requirements,org_tables, any_combination_of_privileges_will_do, number, no_errors); deny: thd->security_ctx= backup_ctx; return TRUE; } bool check_routine_access(THD *thd, ulong want_access,char *db, char *name, bool is_proc, bool no_errors) { TABLE_LIST tables[1]; bzero((char *)tables, sizeof(TABLE_LIST)); tables->db= db; tables->table_name= tables->alias= name; /* The following test is just a shortcut for check_access() (to avoid calculating db_access) under the assumption that it's common to give persons global right to execute all stored SP (but not necessary to create them). Note that this effectively bypasses the ACL_internal_schema_access checks that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA, which are located in check_access(). Since the I_S and P_S do not contain routines, this bypass is ok, as long as this code path is not abused to create routines. The assert enforce that. */ DBUG_ASSERT((want_access & CREATE_PROC_ACL) == 0); if ((thd->security_ctx->master_access & want_access) == want_access) tables->grant.privilege= want_access; else if (check_access(thd, want_access, db, &tables->grant.privilege, &tables->grant.m_internal, 0, no_errors)) return TRUE; return check_grant_routine(thd, want_access, tables, is_proc, no_errors); } /** Check if the routine has any of the routine privileges. @param thd Thread handler @param db Database name @param name Routine name @retval 0 ok @retval 1 error */ bool check_some_routine_access(THD *thd, const char *db, const char *name, bool is_proc) { ulong save_priv; /* The following test is just a shortcut for check_access() (to avoid calculating db_access) Note that this effectively bypasses the ACL_internal_schema_access checks that are implemented for the INFORMATION_SCHEMA and PERFORMANCE_SCHEMA, which are located in check_access(). Since the I_S and P_S do not contain routines, this bypass is ok, as it only opens SHOW_PROC_ACLS. */ if (thd->security_ctx->master_access & SHOW_PROC_ACLS) return FALSE; if (!check_access(thd, SHOW_PROC_ACLS, db, &save_priv, NULL, 0, 1) || (save_priv & SHOW_PROC_ACLS)) return FALSE; return check_routine_level_acl(thd, db, name, is_proc); } /* Check if the given table has any of the asked privileges @param thd Thread handler @param want_access Bitmap of possible privileges to check for @retval 0 ok @retval 1 error */ bool check_some_access(THD *thd, ulong want_access, TABLE_LIST *table) { ulong access; DBUG_ENTER("check_some_access"); /* This loop will work as long as we have less than 32 privileges */ for (access= 1; access < want_access ; access<<= 1) { if (access & want_access) { if (!check_access(thd, access, table->db, &table->grant.privilege, &table->grant.m_internal, 0, 1) && !check_grant(thd, access, table, FALSE, 1, TRUE)) DBUG_RETURN(0); } } DBUG_PRINT("exit",("no matching access rights")); DBUG_RETURN(1); } #endif /*NO_EMBEDDED_ACCESS_CHECKS*/ /** check for global access and give descriptive error message if it fails. @param thd Thread handler @param want_access Use should have any of these global rights @warning One gets access right if one has ANY of the rights in want_access. This is useful as one in most cases only need one global right, but in some case we want to check if the user has SUPER or REPL_CLIENT_ACL rights. @retval 0 ok @retval 1 Access denied. In this case an error is sent to the client */ bool check_global_access(THD *thd, ulong want_access, bool no_errors) { #ifndef NO_EMBEDDED_ACCESS_CHECKS char command[128]; if ((thd->security_ctx->master_access & want_access)) return 0; if (!no_errors) { get_privilege_desc(command, sizeof(command), want_access); my_error(ER_SPECIFIC_ACCESS_DENIED_ERROR, MYF(0), command); } status_var_increment(thd->status_var.access_denied_errors); return 1; #else return 0; #endif } /**************************************************************************** Check stack size; Send error if there isn't enough stack to continue ****************************************************************************/ #if STACK_DIRECTION < 0 #define used_stack(A,B) (long) (A - B) #else #define used_stack(A,B) (long) (B - A) #endif #ifndef DBUG_OFF long max_stack_used; #endif /** @note Note: The 'buf' parameter is necessary, even if it is unused here. - fix_fields functions has a "dummy" buffer large enough for the corresponding exec. (Thus we only have to check in fix_fields.) - Passing to check_stack_overrun() prevents the compiler from removing it. */ bool check_stack_overrun(THD *thd, long margin, uchar *buf __attribute__((unused))) { long stack_used; DBUG_ASSERT(thd == current_thd); if ((stack_used=used_stack(thd->thread_stack,(char*) &stack_used)) >= (long) (my_thread_stack_size - margin)) { /* Do not use stack for the message buffer to ensure correct behaviour in cases we have close to no stack left. */ char* ebuff= new char[MYSQL_ERRMSG_SIZE]; if (ebuff) { my_snprintf(ebuff, MYSQL_ERRMSG_SIZE, ER(ER_STACK_OVERRUN_NEED_MORE), stack_used, my_thread_stack_size, margin); my_message(ER_STACK_OVERRUN_NEED_MORE, ebuff, MYF(ME_FATALERROR)); delete [] ebuff; } return 1; } #ifndef DBUG_OFF max_stack_used= MY_MAX(max_stack_used, stack_used); #endif return 0; } #define MY_YACC_INIT 1000 // Start with big alloc #define MY_YACC_MAX 32000 // Because of 'short' bool my_yyoverflow(short **yyss, YYSTYPE **yyvs, ulong *yystacksize) { Yacc_state *state= & current_thd->m_parser_state->m_yacc; ulong old_info=0; DBUG_ASSERT(state); if ((uint) *yystacksize >= MY_YACC_MAX) return 1; if (!state->yacc_yyvs) old_info= *yystacksize; *yystacksize= set_zone((*yystacksize)*2,MY_YACC_INIT,MY_YACC_MAX); if (!(state->yacc_yyvs= (uchar*) my_realloc(state->yacc_yyvs, *yystacksize*sizeof(**yyvs), MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR))) || !(state->yacc_yyss= (uchar*) my_realloc(state->yacc_yyss, *yystacksize*sizeof(**yyss), MYF(MY_ALLOW_ZERO_PTR | MY_FREE_ON_ERROR)))) return 1; if (old_info) { /* Only copy the old stack on the first call to my_yyoverflow(), when replacing a static stack (YYINITDEPTH) by a dynamic stack. For subsequent calls, my_realloc already did preserve the old stack. */ memcpy(state->yacc_yyss, *yyss, old_info*sizeof(**yyss)); memcpy(state->yacc_yyvs, *yyvs, old_info*sizeof(**yyvs)); } *yyss= (short*) state->yacc_yyss; *yyvs= (YYSTYPE*) state->yacc_yyvs; return 0; } /** Reset the part of THD responsible for the state of command processing. This needs to be called before execution of every statement (prepared or conventional). It is not called by substatements of routines. @todo Remove mysql_reset_thd_for_next_command and only use the member function. @todo Call it after we use THD for queries, not before. */ void mysql_reset_thd_for_next_command(THD *thd) { thd->reset_for_next_command(); } void THD::reset_for_next_command() { THD *thd= this; DBUG_ENTER("THD::reset_for_next_command"); DBUG_ASSERT(!thd->spcont); /* not for substatements of routines */ DBUG_ASSERT(! thd->in_sub_stmt); thd->free_list= 0; thd->select_number= 1; /* Those two lines below are theoretically unneeded as THD::cleanup_after_query() should take care of this already. */ thd->auto_inc_intervals_in_cur_stmt_for_binlog.empty(); thd->stmt_depends_on_first_successful_insert_id_in_prev_stmt= 0; thd->query_start_used= 0; thd->query_start_sec_part_used= 0; thd->is_fatal_error= thd->time_zone_used= 0; thd->log_current_statement= 0; /* Clear the status flag that are expected to be cleared at the beginning of each SQL statement. */ thd->server_status&= ~SERVER_STATUS_CLEAR_SET; /* If in autocommit mode and not in a transaction, reset OPTION_STATUS_NO_TRANS_UPDATE | OPTION_KEEP_LOG to not get warnings in ha_rollback_trans() about some tables couldn't be rolled back. */ if (!thd->in_multi_stmt_transaction_mode()) { thd->variables.option_bits&= ~OPTION_KEEP_LOG; thd->transaction.all.modified_non_trans_table= FALSE; } DBUG_ASSERT(thd->security_ctx== &thd->main_security_ctx); thd->thread_specific_used= FALSE; if (opt_bin_log) { reset_dynamic(&thd->user_var_events); thd->user_var_events_alloc= thd->mem_root; } thd->clear_error(); thd->get_stmt_da()->reset_diagnostics_area(); thd->get_stmt_da()->reset_for_next_command(); thd->rand_used= 0; thd->m_sent_row_count= thd->m_examined_row_count= 0; thd->accessed_rows_and_keys= 0; thd->query_plan_flags= QPLAN_INIT; thd->query_plan_fsort_passes= 0; thd->reset_current_stmt_binlog_format_row(); thd->binlog_unsafe_warning_flags= 0; DBUG_PRINT("debug", ("is_current_stmt_binlog_format_row(): %d", thd->is_current_stmt_binlog_format_row())); DBUG_VOID_RETURN; } /** Resets the lex->current_select object. @note It is assumed that lex->current_select != NULL This function is a wrapper around select_lex->init_select() with an added check for the special situation when using INTO OUTFILE and LOAD DATA. */ void mysql_init_select(LEX *lex) { SELECT_LEX *select_lex= lex->current_select; select_lex->init_select(); lex->wild= 0; if (select_lex == &lex->select_lex) { DBUG_ASSERT(lex->result == 0); lex->exchange= 0; } } /** Used to allocate a new SELECT_LEX object on the current thd mem_root and link it into the relevant lists. This function is always followed by mysql_init_select. @see mysql_init_select @retval TRUE An error occurred @retval FALSE The new SELECT_LEX was successfully allocated. */ bool mysql_new_select(LEX *lex, bool move_down) { SELECT_LEX *select_lex; THD *thd= lex->thd; DBUG_ENTER("mysql_new_select"); if (!(select_lex= new (thd->mem_root) SELECT_LEX())) DBUG_RETURN(1); select_lex->select_number= ++thd->select_number; select_lex->parent_lex= lex; /* Used in init_query. */ select_lex->init_query(); select_lex->init_select(); lex->nest_level++; if (lex->nest_level > (int) MAX_SELECT_NESTING) { my_error(ER_TOO_HIGH_LEVEL_OF_NESTING_FOR_SELECT, MYF(0)); DBUG_RETURN(1); } select_lex->nest_level= lex->nest_level; select_lex->nest_level_base= &thd->lex->unit; if (move_down) { SELECT_LEX_UNIT *unit; lex->subqueries= TRUE; /* first select_lex of subselect or derived table */ if (!(unit= new (thd->mem_root) SELECT_LEX_UNIT())) DBUG_RETURN(1); unit->init_query(); unit->init_select(); unit->thd= thd; unit->include_down(lex->current_select); unit->link_next= 0; unit->link_prev= 0; unit->return_to= lex->current_select; select_lex->include_down(unit); /* By default we assume that it is usual subselect and we have outer name resolution context, if no we will assign it to 0 later */ select_lex->context.outer_context= &select_lex->outer_select()->context; } else { if (lex->current_select->order_list.first && !lex->current_select->braces) { my_error(ER_WRONG_USAGE, MYF(0), "UNION", "ORDER BY"); DBUG_RETURN(1); } select_lex->include_neighbour(lex->current_select); SELECT_LEX_UNIT *unit= select_lex->master_unit(); if (!unit->fake_select_lex && unit->add_fake_select_lex(lex->thd)) DBUG_RETURN(1); select_lex->context.outer_context= unit->first_select()->context.outer_context; } select_lex->master_unit()->global_parameters= select_lex; select_lex->include_global((st_select_lex_node**)&lex->all_selects_list); lex->current_select= select_lex; /* in subquery is SELECT query and we allow resolution of names in SELECT list */ select_lex->context.resolve_in_select_list= TRUE; DBUG_RETURN(0); } /** Create a select to return the same output as 'SELECT @@var_name'. Used for SHOW COUNT(*) [ WARNINGS | ERROR]. This will crash with a core dump if the variable doesn't exists. @param var_name Variable name */ void create_select_for_variable(const char *var_name) { THD *thd; LEX *lex; LEX_STRING tmp, null_lex_string; Item *var; char buff[MAX_SYS_VAR_LENGTH*2+4+8], *end; DBUG_ENTER("create_select_for_variable"); thd= current_thd; lex= thd->lex; mysql_init_select(lex); lex->sql_command= SQLCOM_SELECT; tmp.str= (char*) var_name; tmp.length=strlen(var_name); bzero((char*) &null_lex_string.str, sizeof(null_lex_string)); /* We set the name of Item to @@session.var_name because that then is used as the column name in the output. */ if ((var= get_system_var(thd, OPT_SESSION, tmp, null_lex_string))) { end= strxmov(buff, "@@session.", var_name, NullS); var->set_name(buff, end-buff, system_charset_info); add_item_to_list(thd, var); } DBUG_VOID_RETURN; } void mysql_init_multi_delete(LEX *lex) { lex->sql_command= SQLCOM_DELETE_MULTI; mysql_init_select(lex); lex->select_lex.select_limit= 0; lex->unit.select_limit_cnt= HA_POS_ERROR; lex->select_lex.table_list.save_and_clear(&lex->auxiliary_table_list); lex->query_tables= 0; lex->query_tables_last= &lex->query_tables; } /* When you modify mysql_parse(), you may need to mofify mysql_test_parse_for_slave() in this same file. */ /** Parse a query. @param thd Current thread @param rawbuf Begining of the query text @param length Length of the query text @param[out] found_semicolon For multi queries, position of the character of the next query in the query text. */ void mysql_parse(THD *thd, char *rawbuf, uint length, Parser_state *parser_state) { int error __attribute__((unused)); DBUG_ENTER("mysql_parse"); DBUG_EXECUTE_IF("parser_debug", turn_parser_debug_on();); /* Warning. The purpose of query_cache_send_result_to_client() is to lookup the query in the query cache first, to avoid parsing and executing it. So, the natural implementation would be to: - first, call query_cache_send_result_to_client, - second, if caching failed, initialise the lexical and syntactic parser. The problem is that the query cache depends on a clean initialization of (among others) lex->safe_to_cache_query and thd->server_status, which are reset respectively in - lex_start() - mysql_reset_thd_for_next_command() So, initializing the lexical analyser *before* using the query cache is required for the cache to work properly. FIXME: cleanup the dependencies in the code to simplify this. */ lex_start(thd); mysql_reset_thd_for_next_command(thd); if (query_cache_send_result_to_client(thd, rawbuf, length) <= 0) { LEX *lex= thd->lex; bool err= parse_sql(thd, parser_state, NULL, true); if (!err) { thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi, sql_statement_info[thd->lex->sql_command]. m_key); #ifndef NO_EMBEDDED_ACCESS_CHECKS if (mqh_used && thd->user_connect && check_mqh(thd, lex->sql_command)) { thd->net.error = 0; } else #endif { if (! thd->is_error()) { const char *found_semicolon= parser_state->m_lip.found_semicolon; /* Binlog logs a string starting from thd->query and having length thd->query_length; so we set thd->query_length correctly (to not log several statements in one event, when we executed only first). We set it to not see the ';' (otherwise it would get into binlog and Query_log_event::print() would give ';;' output). This also helps display only the current query in SHOW PROCESSLIST. Note that we don't need LOCK_thread_count to modify query_length. */ if (found_semicolon && (ulong) (found_semicolon - thd->query())) thd->set_query_inner(thd->query(), (uint32) (found_semicolon - thd->query() - 1), thd->charset()); /* Actually execute the query */ if (found_semicolon) { lex->safe_to_cache_query= 0; thd->server_status|= SERVER_MORE_RESULTS_EXISTS; } lex->set_trg_event_type_for_tables(); MYSQL_QUERY_EXEC_START(thd->query(), thd->thread_id, (char *) (thd->db ? thd->db : ""), &thd->security_ctx->priv_user[0], (char *) thd->security_ctx->host_or_ip, 0); error= mysql_execute_command(thd); MYSQL_QUERY_EXEC_DONE(error); } } } else { /* Instrument this broken statement as "statement/sql/error" */ thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi, sql_statement_info[SQLCOM_END].m_key); DBUG_ASSERT(thd->is_error()); DBUG_PRINT("info",("Command aborted. Fatal_error: %d", thd->is_fatal_error)); query_cache_abort(&thd->query_cache_tls); } THD_STAGE_INFO(thd, stage_freeing_items); sp_cache_enforce_limit(thd->sp_proc_cache, stored_program_cache_size); sp_cache_enforce_limit(thd->sp_func_cache, stored_program_cache_size); thd->end_statement(); thd->cleanup_after_query(); DBUG_ASSERT(thd->change_list.is_empty()); } else { /* Update statistics for getting the query from the cache */ thd->lex->sql_command= SQLCOM_SELECT; thd->m_statement_psi= MYSQL_REFINE_STATEMENT(thd->m_statement_psi, sql_statement_info[SQLCOM_SELECT].m_key); status_var_increment(thd->status_var.com_stat[SQLCOM_SELECT]); thd->update_stats(); } DBUG_VOID_RETURN; } #ifdef HAVE_REPLICATION /* Usable by the replication SQL thread only: just parse a query to know if it can be ignored because of replicate-*-table rules. @retval 0 cannot be ignored @retval 1 can be ignored */ bool mysql_test_parse_for_slave(THD *thd, char *rawbuf, uint length) { LEX *lex= thd->lex; bool error= 0; DBUG_ENTER("mysql_test_parse_for_slave"); Parser_state parser_state; if (!(error= parser_state.init(thd, rawbuf, length))) { lex_start(thd); mysql_reset_thd_for_next_command(thd); if (!parse_sql(thd, & parser_state, NULL, true) && all_tables_not_ok(thd, lex->select_lex.table_list.first)) error= 1; /* Ignore question */ thd->end_statement(); } thd->cleanup_after_query(); DBUG_RETURN(error); } #endif /** Store field definition for create. @return Return 0 if ok */ bool add_field_to_list(THD *thd, LEX_STRING *field_name, enum_field_types type, char *length, char *decimals, uint type_modifier, Item *default_value, Item *on_update_value, LEX_STRING *comment, char *change, List<String> *interval_list, CHARSET_INFO *cs, uint uint_geom_type, Virtual_column_info *vcol_info, engine_option_value *create_options) { register Create_field *new_field; LEX *lex= thd->lex; uint8 datetime_precision= length ? atoi(length) : 0; DBUG_ENTER("add_field_to_list"); if (check_string_char_length(field_name, "", NAME_CHAR_LEN, system_charset_info, 1)) { my_error(ER_TOO_LONG_IDENT, MYF(0), field_name->str); /* purecov: inspected */ DBUG_RETURN(1); /* purecov: inspected */ } if (type_modifier & PRI_KEY_FLAG) { Key *key; lex->col_list.push_back(new Key_part_spec(*field_name, 0)); key= new Key(Key::PRIMARY, null_lex_str, &default_key_create_info, 0, lex->col_list, NULL, lex->check_exists); lex->alter_info.key_list.push_back(key); lex->col_list.empty(); } if (type_modifier & (UNIQUE_FLAG | UNIQUE_KEY_FLAG)) { Key *key; lex->col_list.push_back(new Key_part_spec(*field_name, 0)); key= new Key(Key::UNIQUE, null_lex_str, &default_key_create_info, 0, lex->col_list, NULL, lex->check_exists); lex->alter_info.key_list.push_back(key); lex->col_list.empty(); } if (default_value) { /* Default value should be literal => basic constants => no need fix_fields() We allow only one function as part of default value - NOW() as default for TIMESTAMP and DATETIME type. */ if (default_value->type() == Item::FUNC_ITEM && (static_cast<Item_func*>(default_value)->functype() != Item_func::NOW_FUNC || (mysql_type_to_time_type(type) != MYSQL_TIMESTAMP_DATETIME) || default_value->decimals < datetime_precision)) { my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str); DBUG_RETURN(1); } else if (default_value->type() == Item::NULL_ITEM) { default_value= 0; if ((type_modifier & (NOT_NULL_FLAG | AUTO_INCREMENT_FLAG)) == NOT_NULL_FLAG) { my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str); DBUG_RETURN(1); } } else if (type_modifier & AUTO_INCREMENT_FLAG) { my_error(ER_INVALID_DEFAULT, MYF(0), field_name->str); DBUG_RETURN(1); } } if (on_update_value && (mysql_type_to_time_type(type) != MYSQL_TIMESTAMP_DATETIME || on_update_value->decimals < datetime_precision)) { my_error(ER_INVALID_ON_UPDATE, MYF(0), field_name->str); DBUG_RETURN(1); } if (!(new_field= new Create_field()) || new_field->init(thd, field_name->str, type, length, decimals, type_modifier, default_value, on_update_value, comment, change, interval_list, cs, uint_geom_type, vcol_info, create_options, lex->check_exists)) DBUG_RETURN(1); lex->alter_info.create_list.push_back(new_field); lex->last_field=new_field; DBUG_RETURN(0); } /** Store position for column in ALTER TABLE .. ADD column. */ void store_position_for_column(const char *name) { current_thd->lex->last_field->after=(char*) (name); } bool add_proc_to_list(THD* thd, Item *item) { ORDER *order; Item **item_ptr; if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)+sizeof(Item*)))) return 1; item_ptr = (Item**) (order+1); *item_ptr= item; order->item=item_ptr; order->free_me=0; thd->lex->proc_list.link_in_list(order, &order->next); return 0; } /** save order by and tables in own lists. */ bool add_to_list(THD *thd, SQL_I_List<ORDER> &list, Item *item,bool asc) { ORDER *order; DBUG_ENTER("add_to_list"); if (!(order = (ORDER *) thd->alloc(sizeof(ORDER)))) DBUG_RETURN(1); order->item_ptr= item; order->item= &order->item_ptr; order->asc = asc; order->free_me=0; order->used=0; order->counter_used= 0; order->fast_field_copier_setup= 0; list.link_in_list(order, &order->next); DBUG_RETURN(0); } /** Add a table to list of used tables. @param table Table to add @param alias alias for table (or null if no alias) @param table_options A set of the following bits: - TL_OPTION_UPDATING : Table will be updated - TL_OPTION_FORCE_INDEX : Force usage of index - TL_OPTION_ALIAS : an alias in multi table DELETE @param lock_type How table should be locked @param mdl_type Type of metadata lock to acquire on the table. @param use_index List of indexed used in USE INDEX @param ignore_index List of indexed used in IGNORE INDEX @retval 0 Error @retval \# Pointer to TABLE_LIST element added to the total table list */ TABLE_LIST *st_select_lex::add_table_to_list(THD *thd, Table_ident *table, LEX_STRING *alias, ulong table_options, thr_lock_type lock_type, enum_mdl_type mdl_type, List<Index_hint> *index_hints_arg, List<String> *partition_names, LEX_STRING *option) { register TABLE_LIST *ptr; TABLE_LIST *previous_table_ref; /* The table preceding the current one. */ char *alias_str; LEX *lex= thd->lex; DBUG_ENTER("add_table_to_list"); LINT_INIT(previous_table_ref); if (!table) DBUG_RETURN(0); // End of memory alias_str= alias ? alias->str : table->table.str; if (!MY_TEST(table_options & TL_OPTION_ALIAS) && check_table_name(table->table.str, table->table.length, FALSE)) { my_error(ER_WRONG_TABLE_NAME, MYF(0), table->table.str); DBUG_RETURN(0); } if (table->is_derived_table() == FALSE && table->db.str && check_db_name(&table->db)) { my_error(ER_WRONG_DB_NAME, MYF(0), table->db.str); DBUG_RETURN(0); } if (!alias) /* Alias is case sensitive */ { if (table->sel) { my_message(ER_DERIVED_MUST_HAVE_ALIAS, ER(ER_DERIVED_MUST_HAVE_ALIAS), MYF(0)); DBUG_RETURN(0); } if (!(alias_str= (char*) thd->memdup(alias_str,table->table.length+1))) DBUG_RETURN(0); } if (!(ptr = (TABLE_LIST *) thd->calloc(sizeof(TABLE_LIST)))) DBUG_RETURN(0); /* purecov: inspected */ if (table->db.str) { ptr->is_fqtn= TRUE; ptr->db= table->db.str; ptr->db_length= table->db.length; } else if (lex->copy_db_to(&ptr->db, &ptr->db_length)) DBUG_RETURN(0); else ptr->is_fqtn= FALSE; ptr->alias= alias_str; ptr->is_alias= alias ? TRUE : FALSE; if (lower_case_table_names) { if (table->table.length) table->table.length= my_casedn_str(files_charset_info, table->table.str); if (ptr->db_length && ptr->db != any_db) ptr->db_length= my_casedn_str(files_charset_info, ptr->db); } ptr->table_name=table->table.str; ptr->table_name_length=table->table.length; ptr->lock_type= lock_type; ptr->updating= MY_TEST(table_options & TL_OPTION_UPDATING); /* TODO: remove TL_OPTION_FORCE_INDEX as it looks like it's not used */ ptr->force_index= MY_TEST(table_options & TL_OPTION_FORCE_INDEX); ptr->ignore_leaves= MY_TEST(table_options & TL_OPTION_IGNORE_LEAVES); ptr->derived= table->sel; if (!ptr->derived && is_infoschema_db(ptr->db, ptr->db_length)) { ST_SCHEMA_TABLE *schema_table; if (ptr->updating && /* Special cases which are processed by commands itself */ lex->sql_command != SQLCOM_CHECK && lex->sql_command != SQLCOM_CHECKSUM) { my_error(ER_DBACCESS_DENIED_ERROR, MYF(0), thd->security_ctx->priv_user, thd->security_ctx->priv_host, INFORMATION_SCHEMA_NAME.str); DBUG_RETURN(0); } schema_table= find_schema_table(thd, ptr->table_name); if (!schema_table || (schema_table->hidden && ((sql_command_flags[lex->sql_command] & CF_STATUS_COMMAND) == 0 || /* this check is used for show columns|keys from I_S hidden table */ lex->sql_command == SQLCOM_SHOW_FIELDS || lex->sql_command == SQLCOM_SHOW_KEYS))) { my_error(ER_UNKNOWN_TABLE, MYF(0), ptr->table_name, INFORMATION_SCHEMA_NAME.str); DBUG_RETURN(0); } ptr->schema_table_name= ptr->table_name; ptr->schema_table= schema_table; } ptr->select_lex= lex->current_select; /* We can't cache internal temporary tables between prepares as the table may be deleted before next exection. */ ptr->cacheable_table= !table->is_derived_table(); ptr->index_hints= index_hints_arg; ptr->option= option ? option->str : 0; /* check that used name is unique */ if (lock_type != TL_IGNORE) { TABLE_LIST *first_table= table_list.first; if (lex->sql_command == SQLCOM_CREATE_VIEW) first_table= first_table ? first_table->next_local : NULL; for (TABLE_LIST *tables= first_table ; tables ; tables=tables->next_local) { if (!my_strcasecmp(table_alias_charset, alias_str, tables->alias) && !strcmp(ptr->db, tables->db)) { my_error(ER_NONUNIQ_TABLE, MYF(0), alias_str); /* purecov: tested */ DBUG_RETURN(0); /* purecov: tested */ } } } /* Store the table reference preceding the current one. */ if (table_list.elements > 0) { /* table_list.next points to the last inserted TABLE_LIST->next_local' element We don't use the offsetof() macro here to avoid warnings from gcc */ previous_table_ref= (TABLE_LIST*) ((char*) table_list.next - ((char*) &(ptr->next_local) - (char*) ptr)); /* Set next_name_resolution_table of the previous table reference to point to the current table reference. In effect the list TABLE_LIST::next_name_resolution_table coincides with TABLE_LIST::next_local. Later this may be changed in store_top_level_join_columns() for NATURAL/USING joins. */ previous_table_ref->next_name_resolution_table= ptr; } /* Link the current table reference in a local list (list for current select). Notice that as a side effect here we set the next_local field of the previous table reference to 'ptr'. Here we also add one element to the list 'table_list'. */ table_list.link_in_list(ptr, &ptr->next_local); ptr->next_name_resolution_table= NULL; #ifdef WITH_PARTITION_STORAGE_ENGINE ptr->partition_names= partition_names; #endif /* WITH_PARTITION_STORAGE_ENGINE */ /* Link table in global list (all used tables) */ lex->add_to_query_tables(ptr); // Pure table aliases do not need to be locked: if (!MY_TEST(table_options & TL_OPTION_ALIAS)) { ptr->mdl_request.init(MDL_key::TABLE, ptr->db, ptr->table_name, mdl_type, MDL_TRANSACTION); } DBUG_RETURN(ptr); } /** Initialize a new table list for a nested join. The function initializes a structure of the TABLE_LIST type for a nested join. It sets up its nested join list as empty. The created structure is added to the front of the current join list in the st_select_lex object. Then the function changes the current nest level for joins to refer to the newly created empty list after having saved the info on the old level in the initialized structure. @param thd current thread @retval 0 if success @retval 1 otherwise */ bool st_select_lex::init_nested_join(THD *thd) { TABLE_LIST *ptr; NESTED_JOIN *nested_join; DBUG_ENTER("init_nested_join"); if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+ sizeof(NESTED_JOIN)))) DBUG_RETURN(1); nested_join= ptr->nested_join= ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST)))); join_list->push_front(ptr); ptr->embedding= embedding; ptr->join_list= join_list; ptr->alias= (char*) "(nested_join)"; embedding= ptr; join_list= &nested_join->join_list; join_list->empty(); DBUG_RETURN(0); } /** End a nested join table list. The function returns to the previous join nest level. If the current level contains only one member, the function moves it one level up, eliminating the nest. @param thd current thread @return - Pointer to TABLE_LIST element added to the total table list, if success - 0, otherwise */ TABLE_LIST *st_select_lex::end_nested_join(THD *thd) { TABLE_LIST *ptr; NESTED_JOIN *nested_join; DBUG_ENTER("end_nested_join"); DBUG_ASSERT(embedding); ptr= embedding; join_list= ptr->join_list; embedding= ptr->embedding; nested_join= ptr->nested_join; if (nested_join->join_list.elements == 1) { TABLE_LIST *embedded= nested_join->join_list.head(); join_list->pop(); embedded->join_list= join_list; embedded->embedding= embedding; join_list->push_front(embedded); ptr= embedded; embedded->lifted= 1; } else if (nested_join->join_list.elements == 0) { join_list->pop(); ptr= 0; // return value } DBUG_RETURN(ptr); } /** Nest last join operation. The function nest last join operation as if it was enclosed in braces. @param thd current thread @retval 0 Error @retval \# Pointer to TABLE_LIST element created for the new nested join */ TABLE_LIST *st_select_lex::nest_last_join(THD *thd) { TABLE_LIST *ptr; NESTED_JOIN *nested_join; List<TABLE_LIST> *embedded_list; DBUG_ENTER("nest_last_join"); if (!(ptr= (TABLE_LIST*) thd->calloc(ALIGN_SIZE(sizeof(TABLE_LIST))+ sizeof(NESTED_JOIN)))) DBUG_RETURN(0); nested_join= ptr->nested_join= ((NESTED_JOIN*) ((uchar*) ptr + ALIGN_SIZE(sizeof(TABLE_LIST)))); ptr->embedding= embedding; ptr->join_list= join_list; ptr->alias= (char*) "(nest_last_join)"; embedded_list= &nested_join->join_list; embedded_list->empty(); for (uint i=0; i < 2; i++) { TABLE_LIST *table= join_list->pop(); if (!table) DBUG_RETURN(NULL); table->join_list= embedded_list; table->embedding= ptr; embedded_list->push_back(table); if (table->natural_join) { ptr->is_natural_join= TRUE; /* If this is a JOIN ... USING, move the list of joined fields to the table reference that describes the join. */ if (prev_join_using) ptr->join_using_fields= prev_join_using; } } join_list->push_front(ptr); nested_join->used_tables= nested_join->not_null_tables= (table_map) 0; DBUG_RETURN(ptr); } /** Add a table to the current join list. The function puts a table in front of the current join list of st_select_lex object. Thus, joined tables are put into this list in the reverse order (the most outer join operation follows first). @param table the table to add @return None */ void st_select_lex::add_joined_table(TABLE_LIST *table) { DBUG_ENTER("add_joined_table"); join_list->push_front(table); table->join_list= join_list; table->embedding= embedding; DBUG_VOID_RETURN; } /** Convert a right join into equivalent left join. The function takes the current join list t[0],t[1] ... and effectively converts it into the list t[1],t[0] ... Although the outer_join flag for the new nested table contains JOIN_TYPE_RIGHT, it will be handled as the inner table of a left join operation. EXAMPLES @verbatim SELECT * FROM t1 RIGHT JOIN t2 ON on_expr => SELECT * FROM t2 LEFT JOIN t1 ON on_expr SELECT * FROM t1,t2 RIGHT JOIN t3 ON on_expr => SELECT * FROM t1,t3 LEFT JOIN t2 ON on_expr SELECT * FROM t1,t2 RIGHT JOIN (t3,t4) ON on_expr => SELECT * FROM t1,(t3,t4) LEFT JOIN t2 ON on_expr SELECT * FROM t1 LEFT JOIN t2 ON on_expr1 RIGHT JOIN t3 ON on_expr2 => SELECT * FROM t3 LEFT JOIN (t1 LEFT JOIN t2 ON on_expr2) ON on_expr1 @endverbatim @param thd current thread @return - Pointer to the table representing the inner table, if success - 0, otherwise */ TABLE_LIST *st_select_lex::convert_right_join() { TABLE_LIST *tab2= join_list->pop(); TABLE_LIST *tab1= join_list->pop(); DBUG_ENTER("convert_right_join"); join_list->push_front(tab2); join_list->push_front(tab1); tab1->outer_join|= JOIN_TYPE_RIGHT; DBUG_RETURN(tab1); } /** Set lock for all tables in current select level. @param lock_type Lock to set for tables @note If lock is a write lock, then tables->updating is set 1 This is to get tables_ok to know that the table is updated by the query */ void st_select_lex::set_lock_for_tables(thr_lock_type lock_type) { bool for_update= lock_type >= TL_READ_NO_INSERT; DBUG_ENTER("set_lock_for_tables"); DBUG_PRINT("enter", ("lock_type: %d for_update: %d", lock_type, for_update)); for (TABLE_LIST *tables= table_list.first; tables; tables= tables->next_local) { tables->lock_type= lock_type; tables->updating= for_update; tables->mdl_request.set_type((lock_type >= TL_WRITE_ALLOW_WRITE) ? MDL_SHARED_WRITE : MDL_SHARED_READ); } DBUG_VOID_RETURN; } /** Create a fake SELECT_LEX for a unit. The method create a fake SELECT_LEX object for a unit. This object is created for any union construct containing a union operation and also for any single select union construct of the form @verbatim (SELECT ... ORDER BY order_list [LIMIT n]) ORDER BY ... @endvarbatim or of the form @varbatim (SELECT ... ORDER BY LIMIT n) ORDER BY ... @endvarbatim @param thd_arg thread handle @note The object is used to retrieve rows from the temporary table where the result on the union is obtained. @retval 1 on failure to create the object @retval 0 on success */ bool st_select_lex_unit::add_fake_select_lex(THD *thd_arg) { SELECT_LEX *first_sl= first_select(); DBUG_ENTER("add_fake_select_lex"); DBUG_ASSERT(!fake_select_lex); if (!(fake_select_lex= new (thd_arg->mem_root) SELECT_LEX())) DBUG_RETURN(1); fake_select_lex->include_standalone(this, (SELECT_LEX_NODE**)&fake_select_lex); fake_select_lex->select_number= INT_MAX; fake_select_lex->parent_lex= thd_arg->lex; /* Used in init_query. */ fake_select_lex->make_empty_select(); fake_select_lex->linkage= GLOBAL_OPTIONS_TYPE; fake_select_lex->select_limit= 0; fake_select_lex->context.outer_context=first_sl->context.outer_context; /* allow item list resolving in fake select for ORDER BY */ fake_select_lex->context.resolve_in_select_list= TRUE; fake_select_lex->context.select_lex= fake_select_lex; if (!is_union()) { /* This works only for (SELECT ... ORDER BY list [LIMIT n]) ORDER BY order_list [LIMIT m], (SELECT ... LIMIT n) ORDER BY order_list [LIMIT m] just before the parser starts processing order_list */ global_parameters= fake_select_lex; fake_select_lex->no_table_names_allowed= 1; thd_arg->lex->current_select= fake_select_lex; } thd_arg->lex->pop_context(); DBUG_RETURN(0); } /** Push a new name resolution context for a JOIN ... ON clause to the context stack of a query block. Create a new name resolution context for a JOIN ... ON clause, set the first and last leaves of the list of table references to be used for name resolution, and push the newly created context to the stack of contexts of the query. @param thd pointer to current thread @param left_op left operand of the JOIN @param right_op rigth operand of the JOIN @retval FALSE if all is OK @retval TRUE if a memory allocation error occured */ bool push_new_name_resolution_context(THD *thd, TABLE_LIST *left_op, TABLE_LIST *right_op) { Name_resolution_context *on_context; if (!(on_context= new (thd->mem_root) Name_resolution_context)) return TRUE; on_context->init(); on_context->first_name_resolution_table= left_op->first_leaf_for_name_resolution(); on_context->last_name_resolution_table= right_op->last_leaf_for_name_resolution(); return thd->lex->push_context(on_context); } /** Fix condition which contains only field (f turns to f <> 0 ) @param cond The condition to fix @return fixed condition */ Item *normalize_cond(Item *cond) { if (cond) { Item::Type type= cond->type(); if (type == Item::FIELD_ITEM || type == Item::REF_ITEM) { cond= new Item_func_ne(cond, new Item_int(0)); } } return cond; } /** Add an ON condition to the second operand of a JOIN ... ON. Add an ON condition to the right operand of a JOIN ... ON clause. @param b the second operand of a JOIN ... ON @param expr the condition to be added to the ON clause @retval FALSE if there was some error @retval TRUE if all is OK */ void add_join_on(TABLE_LIST *b, Item *expr) { if (expr) { expr= normalize_cond(expr); if (!b->on_expr) b->on_expr= expr; else { /* If called from the parser, this happens if you have both a right and left join. If called later, it happens if we add more than one condition to the ON clause. */ b->on_expr= new Item_cond_and(b->on_expr,expr); } b->on_expr->top_level_item(); } } /** Mark that there is a NATURAL JOIN or JOIN ... USING between two tables. This function marks that table b should be joined with a either via a NATURAL JOIN or via JOIN ... USING. Both join types are special cases of each other, so we treat them together. The function setup_conds() creates a list of equal condition between all fields of the same name for NATURAL JOIN or the fields in 'using_fields' for JOIN ... USING. The list of equality conditions is stored either in b->on_expr, or in JOIN::conds, depending on whether there was an outer join. EXAMPLE @verbatim SELECT * FROM t1 NATURAL LEFT JOIN t2 <=> SELECT * FROM t1 LEFT JOIN t2 ON (t1.i=t2.i and t1.j=t2.j ... ) SELECT * FROM t1 NATURAL JOIN t2 WHERE <some_cond> <=> SELECT * FROM t1, t2 WHERE (t1.i=t2.i and t1.j=t2.j and <some_cond>) SELECT * FROM t1 JOIN t2 USING(j) WHERE <some_cond> <=> SELECT * FROM t1, t2 WHERE (t1.j=t2.j and <some_cond>) @endverbatim @param a Left join argument @param b Right join argument @param using_fields Field names from USING clause */ void add_join_natural(TABLE_LIST *a, TABLE_LIST *b, List<String> *using_fields, SELECT_LEX *lex) { b->natural_join= a; lex->prev_join_using= using_fields; } /** Find a thread by id and return it, locking it LOCK_thd_data @param id Identifier of the thread we're looking for @param query_id If true, search by query_id instead of thread_id @return NULL - not found pointer - thread found, and its LOCK_thd_data is locked. */ THD *find_thread_by_id(longlong id, bool query_id) { THD *tmp; mysql_mutex_lock(&LOCK_thread_count); // For unlink from list I_List_iterator<THD> it(threads); while ((tmp=it++)) { if (tmp->get_command() == COM_DAEMON) continue; if (id == (query_id ? tmp->query_id : (longlong) tmp->thread_id)) { mysql_mutex_lock(&tmp->LOCK_thd_data); // Lock from delete break; } } mysql_mutex_unlock(&LOCK_thread_count); return tmp; } /** kill one thread. @param thd Thread class @param id Thread id or query id @param kill_signal Should it kill the query or the connection @param type Type of id: thread id or query id @note This is written such that we have a short lock on LOCK_thread_count */ uint kill_one_thread(THD *thd, longlong id, killed_state kill_signal, killed_type type) { THD *tmp; uint error= (type == KILL_TYPE_QUERY ? ER_NO_SUCH_QUERY : ER_NO_SUCH_THREAD); DBUG_ENTER("kill_one_thread"); DBUG_PRINT("enter", ("id: %lld signal: %u", id, (uint) kill_signal)); if (id && (tmp= find_thread_by_id(id, type == KILL_TYPE_QUERY))) { /* If we're SUPER, we can KILL anything, including system-threads. No further checks. KILLer: thd->security_ctx->user could in theory be NULL while we're still in "unauthenticated" state. This is a theoretical case (the code suggests this could happen, so we play it safe). KILLee: tmp->security_ctx->user will be NULL for system threads. We need to check so Jane Random User doesn't crash the server when trying to kill a) system threads or b) unauthenticated users' threads (Bug#43748). If user of both killer and killee are non-NULL, proceed with slayage if both are string-equal. It's ok to also kill DELAYED threads with KILL_CONNECTION instead of KILL_SYSTEM_THREAD; The difference is that KILL_CONNECTION may be faster and do a harder kill than KILL_SYSTEM_THREAD; */ if ((thd->security_ctx->master_access & SUPER_ACL) || thd->security_ctx->user_matches(tmp->security_ctx)) { tmp->awake(kill_signal); error=0; } else error=ER_KILL_DENIED_ERROR; mysql_mutex_unlock(&tmp->LOCK_thd_data); } DBUG_PRINT("exit", ("%d", error)); DBUG_RETURN(error); } /** kill all threads from one user @param thd Thread class @param user_name User name for threads we should kill @param only_kill_query Should it kill the query or the connection @note This is written such that we have a short lock on LOCK_thread_count If we can't kill all threads because of security issues, no threads are killed. */ static uint kill_threads_for_user(THD *thd, LEX_USER *user, killed_state kill_signal, ha_rows *rows) { THD *tmp; List<THD> threads_to_kill; DBUG_ENTER("kill_threads_for_user"); *rows= 0; if (thd->is_fatal_error) // If we run out of memory DBUG_RETURN(ER_OUT_OF_RESOURCES); DBUG_PRINT("enter", ("user: %s signal: %u", user->user.str, (uint) kill_signal)); mysql_mutex_lock(&LOCK_thread_count); // For unlink from list I_List_iterator<THD> it(threads); while ((tmp=it++)) { if (tmp->get_command() == COM_DAEMON) continue; /* Check that hostname (if given) and user name matches. host.str[0] == '%' means that host name was not given. See sql_yacc.yy */ if (((user->host.str[0] == '%' && !user->host.str[1]) || !strcmp(tmp->security_ctx->host, user->host.str)) && !strcmp(tmp->security_ctx->user, user->user.str)) { if (!(thd->security_ctx->master_access & SUPER_ACL) && !thd->security_ctx->user_matches(tmp->security_ctx)) { mysql_mutex_unlock(&LOCK_thread_count); DBUG_RETURN(ER_KILL_DENIED_ERROR); } if (!threads_to_kill.push_back(tmp, thd->mem_root)) mysql_mutex_lock(&tmp->LOCK_thd_data); // Lock from delete } } mysql_mutex_unlock(&LOCK_thread_count); if (!threads_to_kill.is_empty()) { List_iterator_fast<THD> it(threads_to_kill); THD *next_ptr; THD *ptr= it++; do { ptr->awake(kill_signal); /* Careful here: The list nodes are allocated on the memroots of the THDs to be awakened. But those THDs may be terminated and deleted as soon as we release LOCK_thd_data, which will make the list nodes invalid. Since the operation "it++" dereferences the "next" pointer of the previous list node, we need to do this while holding LOCK_thd_data. */ next_ptr= it++; mysql_mutex_unlock(&ptr->LOCK_thd_data); (*rows)++; } while ((ptr= next_ptr)); } DBUG_RETURN(0); } /** kills a thread and sends response. @param thd Thread class @param id Thread id or query id @param state Should it kill the query or the connection @param type Type of id: thread id or query id */ static void sql_kill(THD *thd, longlong id, killed_state state, killed_type type) { uint error; if (!(error= kill_one_thread(thd, id, state, type))) { if ((!thd->killed)) my_ok(thd); else my_error(killed_errno(thd->killed), MYF(0), id); } else my_error(error, MYF(0), id); } static void sql_kill_user(THD *thd, LEX_USER *user, killed_state state) { uint error; ha_rows rows; if (!(error= kill_threads_for_user(thd, user, state, &rows))) my_ok(thd, rows); else { /* This is probably ER_OUT_OF_RESOURCES, but in the future we may want to write the name of the user we tried to kill */ my_error(error, MYF(0), user->host.str, user->user.str); } } /** If pointer is not a null pointer, append filename to it. */ bool append_file_to_dir(THD *thd, const char **filename_ptr, const char *table_name) { char buff[FN_REFLEN],*ptr, *end; if (!*filename_ptr) return 0; // nothing to do /* Check that the filename is not too long and it's a hard path */ if (strlen(*filename_ptr)+strlen(table_name) >= FN_REFLEN-1 || !test_if_hard_path(*filename_ptr)) { my_error(ER_WRONG_TABLE_NAME, MYF(0), *filename_ptr); return 1; } /* Fix is using unix filename format on dos */ strmov(buff,*filename_ptr); end=convert_dirname(buff, *filename_ptr, NullS); if (!(ptr= (char*) thd->alloc((size_t) (end-buff) + strlen(table_name)+1))) return 1; // End of memory *filename_ptr=ptr; strxmov(ptr,buff,table_name,NullS); return 0; } /** Check if the select is a simple select (not an union). @retval 0 ok @retval 1 error ; In this case the error messege is sent to the client */ bool check_simple_select() { THD *thd= current_thd; LEX *lex= thd->lex; if (lex->current_select != &lex->select_lex) { char command[80]; Lex_input_stream *lip= & thd->m_parser_state->m_lip; strmake(command, lip->yylval->symbol.str, MY_MIN(lip->yylval->symbol.length, sizeof(command)-1)); my_error(ER_CANT_USE_OPTION_HERE, MYF(0), command); return 1; } return 0; } Comp_creator *comp_eq_creator(bool invert) { return invert?(Comp_creator *)&ne_creator:(Comp_creator *)&eq_creator; } Comp_creator *comp_ge_creator(bool invert) { return invert?(Comp_creator *)&lt_creator:(Comp_creator *)&ge_creator; } Comp_creator *comp_gt_creator(bool invert) { return invert?(Comp_creator *)&le_creator:(Comp_creator *)&gt_creator; } Comp_creator *comp_le_creator(bool invert) { return invert?(Comp_creator *)&gt_creator:(Comp_creator *)&le_creator; } Comp_creator *comp_lt_creator(bool invert) { return invert?(Comp_creator *)&ge_creator:(Comp_creator *)&lt_creator; } Comp_creator *comp_ne_creator(bool invert) { return invert?(Comp_creator *)&eq_creator:(Comp_creator *)&ne_creator; } /** Construct ALL/ANY/SOME subquery Item. @param left_expr pointer to left expression @param cmp compare function creator @param all true if we create ALL subquery @param select_lex pointer on parsed subquery structure @return constructed Item (or 0 if out of memory) */ Item * all_any_subquery_creator(Item *left_expr, chooser_compare_func_creator cmp, bool all, SELECT_LEX *select_lex) { if ((cmp == &comp_eq_creator) && !all) // = ANY <=> IN return new Item_in_subselect(left_expr, select_lex); if ((cmp == &comp_ne_creator) && all) // <> ALL <=> NOT IN return new Item_func_not(new Item_in_subselect(left_expr, select_lex)); Item_allany_subselect *it= new Item_allany_subselect(left_expr, cmp, select_lex, all); if (all) return it->upper_item= new Item_func_not_all(it); /* ALL */ return it->upper_item= new Item_func_nop_all(it); /* ANY/SOME */ } /** Multi update query pre-check. @param thd Thread handler @param tables Global/local table list (have to be the same) @retval FALSE OK @retval TRUE Error */ bool multi_update_precheck(THD *thd, TABLE_LIST *tables) { const char *msg= 0; TABLE_LIST *table; LEX *lex= thd->lex; SELECT_LEX *select_lex= &lex->select_lex; DBUG_ENTER("multi_update_precheck"); if (select_lex->item_list.elements != lex->value_list.elements) { my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0)); DBUG_RETURN(TRUE); } /* Ensure that we have UPDATE or SELECT privilege for each table The exact privilege is checked in mysql_multi_update() */ for (table= tables; table; table= table->next_local) { if (table->derived) table->grant.privilege= SELECT_ACL; else if ((check_access(thd, UPDATE_ACL, table->db, &table->grant.privilege, &table->grant.m_internal, 0, 1) || check_grant(thd, UPDATE_ACL, table, FALSE, 1, TRUE)) && (check_access(thd, SELECT_ACL, table->db, &table->grant.privilege, &table->grant.m_internal, 0, 0) || check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE))) DBUG_RETURN(TRUE); table->grant.orig_want_privilege= 0; table->table_in_first_from_clause= 1; } /* Is there tables of subqueries? */ if (&lex->select_lex != lex->all_selects_list) { DBUG_PRINT("info",("Checking sub query list")); for (table= tables; table; table= table->next_global) { if (!table->table_in_first_from_clause) { if (check_access(thd, SELECT_ACL, table->db, &table->grant.privilege, &table->grant.m_internal, 0, 0) || check_grant(thd, SELECT_ACL, table, FALSE, 1, FALSE)) DBUG_RETURN(TRUE); } } } if (select_lex->order_list.elements) msg= "ORDER BY"; else if (select_lex->select_limit) msg= "LIMIT"; if (msg) { my_error(ER_WRONG_USAGE, MYF(0), "UPDATE", msg); DBUG_RETURN(TRUE); } DBUG_RETURN(FALSE); } /** Multi delete query pre-check. @param thd Thread handler @param tables Global/local table list @retval FALSE OK @retval TRUE error */ bool multi_delete_precheck(THD *thd, TABLE_LIST *tables) { SELECT_LEX *select_lex= &thd->lex->select_lex; TABLE_LIST *aux_tables= thd->lex->auxiliary_table_list.first; TABLE_LIST **save_query_tables_own_last= thd->lex->query_tables_own_last; DBUG_ENTER("multi_delete_precheck"); /* Temporary tables are pre-opened in 'tables' list only. Here we need to initialize TABLE instances in 'aux_tables' list. */ for (TABLE_LIST *tl= aux_tables; tl; tl= tl->next_global) { if (tl->table) continue; if (tl->correspondent_table) tl->table= tl->correspondent_table->table; } /* sql_yacc guarantees that tables and aux_tables are not zero */ DBUG_ASSERT(aux_tables != 0); if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE)) DBUG_RETURN(TRUE); /* Since aux_tables list is not part of LEX::query_tables list we have to juggle with LEX::query_tables_own_last value to be able call check_table_access() safely. */ thd->lex->query_tables_own_last= 0; if (check_table_access(thd, DELETE_ACL, aux_tables, FALSE, UINT_MAX, FALSE)) { thd->lex->query_tables_own_last= save_query_tables_own_last; DBUG_RETURN(TRUE); } thd->lex->query_tables_own_last= save_query_tables_own_last; if ((thd->variables.option_bits & OPTION_SAFE_UPDATES) && !select_lex->where) { my_message(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE, ER(ER_UPDATE_WITHOUT_KEY_IN_SAFE_MODE), MYF(0)); DBUG_RETURN(TRUE); } DBUG_RETURN(FALSE); } /* Given a table in the source list, find a correspondent table in the table references list. @param lex Pointer to LEX representing multi-delete. @param src Source table to match. @param ref Table references list. @remark The source table list (tables listed before the FROM clause or tables listed in the FROM clause before the USING clause) may contain table names or aliases that must match unambiguously one, and only one, table in the target table list (table references list, after FROM/USING clause). @return Matching table, NULL otherwise. */ static TABLE_LIST *multi_delete_table_match(LEX *lex, TABLE_LIST *tbl, TABLE_LIST *tables) { TABLE_LIST *match= NULL; DBUG_ENTER("multi_delete_table_match"); for (TABLE_LIST *elem= tables; elem; elem= elem->next_local) { int cmp; if (tbl->is_fqtn && elem->is_alias) continue; /* no match */ if (tbl->is_fqtn && elem->is_fqtn) cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) || strcmp(tbl->db, elem->db); else if (elem->is_alias) cmp= my_strcasecmp(table_alias_charset, tbl->alias, elem->alias); else cmp= my_strcasecmp(table_alias_charset, tbl->table_name, elem->table_name) || strcmp(tbl->db, elem->db); if (cmp) continue; if (match) { my_error(ER_NONUNIQ_TABLE, MYF(0), elem->alias); DBUG_RETURN(NULL); } match= elem; } if (!match) my_error(ER_UNKNOWN_TABLE, MYF(0), tbl->table_name, "MULTI DELETE"); DBUG_RETURN(match); } /** Link tables in auxilary table list of multi-delete with corresponding elements in main table list, and set proper locks for them. @param lex pointer to LEX representing multi-delete @retval FALSE success @retval TRUE error */ bool multi_delete_set_locks_and_link_aux_tables(LEX *lex) { TABLE_LIST *tables= lex->select_lex.table_list.first; TABLE_LIST *target_tbl; DBUG_ENTER("multi_delete_set_locks_and_link_aux_tables"); lex->table_count= 0; for (target_tbl= lex->auxiliary_table_list.first; target_tbl; target_tbl= target_tbl->next_local) { lex->table_count++; /* All tables in aux_tables must be found in FROM PART */ TABLE_LIST *walk= multi_delete_table_match(lex, target_tbl, tables); if (!walk) DBUG_RETURN(TRUE); if (!walk->derived) { target_tbl->table_name= walk->table_name; target_tbl->table_name_length= walk->table_name_length; } walk->updating= target_tbl->updating; walk->lock_type= target_tbl->lock_type; /* We can assume that tables to be deleted from are locked for write. */ DBUG_ASSERT(walk->lock_type >= TL_WRITE_ALLOW_WRITE); walk->mdl_request.set_type(MDL_SHARED_WRITE); target_tbl->correspondent_table= walk; // Remember corresponding table } DBUG_RETURN(FALSE); } /** simple UPDATE query pre-check. @param thd Thread handler @param tables Global table list @retval FALSE OK @retval TRUE Error */ bool update_precheck(THD *thd, TABLE_LIST *tables) { DBUG_ENTER("update_precheck"); if (thd->lex->select_lex.item_list.elements != thd->lex->value_list.elements) { my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0)); DBUG_RETURN(TRUE); } DBUG_RETURN(check_one_table_access(thd, UPDATE_ACL, tables)); } /** simple DELETE query pre-check. @param thd Thread handler @param tables Global table list @retval FALSE OK @retval TRUE error */ bool delete_precheck(THD *thd, TABLE_LIST *tables) { DBUG_ENTER("delete_precheck"); if (check_one_table_access(thd, DELETE_ACL, tables)) DBUG_RETURN(TRUE); /* Set privilege for the WHERE clause */ tables->grant.want_privilege=(SELECT_ACL & ~tables->grant.privilege); DBUG_RETURN(FALSE); } /** simple INSERT query pre-check. @param thd Thread handler @param tables Global table list @retval FALSE OK @retval TRUE error */ bool insert_precheck(THD *thd, TABLE_LIST *tables) { LEX *lex= thd->lex; DBUG_ENTER("insert_precheck"); /* Check that we have modify privileges for the first table and select privileges for the rest */ ulong privilege= (INSERT_ACL | (lex->duplicates == DUP_REPLACE ? DELETE_ACL : 0) | (lex->value_list.elements ? UPDATE_ACL : 0)); if (check_one_table_access(thd, privilege, tables)) DBUG_RETURN(TRUE); if (lex->update_list.elements != lex->value_list.elements) { my_message(ER_WRONG_VALUE_COUNT, ER(ER_WRONG_VALUE_COUNT), MYF(0)); DBUG_RETURN(TRUE); } DBUG_RETURN(FALSE); } /** Set proper open mode and table type for element representing target table of CREATE TABLE statement, also adjust statement table list if necessary. */ void create_table_set_open_action_and_adjust_tables(LEX *lex) { TABLE_LIST *create_table= lex->query_tables; if (lex->create_info.tmp_table()) create_table->open_type= OT_TEMPORARY_ONLY; else create_table->open_type= OT_BASE_ONLY; if (!lex->select_lex.item_list.elements) { /* Avoid opening and locking target table for ordinary CREATE TABLE or CREATE TABLE LIKE for write (unlike in CREATE ... SELECT we won't do any insertions in it anyway). Not doing this causes problems when running CREATE TABLE IF NOT EXISTS for already existing log table. */ create_table->lock_type= TL_READ; } } /** CREATE TABLE query pre-check. @param thd Thread handler @param tables Global table list @param create_table Table which will be created @retval FALSE OK @retval TRUE Error */ bool create_table_precheck(THD *thd, TABLE_LIST *tables, TABLE_LIST *create_table) { LEX *lex= thd->lex; SELECT_LEX *select_lex= &lex->select_lex; ulong want_priv; bool error= TRUE; // Error message is given DBUG_ENTER("create_table_precheck"); /* Require CREATE [TEMPORARY] privilege on new table; for CREATE TABLE ... SELECT, also require INSERT. */ want_priv= lex->create_info.tmp_table() ? CREATE_TMP_ACL : (CREATE_ACL | (select_lex->item_list.elements ? INSERT_ACL : 0)); /* CREATE OR REPLACE on not temporary tables require DROP_ACL */ if ((lex->create_info.options & HA_LEX_CREATE_REPLACE) && !lex->create_info.tmp_table()) want_priv|= DROP_ACL; if (check_access(thd, want_priv, create_table->db, &create_table->grant.privilege, &create_table->grant.m_internal, 0, 0)) goto err; /* If it is a merge table, check privileges for merge children. */ if (lex->create_info.merge_list.first) { /* The user must have (SELECT_ACL | UPDATE_ACL | DELETE_ACL) on the underlying base tables, even if there are temporary tables with the same names. From user's point of view, it might look as if the user must have these privileges on temporary tables to create a merge table over them. This is one of two cases when a set of privileges is required for operations on temporary tables (see also CREATE TABLE). The reason for this behavior stems from the following facts: - For merge tables, the underlying table privileges are checked only at CREATE TABLE / ALTER TABLE time. In other words, once a merge table is created, the privileges of the underlying tables can be revoked, but the user will still have access to the merge table (provided that the user has privileges on the merge table itself). - Temporary tables shadow base tables. I.e. there might be temporary and base tables with the same name, and the temporary table takes the precedence in all operations. - For temporary MERGE tables we do not track if their child tables are base or temporary. As result we can't guarantee that privilege check which was done in presence of temporary child will stay relevant later as this temporary table might be removed. If SELECT_ACL | UPDATE_ACL | DELETE_ACL privileges were not checked for the underlying *base* tables, it would create a security breach as in Bug#12771903. */ if (check_table_access(thd, SELECT_ACL | UPDATE_ACL | DELETE_ACL, lex->create_info.merge_list.first, FALSE, UINT_MAX, FALSE)) goto err; } if (want_priv != CREATE_TMP_ACL && check_grant(thd, want_priv, create_table, FALSE, 1, FALSE)) goto err; if (select_lex->item_list.elements) { /* Check permissions for used tables in CREATE TABLE ... SELECT */ if (tables && check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE)) goto err; } else if (lex->create_info.options & HA_LEX_CREATE_TABLE_LIKE) { if (check_table_access(thd, SELECT_ACL, tables, FALSE, UINT_MAX, FALSE)) goto err; } error= FALSE; /* For CREATE TABLE we should not open the table even if it exists. If the table exists, we should either not create it or replace it */ lex->query_tables->open_strategy= TABLE_LIST::OPEN_STUB; err: DBUG_RETURN(error); } /** Check privileges for LOCK TABLES statement. @param thd Thread context. @param tables List of tables to be locked. @retval FALSE - Success. @retval TRUE - Failure. */ static bool lock_tables_precheck(THD *thd, TABLE_LIST *tables) { TABLE_LIST *first_not_own_table= thd->lex->first_not_own_table(); for (TABLE_LIST *table= tables; table != first_not_own_table && table; table= table->next_global) { if (is_temporary_table(table)) continue; if (check_table_access(thd, LOCK_TABLES_ACL | SELECT_ACL, table, FALSE, 1, FALSE)) return TRUE; } return FALSE; } /** negate given expression. @param thd thread handler @param expr expression for negation @return negated expression */ Item *negate_expression(THD *thd, Item *expr) { Item *negated; if (expr->type() == Item::FUNC_ITEM && ((Item_func *) expr)->functype() == Item_func::NOT_FUNC) { /* it is NOT(NOT( ... )) */ Item *arg= ((Item_func *) expr)->arguments()[0]; enum_parsing_place place= thd->lex->current_select->parsing_place; if (arg->is_bool_func() || place == IN_WHERE || place == IN_HAVING) return arg; /* if it is not boolean function then we have to emulate value of not(not(a)), it will be a != 0 */ return new Item_func_ne(arg, new Item_int((char*) "0", 0, 1)); } if ((negated= expr->neg_transformer(thd)) != 0) return negated; return new Item_func_not(expr); } /** Set the specified definer to the default value, which is the current user in the thread. @param[in] thd thread handler @param[out] definer definer */ void get_default_definer(THD *thd, LEX_USER *definer, bool role) { const Security_context *sctx= thd->security_ctx; if (role) { definer->user.str= const_cast<char*>(sctx->priv_role); definer->host= empty_lex_str; } else { definer->user.str= const_cast<char*>(sctx->priv_user); definer->host.str= const_cast<char*>(sctx->priv_host); definer->host.length= strlen(definer->host.str); } definer->user.length= strlen(definer->user.str); definer->password= null_lex_str; definer->plugin= empty_lex_str; definer->auth= empty_lex_str; } /** Create default definer for the specified THD. @param[in] thd thread handler @return - On success, return a valid pointer to the created and initialized LEX_USER, which contains definer information. - On error, return 0. */ LEX_USER *create_default_definer(THD *thd, bool role) { LEX_USER *definer; if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER)))) return 0; thd->get_definer(definer, role); if (role && definer->user.length == 0) { my_error(ER_MALFORMED_DEFINER, MYF(0)); return 0; } else return definer; } /** Create definer with the given user and host names. @param[in] thd thread handler @param[in] user_name user name @param[in] host_name host name @return - On success, return a valid pointer to the created and initialized LEX_USER, which contains definer information. - On error, return 0. */ LEX_USER *create_definer(THD *thd, LEX_STRING *user_name, LEX_STRING *host_name) { LEX_USER *definer; /* Create and initialize. */ if (! (definer= (LEX_USER*) thd->alloc(sizeof(LEX_USER)))) return 0; definer->user= *user_name; definer->host= *host_name; definer->password.str= NULL; definer->password.length= 0; return definer; } /** Check that byte length of a string does not exceed some limit. @param str string to be checked @param err_msg error message to be displayed if the string is too long @param max_length max length @retval FALSE the passed string is not longer than max_length @retval TRUE the passed string is longer than max_length NOTE The function is not used in existing code but can be useful later? */ bool check_string_byte_length(LEX_STRING *str, const char *err_msg, uint max_byte_length) { if (str->length <= max_byte_length) return FALSE; my_error(ER_WRONG_STRING_LENGTH, MYF(0), str->str, err_msg, max_byte_length); return TRUE; } /* Check that char length of a string does not exceed some limit. SYNOPSIS check_string_char_length() str string to be checked err_msg error message to be displayed if the string is too long max_char_length max length in symbols cs string charset RETURN FALSE the passed string is not longer than max_char_length TRUE the passed string is longer than max_char_length */ bool check_string_char_length(LEX_STRING *str, const char *err_msg, uint max_char_length, CHARSET_INFO *cs, bool no_error) { int well_formed_error; uint res= cs->cset->well_formed_len(cs, str->str, str->str + str->length, max_char_length, &well_formed_error); if (!well_formed_error && str->length == res) return FALSE; if (!no_error) { ErrConvString err(str->str, str->length, cs); my_error(ER_WRONG_STRING_LENGTH, MYF(0), err.ptr(), err_msg, max_char_length); } return TRUE; } C_MODE_START /* Check if path does not contain mysql data home directory SYNOPSIS test_if_data_home_dir() dir directory RETURN VALUES 0 ok 1 error ; Given path contains data directory */ int test_if_data_home_dir(const char *dir) { char path[FN_REFLEN]; int dir_len; DBUG_ENTER("test_if_data_home_dir"); if (!dir) DBUG_RETURN(0); /* data_file_name and index_file_name include the table name without extension. Mostly this does not refer to an existing file. When comparing data_file_name or index_file_name against the data directory, we try to resolve all symbolic links. On some systems, we use realpath(3) for the resolution. This returns ENOENT if the resolved path does not refer to an existing file. my_realpath() does then copy the requested path verbatim, without symlink resolution. Thereafter the comparison can fail even if the requested path is within the data directory. E.g. if symlinks to another file system are used. To make realpath(3) return the resolved path, we strip the table name and compare the directory path only. If the directory doesn't exist either, table creation will fail anyway. */ (void) fn_format(path, dir, "", "", (MY_RETURN_REAL_PATH|MY_RESOLVE_SYMLINKS)); dir_len= strlen(path); if (mysql_unpacked_real_data_home_len<= dir_len) { if (dir_len > mysql_unpacked_real_data_home_len && path[mysql_unpacked_real_data_home_len] != FN_LIBCHAR) DBUG_RETURN(0); if (lower_case_file_system) { if (!my_strnncoll(default_charset_info, (const uchar*) path, mysql_unpacked_real_data_home_len, (const uchar*) mysql_unpacked_real_data_home, mysql_unpacked_real_data_home_len)) { DBUG_PRINT("error", ("Path is part of mysql_real_data_home")); DBUG_RETURN(1); } } else if (!memcmp(path, mysql_unpacked_real_data_home, mysql_unpacked_real_data_home_len)) { DBUG_PRINT("error", ("Path is part of mysql_real_data_home")); DBUG_RETURN(1); } } DBUG_RETURN(0); } C_MODE_END int error_if_data_home_dir(const char *path, const char *what) { size_t dirlen; char dirpath[FN_REFLEN]; if (path) { dirname_part(dirpath, path, &dirlen); if (test_if_data_home_dir(dirpath)) { my_error(ER_WRONG_ARGUMENTS, MYF(0), what); return 1; } } return 0; } /** Check that host name string is valid. @param[in] str string to be checked @return Operation status @retval FALSE host name is ok @retval TRUE host name string is longer than max_length or has invalid symbols */ bool check_host_name(LEX_STRING *str) { const char *name= str->str; const char *end= str->str + str->length; if (check_string_byte_length(str, ER(ER_HOSTNAME), HOSTNAME_LENGTH)) return TRUE; while (name != end) { if (*name == '@') { my_printf_error(ER_UNKNOWN_ERROR, "Malformed hostname (illegal symbol: '%c')", MYF(0), *name); return TRUE; } name++; } return FALSE; } extern int MYSQLparse(THD *thd); // from sql_yacc.cc /** This is a wrapper of MYSQLparse(). All the code should call parse_sql() instead of MYSQLparse(). @param thd Thread context. @param parser_state Parser state. @param creation_ctx Object creation context. @return Error status. @retval FALSE on success. @retval TRUE on parsing error. */ bool parse_sql(THD *thd, Parser_state *parser_state, Object_creation_ctx *creation_ctx, bool do_pfs_digest) { bool ret_value; DBUG_ENTER("parse_sql"); DBUG_ASSERT(thd->m_parser_state == NULL); DBUG_ASSERT(thd->lex->m_sql_cmd == NULL); MYSQL_QUERY_PARSE_START(thd->query()); /* Backup creation context. */ Object_creation_ctx *backup_ctx= NULL; if (creation_ctx) backup_ctx= creation_ctx->set_n_backup(thd); /* Set parser state. */ thd->m_parser_state= parser_state; #ifdef HAVE_PSI_STATEMENT_DIGEST_INTERFACE /* Start Digest */ thd->m_parser_state->m_lip.m_digest_psi= MYSQL_DIGEST_START(do_pfs_digest ? thd->m_statement_psi : NULL); #endif /* Parse the query. */ bool mysql_parse_status= MYSQLparse(thd) != 0; /* Check that if MYSQLparse() failed either thd->is_error() is set, or an internal error handler is set. The assert will not catch a situation where parsing fails without an error reported if an error handler exists. The problem is that the error handler might have intercepted the error, so thd->is_error() is not set. However, there is no way to be 100% sure here (the error handler might be for other errors than parsing one). */ DBUG_ASSERT(!mysql_parse_status || thd->is_error() || thd->get_internal_handler()); /* Reset parser state. */ thd->m_parser_state= NULL; /* Restore creation context. */ if (creation_ctx) creation_ctx->restore_env(thd, backup_ctx); /* That's it. */ ret_value= mysql_parse_status || thd->is_fatal_error; MYSQL_QUERY_PARSE_DONE(ret_value); DBUG_RETURN(ret_value); } /** @} (end of group Runtime_Environment) */ /** Check and merge "CHARACTER SET cs [ COLLATE cl ]" clause @param cs character set pointer. @param cl collation pointer. Check if collation "cl" is applicable to character set "cs". If "cl" is NULL (e.g. when COLLATE clause is not specified), then simply "cs" is returned. @return Error status. @retval NULL, if "cl" is not applicable to "cs". @retval pointer to merged CHARSET_INFO on success. */ CHARSET_INFO* merge_charset_and_collation(CHARSET_INFO *cs, CHARSET_INFO *cl) { if (cl) { if (!my_charset_same(cs, cl)) { my_error(ER_COLLATION_CHARSET_MISMATCH, MYF(0), cl->name, cs->csname); return NULL; } return cl; } return cs; }
knielsen/mariadb
sql/sql_parse.cc
C++
gpl-2.0
274,026
# # Gramps - a GTK+/GNOME based genealogy program # # Copyright (C) 2000-2007 Donald N. Allingham # Copyright (C) 2008 Raphael Ackermann # Copyright (C) 2010 Benny Malengier # Copyright (C) 2010 Nick Hall # Copyright (C) 2012 Doug Blank <doug.blank@gmail.com> # # This program is free software; you can redistribute it and/or modify # it under the terms of the GNU General Public License as published by # the Free Software Foundation; either version 2 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU General Public License for more details. # # You should have received a copy of the GNU General Public License # along with this program; if not, write to the Free Software # Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. # #------------------------------------------------------------------------- # # Standard python modules # #------------------------------------------------------------------------- from __future__ import print_function import random import os from xml.sax.saxutils import escape import collections #------------------------------------------------------------------------- # # GTK/Gnome modules # #------------------------------------------------------------------------- from gi.repository import GObject from gi.repository import Gdk from gi.repository import Gtk #------------------------------------------------------------------------- # # gramps modules # #------------------------------------------------------------------------- from gramps.gen.config import config from gramps.gen.const import GRAMPS_LOCALE as glocale from gramps.gen.const import HOME_DIR, URL_WIKISTRING from gramps.gen.datehandler import get_date_formats from gramps.gen.display.name import displayer as _nd from gramps.gen.display.name import NameDisplayError from gramps.gen.utils.alive import update_constants from gramps.gen.utils.keyword import (get_keywords, get_translation_from_keyword, get_translations, get_keyword_from_translation) from gramps.gen.lib import Date, FamilyRelType from gramps.gen.lib import Name, Surname, NameOriginType from gramps.gen.constfunc import conv_to_unicode from .managedwindow import ManagedWindow from .widgets import MarkupLabel, BasicLabel from .dialog import ErrorDialog, QuestionDialog2, OkDialog from .glade import Glade from gramps.gen.plug.utils import available_updates from .plug import PluginWindows from gramps.gen.errors import WindowActiveError from .spell import HAVE_GTKSPELL _ = glocale.translation.gettext #------------------------------------------------------------------------- # # Constants # #------------------------------------------------------------------------- _surname_styles = [ _("Father's surname"), _("None"), _("Combination of mother's and father's surname"), _("Icelandic style"), ] # column numbers for the 'name format' model COL_NUM = 0 COL_NAME = 1 COL_FMT = 2 COL_EXPL = 3 #------------------------------------------------------------------------- # # # #------------------------------------------------------------------------- class DisplayNameEditor(ManagedWindow): def __init__(self, uistate, dbstate, track, dialog): # Assumes that there are two methods: dialog.name_changed_check(), # and dialog._build_custom_name_ui() ManagedWindow.__init__(self, uistate, [], DisplayNameEditor) self.dialog = dialog self.dbstate = dbstate self.set_window( Gtk.Dialog(_('Display Name Editor'), buttons=(Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)), None, _('Display Name Editor'), None) table = self.dialog._build_custom_name_ui() label = Gtk.Label(label=_("""The following keywords are replaced with the appropriate name parts: <tt> <b>Given</b> - given name (first name) <b>Surname</b> - surnames (with prefix and connectors) <b>Title</b> - title (Dr., Mrs.) <b>Suffix</b> - suffix (Jr., Sr.) <b>Call</b> - call name <b>Nickname</b> - nick name <b>Initials</b> - first letters of Given <b>Common</b> - nick name, otherwise first of Given <b>Primary, Primary[pre] or [sur] or [con]</b>- full primary surname, prefix, surname only, connector <b>Patronymic, or [pre] or [sur] or [con]</b> - full pa/matronymic surname, prefix, surname only, connector <b>Familynick</b> - family nick name <b>Prefix</b> - all prefixes (von, de) <b>Rest</b> - non primary surnames <b>Notpatronymic</b>- all surnames, except pa/matronymic &amp; primary <b>Rawsurnames</b>- surnames (no prefixes and connectors) </tt> UPPERCASE keyword forces uppercase. Extra parentheses, commas are removed. Other text appears literally. <b>Example</b>: 'Dr. Edwin Jose von der Smith and Weston Wilson Sr ("Ed") - Underhills' <i>Edwin Jose</i> is given name, <i>von der</i> is the prefix, <i>Smith</i> and <i>Weston</i> surnames, <i>and</i> a connector, <i>Wilson</i> patronymic surname, <i>Dr.</i> title, <i>Sr</i> suffix, <i>Ed</i> nick name, <i>Underhills</i> family nick name, <i>Jose</i> callname. """)) label.set_use_markup(True) self.window.vbox.pack_start(label, False, True, 0) self.window.vbox.pack_start(table, True, True, 0) self.window.set_default_size(600, 550) self.window.connect('response', self.close) self.show() def close(self, *obj): self.dialog.name_changed_check() ManagedWindow.close(self, *obj) def build_menu_names(self, obj): return (_(" Name Editor"), _("Preferences")) #------------------------------------------------------------------------- # # ConfigureDialog # #------------------------------------------------------------------------- class ConfigureDialog(ManagedWindow): """ Base class for configuration dialogs. They provide a Notebook, to which pages are added with configuration options, and a Cancel and Save button. On save, a config file on which the dialog works, is saved to disk, and a callback called. """ def __init__(self, uistate, dbstate, configure_page_funcs, configobj, configmanager, dialogtitle=_("Preferences"), on_close=None): """ Set up a configuration dialog :param uistate: a DisplayState instance :param dbstate: a DbState instance :param configure_page_funcs: a list of function that return a tuple (str, Gtk.Widget). The string is used as label for the configuration page, and the widget as the content of the configuration page :param configobj: the unique object that is configured, it must be identifiable (id(configobj)). If the configure dialog of the configobj is already open, a WindowActiveError will be raised. Grab this exception in the calling method :param configmanager: a configmanager object. Several convenience methods are present in ConfigureDialog to set up widgets that write changes directly via this configmanager. :param dialogtitle: the title of the configuration dialog :param on_close: callback that is called on close """ self.dbstate = dbstate self.__config = configmanager ManagedWindow.__init__(self, uistate, [], configobj) self.set_window( Gtk.Dialog(dialogtitle, buttons=(Gtk.STOCK_CLOSE, Gtk.ResponseType.CLOSE)), None, dialogtitle, None) self.panel = Gtk.Notebook() self.panel.set_scrollable(True) self.window.vbox.pack_start(self.panel, True, True, 0) self.__on_close = on_close self.window.connect('response', self.done) self.__setup_pages(configure_page_funcs) self.window.show_all() self.show() def __setup_pages(self, configure_page_funcs): """ This method builds the notebookpages in the panel """ if isinstance(configure_page_funcs, collections.Callable): pages = configure_page_funcs() else: pages = configure_page_funcs for func in pages: labeltitle, widget = func(self) self.panel.append_page(widget, MarkupLabel(labeltitle)) def done(self, obj, value): if self.__on_close: self.__on_close() self.close() def update_int_entry(self, obj, constant): """ :param obj: an object with get_text method that should contain an integer :param constant: the config setting to which the integer value must be saved """ try: self.__config.set(constant, int(obj.get_text())) except: print("WARNING: ignoring invalid value for '%s'" % constant) def update_markup_entry(self, obj, constant): """ :param obj: an object with get_text method :param constant: the config setting to which the text value must be saved """ try: obj.get_text() % 'test_markup' except TypeError: print("WARNING: ignoring invalid value for '%s'" % constant) ErrorDialog(_("Invalid or incomplete format definition."), obj.get_text()) obj.set_text('<b>%s</b>') except ValueError: print("WARNING: ignoring invalid value for '%s'" % constant) ErrorDialog(_("Invalid or incomplete format definition."), obj.get_text()) obj.set_text('<b>%s</b>') self.__config.set(constant, unicode(obj.get_text())) def update_entry(self, obj, constant): """ :param obj: an object with get_text method :param constant: the config setting to which the text value must be saved """ self.__config.set(constant, conv_to_unicode(obj.get_text())) def update_color(self, obj, constant, color_hex_label): color = obj.get_color() hexval = "#%02x%02x%02x" % (color.red/256, color.green/256, color.blue/256) color_hex_label.set_text(hexval) self.__config.set(constant, hexval) def update_checkbox(self, obj, constant, config=None): if not config: config = self.__config config.set(constant, obj.get_active()) def update_radiobox(self, obj, constant): self.__config.set(constant, obj.get_active()) def update_combo(self, obj, constant): """ :param obj: the ComboBox object :param constant: the config setting to which the value must be saved """ self.__config.set(constant, obj.get_active()) def update_slider(self, obj, constant): """ :param obj: the HScale object :param constant: the config setting to which the value must be saved """ self.__config.set(constant, int(obj.get_value())) def update_spinner(self, obj, constant): """ :param obj: the SpinButton object :param constant: the config setting to which the value must be saved """ self.__config.set(constant, int(obj.get_value())) def add_checkbox(self, table, label, index, constant, start=1, stop=9, config=None, extra_callback=None): if not config: config = self.__config checkbox = Gtk.CheckButton(label=label) checkbox.set_active(config.get(constant)) checkbox.connect('toggled', self.update_checkbox, constant, config) if extra_callback: checkbox.connect('toggled', extra_callback) table.attach(checkbox, start, stop, index, index+1, yoptions=0) return checkbox def add_radiobox(self, table, label, index, constant, group, column, config=None): if not config: config = self.__config radiobox = Gtk.RadioButton.new_with_mnemonic_from_widget(group, label) if config.get(constant) == True: radiobox.set_active(True) radiobox.connect('toggled', self.update_radiobox, constant) table.attach(radiobox, column, column+1, index, index+1, yoptions=0) return radiobox def add_text(self, table, label, index, config=None, line_wrap=True): if not config: config = self.__config text = Gtk.Label() text.set_line_wrap(line_wrap) text.set_alignment(0.,0.) text.set_text(label) table.attach(text, 1, 9, index, index+1, yoptions=Gtk.AttachOptions.SHRINK) def add_path_box(self, table, label, index, entry, path, callback_label, callback_sel, config=None): """ Add an entry to give in path and a select button to open a dialog. Changing entry calls callback_label Clicking open button call callback_sel """ if not config: config = self.__config lwidget = BasicLabel("%s: " %label) hbox = Gtk.HBox() if path: entry.set_text(path) entry.connect('changed', callback_label) btn = Gtk.Button() btn.connect('clicked', callback_sel) image = Gtk.Image() image.set_from_stock(Gtk.STOCK_OPEN, Gtk.IconSize.BUTTON) image.show() btn.add(image) hbox.pack_start(entry, True, True, 0) hbox.pack_start(btn, False, False, 0) table.attach(lwidget, 1, 2, index, index+1, yoptions=0, xoptions=Gtk.AttachOptions.FILL) table.attach(hbox, 2, 3, index, index+1, yoptions=0) def add_entry(self, table, label, index, constant, callback=None, config=None, col_attach=0): if not config: config = self.__config if not callback: callback = self.update_entry if label: lwidget = BasicLabel("%s: " % label) entry = Gtk.Entry() entry.set_text(config.get(constant)) entry.connect('changed', callback, constant) if label: table.attach(lwidget, col_attach, col_attach+1, index, index+1, yoptions=0, xoptions=Gtk.AttachOptions.FILL) table.attach(entry, col_attach+1, col_attach+2, index, index+1, yoptions=0) else: table.attach(entry, col_attach, col_attach+1, index, index+1, yoptions=0) return entry def add_pos_int_entry(self, table, label, index, constant, callback=None, config=None, col_attach=1, helptext=''): """ entry field for positive integers """ if not config: config = self.__config lwidget = BasicLabel("%s: " % label) entry = Gtk.Entry() entry.set_text(str(config.get(constant))) entry.set_tooltip_markup(helptext) if callback: entry.connect('changed', callback, constant) table.attach(lwidget, col_attach, col_attach+1, index, index+1, yoptions=0, xoptions=Gtk.AttachOptions.FILL) table.attach(entry, col_attach+1, col_attach+2, index, index+1, yoptions=0) def add_color(self, table, label, index, constant, config=None, col=0): if not config: config = self.__config lwidget = BasicLabel("%s: " % label) hexval = config.get(constant) color = Gdk.color_parse(hexval) entry = Gtk.ColorButton(color=color) color_hex_label = BasicLabel(hexval) entry.connect('color-set', self.update_color, constant, color_hex_label) table.attach(lwidget, col, col+1, index, index+1, yoptions=0, xoptions=Gtk.AttachOptions.FILL) table.attach(entry, col+1, col+2, index, index+1, yoptions=0, xoptions=0) table.attach(color_hex_label, col+2, col+3, index, index+1, yoptions=0) return entry def add_combo(self, table, label, index, constant, opts, callback=None, config=None, valueactive=False, setactive=None): """ A drop-down list allowing selection from a number of fixed options. :param opts: A list of options. Each option is a tuple containing an integer code and a textual description. If valueactive = True, the constant stores the value, not the position in the list """ if not config: config = self.__config if not callback: callback = self.update_combo lwidget = BasicLabel("%s: " % label) store = Gtk.ListStore(int, str) for item in opts: store.append(item) combo = Gtk.ComboBox(model=store) cell = Gtk.CellRendererText() combo.pack_start(cell, True) combo.add_attribute(cell, 'text', 1) if valueactive: val = config.get(constant) pos = 0 for nr, item in enumerate(opts): if item[-1] == val: pos = nr break combo.set_active(pos) else: if setactive is None: combo.set_active(config.get(constant)) else: combo.set_active(setactive) combo.connect('changed', callback, constant) table.attach(lwidget, 1, 2, index, index+1, yoptions=0, xoptions=Gtk.AttachOptions.FILL) table.attach(combo, 2, 3, index, index+1, yoptions=0) return combo def add_slider(self, table, label, index, constant, range, callback=None, config=None): """ A slider allowing the selection of an integer within a specified range. :param range: A tuple containing the minimum and maximum allowed values. """ if not config: config = self.__config if not callback: callback = self.update_slider lwidget = BasicLabel("%s: " % label) adj = Gtk.Adjustment(config.get(constant), range[0], range[1], 1, 0, 0) slider = Gtk.HScale(adjustment=adj) slider.set_digits(0) slider.set_value_pos(Gtk.PositionType.BOTTOM) slider.connect('value-changed', callback, constant) table.attach(lwidget, 1, 2, index, index+1, yoptions=0, xoptions=Gtk.AttachOptions.FILL) table.attach(slider, 2, 3, index, index+1, yoptions=0) return slider def add_spinner(self, table, label, index, constant, range, callback=None, config=None): """ A spinner allowing the selection of an integer within a specified range. :param range: A tuple containing the minimum and maximum allowed values. """ if not config: config = self.__config if not callback: callback = self.update_spinner lwidget = BasicLabel("%s: " % label) adj = Gtk.Adjustment(config.get(constant), range[0], range[1], 1, 0, 0) spinner = Gtk.SpinButton(adjustment=adj, climb_rate=0.0, digits=0) spinner.connect('value-changed', callback, constant) table.attach(lwidget, 1, 2, index, index+1, yoptions=0, xoptions=Gtk.AttachOptions.FILL) table.attach(spinner, 2, 3, index, index+1, yoptions=0) return spinner #------------------------------------------------------------------------- # # GrampsPreferences # #------------------------------------------------------------------------- class GrampsPreferences(ConfigureDialog): def __init__(self, uistate, dbstate): page_funcs = ( self.add_behavior_panel, self.add_famtree_panel, self.add_formats_panel, self.add_text_panel, self.add_prefix_panel, self.add_date_panel, self.add_researcher_panel, self.add_advanced_panel, self.add_color_panel ) ConfigureDialog.__init__(self, uistate, dbstate, page_funcs, GrampsPreferences, config, on_close=update_constants) def add_researcher_panel(self, configdialog): table = Gtk.Table(n_rows=3, n_columns=8) table.set_border_width(12) table.set_col_spacings(6) table.set_row_spacings(6) self.add_text(table, _('Enter your information so people can contact you when you' ' distribute your Family Tree'), 0, line_wrap=False) self.add_entry(table, _('Name'), 1, 'researcher.researcher-name') self.add_entry(table, _('Address'), 2, 'researcher.researcher-addr') self.add_entry(table, _('Locality'), 3, 'researcher.researcher-locality') self.add_entry(table, _('City'), 4, 'researcher.researcher-city') self.add_entry(table, _('State/County'), 5, 'researcher.researcher-state') self.add_entry(table, _('Country'), 6, 'researcher.researcher-country') self.add_entry(table, _('ZIP/Postal Code'), 7, 'researcher.researcher-postal') self.add_entry(table, _('Phone'), 8, 'researcher.researcher-phone') self.add_entry(table, _('Email'), 9, 'researcher.researcher-email') return _('Researcher'), table def add_prefix_panel(self, configdialog): """ Add the ID prefix tab to the preferences. """ table = Gtk.Table(n_rows=3, n_columns=8) table.set_border_width(12) table.set_col_spacings(6) table.set_row_spacings(6) self.add_entry(table, _('Person'), 0, 'preferences.iprefix', self.update_idformat_entry) self.add_entry(table, _('Family'), 1, 'preferences.fprefix', self.update_idformat_entry) self.add_entry(table, _('Place'), 2, 'preferences.pprefix', self.update_idformat_entry) self.add_entry(table, _('Source'), 3, 'preferences.sprefix', self.update_idformat_entry) self.add_entry(table, _('Citation'), 4, 'preferences.cprefix', self.update_idformat_entry) self.add_entry(table, _('Media Object'), 5, 'preferences.oprefix', self.update_idformat_entry) self.add_entry(table, _('Event'), 6, 'preferences.eprefix', self.update_idformat_entry) self.add_entry(table, _('Repository'), 7, 'preferences.rprefix', self.update_idformat_entry) self.add_entry(table, _('Note'), 8, 'preferences.nprefix', self.update_idformat_entry) return _('ID Formats'), table def add_color_panel(self, configdialog): """ Add the tab to set defaults colors for graph boxes """ table = Gtk.Table(n_rows=17, n_columns=8) self.add_text(table, _('Set the colors used for boxes in the graphical views'), 0, line_wrap=False) self.add_color(table, _('Gender Male Alive'), 1, 'preferences.color-gender-male-alive') self.add_color(table, _('Border Male Alive'), 2, 'preferences.bordercolor-gender-male-alive') self.add_color(table, _('Gender Male Death'), 3, 'preferences.color-gender-male-death') self.add_color(table, _('Border Male Death'), 4, 'preferences.bordercolor-gender-male-death') self.add_color(table, _('Gender Female Alive'), 1, 'preferences.color-gender-female-alive', col=4) self.add_color(table, _('Border Female Alive'), 2, 'preferences.bordercolor-gender-female-alive', col=4) self.add_color(table, _('Gender Female Death'), 3, 'preferences.color-gender-female-death', col=4) self.add_color(table, _('Border Female Death'), 4, 'preferences.bordercolor-gender-female-death', col=4) ## self.add_color(table, _('Gender Other Alive'), 5, ## 'preferences.color-gender-other-alive') ## self.add_color(table, _('Border Other Alive'), 6, ## 'preferences.bordercolor-gender-other-alive') ## self.add_color(table, _('Gender Other Death'), 7, ## 'preferences.color-gender-other-death') ## self.add_color(table, _('Border Other Death'), 8, ## 'preferences.bordercolor-gender-other-death') self.add_color(table, _('Gender Unknown Alive'), 5, 'preferences.color-gender-unknown-alive', col=4) self.add_color(table, _('Border Unknown Alive'), 6, 'preferences.bordercolor-gender-unknown-alive', col=4) self.add_color(table, _('Gender Unknown Death'), 7, 'preferences.color-gender-unknown-death', col=4) self.add_color(table, _('Border Unknown Death'), 8, 'preferences.bordercolor-gender-unknown-death', col=4) return _('Colors'), table def add_advanced_panel(self, configdialog): table = Gtk.Table(n_rows=4, n_columns=8) table.set_border_width(12) table.set_col_spacings(6) table.set_row_spacings(6) self.add_checkbox( table, _('Suppress warning when adding parents to a child.'), 0, 'preferences.family-warn') self.add_checkbox( table, _('Suppress warning when canceling with changed data.'), 1, 'interface.dont-ask') self.add_checkbox( table, _('Suppress warning about missing researcher when' ' exporting to GEDCOM.'), 2, 'behavior.owner-warn') self.add_checkbox( table, _('Show plugin status dialog on plugin load error.'), 3, 'behavior.pop-plugin-status') return _('Warnings'), table def _build_name_format_model(self, active): """ Create a common model for ComboBox and TreeView """ name_format_model = Gtk.ListStore(GObject.TYPE_INT, GObject.TYPE_STRING, GObject.TYPE_STRING, GObject.TYPE_STRING) index = 0 the_index = 0 for num, name, fmt_str, act in _nd.get_name_format(): translation = fmt_str for key in get_keywords(): if key in translation: translation = translation.replace(key, get_translation_from_keyword(key)) self.examplename.set_display_as(num) name_format_model.append( row=[num, translation, fmt_str, _nd.display_name(self.examplename)]) if num == active: the_index = index index += 1 return name_format_model, the_index def __new_name(self, obj): lyst = ["%s, %s %s (%s)" % (_("Surname"), _("Given"), _("Suffix"), _("Common")), "%s, %s %s (%s)" % (_("Surname"), _("Given"), _("Suffix"), _("Nickname")), "%s, %s %s (%s)" % (_("Surname"), _("Name|Common"), _("Suffix"), _("Nickname")), "%s, %s %s" % (_("Surname"), _("Name|Common"), _("Suffix")), "%s, %s %s (%s)" % (_("SURNAME"), _("Given"), _("Suffix"), _("Call")), "%s, %s (%s)" % (_("Surname"), _("Given"), _("Name|Common")), "%s, %s (%s)" % (_("Surname"), _("Name|Common"), _("Nickname")), "%s %s" % (_("Given"), _("Surname")), "%s %s, %s" % (_("Given"), _("Surname"), _("Suffix")), "%s %s %s" % (_("Given"), _("NotPatronymic"), _("Patronymic")), "%s, %s %s (%s)" % (_("SURNAME"), _("Given"), _("Suffix"), _("Common")), "%s, %s (%s)" % (_("SURNAME"), _("Given"), _("Name|Common")), "%s, %s (%s)" % (_("SURNAME"), _("Given"), _("Nickname")), "%s %s" % (_("Given"), _("SURNAME")), "%s %s, %s" % (_("Given"), _("SURNAME"), _("Suffix")), "%s /%s/" % (_("Given"), _("SURNAME")), "%s %s, %s" % (_("Given"), _("Rawsurnames"), _("Suffix")), ] #repeat above list, but not translated. fmtlyst = ["%s, %s %s (%s)" % (("Surname"), ("Given"), ("Suffix"), ("Common")), "%s, %s %s (%s)" % (("Surname"), ("Given"), ("Suffix"), ("Nickname")), "%s, %s %s (%s)" % (("Surname"), ("Name|Common"), ("Suffix"), ("Nickname")), "%s, %s %s" % (("Surname"), ("Name|Common"), ("Suffix")), "%s, %s %s (%s)" % (("SURNAME"), ("Given"), ("Suffix"), ("Call")), "%s, %s (%s)" % (("Surname"), ("Given"), ("Name|Common")), "%s, %s (%s)" % (("Surname"), ("Name|Common"), ("Nickname")), "%s %s" % (("Given"), ("Surname")), "%s %s, %s" % (("Given"), ("Surname"), ("Suffix")), "%s %s %s" % (("Given"), ("NotPatronymic"), ("Patronymic")), "%s, %s %s (%s)" % (("SURNAME"), ("Given"), ("Suffix"), ("Common")), "%s, %s (%s)" % (("SURNAME"), ("Given"), ("Name|Common")), "%s, %s (%s)" % (("SURNAME"), ("Given"), ("Nickname")), "%s %s" % (("Given"), ("SURNAME")), "%s %s, %s" % (("Given"), ("SURNAME"), ("Suffix")), "%s /%s/" % (("Given"), ("SURNAME")), "%s %s, %s" % (("Given"), ("Rawsurnames"), ("Suffix")), ] rand = int(random.random() * len(lyst)) f = lyst[rand] fmt = fmtlyst[rand] i = _nd.add_name_format(f, fmt) node = self.fmt_model.append(row=[i, f, fmt, _nd.format_str(self.examplename, fmt)]) path = self.fmt_model.get_path(node) self.format_list.set_cursor(path, self.name_column, True) self.edit_button.set_sensitive(False) self.remove_button.set_sensitive(False) self.insert_button.set_sensitive(False) def __edit_name(self, obj): store, node = self.format_list.get_selection().get_selected() path = self.fmt_model.get_path(node) self.edit_button.set_sensitive(False) self.remove_button.set_sensitive(False) self.insert_button.set_sensitive(False) self.format_list.set_cursor(path, self.name_column, True) def __check_for_name(self, name, oldnode): """ Check to see if there is another name the same as name in the format list. Don't compare with self (oldnode). """ model = self.fmt_obox.get_model() iter = model.get_iter_first() while iter is not None: othernum = model.get_value(iter, COL_NUM) oldnum = model.get_value(oldnode, COL_NUM) if othernum == oldnum: pass# skip comparison with self else: othername = model.get_value(iter, COL_NAME) if othername == name: return True iter = model.iter_next(iter) return False def __start_name_editing(self, dummy_renderer, dummy_editable, dummy_path): """ Method called at the start of editing a name format. """ self.format_list.set_tooltip_text(_("Enter to save, Esc to cancel " "editing")) def __cancel_change(self, dummy_renderer): """ Break off the editing of a name format. """ self.format_list.set_tooltip_text('') num = self.selected_fmt[COL_NUM] if any(fmt[COL_NUM] == num for fmt in self.dbstate.db.name_formats): return else: # editing a new format not yet in db, cleanup is needed self.fmt_model.remove(self.iter) _nd.del_name_format(num) self.insert_button.set_sensitive(True) def __change_name(self, text, path, new_text): """ Called when a name format changed and needs to be stored in the db. """ self.format_list.set_tooltip_text('') if len(new_text) > 0 and text != new_text: # build a pattern from translated pattern: pattern = new_text if (len(new_text) > 2 and new_text[0] == '"' and new_text[-1] == '"'): pass else: for key in get_translations(): if key in pattern: pattern = pattern.replace(key, get_keyword_from_translation(key)) # now build up a proper translation: translation = pattern if (len(new_text) > 2 and new_text[0] == '"' and new_text[-1] == '"'): pass else: for key in get_keywords(): if key in translation: translation = translation.replace(key, get_translation_from_keyword(key)) num, name, fmt = self.selected_fmt[COL_NUM:COL_EXPL] node = self.fmt_model.get_iter(path) oldname = self.fmt_model.get_value(node, COL_NAME) # check to see if this pattern already exists if self.__check_for_name(translation, node): ErrorDialog(_("This format exists already."), translation) self.edit_button.emit('clicked') return # else, change the name self.edit_button.set_sensitive(True) self.remove_button.set_sensitive(True) self.insert_button.set_sensitive(True) exmpl = _nd.format_str(self.examplename, pattern) self.fmt_model.set(self.iter, COL_NAME, translation, COL_FMT, pattern, COL_EXPL, exmpl) self.selected_fmt = (num, translation, pattern, exmpl) _nd.edit_name_format(num, translation, pattern) self.dbstate.db.name_formats = _nd.get_name_format(only_custom=True, only_active=False) def __format_change(self, obj): try: t = (_nd.format_str(self.name, escape(obj.get_text()))) self.valid = True except NameDisplayError: t = _("Invalid or incomplete format definition.") self.valid = False self.fmt_model.set(self.iter, COL_EXPL, t) def _build_custom_name_ui(self): """ UI to manage the custom name formats """ table = Gtk.Table(n_rows=2, n_columns=3) table.set_border_width(6) table.set_col_spacings(6) table.set_row_spacings(6) # make a treeview for listing all the name formats format_tree = Gtk.TreeView(self.fmt_model) name_renderer = Gtk.CellRendererText() name_column = Gtk.TreeViewColumn(_('Format'), name_renderer, text=COL_NAME) name_renderer.set_property('editable', False) name_renderer.connect('editing-started', self.__start_name_editing) name_renderer.connect('edited', self.__change_name) name_renderer.connect('editing-canceled', self.__cancel_change) self.name_renderer = name_renderer format_tree.append_column(name_column) example_renderer = Gtk.CellRendererText() example_column = Gtk.TreeViewColumn(_('Example'), example_renderer, text=COL_EXPL) format_tree.append_column(example_column) format_tree.get_selection().connect('changed', self.cb_format_tree_select) format_tree.set_rules_hint(True) # ... and put it into a scrolled win format_sw = Gtk.ScrolledWindow() format_sw.set_policy(Gtk.PolicyType.AUTOMATIC, Gtk.PolicyType.AUTOMATIC) format_sw.add(format_tree) format_sw.set_shadow_type(Gtk.ShadowType.IN) table.attach(format_sw, 0, 3, 0, 1, yoptions=Gtk.AttachOptions.FILL|Gtk.AttachOptions.EXPAND) # to hold the values of the selected row of the tree and the iter self.selected_fmt = () self.iter = None self.insert_button = Gtk.Button(stock=Gtk.STOCK_ADD) self.insert_button.connect('clicked', self.__new_name) self.edit_button = Gtk.Button(stock=Gtk.STOCK_EDIT) self.edit_button.connect('clicked', self.__edit_name) self.edit_button.set_sensitive(False) self.remove_button = Gtk.Button(stock=Gtk.STOCK_REMOVE) self.remove_button.connect('clicked', self.cb_del_fmt_str) self.remove_button.set_sensitive(False) table.attach(self.insert_button, 0, 1, 1, 2, yoptions=0) table.attach(self.remove_button, 1, 2, 1, 2, yoptions=0) table.attach(self.edit_button, 2, 3, 1, 2, yoptions=0) self.format_list = format_tree self.name_column = name_column return table def name_changed_check(self): """ Method to check for a name change. Called by Name Edit Dialog. """ obj = self.fmt_obox the_list = obj.get_model() the_iter = obj.get_active_iter() format = the_list.get_value(the_iter, COL_FMT) if format != self.old_format: # Yes a change; call the callback self.cb_name_changed(obj) def cb_name_changed(self, obj): """ Preset name format ComboBox callback """ the_list = obj.get_model() the_iter = obj.get_active_iter() new_idx = the_list.get_value(the_iter, COL_NUM) config.set('preferences.name-format', new_idx) _nd.set_default_format(new_idx) self.uistate.emit('nameformat-changed') def cb_pa_sur_changed(self,*args): """ checkbox patronymic as surname changed, propagate to namedisplayer """ _nd.change_pa_sur() self.uistate.emit('nameformat-changed') def cb_format_tree_select(self, tree_selection): """ Name format editor TreeView callback Remember the values of the selected row (self.selected_fmt, self.iter) and set the Remove and Edit button sensitivity """ model, self.iter = tree_selection.get_selected() if self.iter is None: tree_selection.select_path(0) model, self.iter = tree_selection.get_selected() self.selected_fmt = model.get(self.iter, 0, 1, 2) idx = self.selected_fmt[COL_NUM] < 0 self.remove_button.set_sensitive(idx) self.edit_button.set_sensitive(idx) self.name_renderer.set_property('editable', idx) def cb_del_fmt_str(self, obj): """ Name format editor Remove button callback """ num = self.selected_fmt[COL_NUM] if _nd.get_default_format() == num: self.fmt_obox.set_active(0) self.fmt_model.remove(self.iter) _nd.set_format_inactive(num) self.dbstate.db.name_formats = _nd.get_name_format(only_custom=True, only_active=False) def cb_grampletbar_close(self, obj): """ Gramplet bar close button preference callback """ self.uistate.emit('grampletbar-close-changed') def add_formats_panel(self, configdialog): row = 0 table = Gtk.Table(n_rows=4, n_columns=4) table.set_border_width(12) table.set_col_spacings(6) table.set_row_spacings(6) # Display name: self.examplename = Name() examplesurname = Surname() examplesurnamesecond = Surname() examplesurnamepat = Surname() self.examplename.set_title('Dr.') self.examplename.set_first_name('Edwin Jose') examplesurname.set_prefix('von der') examplesurname.set_surname('Smith') examplesurname.set_connector('and') self.examplename.add_surname(examplesurname) examplesurnamesecond.set_surname('Weston') self.examplename.add_surname(examplesurnamesecond) examplesurnamepat.set_surname('Wilson') examplesurnamepat.set_origintype( NameOriginType(NameOriginType.PATRONYMIC)) self.examplename.add_surname(examplesurnamepat) self.examplename.set_primary_surname(0) self.examplename.set_suffix('Sr') self.examplename.set_call_name('Jose') self.examplename.set_nick_name('Ed') self.examplename.set_family_nick_name('Underhills') # get the model for the combo and the treeview active = _nd.get_default_format() self.fmt_model, active = self._build_name_format_model(active) # set up the combo to choose the preset format self.fmt_obox = Gtk.ComboBox() cell = Gtk.CellRendererText() self.fmt_obox.pack_start(cell, True) self.fmt_obox.add_attribute(cell, 'text', 1) self.fmt_obox.set_model(self.fmt_model) # set the default value as active in the combo self.fmt_obox.set_active(active) self.fmt_obox.connect('changed', self.cb_name_changed) # label for the combo lwidget = BasicLabel("%s: " % _('Name format')) lwidget.set_use_underline(True) lwidget.set_mnemonic_widget(self.fmt_obox) hbox = Gtk.HBox() btn = Gtk.Button("%s..." % _('Edit') ) btn.connect('clicked', self.cb_name_dialog) hbox.pack_start(self.fmt_obox, True, True, 0) hbox.pack_start(btn, False, False, 0) table.attach(lwidget, 0, 1, row, row+1, yoptions=0) table.attach(hbox, 1, 3, row, row+1, yoptions=0) row += 1 # Pa/Matronymic surname handling self.add_checkbox(table, _("Consider single pa/matronymic as surname"), row, 'preferences.patronimic-surname', stop=3, extra_callback=self.cb_pa_sur_changed) row += 1 # Date format: obox = Gtk.ComboBoxText() formats = get_date_formats() list(map(obox.append_text, formats)) active = config.get('preferences.date-format') if active >= len(formats): active = 0 obox.set_active(active) obox.connect('changed', self.date_format_changed) lwidget = BasicLabel("%s: " % _('Date format')) table.attach(lwidget, 0, 1, row, row+1, yoptions=0) table.attach(obox, 1, 3, row, row+1, yoptions=0) row += 1 # Age precision: # precision=1 for "year", 2: "year, month" or 3: "year, month, days" obox = Gtk.ComboBoxText() age_precision = [_("Years"), _("Years, Months"), _("Years, Months, Days")] list(map(obox.append_text, age_precision)) # Combo_box active index is from 0 to 2, we need values from 1 to 3 active = config.get('preferences.age-display-precision') - 1 if active >= 0 and active <= 2: obox.set_active(active) else: obox.set_active(0) obox.connect('changed', lambda obj: config.set('preferences.age-display-precision', obj.get_active() + 1)) lwidget = BasicLabel("%s: " % _('Age display precision (requires restart)')) table.attach(lwidget, 0, 1, row, row+1, yoptions=0) table.attach(obox, 1, 3, row, row+1, yoptions=0) row += 1 # Calendar format on report: obox = Gtk.ComboBoxText() list(map(obox.append_text, Date.ui_calendar_names)) active = config.get('preferences.calendar-format-report') if active >= len(formats): active = 0 obox.set_active(active) obox.connect('changed', self.date_calendar_changed) lwidget = BasicLabel("%s: " % _('Calendar on reports')) table.attach(lwidget, 0, 1, row, row+1, yoptions=0) table.attach(obox, 1, 3, row, row+1, yoptions=0) row += 1 # Surname guessing: obox = Gtk.ComboBoxText() formats = _surname_styles list(map(obox.append_text, formats)) obox.set_active(config.get('behavior.surname-guessing')) obox.connect('changed', lambda obj: config.set('behavior.surname-guessing', obj.get_active())) lwidget = BasicLabel("%s: " % _('Surname guessing')) table.attach(lwidget, 0, 1, row, row+1, yoptions=0) table.attach(obox, 1, 3, row, row+1, yoptions=0) row += 1 # Default Family Relationship obox = Gtk.ComboBoxText() formats = FamilyRelType().get_standard_names() list(map(obox.append_text, formats)) obox.set_active(config.get('preferences.family-relation-type')) obox.connect('changed', lambda obj: config.set('preferences.family-relation-type', obj.get_active())) lwidget = BasicLabel("%s: " % _('Default family relationship')) table.attach(lwidget, 0, 1, row, row+1, yoptions=0) table.attach(obox, 1, 3, row, row+1, yoptions=0) row += 1 #height multiple surname table self.add_pos_int_entry(table, _('Height multiple surname box (pixels)'), row, 'interface.surname-box-height', self.update_surn_height, col_attach=0) row += 1 # Status bar: obox = Gtk.ComboBoxText() formats = [_("Active person's name and ID"), _("Relationship to home person")] list(map(obox.append_text, formats)) active = config.get('interface.statusbar') if active < 2: obox.set_active(0) else: obox.set_active(1) obox.connect('changed', lambda obj: config.set('interface.statusbar', 2*obj.get_active())) lwidget = BasicLabel("%s: " % _('Status bar')) table.attach(lwidget, 0, 1, row, row+1, yoptions=0) table.attach(obox, 1, 3, row, row+1, yoptions=0) row += 1 # Text in sidebar: self.add_checkbox(table, _("Show text in sidebar buttons (requires restart)"), row, 'interface.sidebar-text', stop=3) row += 1 # Gramplet bar close buttons: self.add_checkbox(table, _("Show close button in gramplet bar tabs"), row, 'interface.grampletbar-close', stop=3, extra_callback=self.cb_grampletbar_close) row += 1 return _('Display'), table def add_text_panel(self, configdialog): row = 0 table = Gtk.Table(n_rows=6, n_columns=8) table.set_border_width(12) table.set_col_spacings(6) table.set_row_spacings(6) self.add_entry(table, _('Missing surname'), row, 'preferences.no-surname-text') row += 1 self.add_entry(table, _('Missing given name'), row, 'preferences.no-given-text') row += 1 self.add_entry(table, _('Missing record'), row, 'preferences.no-record-text') row += 1 self.add_entry(table, _('Private surname'), row, 'preferences.private-surname-text') row += 1 self.add_entry(table, _('Private given name'), row, 'preferences.private-given-text') row += 1 self.add_entry(table, _('Private record'), row, 'preferences.private-record-text') row += 1 return _('Text'), table def cb_name_dialog(self, obj): the_list = self.fmt_obox.get_model() the_iter = self.fmt_obox.get_active_iter() self.old_format = the_list.get_value(the_iter, COL_FMT) win = DisplayNameEditor(self.uistate, self.dbstate, self.track, self) def check_for_type_changed(self, obj): active = obj.get_active() if active == 0: # update config.set('behavior.check-for-update-types', ["update"]) elif active == 1: # update config.set('behavior.check-for-update-types', ["new"]) elif active == 2: # update config.set('behavior.check-for-update-types', ["update", "new"]) def toggle_hide_previous_addons(self, obj): active = obj.get_active() config.set('behavior.do-not-show-previously-seen-updates', bool(active)) def toggle_tag_on_import(self, obj): active = obj.get_active() config.set('preferences.tag-on-import', bool(active)) self.tag_format_entry.set_sensitive(bool(active)) def check_for_updates_changed(self, obj): active = obj.get_active() config.set('behavior.check-for-updates', active) def date_format_changed(self, obj): config.set('preferences.date-format', obj.get_active()) OkDialog(_('Change is not immediate'), _('Changing the data format will not take ' 'effect until the next time Gramps is started.')) def date_calendar_changed(self, obj): config.set('preferences.calendar-format-report', obj.get_active()) def add_date_panel(self, configdialog): table = Gtk.Table(n_rows=2, n_columns=7) table.set_border_width(12) table.set_col_spacings(6) table.set_row_spacings(6) self.add_spinner(table, _('Date about range'), 0, 'behavior.date-about-range', (1, 9999)) self.add_spinner(table, _('Date after range'), 1, 'behavior.date-after-range', (1, 9999)) self.add_spinner(table, _('Date before range'), 2, 'behavior.date-before-range', (1, 9999)) self.add_spinner(table, _('Maximum age probably alive'), 3, 'behavior.max-age-prob-alive', (80, 140)) self.add_spinner(table, _('Maximum sibling age difference'), 4, 'behavior.max-sib-age-diff', (10, 30)) self.add_spinner(table, _('Minimum years between generations'), 5, 'behavior.min-generation-years', (5, 20)) self.add_spinner(table, _('Average years between generations'), 6, 'behavior.avg-generation-gap', (10, 30)) self.add_pos_int_entry(table, _('Markup for invalid date format'), 7, 'preferences.invalid-date-format', self.update_markup_entry, helptext = _('Convenience markups are:\n' '<b>&lt;b&gt;Bold&lt;/b&gt;</b>\n' '<big>&lt;big&gt;Makes font relatively larger&lt;/big&gt;</big>\n' '<i>&lt;i&gt;Italic&lt;/i&gt;</i>\n' '<s>&lt;s&gt;Strikethrough&lt;/s&gt;</s>\n' '<sub>&lt;sub&gt;Subscript&lt;/sub&gt;</sub>\n' '<sup>&lt;sup&gt;Superscript&lt;/sup&gt;</sup>\n' '<small>&lt;small&gt;Makes font relatively smaller&lt;/small&gt;</small>\n' '<tt>&lt;tt&gt;Monospace font&lt;/tt&gt;</tt>\n' '<u>&lt;u&gt;Underline&lt;/u&gt;</u>\n\n' 'For example: &lt;u&gt;&lt;b&gt;%s&lt;/b&gt;&lt;/u&gt;\n' 'will display <u><b>Underlined bold date</b></u>.\n') ) return _('Dates'), table def add_behavior_panel(self, configdialog): table = Gtk.Table(n_rows=2, n_columns=8) table.set_border_width(12) table.set_col_spacings(6) table.set_row_spacings(6) current_line = 0 self.add_checkbox(table, _('Add default source on GEDCOM import'), current_line, 'preferences.default-source') current_line += 1 checkbutton = Gtk.CheckButton(label=_("Add tag on import")) checkbutton.set_active(config.get('preferences.tag-on-import')) checkbutton.connect("toggled", self.toggle_tag_on_import) table.attach(checkbutton, 1, 2, current_line, current_line+1, yoptions=0) self.tag_format_entry = self.add_entry(table, None, current_line, 'preferences.tag-on-import-format', col_attach=2) self.tag_format_entry.set_sensitive(config.get('preferences.tag-on-import')) current_line += 1 obj = self.add_checkbox(table, _('Enable spelling checker'), current_line, 'behavior.spellcheck') if not HAVE_GTKSPELL: obj.set_sensitive(False) spell_dict = { 'gramps_wiki_build_spell_url' : URL_WIKISTRING + "GEPS_029:_GTK3-GObject_introspection" "_Conversion#Spell_Check_Install" } obj.set_tooltip_text( _("GtkSpell not loaded. " "Spell checking will not be available.\n" "To build it for Gramps see " "%(gramps_wiki_build_spell_url)s") % spell_dict ) current_line += 1 self.add_checkbox(table, _('Display Tip of the Day'), current_line, 'behavior.use-tips') current_line += 1 self.add_checkbox(table, _('Remember last view displayed'), current_line, 'preferences.use-last-view') current_line += 1 self.add_spinner(table, _('Max generations for relationships'), current_line, 'behavior.generation-depth', (5, 50), self.update_gendepth) current_line += 1 self.path_entry = Gtk.Entry() self.add_path_box(table, _('Base path for relative media paths'), current_line, self.path_entry, self.dbstate.db.get_mediapath(), self.set_mediapath, self.select_mediapath) current_line += 1 # Check for updates: obox = Gtk.ComboBoxText() formats = [_("Never"), _("Once a month"), _("Once a week"), _("Once a day"), _("Always"), ] list(map(obox.append_text, formats)) active = config.get('behavior.check-for-updates') obox.set_active(active) obox.connect('changed', self.check_for_updates_changed) lwidget = BasicLabel("%s: " % _('Check for updates')) table.attach(lwidget, 1, 2, current_line, current_line+1, yoptions=0) table.attach(obox, 2, 3, current_line, current_line+1, yoptions=0) current_line += 1 self.whattype_box = Gtk.ComboBoxText() formats = [_("Updated addons only"), _("New addons only"), _("New and updated addons"),] list(map(self.whattype_box.append_text, formats)) whattype = config.get('behavior.check-for-update-types') if "new" in whattype and "update" in whattype: self.whattype_box.set_active(2) elif "new" in whattype: self.whattype_box.set_active(1) elif "update" in whattype: self.whattype_box.set_active(0) self.whattype_box.connect('changed', self.check_for_type_changed) lwidget = BasicLabel("%s: " % _('What to check')) table.attach(lwidget, 1, 2, current_line, current_line+1, yoptions=0) table.attach(self.whattype_box, 2, 3, current_line, current_line+1, yoptions=0) current_line += 1 self.add_entry(table, _('Where to check'), current_line, 'behavior.addons-url', col_attach=1) current_line += 1 checkbutton = Gtk.CheckButton( label=_("Do not ask about previously notified addons")) checkbutton.set_active(config.get('behavior.do-not-show-previously-seen-updates')) checkbutton.connect("toggled", self.toggle_hide_previous_addons) table.attach(checkbutton, 0, 3, current_line, current_line+1, yoptions=0) button = Gtk.Button(_("Check now")) button.connect("clicked", self.check_for_updates) table.attach(button, 3, 4, current_line, current_line+1, yoptions=0) return _('General'), table def check_for_updates(self, button): try: addon_update_list = available_updates() except: OkDialog(_("Checking Addons Failed"), _("The addon repository appears to be unavailable. " "Please try again later."), self.window) return if len(addon_update_list) > 0: try: PluginWindows.UpdateAddons(self.uistate, [], addon_update_list) except WindowActiveError: pass else: check_types = config.get('behavior.check-for-update-types') OkDialog(_("There are no available addons of this type"), _("Checked for '%s'") % _("' and '").join([_(t) for t in check_types]), self.window) # List of translated strings used here # Dead code for l10n _('new'), _('update') self.uistate.viewmanager.do_reg_plugins(self.dbstate, self.uistate) def add_famtree_panel(self, configdialog): table = Gtk.Table(n_rows=2, n_columns=2) table.set_border_width(12) table.set_col_spacings(6) table.set_row_spacings(6) self.dbpath_entry = Gtk.Entry() self.add_path_box(table, _('Family Tree Database path'), 0, self.dbpath_entry, config.get('behavior.database-path'), self.set_dbpath, self.select_dbpath) #self.add_entry(table, # _('Family Tree Database path'), # 0, 'behavior.database-path') self.add_checkbox(table, _('Automatically load last Family Tree'), 1, 'behavior.autoload') return _('Family Tree'), table def set_mediapath(self, *obj): if self.path_entry.get_text().strip(): self.dbstate.db.set_mediapath(self.path_entry.get_text()) else: self.dbstate.db.set_mediapath(None) def select_mediapath(self, *obj): f = Gtk.FileChooserDialog( _("Select media directory"), action=Gtk.FileChooserAction.SELECT_FOLDER, buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_APPLY, Gtk.ResponseType.OK)) mpath = self.dbstate.db.get_mediapath() if not mpath: mpath = HOME_DIR f.set_current_folder(os.path.dirname(mpath)) status = f.run() if status == Gtk.ResponseType.OK: val = conv_to_unicode(f.get_filename()) if val: self.path_entry.set_text(val) f.destroy() def set_dbpath(self, *obj): path = conv_to_unicode(self.dbpath_entry.get_text().strip()) config.set('behavior.database-path', path) def select_dbpath(self, *obj): f = Gtk.FileChooserDialog( _("Select database directory"), action=Gtk.FileChooserAction.SELECT_FOLDER, buttons=(Gtk.STOCK_CANCEL, Gtk.ResponseType.CANCEL, Gtk.STOCK_APPLY, Gtk.ResponseType.OK)) dbpath = config.get('behavior.database-path') if not dbpath: dbpath = os.path.join(HOME_DIR,'grampsdb') f.set_current_folder(os.path.dirname(dbpath)) status = f.run() if status == Gtk.ResponseType.OK: val = conv_to_unicode(f.get_filename()) if val: self.dbpath_entry.set_text(val) f.destroy() def update_idformat_entry(self, obj, constant): config.set(constant, conv_to_unicode(obj.get_text())) self.dbstate.db.set_prefixes( config.get('preferences.iprefix'), config.get('preferences.oprefix'), config.get('preferences.fprefix'), config.get('preferences.sprefix'), config.get('preferences.cprefix'), config.get('preferences.pprefix'), config.get('preferences.eprefix'), config.get('preferences.rprefix'), config.get('preferences.nprefix') ) def update_gendepth(self, obj, constant): """ Called when the generation depth setting is changed. """ intval = int(obj.get_value()) config.set(constant, intval) #immediately use this value in displaystate. self.uistate.set_gendepth(intval) def update_surn_height(self, obj, constant): ok = True if not obj.get_text(): return try: intval = int(obj.get_text()) except: intval = config.get(constant) ok = False if intval < 0 : intval = config.get(constant) ok = False if ok: config.set(constant, intval) else: obj.set_text(str(intval)) def build_menu_names(self, obj): return (_('Preferences'), None) # FIXME: is this needed? def _set_button(self, stock): button = Gtk.Button() image = Gtk.Image() image.set_from_stock(stock, Gtk.IconSize.BUTTON) image.show() button.add(image) button.show() return button
pmghalvorsen/gramps_branch
gramps/gui/configure.py
Python
gpl-2.0
62,972
using GalaSoft.MvvmLight; using GalaSoft.MvvmLight.Command; using IseWrapper; using MahApps.Metro.Controls; using MahApps.Metro.Controls.Dialogs; using Microsoft.Practices.ServiceLocation; using System; using System.Collections.Generic; using System.Drawing; using System.IO; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Imaging; namespace isetool.ViewModel { public enum StartMode { MODE_VIEWER, MODE_MAKER } public class MainViewModel : ViewModelBase { public MainViewModel() { MenuFileSaveCommand = new RelayCommand(() => SaveFile()); MenuFileOpenCommand = new RelayCommand(() => ExcuteFileOpen()); DialogSubmitCommand = new RelayCommand(() => DialogSubmit()); DialogCancelCommand = new RelayCommand(() => HidePasswordDialog()); MenuSelectionAllCommand = new RelayCommand(() => AllSelection()); MenuSelectionCancelCommand = new RelayCommand(() => CancelSelection()); MenuSelectionFaceCommand = new RelayCommand(() => FaceSelection()); } /// <summary> /// Top Menu Commands /// </summary> public RelayCommand MenuFileOpenCommand { get; set; } public RelayCommand MenuFileSaveCommand { get; set; } //public RelayCommand MenuFileSaveAsCommand { get; set; } public RelayCommand MenuSelectionAllCommand { get; set; } public RelayCommand MenuSelectionCancelCommand { get; set; } public RelayCommand MenuSelectionFaceCommand { get; set; } public RelayCommand DialogSubmitCommand { get; set; } public RelayCommand DialogCancelCommand { get; set; } /// <summary> /// Open Mode Property /// </summary> private StartMode _StMode = StartMode.MODE_MAKER; public StartMode StMode { get { return this._StMode; } set { if (value != this._StMode) { this._StMode = value; RaisePropertyChanged("StMode"); } } } /// <summary> /// Zoom Level Property /// </summary> private int _ZoomLevel = 3; public int ZoomLevel { get { return this._ZoomLevel; } set { if (value != this._ZoomLevel) { this._ZoomLevel = value; RaisePropertyChanged("ZoomLevel"); } } } /// <summary> /// Image Height Property /// </summary> private int _ImageHeight; public int ImageHeight { get { return this._ImageHeight; } set { if (value != this._ImageHeight) { this._ImageHeight = value; RaisePropertyChanged("ImageHeight"); } } } /// <summary> /// Password Property /// </summary> private string _Password = string.Empty; public string Password { get { return this._Password; } set { if (value != this._Password) { this._Password = value; RaisePropertyChanged("Password"); } } } /// <summary> /// Dialog Password Property /// </summary> private string _DialogPassword = string.Empty; public string DialogPassword { get { return this._DialogPassword; } set { if (value != this._DialogPassword) { this._DialogPassword = value; RaisePropertyChanged("DialogPassword"); } } } /// <summary> /// Image Width Property /// </summary> private int _ImageWidth; public int ImageWidth { get { return this._ImageWidth; } set { if (value != this._ImageWidth) { this._ImageWidth = value; RaisePropertyChanged("ImageWidth"); } } } /// <summary> /// Image Property /// </summary> private BitmapImage _Image; public BitmapImage Image { get { return this._Image; } set { if (value != this._Image) { this._Image = value; RaisePropertyChanged("Image"); } } } /// <summary> /// File Path Property /// </summary> private string _FilePath; public string FilePath { get { return this._FilePath; } set { if (value != this._FilePath) { this._FilePath = value.Replace("\\","/"); RaisePropertyChanged("FilePath"); } } } private void SaveFile() { if (FilePath != null && !String.IsNullOrEmpty(Password)) { try { MultiSelectionCanvasViewModel vm = ServiceLocator.Current.GetInstance<MultiSelectionCanvasViewModel>(); List<SecureContainer> scList = new List<SecureContainer>(); foreach (Model.SecureContainerModel model in vm.ContainerList) { scList.Add(new SecureContainer(model.Width, model.Height, model.X, model.Y)); } if (FilePath.EndsWith(".jpg")) { ImageSecureExtention.makeJPGX(FilePath, scList, Password); } else { ImageSecureExtention.makePNGX(FilePath, scList, Password); } } catch (Exception e) { DialogManager.ShowMessageAsync(Application.Current.MainWindow as MetroWindow, "Error", "Failed to save file."); } finally { DialogManager.ShowMessageAsync(Application.Current.MainWindow as MetroWindow, "Result", "Success."); } } else { DialogManager.ShowMessageAsync(Application.Current.MainWindow as MetroWindow, "Warning", "Please Input Password."); } } private void ExcuteFileOpen() { CancelSelection(); Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog(); dlg.Filter = "JPEG Files (*.jpeg,*.jpg)|*.jpg;*.jpeg|PNG Files (*.png)|*.png|JPGX Files (*.jpgx)|*.jpgx|PNGX Files (*.pngx)|*.pngx"; Nullable<bool> result = dlg.ShowDialog(); if (result == true) { FilePath = dlg.FileName; LoadFile(); } } public void ParseParameter() { string[] args = Environment.GetCommandLineArgs(); if (args.Length > 1) { FilePath = args[1]; LoadFile(); } } private void FileOpen(string path) { FilePath = path; Image = new BitmapImage(new Uri(FilePath, UriKind.RelativeOrAbsolute)); ImageWidth = Image.PixelWidth; ImageHeight = Image.PixelHeight; } private void CancelSelection() { MultiSelectionCanvasViewModel vm = ServiceLocator.Current.GetInstance<MultiSelectionCanvasViewModel>(); vm.ContainerList.Clear(); } private void FaceSelection() { CancelSelection(); } private void AllSelection() { CancelSelection(); MultiSelectionCanvasViewModel vm = ServiceLocator.Current.GetInstance<MultiSelectionCanvasViewModel>(); vm.ContainerList.Add(new Model.SecureContainerModel(0, 0, ImageWidth, ImageHeight)); } private void LoadSecurityFile(string path,string pwd="") { if(path.EndsWith(".jpgx")) { JpgxDecompressContainer container = ImageSecureExtention.getJpgxContainer(path, pwd); Bitmap bitmap = container.getImageBitmapRGB(); MemoryStream ms = new MemoryStream(); ms.Seek(0, SeekOrigin.Begin); bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); BitmapImage image = new BitmapImage(); image.BeginInit(); image.StreamSource = ms; image.EndInit(); Image = image; ImageWidth = container.getWidth(); ImageHeight = container.getHeight(); } else { PngxDecompressContainer container = ImageSecureExtention.getPngxContainer(path, pwd); Bitmap bitmap = container.getImageBitmap(); MemoryStream ms = new MemoryStream(); ms.Seek(0, SeekOrigin.Begin); bitmap.Save(ms, System.Drawing.Imaging.ImageFormat.Bmp); BitmapImage image = new BitmapImage(); image.BeginInit(); image.StreamSource = ms; image.EndInit(); Image = image; ImageWidth = container.getWidth(); ImageHeight = container.getHeight(); } } private void LoadFile() { if (FilePath.EndsWith(".jpg") || FilePath.EndsWith(".jpeg") || FilePath.EndsWith(".png")) { StMode = StartMode.MODE_MAKER; FileOpen(FilePath); } else { StMode = StartMode.MODE_VIEWER; LoadSecurityFile(FilePath); OpenPasswordDialog(); } } private void DialogSubmit() { LoadSecurityFile(FilePath, DialogPassword); HidePasswordDialog(); } private void OpenPasswordDialog() { MetroWindow window = Application.Current.MainWindow as MetroWindow; var dialog = (BaseMetroDialog)window.Resources["PasswordDialog"]; window.ShowMetroDialogAsync(dialog); } private void HidePasswordDialog() { MetroWindow window = Application.Current.MainWindow as MetroWindow; var dialog = (BaseMetroDialog)window.Resources["PasswordDialog"]; window.HideMetroDialogAsync(dialog); } } }
cnabro/Image-Secure-Extension
tools/wpf/isetool/ViewModel/MainViewModel.cs
C#
gpl-2.0
11,395
/** * generated by Xtext */ package nl.sison.dsl.mobgen.ui.quickfix; import org.eclipse.xtext.ui.editor.quickfix.DefaultQuickfixProvider; /** * Custom quickfixes. * * see http://www.eclipse.org/Xtext/documentation.html#quickfixes */ @SuppressWarnings("all") public class JsonGenQuickfixProvider extends DefaultQuickfixProvider { }
Buggaboo/xplatform
nl.sison.dsl.mobgen.JsonGen.ui/xtend-gen/nl/sison/dsl/mobgen/ui/quickfix/JsonGenQuickfixProvider.java
Java
gpl-2.0
340
/* * This file is part of PowerDNS or dnsdist. * Copyright -- PowerDNS.COM B.V. and its contributors * * This program is free software; you can redistribute it and/or modify * it under the terms of version 2 of the GNU General Public License as * published by the Free Software Foundation. * * In addition, for the avoidance of any doubt, permission is granted to * link this program with OpenSSL and to (re)distribute the binaries * produced as the result of such linking. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #ifdef HAVE_CONFIG_H #include "config.h" #endif #include <sys/param.h> #include <sys/socket.h> #include <fcntl.h> #include <netdb.h> #include <sys/time.h> #include <time.h> #include <sys/resource.h> #include <netinet/in.h> #include <sys/un.h> #include <unistd.h> #include <fstream> #include "misc.hh" #include <vector> #include <sstream> #include <errno.h> #include <cstring> #include <iostream> #include <sys/types.h> #include <dirent.h> #include <algorithm> #include <poll.h> #include <iomanip> #include <netinet/tcp.h> #include <string.h> #include <stdlib.h> #include <stdio.h> #include "pdnsexception.hh" #include <sys/types.h> #include <boost/algorithm/string.hpp> #include "iputils.hh" #include "dnsparser.hh" #include <sys/types.h> #include <pwd.h> #include <grp.h> #include <limits.h> #ifdef __FreeBSD__ # include <pthread_np.h> #endif #ifdef __NetBSD__ # include <pthread.h> # include <sched.h> #endif size_t writen2(int fd, const void *buf, size_t count) { const char *ptr = reinterpret_cast<const char*>(buf); const char *eptr = ptr + count; ssize_t res; while(ptr != eptr) { res = ::write(fd, ptr, eptr - ptr); if(res < 0) { if (errno == EAGAIN) throw std::runtime_error("used writen2 on non-blocking socket, got EAGAIN"); else unixDie("failed in writen2"); } else if (res == 0) throw std::runtime_error("could not write all bytes, got eof in writen2"); ptr += (size_t) res; } return count; } size_t readn2(int fd, void* buffer, size_t len) { size_t pos=0; ssize_t res; for(;;) { res = read(fd, (char*)buffer + pos, len - pos); if(res == 0) throw runtime_error("EOF while reading message"); if(res < 0) { if (errno == EAGAIN) throw std::runtime_error("used readn2 on non-blocking socket, got EAGAIN"); else unixDie("failed in readn2"); } pos+=(size_t)res; if(pos == len) break; } return len; } size_t readn2WithTimeout(int fd, void* buffer, size_t len, const struct timeval& idleTimeout, const struct timeval& totalTimeout, bool allowIncomplete) { size_t pos = 0; struct timeval start{0,0}; struct timeval remainingTime = totalTimeout; if (totalTimeout.tv_sec != 0 || totalTimeout.tv_usec != 0) { gettimeofday(&start, nullptr); } do { ssize_t got = read(fd, (char *)buffer + pos, len - pos); if (got > 0) { pos += (size_t) got; if (allowIncomplete) { break; } } else if (got == 0) { throw runtime_error("EOF while reading message"); } else { if (errno == EAGAIN) { struct timeval w = ((totalTimeout.tv_sec == 0 && totalTimeout.tv_usec == 0) || idleTimeout <= remainingTime) ? idleTimeout : remainingTime; int res = waitForData(fd, w.tv_sec, w.tv_usec); if (res > 0) { /* there is data available */ } else if (res == 0) { throw runtime_error("Timeout while waiting for data to read"); } else { throw runtime_error("Error while waiting for data to read"); } } else { unixDie("failed in readn2WithTimeout"); } } if (totalTimeout.tv_sec != 0 || totalTimeout.tv_usec != 0) { struct timeval now; gettimeofday(&now, nullptr); struct timeval elapsed = now - start; if (remainingTime < elapsed) { throw runtime_error("Timeout while reading data"); } start = now; remainingTime = remainingTime - elapsed; } } while (pos < len); return len; } size_t writen2WithTimeout(int fd, const void * buffer, size_t len, const struct timeval& timeout) { size_t pos = 0; do { ssize_t written = write(fd, reinterpret_cast<const char *>(buffer) + pos, len - pos); if (written > 0) { pos += (size_t) written; } else if (written == 0) throw runtime_error("EOF while writing message"); else { if (errno == EAGAIN) { int res = waitForRWData(fd, false, timeout.tv_sec, timeout.tv_usec); if (res > 0) { /* there is room available */ } else if (res == 0) { throw runtime_error("Timeout while waiting to write data"); } else { throw runtime_error("Error while waiting for room to write data"); } } else { unixDie("failed in write2WithTimeout"); } } } while (pos < len); return len; } string nowTime() { time_t now = time(nullptr); struct tm tm; localtime_r(&now, &tm); char buffer[30]; // YYYY-mm-dd HH:MM:SS TZOFF strftime(buffer, sizeof(buffer), "%F %T %z", &tm); buffer[sizeof(buffer)-1] = '\0'; return string(buffer); } uint16_t getShort(const unsigned char *p) { return p[0] * 256 + p[1]; } uint16_t getShort(const char *p) { return getShort((const unsigned char *)p); } uint32_t getLong(const unsigned char* p) { return (p[0]<<24) + (p[1]<<16) + (p[2]<<8) + p[3]; } uint32_t getLong(const char* p) { return getLong(reinterpret_cast<const unsigned char *>(p)); } static bool ciEqual(const string& a, const string& b) { if(a.size()!=b.size()) return false; string::size_type pos=0, epos=a.size(); for(;pos < epos; ++pos) if(dns_tolower(a[pos])!=dns_tolower(b[pos])) return false; return true; } /** does domain end on suffix? Is smart about "wwwds9a.nl" "ds9a.nl" not matching */ static bool endsOn(const string &domain, const string &suffix) { if( suffix.empty() || ciEqual(domain, suffix) ) return true; if(domain.size()<=suffix.size()) return false; string::size_type dpos=domain.size()-suffix.size()-1, spos=0; if(domain[dpos++]!='.') return false; for(; dpos < domain.size(); ++dpos, ++spos) if(dns_tolower(domain[dpos]) != dns_tolower(suffix[spos])) return false; return true; } /** strips a domain suffix from a domain, returns true if it stripped */ bool stripDomainSuffix(string *qname, const string &domain) { if(!endsOn(*qname, domain)) return false; if(toLower(*qname)==toLower(domain)) *qname="@"; else { if((*qname)[qname->size()-domain.size()-1]!='.') return false; qname->resize(qname->size()-domain.size()-1); } return true; } static void parseService4(const string &descr, ServiceTuple &st) { vector<string>parts; stringtok(parts,descr,":"); if(parts.empty()) throw PDNSException("Unable to parse '"+descr+"' as a service"); st.host=parts[0]; if(parts.size()>1) st.port=pdns_stou(parts[1]); } static void parseService6(const string &descr, ServiceTuple &st) { string::size_type pos=descr.find(']'); if(pos == string::npos) throw PDNSException("Unable to parse '"+descr+"' as an IPv6 service"); st.host=descr.substr(1, pos-1); if(pos + 2 < descr.length()) st.port=pdns_stou(descr.substr(pos+2)); } void parseService(const string &descr, ServiceTuple &st) { if(descr.empty()) throw PDNSException("Unable to parse '"+descr+"' as a service"); vector<string> parts; stringtok(parts, descr, ":"); if(descr[0]=='[') { parseService6(descr, st); } else if(descr[0]==':' || parts.size() > 2 || descr.find("::") != string::npos) { st.host=descr; } else { parseService4(descr, st); } } // returns -1 in case if error, 0 if no data is available, 1 if there is. In the first two cases, errno is set int waitForData(int fd, int seconds, int useconds) { return waitForRWData(fd, true, seconds, useconds); } int waitForRWData(int fd, bool waitForRead, int seconds, int useconds, bool* error, bool* disconnected) { int ret; struct pollfd pfd; memset(&pfd, 0, sizeof(pfd)); pfd.fd = fd; if(waitForRead) pfd.events=POLLIN; else pfd.events=POLLOUT; ret = poll(&pfd, 1, seconds * 1000 + useconds/1000); if (ret > 0) { if (error && (pfd.revents & POLLERR)) { *error = true; } if (disconnected && (pfd.revents & POLLHUP)) { *disconnected = true; } } return ret; } // returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set int waitForMultiData(const set<int>& fds, const int seconds, const int useconds, int* fdOut) { set<int> realFDs; for (const auto& fd : fds) { if (fd >= 0 && realFDs.count(fd) == 0) { realFDs.insert(fd); } } std::vector<struct pollfd> pfds(realFDs.size()); memset(pfds.data(), 0, realFDs.size()*sizeof(struct pollfd)); int ctr = 0; for (const auto& fd : realFDs) { pfds[ctr].fd = fd; pfds[ctr].events = POLLIN; ctr++; } int ret; if(seconds >= 0) ret = poll(pfds.data(), realFDs.size(), seconds * 1000 + useconds/1000); else ret = poll(pfds.data(), realFDs.size(), -1); if(ret <= 0) return ret; set<int> pollinFDs; for (const auto& pfd : pfds) { if (pfd.revents & POLLIN) { pollinFDs.insert(pfd.fd); } } set<int>::const_iterator it(pollinFDs.begin()); advance(it, random() % pollinFDs.size()); *fdOut = *it; return 1; } // returns -1 in case of error, 0 if no data is available, 1 if there is. In the first two cases, errno is set int waitFor2Data(int fd1, int fd2, int seconds, int useconds, int*fd) { int ret; struct pollfd pfds[2]; memset(&pfds[0], 0, 2*sizeof(struct pollfd)); pfds[0].fd = fd1; pfds[1].fd = fd2; pfds[0].events= pfds[1].events = POLLIN; int nsocks = 1 + (fd2 >= 0); // fd2 can optionally be -1 if(seconds >= 0) ret = poll(pfds, nsocks, seconds * 1000 + useconds/1000); else ret = poll(pfds, nsocks, -1); if(!ret || ret < 0) return ret; if((pfds[0].revents & POLLIN) && !(pfds[1].revents & POLLIN)) *fd = pfds[0].fd; else if((pfds[1].revents & POLLIN) && !(pfds[0].revents & POLLIN)) *fd = pfds[1].fd; else if(ret == 2) { *fd = pfds[random()%2].fd; } else *fd = -1; // should never happen return 1; } string humanDuration(time_t passed) { ostringstream ret; if(passed<60) ret<<passed<<" seconds"; else if(passed<3600) ret<<std::setprecision(2)<<passed/60.0<<" minutes"; else if(passed<86400) ret<<std::setprecision(3)<<passed/3600.0<<" hours"; else if(passed<(86400*30.41)) ret<<std::setprecision(3)<<passed/86400.0<<" days"; else ret<<std::setprecision(3)<<passed/(86400*30.41)<<" months"; return ret.str(); } const string unquotify(const string &item) { if(item.size()<2) return item; string::size_type bpos=0, epos=item.size(); if(item[0]=='"') bpos=1; if(item[epos-1]=='"') epos-=1; return item.substr(bpos,epos-bpos); } void stripLine(string &line) { string::size_type pos=line.find_first_of("\r\n"); if(pos!=string::npos) { line.resize(pos); } } string urlEncode(const string &text) { string ret; for(char i : text) if(i==' ')ret.append("%20"); else ret.append(1,i); return ret; } string getHostname() { #ifndef MAXHOSTNAMELEN #define MAXHOSTNAMELEN 255 #endif char tmp[MAXHOSTNAMELEN]; if(gethostname(tmp, MAXHOSTNAMELEN)) return "UNKNOWN"; return string(tmp); } string itoa(int i) { ostringstream o; o<<i; return o.str(); } string uitoa(unsigned int i) // MSVC 6 doesn't grok overloading (un)signed { ostringstream o; o<<i; return o.str(); } string bitFlip(const string &str) { string::size_type pos=0, epos=str.size(); string ret; ret.reserve(epos); for(;pos < epos; ++pos) ret.append(1, ~str[pos]); return ret; } string stringerror(int err) { return strerror(err); } string stringerror() { return strerror(errno); } void cleanSlashes(string &str) { string::const_iterator i; string out; for(i=str.begin();i!=str.end();++i) { if(*i=='/' && i!=str.begin() && *(i-1)=='/') continue; out.append(1,*i); } str=out; } bool IpToU32(const string &str, uint32_t *ip) { if(str.empty()) { *ip=0; return true; } struct in_addr inp; if(inet_aton(str.c_str(), &inp)) { *ip=inp.s_addr; return true; } return false; } string U32ToIP(uint32_t val) { char tmp[17]; snprintf(tmp, sizeof(tmp), "%u.%u.%u.%u", (val >> 24)&0xff, (val >> 16)&0xff, (val >> 8)&0xff, (val )&0xff); return string(tmp); } string makeHexDump(const string& str) { char tmp[5]; string ret; ret.reserve((int)(str.size()*2.2)); for(char n : str) { snprintf(tmp, sizeof(tmp), "%02x ", (unsigned char)n); ret+=tmp; } return ret; } string makeBytesFromHex(const string &in) { if (in.size() % 2 != 0) { throw std::range_error("odd number of bytes in hex string"); } string ret; ret.reserve(in.size()); unsigned int num; for (size_t i = 0; i < in.size(); i+=2) { string numStr = in.substr(i, 2); num = 0; sscanf(numStr.c_str(), "%02x", &num); ret.push_back((uint8_t)num); } return ret; } void normalizeTV(struct timeval& tv) { if(tv.tv_usec > 1000000) { ++tv.tv_sec; tv.tv_usec-=1000000; } else if(tv.tv_usec < 0) { --tv.tv_sec; tv.tv_usec+=1000000; } } const struct timeval operator+(const struct timeval& lhs, const struct timeval& rhs) { struct timeval ret; ret.tv_sec=lhs.tv_sec + rhs.tv_sec; ret.tv_usec=lhs.tv_usec + rhs.tv_usec; normalizeTV(ret); return ret; } const struct timeval operator-(const struct timeval& lhs, const struct timeval& rhs) { struct timeval ret; ret.tv_sec=lhs.tv_sec - rhs.tv_sec; ret.tv_usec=lhs.tv_usec - rhs.tv_usec; normalizeTV(ret); return ret; } pair<string, string> splitField(const string& inp, char sepa) { pair<string, string> ret; string::size_type cpos=inp.find(sepa); if(cpos==string::npos) ret.first=inp; else { ret.first=inp.substr(0, cpos); ret.second=inp.substr(cpos+1); } return ret; } int logFacilityToLOG(unsigned int facility) { switch(facility) { case 0: return LOG_LOCAL0; case 1: return(LOG_LOCAL1); case 2: return(LOG_LOCAL2); case 3: return(LOG_LOCAL3); case 4: return(LOG_LOCAL4); case 5: return(LOG_LOCAL5); case 6: return(LOG_LOCAL6); case 7: return(LOG_LOCAL7); default: return -1; } } string stripDot(const string& dom) { if(dom.empty()) return dom; if(dom[dom.size()-1]!='.') return dom; return dom.substr(0,dom.size()-1); } int makeIPv6sockaddr(const std::string& addr, struct sockaddr_in6* ret) { if(addr.empty()) return -1; string ourAddr(addr); bool portSet = false; unsigned int port; if(addr[0]=='[') { // [::]:53 style address string::size_type pos = addr.find(']'); if(pos == string::npos) return -1; ourAddr.assign(addr.c_str() + 1, pos-1); if (pos + 1 != addr.size()) { // complete after ], no port specified if (pos + 2 > addr.size() || addr[pos+1]!=':') return -1; try { port = pdns_stou(addr.substr(pos+2)); portSet = true; } catch(const std::out_of_range&) { return -1; } } } ret->sin6_scope_id=0; ret->sin6_family=AF_INET6; if(inet_pton(AF_INET6, ourAddr.c_str(), (void*)&ret->sin6_addr) != 1) { struct addrinfo* res; struct addrinfo hints; memset(&hints, 0, sizeof(hints)); hints.ai_family = AF_INET6; hints.ai_flags = AI_NUMERICHOST; // getaddrinfo has anomalous return codes, anything nonzero is an error, positive or negative if (getaddrinfo(ourAddr.c_str(), nullptr, &hints, &res) != 0) { return -1; } memcpy(ret, res->ai_addr, res->ai_addrlen); freeaddrinfo(res); } if(portSet) { if(port > 65535) return -1; ret->sin6_port = htons(port); } return 0; } int makeIPv4sockaddr(const std::string& str, struct sockaddr_in* ret) { if(str.empty()) { return -1; } struct in_addr inp; string::size_type pos = str.find(':'); if(pos == string::npos) { // no port specified, not touching the port if(inet_aton(str.c_str(), &inp)) { ret->sin_addr.s_addr=inp.s_addr; return 0; } return -1; } if(!*(str.c_str() + pos + 1)) // trailing : return -1; char *eptr = const_cast<char*>(str.c_str()) + str.size(); int port = strtol(str.c_str() + pos + 1, &eptr, 10); if (port < 0 || port > 65535) return -1; if(*eptr) return -1; ret->sin_port = htons(port); if(inet_aton(str.substr(0, pos).c_str(), &inp)) { ret->sin_addr.s_addr=inp.s_addr; return 0; } return -1; } int makeUNsockaddr(const std::string& path, struct sockaddr_un* ret) { if (path.empty()) return -1; memset(ret, 0, sizeof(struct sockaddr_un)); ret->sun_family = AF_UNIX; if (path.length() >= sizeof(ret->sun_path)) return -1; path.copy(ret->sun_path, sizeof(ret->sun_path), 0); return 0; } //! read a line of text from a FILE* to a std::string, returns false on 'no data' bool stringfgets(FILE* fp, std::string& line) { char buffer[1024]; line.clear(); do { if(!fgets(buffer, sizeof(buffer), fp)) return !line.empty(); line.append(buffer); } while(!strchr(buffer, '\n')); return true; } bool readFileIfThere(const char* fname, std::string* line) { line->clear(); auto fp = std::unique_ptr<FILE, int(*)(FILE*)>(fopen(fname, "r"), fclose); if(!fp) return false; stringfgets(fp.get(), *line); fp.reset(); return true; } Regex::Regex(const string &expr) { if(regcomp(&d_preg, expr.c_str(), REG_ICASE|REG_NOSUB|REG_EXTENDED)) throw PDNSException("Regular expression did not compile"); } // if you end up here because valgrind told you were are doing something wrong // with msgh->msg_controllen, please refer to https://github.com/PowerDNS/pdns/pull/3962 // first. // Note that cmsgbuf should be aligned the same as a struct cmsghdr void addCMsgSrcAddr(struct msghdr* msgh, cmsgbuf_aligned* cmsgbuf, const ComboAddress* source, int itfIndex) { struct cmsghdr *cmsg = nullptr; if(source->sin4.sin_family == AF_INET6) { struct in6_pktinfo *pkt; msgh->msg_control = cmsgbuf; #if !defined( __APPLE__ ) /* CMSG_SPACE is not a constexpr on macOS */ static_assert(CMSG_SPACE(sizeof(*pkt)) <= sizeof(*cmsgbuf), "Buffer is too small for in6_pktinfo"); #else /* __APPLE__ */ if (CMSG_SPACE(sizeof(*pkt)) > sizeof(*cmsgbuf)) { throw std::runtime_error("Buffer is too small for in6_pktinfo"); } #endif /* __APPLE__ */ msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt)); cmsg = CMSG_FIRSTHDR(msgh); cmsg->cmsg_level = IPPROTO_IPV6; cmsg->cmsg_type = IPV6_PKTINFO; cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt)); pkt = (struct in6_pktinfo *) CMSG_DATA(cmsg); // Include the padding to stop valgrind complaining about passing uninitialized data memset(pkt, 0, CMSG_SPACE(sizeof(*pkt))); pkt->ipi6_addr = source->sin6.sin6_addr; pkt->ipi6_ifindex = itfIndex; } else { #if defined(IP_PKTINFO) struct in_pktinfo *pkt; msgh->msg_control = cmsgbuf; #if !defined( __APPLE__ ) /* CMSG_SPACE is not a constexpr on macOS */ static_assert(CMSG_SPACE(sizeof(*pkt)) <= sizeof(*cmsgbuf), "Buffer is too small for in_pktinfo"); #else /* __APPLE__ */ if (CMSG_SPACE(sizeof(*pkt)) > sizeof(*cmsgbuf)) { throw std::runtime_error("Buffer is too small for in_pktinfo"); } #endif /* __APPLE__ */ msgh->msg_controllen = CMSG_SPACE(sizeof(*pkt)); cmsg = CMSG_FIRSTHDR(msgh); cmsg->cmsg_level = IPPROTO_IP; cmsg->cmsg_type = IP_PKTINFO; cmsg->cmsg_len = CMSG_LEN(sizeof(*pkt)); pkt = (struct in_pktinfo *) CMSG_DATA(cmsg); // Include the padding to stop valgrind complaining about passing uninitialized data memset(pkt, 0, CMSG_SPACE(sizeof(*pkt))); pkt->ipi_spec_dst = source->sin4.sin_addr; pkt->ipi_ifindex = itfIndex; #elif defined(IP_SENDSRCADDR) struct in_addr *in; msgh->msg_control = cmsgbuf; #if !defined( __APPLE__ ) static_assert(CMSG_SPACE(sizeof(*in)) <= sizeof(*cmsgbuf), "Buffer is too small for in_addr"); #else /* __APPLE__ */ if (CMSG_SPACE(sizeof(*in)) > sizeof(*cmsgbuf)) { throw std::runtime_error("Buffer is too small for in_addr"); } #endif /* __APPLE__ */ msgh->msg_controllen = CMSG_SPACE(sizeof(*in)); cmsg = CMSG_FIRSTHDR(msgh); cmsg->cmsg_level = IPPROTO_IP; cmsg->cmsg_type = IP_SENDSRCADDR; cmsg->cmsg_len = CMSG_LEN(sizeof(*in)); // Include the padding to stop valgrind complaining about passing uninitialized data in = (struct in_addr *) CMSG_DATA(cmsg); memset(in, 0, CMSG_SPACE(sizeof(*in))); *in = source->sin4.sin_addr; #endif } } unsigned int getFilenumLimit(bool hardOrSoft) { struct rlimit rlim; if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) unixDie("Requesting number of available file descriptors"); return hardOrSoft ? rlim.rlim_max : rlim.rlim_cur; } void setFilenumLimit(unsigned int lim) { struct rlimit rlim; if(getrlimit(RLIMIT_NOFILE, &rlim) < 0) unixDie("Requesting number of available file descriptors"); rlim.rlim_cur=lim; if(setrlimit(RLIMIT_NOFILE, &rlim) < 0) unixDie("Setting number of available file descriptors"); } #define burtlemix(a,b,c) \ { \ a -= b; a -= c; a ^= (c>>13); \ b -= c; b -= a; b ^= (a<<8); \ c -= a; c -= b; c ^= (b>>13); \ a -= b; a -= c; a ^= (c>>12); \ b -= c; b -= a; b ^= (a<<16); \ c -= a; c -= b; c ^= (b>>5); \ a -= b; a -= c; a ^= (c>>3); \ b -= c; b -= a; b ^= (a<<10); \ c -= a; c -= b; c ^= (b>>15); \ } uint32_t burtle(const unsigned char* k, uint32_t length, uint32_t initval) { uint32_t a,b,c,len; /* Set up the internal state */ len = length; a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */ c = initval; /* the previous hash value */ /*---------------------------------------- handle most of the key */ while (len >= 12) { a += (k[0] +((uint32_t)k[1]<<8) +((uint32_t)k[2]<<16) +((uint32_t)k[3]<<24)); b += (k[4] +((uint32_t)k[5]<<8) +((uint32_t)k[6]<<16) +((uint32_t)k[7]<<24)); c += (k[8] +((uint32_t)k[9]<<8) +((uint32_t)k[10]<<16)+((uint32_t)k[11]<<24)); burtlemix(a,b,c); k += 12; len -= 12; } /*------------------------------------- handle the last 11 bytes */ c += length; switch(len) { /* all the case statements fall through */ case 11: c+=((uint32_t)k[10]<<24); /* fall-through */ case 10: c+=((uint32_t)k[9]<<16); /* fall-through */ case 9 : c+=((uint32_t)k[8]<<8); /* the first byte of c is reserved for the length */ /* fall-through */ case 8 : b+=((uint32_t)k[7]<<24); /* fall-through */ case 7 : b+=((uint32_t)k[6]<<16); /* fall-through */ case 6 : b+=((uint32_t)k[5]<<8); /* fall-through */ case 5 : b+=k[4]; /* fall-through */ case 4 : a+=((uint32_t)k[3]<<24); /* fall-through */ case 3 : a+=((uint32_t)k[2]<<16); /* fall-through */ case 2 : a+=((uint32_t)k[1]<<8); /* fall-through */ case 1 : a+=k[0]; /* case 0: nothing left to add */ } burtlemix(a,b,c); /*-------------------------------------------- report the result */ return c; } uint32_t burtleCI(const unsigned char* k, uint32_t length, uint32_t initval) { uint32_t a,b,c,len; /* Set up the internal state */ len = length; a = b = 0x9e3779b9; /* the golden ratio; an arbitrary value */ c = initval; /* the previous hash value */ /*---------------------------------------- handle most of the key */ while (len >= 12) { a += (dns_tolower(k[0]) +((uint32_t)dns_tolower(k[1])<<8) +((uint32_t)dns_tolower(k[2])<<16) +((uint32_t)dns_tolower(k[3])<<24)); b += (dns_tolower(k[4]) +((uint32_t)dns_tolower(k[5])<<8) +((uint32_t)dns_tolower(k[6])<<16) +((uint32_t)dns_tolower(k[7])<<24)); c += (dns_tolower(k[8]) +((uint32_t)dns_tolower(k[9])<<8) +((uint32_t)dns_tolower(k[10])<<16)+((uint32_t)dns_tolower(k[11])<<24)); burtlemix(a,b,c); k += 12; len -= 12; } /*------------------------------------- handle the last 11 bytes */ c += length; switch(len) { /* all the case statements fall through */ case 11: c+=((uint32_t)dns_tolower(k[10])<<24); /* fall-through */ case 10: c+=((uint32_t)dns_tolower(k[9])<<16); /* fall-through */ case 9 : c+=((uint32_t)dns_tolower(k[8])<<8); /* the first byte of c is reserved for the length */ /* fall-through */ case 8 : b+=((uint32_t)dns_tolower(k[7])<<24); /* fall-through */ case 7 : b+=((uint32_t)dns_tolower(k[6])<<16); /* fall-through */ case 6 : b+=((uint32_t)dns_tolower(k[5])<<8); /* fall-through */ case 5 : b+=dns_tolower(k[4]); /* fall-through */ case 4 : a+=((uint32_t)dns_tolower(k[3])<<24); /* fall-through */ case 3 : a+=((uint32_t)dns_tolower(k[2])<<16); /* fall-through */ case 2 : a+=((uint32_t)dns_tolower(k[1])<<8); /* fall-through */ case 1 : a+=dns_tolower(k[0]); /* case 0: nothing left to add */ } burtlemix(a,b,c); /*-------------------------------------------- report the result */ return c; } bool setSocketTimestamps(int fd) { #ifdef SO_TIMESTAMP int on=1; return setsockopt(fd, SOL_SOCKET, SO_TIMESTAMP, (char*)&on, sizeof(on)) == 0; #else return true; // we pretend this happened. #endif } bool setTCPNoDelay(int sock) { int flag = 1; return setsockopt(sock, /* socket affected */ IPPROTO_TCP, /* set option at TCP level */ TCP_NODELAY, /* name of option */ (char *) &flag, /* the cast is historical cruft */ sizeof(flag)) == 0; /* length of option value */ } bool setNonBlocking(int sock) { int flags=fcntl(sock,F_GETFL,0); if(flags<0 || fcntl(sock, F_SETFL,flags|O_NONBLOCK) <0) return false; return true; } bool setBlocking(int sock) { int flags=fcntl(sock,F_GETFL,0); if(flags<0 || fcntl(sock, F_SETFL,flags&(~O_NONBLOCK)) <0) return false; return true; } bool setReuseAddr(int sock) { int tmp = 1; if (setsockopt(sock, SOL_SOCKET, SO_REUSEADDR, (char*)&tmp, static_cast<unsigned>(sizeof tmp))<0) throw PDNSException(string("Setsockopt failed: ")+stringerror()); return true; } bool isNonBlocking(int sock) { int flags=fcntl(sock,F_GETFL,0); return flags & O_NONBLOCK; } bool setReceiveSocketErrors(int sock, int af) { #ifdef __linux__ int tmp = 1, ret; if (af == AF_INET) { ret = setsockopt(sock, IPPROTO_IP, IP_RECVERR, &tmp, sizeof(tmp)); } else { ret = setsockopt(sock, IPPROTO_IPV6, IPV6_RECVERR, &tmp, sizeof(tmp)); } if (ret < 0) { throw PDNSException(string("Setsockopt failed: ") + stringerror()); } #endif return true; } // Closes a socket. int closesocket( int socket ) { int ret=::close(socket); if(ret < 0 && errno == ECONNRESET) // see ticket 192, odd BSD behaviour return 0; if(ret < 0) throw PDNSException("Error closing socket: "+stringerror()); return ret; } bool setCloseOnExec(int sock) { int flags=fcntl(sock,F_GETFD,0); if(flags<0 || fcntl(sock, F_SETFD,flags|FD_CLOEXEC) <0) return false; return true; } string getMACAddress(const ComboAddress& ca) { string ret; #ifdef __linux__ ifstream ifs("/proc/net/arp"); if(!ifs) return ret; string line; string match=ca.toString()+' '; while(getline(ifs, line)) { if(boost::starts_with(line, match)) { vector<string> parts; stringtok(parts, line, " \n\t\r"); if(parts.size() < 4) return ret; unsigned int tmp[6]; if (sscanf(parts[3].c_str(), "%02x:%02x:%02x:%02x:%02x:%02x", tmp, tmp+1, tmp+2, tmp+3, tmp+4, tmp+5) != 6) { return ret; } for(unsigned int i : tmp) ret.append(1, (char)i); return ret; } } #endif return ret; } uint64_t udpErrorStats(const std::string& str) { #ifdef __linux__ ifstream ifs("/proc/net/snmp"); if(!ifs) return 0; string line; vector<string> parts; while(getline(ifs,line)) { if(boost::starts_with(line, "Udp: ") && isdigit(line[5])) { stringtok(parts, line, " \n\t\r"); if(parts.size() < 7) break; if(str=="udp-rcvbuf-errors") return std::stoull(parts[5]); else if(str=="udp-sndbuf-errors") return std::stoull(parts[6]); else if(str=="udp-noport-errors") return std::stoull(parts[2]); else if(str=="udp-in-errors") return std::stoull(parts[3]); else return 0; } } #endif return 0; } uint64_t tcpErrorStats(const std::string& str) { #ifdef __linux__ ifstream ifs("/proc/net/netstat"); if (!ifs) { return 0; } string line; vector<string> parts; while (getline(ifs,line)) { if (line.size() > 9 && boost::starts_with(line, "TcpExt: ") && isdigit(line.at(8))) { stringtok(parts, line, " \n\t\r"); if (parts.size() < 21) { break; } return std::stoull(parts.at(20)); } } #endif return 0; } uint64_t getCPUIOWait(const std::string& str) { #ifdef __linux__ ifstream ifs("/proc/stat"); if (!ifs) { return 0; } string line; vector<string> parts; while (getline(ifs, line)) { if (boost::starts_with(line, "cpu ")) { stringtok(parts, line, " \n\t\r"); if (parts.size() < 6) { break; } return std::stoull(parts[5]); } } #endif return 0; } uint64_t getCPUSteal(const std::string& str) { #ifdef __linux__ ifstream ifs("/proc/stat"); if (!ifs) { return 0; } string line; vector<string> parts; while (getline(ifs, line)) { if (boost::starts_with(line, "cpu ")) { stringtok(parts, line, " \n\t\r"); if (parts.size() < 9) { break; } return std::stoull(parts[8]); } } #endif return 0; } bool getTSIGHashEnum(const DNSName& algoName, TSIGHashEnum& algoEnum) { if (algoName == DNSName("hmac-md5.sig-alg.reg.int") || algoName == DNSName("hmac-md5")) algoEnum = TSIG_MD5; else if (algoName == DNSName("hmac-sha1")) algoEnum = TSIG_SHA1; else if (algoName == DNSName("hmac-sha224")) algoEnum = TSIG_SHA224; else if (algoName == DNSName("hmac-sha256")) algoEnum = TSIG_SHA256; else if (algoName == DNSName("hmac-sha384")) algoEnum = TSIG_SHA384; else if (algoName == DNSName("hmac-sha512")) algoEnum = TSIG_SHA512; else if (algoName == DNSName("gss-tsig")) algoEnum = TSIG_GSS; else { return false; } return true; } DNSName getTSIGAlgoName(TSIGHashEnum& algoEnum) { switch(algoEnum) { case TSIG_MD5: return DNSName("hmac-md5.sig-alg.reg.int."); case TSIG_SHA1: return DNSName("hmac-sha1."); case TSIG_SHA224: return DNSName("hmac-sha224."); case TSIG_SHA256: return DNSName("hmac-sha256."); case TSIG_SHA384: return DNSName("hmac-sha384."); case TSIG_SHA512: return DNSName("hmac-sha512."); case TSIG_GSS: return DNSName("gss-tsig."); } throw PDNSException("getTSIGAlgoName does not understand given algorithm, please fix!"); } uint64_t getOpenFileDescriptors(const std::string&) { #ifdef __linux__ DIR* dirhdl=opendir(("/proc/"+std::to_string(getpid())+"/fd/").c_str()); if(!dirhdl) return 0; struct dirent *entry; int ret=0; while((entry = readdir(dirhdl))) { uint32_t num; try { num = pdns_stou(entry->d_name); } catch (...) { continue; // was not a number. } if(std::to_string(num) == entry->d_name) ret++; } closedir(dirhdl); return ret; #else return 0; #endif } uint64_t getRealMemoryUsage(const std::string&) { #ifdef __linux__ ifstream ifs("/proc/self/statm"); if(!ifs) return 0; uint64_t size, resident, shared, text, lib, data; ifs >> size >> resident >> shared >> text >> lib >> data; // We used to use "data" here, but it proves unreliable and even is marked "broken" // in https://www.kernel.org/doc/html/latest/filesystems/proc.html return resident * getpagesize(); #else struct rusage ru; if (getrusage(RUSAGE_SELF, &ru) != 0) return 0; return ru.ru_maxrss * 1024; #endif } uint64_t getSpecialMemoryUsage(const std::string&) { #ifdef __linux__ ifstream ifs("/proc/self/smaps"); if(!ifs) return 0; string line; uint64_t bytes=0; string header("Private_Dirty:"); while(getline(ifs, line)) { if(boost::starts_with(line, header)) { bytes += std::stoull(line.substr(header.length() + 1))*1024; } } return bytes; #else return 0; #endif } uint64_t getCPUTimeUser(const std::string&) { struct rusage ru; getrusage(RUSAGE_SELF, &ru); return (ru.ru_utime.tv_sec*1000ULL + ru.ru_utime.tv_usec/1000); } uint64_t getCPUTimeSystem(const std::string&) { struct rusage ru; getrusage(RUSAGE_SELF, &ru); return (ru.ru_stime.tv_sec*1000ULL + ru.ru_stime.tv_usec/1000); } double DiffTime(const struct timespec& first, const struct timespec& second) { int seconds=second.tv_sec - first.tv_sec; int nseconds=second.tv_nsec - first.tv_nsec; if(nseconds < 0) { seconds-=1; nseconds+=1000000000; } return seconds + nseconds/1000000000.0; } double DiffTime(const struct timeval& first, const struct timeval& second) { int seconds=second.tv_sec - first.tv_sec; int useconds=second.tv_usec - first.tv_usec; if(useconds < 0) { seconds-=1; useconds+=1000000; } return seconds + useconds/1000000.0; } uid_t strToUID(const string &str) { uid_t result = 0; const char * cstr = str.c_str(); struct passwd * pwd = getpwnam(cstr); if (pwd == nullptr) { long long val; try { val = stoll(str); } catch(std::exception& e) { throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str() ); } if (val < std::numeric_limits<uid_t>::min() || val > std::numeric_limits<uid_t>::max()) { throw runtime_error((boost::format("Error: Unable to parse user ID %s") % cstr).str() ); } result = static_cast<uid_t>(val); } else { result = pwd->pw_uid; } return result; } gid_t strToGID(const string &str) { gid_t result = 0; const char * cstr = str.c_str(); struct group * grp = getgrnam(cstr); if (grp == nullptr) { long long val; try { val = stoll(str); } catch(std::exception& e) { throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str() ); } if (val < std::numeric_limits<gid_t>::min() || val > std::numeric_limits<gid_t>::max()) { throw runtime_error((boost::format("Error: Unable to parse group ID %s") % cstr).str() ); } result = static_cast<gid_t>(val); } else { result = grp->gr_gid; } return result; } unsigned int pdns_stou(const std::string& str, size_t * idx, int base) { if (str.empty()) return 0; // compatibility unsigned long result; try { result = std::stoul(str, idx, base); } catch(std::invalid_argument& e) { throw std::invalid_argument(string(e.what()) + "; (invalid argument during std::stoul); data was \""+str+"\""); } catch(std::out_of_range& e) { throw std::out_of_range(string(e.what()) + "; (out of range during std::stoul); data was \""+str+"\""); } if (result > std::numeric_limits<unsigned int>::max()) { throw std::out_of_range("stoul returned result out of unsigned int range; data was \""+str+"\""); } return static_cast<unsigned int>(result); } bool isSettingThreadCPUAffinitySupported() { #ifdef HAVE_PTHREAD_SETAFFINITY_NP return true; #else return false; #endif } int mapThreadToCPUList(pthread_t tid, const std::set<int>& cpus) { #ifdef HAVE_PTHREAD_SETAFFINITY_NP # ifdef __NetBSD__ cpuset_t *cpuset; cpuset = cpuset_create(); for (const auto cpuID : cpus) { cpuset_set(cpuID, cpuset); } return pthread_setaffinity_np(tid, cpuset_size(cpuset), cpuset); # else # ifdef __FreeBSD__ # define cpu_set_t cpuset_t # endif cpu_set_t cpuset; CPU_ZERO(&cpuset); for (const auto cpuID : cpus) { CPU_SET(cpuID, &cpuset); } return pthread_setaffinity_np(tid, sizeof(cpuset), &cpuset); # endif #else return ENOSYS; #endif /* HAVE_PTHREAD_SETAFFINITY_NP */ } std::vector<ComboAddress> getResolvers(const std::string& resolvConfPath) { std::vector<ComboAddress> results; ifstream ifs(resolvConfPath); if (!ifs) { return results; } string line; while(std::getline(ifs, line)) { boost::trim_right_if(line, boost::is_any_of(" \r\n\x1a")); boost::trim_left(line); // leading spaces, let's be nice string::size_type tpos = line.find_first_of(";#"); if (tpos != string::npos) { line.resize(tpos); } if (boost::starts_with(line, "nameserver ") || boost::starts_with(line, "nameserver\t")) { vector<string> parts; stringtok(parts, line, " \t,"); // be REALLY nice for(vector<string>::const_iterator iter = parts.begin() + 1; iter != parts.end(); ++iter) { try { results.emplace_back(*iter, 53); } catch(...) { } } } } return results; } size_t getPipeBufferSize(int fd) { #ifdef F_GETPIPE_SZ int res = fcntl(fd, F_GETPIPE_SZ); if (res == -1) { return 0; } return res; #else errno = ENOSYS; return 0; #endif /* F_GETPIPE_SZ */ } bool setPipeBufferSize(int fd, size_t size) { #ifdef F_SETPIPE_SZ if (size > static_cast<size_t>(std::numeric_limits<int>::max())) { errno = EINVAL; return false; } int newSize = static_cast<int>(size); int res = fcntl(fd, F_SETPIPE_SZ, newSize); if (res == -1) { return false; } return true; #else errno = ENOSYS; return false; #endif /* F_SETPIPE_SZ */ } DNSName reverseNameFromIP(const ComboAddress& ip) { if (ip.isIPv4()) { std::string result("in-addr.arpa."); auto ptr = reinterpret_cast<const uint8_t*>(&ip.sin4.sin_addr.s_addr); for (size_t idx = 0; idx < sizeof(ip.sin4.sin_addr.s_addr); idx++) { result = std::to_string(ptr[idx]) + "." + result; } return DNSName(result); } else if (ip.isIPv6()) { std::string result("ip6.arpa."); auto ptr = reinterpret_cast<const uint8_t*>(&ip.sin6.sin6_addr.s6_addr[0]); for (size_t idx = 0; idx < sizeof(ip.sin6.sin6_addr.s6_addr); idx++) { std::stringstream stream; stream << std::hex << (ptr[idx] & 0x0F); stream << '.'; stream << std::hex << (((ptr[idx]) >> 4) & 0x0F); stream << '.'; result = stream.str() + result; } return DNSName(result); } throw std::runtime_error("Calling reverseNameFromIP() for an address which is neither an IPv4 nor an IPv6"); } static size_t getMaxHostNameSize() { #if defined(HOST_NAME_MAX) return HOST_NAME_MAX; #endif #if defined(_SC_HOST_NAME_MAX) auto tmp = sysconf(_SC_HOST_NAME_MAX); if (tmp != -1) { return tmp; } #endif /* _POSIX_HOST_NAME_MAX */ return 255; } std::string getCarbonHostName() { std::string hostname; hostname.resize(getMaxHostNameSize() + 1, 0); if (gethostname(const_cast<char*>(hostname.c_str()), hostname.size()) != 0) { throw std::runtime_error(stringerror()); } boost::replace_all(hostname, ".", "_"); hostname.resize(strlen(hostname.c_str())); return hostname; } std::string makeLuaString(const std::string& in) { ostringstream str; str<<'"'; char item[5]; for (unsigned char n : in) { if (islower(n) || isupper(n)) { item[0] = n; item[1] = 0; } else { snprintf(item, sizeof(item), "\\%03d", n); } str << item; } str<<'"'; return str.str(); } size_t parseSVCBValueList(const std::string &in, vector<std::string> &val) { std::string parsed; auto ret = parseRFC1035CharString(in, parsed); parseSVCBValueListFromParsedRFC1035CharString(parsed, val); return ret; }; #ifdef HAVE_CRYPTO_MEMCMP #include <openssl/crypto.h> #else /* HAVE_CRYPTO_MEMCMP */ #ifdef HAVE_SODIUM_MEMCMP #include <sodium.h> #endif /* HAVE_SODIUM_MEMCMP */ #endif /* HAVE_CRYPTO_MEMCMP */ bool constantTimeStringEquals(const std::string& a, const std::string& b) { if (a.size() != b.size()) { return false; } const size_t size = a.size(); #ifdef HAVE_CRYPTO_MEMCMP return CRYPTO_memcmp(a.c_str(), b.c_str(), size) == 0; #else /* HAVE_CRYPTO_MEMCMP */ #ifdef HAVE_SODIUM_MEMCMP return sodium_memcmp(a.c_str(), b.c_str(), size) == 0; #else /* HAVE_SODIUM_MEMCMP */ const volatile unsigned char *_a = (const volatile unsigned char *) a.c_str(); const volatile unsigned char *_b = (const volatile unsigned char *) b.c_str(); unsigned char res = 0; for (size_t idx = 0; idx < size; idx++) { res |= _a[idx] ^ _b[idx]; } return res == 0; #endif /* !HAVE_SODIUM_MEMCMP */ #endif /* !HAVE_CRYPTO_MEMCMP */ }
shinsterneck/pdns
pdns/misc.cc
C++
gpl-2.0
41,490
//New options : //cheking the use of camel case // camelcase : true || false //checking for useless quote // unquote : true || false //checking dojo internal rules // dojo : true || false //Cheking the quote consistancy // quote: "no" || "single" || "double" //Force setters and getter to have this.inherited. Work only if dojo = true // dojo_inheritedgetset: true || false //For the pair getter/setter. Work only if dojo = true // dojo_getset : true || false //Check if function are commented (according to dojo standards). Work only if dojo = true // dojo_comments: true || false //For use of absolute path in require/define // dojo_define_force_absolute: true || false //Force function in class to be anonymous // anonymousFunctions: true || false //Prevent String duplication // preventStringDuplication: true || false || <number of ducplucation allowed> //Support for deprecated files, add <old filename>:<new filename> to the object dojo.deprecated //search for "deprecated" var OPTIONS = { "ass": true, "browser": true, "continue": true, "devel": true, "indent": 100, "maxerr": 100000, "nomen": true, "plusplus": true, "regexp": true, "sloppy": true, "todo": true, "undef": false, "unparam": false, "white": false, "windows": true, "dojo": true, "dojo_comments": true, "unquote": true, "camelcase": true, "quote": "single", "dojo_inheritedgetset": false, "dojo_getset": false, "dojo_define_force_absolute": true, "anonymousFunctions": true, "preventStringDuplication": false, "camelcase_deviations": {"gpm_eventname": true}, "predef": [ "CKEDITOR","define","escape","Highcharts","Raphael","require","console", 'clearInterval', 'clearTimeout', 'document', 'event', 'FormData', 'frames', 'history', 'Image', 'localStorage', 'location', 'name', 'navigator', 'Option', 'parent', 'screen', 'sessionStorage', 'setInterval', 'setTimeout', 'Storage', 'window', 'XMLHttpRequest' ], "mustInherits": [ "onOrganisationChange" ], "customRules": function(id, token, line) { var idep; var custom = { deprecated:{ 'ing/ui/_StubsMixin': 'ing/manager/stub', 'ing/ui/behavior/Tooltip': 'ing/ui/_TooltipMixin', 'ingx/ui/contextmenu/IconContextMenu': 'ing/ui/business/ExportMenu', 'ingx/ui/scrollabletable/JITLoader': 'ing/ui/scrollabletable/JITLoader', 'dojo/on': 'ing/core/on', 'handlers/common/settings/Settings': 'ing/core/include!json|handlers/common/settings/getSettings.do', 'webcomponent/itrf/selection/list/util/Normalisation': 'ing/core/string', 'ing/ui/form/ContextSensitiveHelp': 'ing/ui/ContextSensitiveHelp' }, deprecatedCode: { } }; if(id && token.line > 0 && /'itrf\//.test(line) && !/'itrf\/selection/.test(line) && !/'itrf\/widget\/starlite/.test(line)) { token.warn('i_itrf'); } if(id && token.line > 0 && /'itrf\/selection/.test(line) && !/'itrf\/selection\/config/.test(line)) { token.warn('i_selection'); } if(id && token.line > 0) { for(idep in custom.deprecated) { if(line.indexOf('\''+idep) !== -1 || line.indexOf('"'+idep) !== -1) { token.warn('i_deprecated', idep, custom.deprecated[idep]); } } } if(line && token.line > 0) { for(idep in custom.deprecatedCode) { if(line.indexOf(idep) !== -1) { token.warn('i_deprecated', idep, custom.deprecatedCode[idep]); } } } } }; // jslint.js // 2014-07-08 // Copyright (c) 2002 Douglas Crockford (www.JSLint.com) // 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 shall be used for Good, not Evil. // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // WARNING: JSLint will hurt your feelings. // JSLINT is a global function. It takes two parameters. // var myResult = JSLINT(source, option); // The first parameter is either a string or an array of strings. If it is a // string, it will be split on '\n' or '\r'. If it is an array of strings, it // is assumed that each string represents one line. The source can be a // JavaScript text or a JSON text. // The second parameter is an optional object of options that control the // operation of JSLINT. Most of the options are booleans: They are all // optional and have a default value of false. One of the options, predef, // can be an array of names, which will be used to declare global variables, // or an object whose keys are used as global names, with a boolean value // that determines if they are assignable. // If it checks out, JSLINT returns true. Otherwise, it returns false. // If false, you can inspect JSLINT.errors to find out the problems. // JSLINT.errors is an array of objects containing these properties: // { // line : The line (relative to 0) at which the lint was found // character : The character (relative to 0) at which the lint was found // reason : The problem // evidence : The text line in which the problem occurred // raw : The raw message before the details were inserted // a : The first detail // b : The second detail // c : The third detail // d : The fourth detail // } // If a stopping error was found, a null will be the last element of the // JSLINT.errors array. A stopping error means that JSLint was not confident // enough to continue. It does not necessarily mean that the error was // especially heinous. // You can request a data structure that contains JSLint's results. // var myData = JSLINT.data(); // It returns a structure with this form: // { // errors: [ // { // line: NUMBER, // character: NUMBER, // reason: STRING, // evidence: STRING // } // ], // functions: [ // { // name: STRING, // line: NUMBER, // level: NUMBER, // parameter: [ // STRING // ], // var: [ // STRING // ], // exception: [ // STRING // ], // closure: [ // STRING // ], // outer: [ // STRING // ], // global: [ // STRING // ], // label: [ // STRING // ] // } // ], // global: [ // STRING // ], // member: { // STRING: NUMBER // }, // json: BOOLEAN // } // You can request a Function Report, which shows all of the functions // and the parameters and vars that they use. This can be used to find // implied global variables and other problems. The report is in HTML and // can be inserted into an HTML <body>. It should be given the result of the // JSLINT.data function. // var myReport = JSLINT.report(data); // You can request an HTML error report. // var myErrorReport = JSLINT.error_report(data); // You can obtain an object containing all of the properties found in the // file. JSLINT.property contains an object containing a key for each // property used in the program, the value being the number of times that // property name was used in the file. // You can request a properties report, which produces a list of the program's // properties in the form of a /*properties*/ declaration. // var myPropertyReport = JSLINT.properties_report(JSLINT.property); // You can obtain the parse tree that JSLint constructed while parsing. The // latest tree is kept in JSLINT.tree. A nice stringification can be produced // with // JSON.stringify(JSLINT.tree, [ // 'string', 'arity', 'name', 'first', // 'second', 'third', 'block', 'else' // ], 4)); // You can request a context coloring table. It contains information that can be // applied to the file that was analyzed. Context coloring colors functions // based on their nesting level, and variables on the color of the functions // in which they are defined. // var myColorization = JSLINT.color(data); // It returns an array containing objects of this form: // { // from: COLUMN, // thru: COLUMN, // line: ROW, // level: 0 or higher // } // JSLint provides three inline directives. They look like slashstar comments, // and allow for setting options, declaring global variables, and establishing a // set of allowed property names. // These directives respect function scope. // The jslint directive is a special comment that can set one or more options. // For example: /*jslint evil: true, nomen: true, regexp: true, todo: true */ // The current option set is // ass true, if assignment expressions should be allowed // bitwise true, if bitwise operators should be allowed // browser true, if the standard browser globals should be predefined // closure true, if Google Closure idioms should be tolerated // continue true, if the continuation statement should be tolerated // debug true, if debugger statements should be allowed // devel true, if logging should be allowed (console, alert, etc.) // eqeq true, if == should be allowed // evil true, if eval should be allowed // forin true, if for in statements need not filter // indent the indentation factor // maxerr the maximum number of errors to allow // maxlen the maximum length of a source line // newcap true, if constructor names capitalization is ignored // node true, if Node.js globals should be predefined // nomen true, if names may have dangling _ // passfail true, if the scan should stop on first error // plusplus true, if increment/decrement should be allowed // properties true, if all property names must be declared with /*properties*/ // regexp true, if the . should be allowed in regexp literals // rhino true, if the Rhino environment globals should be predefined // unparam true, if unused parameters should be tolerated // sloppy true, if the 'use strict'; pragma is optional // stupid true, if really stupid practices are tolerated // sub true, if all forms of subscript notation are tolerated // todo true, if TODO comments are tolerated // vars true, if multiple var statements per function should be allowed // white true, if sloppy whitespace is tolerated // The properties directive declares an exclusive list of property names. // Any properties named in the program that are not in the list will // produce a warning. // For example: /*properties '\b', '\t', '\n', '\f', '\r', '!', '!=', '!==', '"', '%', '\'', '(begin)', '(error)', '*', '+', '-', '/', '<', '<=', '==', '===', '>', '>=', '\\', a, a_label, a_scope, already_defined, and, apply, arguments, arity, ass, assign, assignment_expression, assignment_function_expression, at, avoid_a, b, bad_assignment, bad_constructor, bad_in_a, bad_invocation, bad_new, bad_number, bad_operand, bad_wrap, bitwise, block, break, breakage, browser, c, call, charAt, charCodeAt, character, closure, code, color, combine_var, comments, conditional_assignment, confusing_a, confusing_regexp, constructor_name_a, continue, control_a, couch, create, d, dangling_a, data, dead, debug, deleted, devel, disrupt, duplicate_a, edge, edition, elif, else, empty_block, empty_case, empty_class, entityify, eqeq, error_report, errors, evidence, evil, exception, exec, expected_a_at_b_c, expected_a_b, expected_a_b_from_c_d, expected_id_a, expected_identifier_a, expected_identifier_a_reserved, expected_number_a, expected_operator_a, expected_positive_a, expected_small_a, expected_space_a_b, expected_string_a, f, first, flag, floor, forEach, for_if, forin, from, fromCharCode, fud, function, function_block, function_eval, function_loop, function_statement, function_strict, functions, global, hasOwnProperty, id, identifier, identifier_function, immed, implied_evil, indent, indexOf, infix_in, init, insecure_a, isAlpha, isArray, isDigit, isNaN, join, jslint, json, keys, kind, label, labeled, lbp, leading_decimal_a, led, left, length, level, line, loopage, master, match, maxerr, maxlen, message, missing_a, missing_a_after_b, missing_property, missing_space_a_b, missing_use_strict, mode, move_invocation, move_var, n, name, name_function, nested_comment, newcap, node, nomen, not, not_a_constructor, not_a_defined, not_a_function, not_a_label, not_a_scope, not_greater, nud, number, octal_a, open, outer, parameter, parameter_a_get_b, parameter_arguments_a, parameter_set_a, params, paren, passfail, plusplus, pop, postscript, predef, properties, properties_report, property, prototype, push, quote, r, radix, raw, read_only, reason, redefinition_a_b, regexp, relation, replace, report, reserved, reserved_a, rhino, right, scanned_a_b, scope, search, second, shift, slash_equal, slice, sloppy, sort, split, statement, statement_block, stop, stopping, strange_loop, strict, string, stupid, sub, subscript, substr, supplant, sync_a, t, tag_a_in_b, test, third, thru, toString, todo, todo_comment, token, tokens, too_long, too_many, trailing_decimal_a, tree, unclosed, unclosed_comment, unclosed_regexp, unescaped_a, unexpected_a, unexpected_char_a, unexpected_comment, unexpected_label_a, unexpected_property_a, unexpected_space_a_b, unexpected_typeof_a, uninitialized_a, unnecessary_else, unnecessary_initialize, unnecessary_use, unparam, unreachable_a_b, unsafe, unused_a, url, use_array, use_braces, use_nested_if, use_object, use_or, use_param, use_spaces, used, used_before_a, var, var_a_not, var_loop, vars, varstatement, warn, warning, was, weird_assignment, weird_condition, weird_new, weird_program, weird_relation, weird_ternary, white, wrap, wrap_immediate, wrap_regexp, write_is_wrong, writeable */ // The global directive is used to declare global variables that can // be accessed by the program. If a declaration is true, then the variable // is writeable. Otherwise, it is read-only. // We build the application inside a function so that we produce only a single // global variable. That function will be invoked immediately, and its return // value is the JSLINT function itself. That function is also an object that // can contain data and other functions. var JSLINT = (function () { 'use strict'; function array_to_object(array, value) { // Make an object from an array of keys and a common value. var i, length = array.length, object = Object.create(null); for (i = 0; i < length; i += 1) { object[array[i]] = value; } return object; } var allowed_option = { ass : true, bitwise : true, browser : true, closure : true, continue : true, couch : true, debug : true, devel : true, eqeq : true, evil : true, forin : true, indent : 10, maxerr : 1000, maxlen : 256, newcap : true, node : true, nomen : true, passfail : true, plusplus : true, properties: true, regexp : true, rhino : true, unparam : true, sloppy : true, stupid : true, sub : true, todo : true, vars : true, white : true }, anonname, // The guessed name for anonymous functions. // These are operators that should not be used with the ! operator. bang = { '<' : true, '<=' : true, '==' : true, '===': true, '!==': true, '!=' : true, '>' : true, '>=' : true, '+' : true, '-' : true, '*' : true, '/' : true, '%' : true }, begin, // The root token block_var, // vars defined in the current block // browser contains a set of global names that are commonly provided by a // web browser environment. browser = array_to_object([ 'clearInterval', 'clearTimeout', 'document', 'event', 'FormData', 'frames', 'history', 'Image', 'localStorage', 'location', 'name', 'navigator', 'Option', 'parent', 'screen', 'sessionStorage', 'setInterval', 'setTimeout', 'Storage', 'window', 'XMLHttpRequest' ], false), // bundle contains the text messages. reservedPropertyName = {}, dojo = { deprecated: { 'dojo/_base/json': 'dojo/json', 'dojo/DeferredList': 'dojo/promise/all' }, deprecatedCode: { 'this._connects': 'this.own()', 'this._supportingWidgets': 'this.own()', 'isArray': 'myVar instanceof Array' }, lifecycle:["constructor", "create", "postscript", "buildRendering", "postCreate", "startup", "postMixInProperties", "destroy", "destroyRecursive", "destroyRendering"], mustInherits:["buildRendering", "postCreate", "startup", "postMixInProperties", "destroy", "destroyRendering"], neverInherits:["constructor"], mustTestStarted:["startup"], dojoProtected:["getChildren", 'buildRendering', 'create', '_onFocus', '_onBlur', 'unsubscribe', 'subscribe', 'connect', "destroyRendering"], mustcheckargs:["_fillContent"], isInDefine: false }, bundle = { a_label: "'{a}' is a statement label.", a_scope: "'{a}' used out of scope.", already_defined: "'{a}' is already defined.", and: "The '&&' subexpression should be wrapped in parens.", assignment_expression: "Unexpected assignment expression.", assignment_function_expression: "Expected an assignment or " + "function call and instead saw an expression.", avoid_a: "Avoid '{a}'.", bad_assignment: "Bad assignment.", bad_constructor: "Bad constructor.", bad_in_a: "Bad for in variable '{a}'.", bad_invocation: "Bad invocation.", bad_new: "Do not use 'new' for side effects.", bad_number: "Bad number '{a}'.", bad_operand: "Bad operand.", bad_wrap: "Do not wrap function literals in parens unless they " + "are to be immediately invoked.", combine_var: "Combine this with the previous 'var' statement.", conditional_assignment: "Expected a conditional expression and " + "instead saw an assignment.", confusing_a: "Confusing use of '{a}'.", confusing_regexp: "Confusing regular expression.", constructor_name_a: "A constructor name '{a}' should start with " + "an uppercase letter.", control_a: "Unexpected control character '{a}'.", dangling_a: "Unexpected dangling '_' in '{a}'.", deleted: "Only properties should be deleted.", duplicate_a: "Duplicate '{a}'.", empty_block: "Empty block.", empty_case: "Empty case.", empty_class: "Empty class.", evil: "eval is evil.", expected_a_b: "Expected '{a}' and instead saw '{b}'.", expected_a_b_from_c_d: "Expected '{a}' to match '{b}' from line " + "{c} and instead saw '{d}'.", expected_a_at_b_c: "Expected '{a}' at column {b}, not column {c}.", expected_id_a: "Expected an id, and instead saw #{a}.", expected_identifier_a: "Expected an identifier and instead saw '{a}'.", expected_identifier_a_reserved: "Expected an identifier and " + "instead saw '{a}' (a reserved word).", expected_number_a: "Expected a number and instead saw '{a}'.", expected_operator_a: "Expected an operator and instead saw '{a}'.", expected_positive_a: "Expected a positive number and instead saw '{a}'", expected_small_a: "Expected a small positive integer and instead saw '{a}'", expected_space_a_b: "Expected exactly one space between '{a}' and '{b}'.", expected_string_a: "Expected a string and instead saw '{a}'.", for_if: "The body of a for in should be wrapped in an if " + "statement to filter unwanted properties from the prototype.", function_block: "Function statements should not be placed in blocks." + "Use a function expression or move the statement to the top of " + "the outer function.", function_eval: "The Function constructor is eval.", function_loop: "Don't make functions within a loop.", function_statement: "Function statements are not invocable. " + "Wrap the whole function invocation in parens.", function_strict: "Use the function form of 'use strict'.", identifier_function: "Expected an identifier in an assignment " + "and instead saw a function invocation.", implied_evil: "Implied eval is evil. Pass a function instead of a string.", infix_in: "Unexpected 'in'. Compare with undefined, or use the " + "hasOwnProperty method instead.", insecure_a: "Insecure '{a}'.", isNaN: "Use the isNaN function to compare with NaN.", leading_decimal_a: "A leading decimal point can be confused with a dot: '.{a}'.", missing_a: "Missing '{a}'.", missing_a_after_b: "Missing '{a}' after '{b}'.", missing_property: "Missing property name.", missing_space_a_b: "Missing space between '{a}' and '{b}'.", missing_use_strict: "Missing 'use strict' statement.", move_invocation: "Move the invocation into the parens that " + "contain the function.", move_var: "Move 'var' declarations to the top of the function.", name_function: "Missing name in function statement.", nested_comment: "Nested comment.", not: "Nested not.", not_a_constructor: "Do not use {a} as a constructor.", not_a_defined: "'{a}' has not been fully defined yet.", not_a_function: "'{a}' is not a function.", not_a_label: "'{a}' is not a label.", not_a_scope: "'{a}' is out of scope.", not_greater: "'{a}' should not be greater than '{b}'.", octal_a: "Don't use octal: '{a}'. Use '\\u....' instead.", parameter_arguments_a: "Do not mutate parameter '{a}' when using 'arguments'.", parameter_a_get_b: "Unexpected parameter '{a}' in get {b} function.", parameter_set_a: "Expected parameter (value) in set {a} function.", radix: "Missing radix parameter.", read_only: "Read only.", redefinition_a_b: "Redefinition of '{a}' from line {b}.", reserved_a: "Reserved name '{a}'.", scanned_a_b: "{a} ({b}% scanned).", slash_equal: "A regular expression literal can be confused with '/='.", statement_block: "Expected to see a statement and instead saw a block.", stopping: "Stopping.", strange_loop: "Strange loop.", strict: "Strict violation.", subscript: "['{a}'] is better written in dot notation.", sync_a: "Unexpected sync method: '{a}'.", tag_a_in_b: "A '<{a}>' must be within '<{b}>'.", todo_comment: "Unexpected TODO comment.", too_long: "Line too long.", too_many: "Too many errors.", trailing_decimal_a: "A trailing decimal point can be confused " + "with a dot: '.{a}'.", unclosed: "Unclosed string.", unclosed_comment: "Unclosed comment.", unclosed_regexp: "Unclosed regular expression.", unescaped_a: "Unescaped '{a}'.", unexpected_a: "Unexpected '{a}'.", unexpected_char_a: "Unexpected character '{a}'.", unexpected_comment: "Unexpected comment.", unexpected_label_a: "Unexpected label '{a}'.", unexpected_property_a: "Unexpected /*property*/ '{a}'.", unexpected_space_a_b: "Unexpected space between '{a}' and '{b}'.", unexpected_typeof_a: "Unexpected 'typeof'. " + "Use '===' to compare directly with {a}.", uninitialized_a: "Uninitialized '{a}'.", unnecessary_else: "Unnecessary 'else' after disruption.", unnecessary_initialize: "It is not necessary to initialize '{a}' " + "to 'undefined'.", unnecessary_use: "Unnecessary 'use strict'.", unreachable_a_b: "Unreachable '{a}' after '{b}'.", unsafe: "Unsafe character.", unused_a: "Unused '{a}'.", url: "JavaScript URL.", use_array: "Use the array literal notation [].", use_braces: "Spaces are hard to count. Use {{a}}.", use_nested_if: "Expected 'else { if' and instead saw 'else if'.", use_object: "Use the object literal notation {} or Object.create(null).", use_or: "Use the || operator.", use_param: "Use a named parameter.", use_spaces: "Use spaces, not tabs.", mixed_tab: "Mixed tabs and spaces, use only tabs", illegal_private_call: "Illegal call to the private '{a}' function/property", illegal_attach_point_call: "Illegal call to the protected '{a}' attach point", use_dummy: "'{a}' is defined but not used. Add 'dummy' in the name to avoid this warning", use_camel_case: "'{a}' is not CamelCase", remove_quote: "please remove useless quotes", braket_notation: "{a} must be written using braket notation. (a reserved word)", use_single_quote: "Mixed double/single quote. Please use only single quote", use_double_quote: "Mixed double/single quote. Please use only double quote", maybe_illegal_private_call: "Expected '{a}'. Maybe an illegal call to a private function/property", maybe_illegal_attach_point_call: "Expected '{a}'. Maybe an illegal call to a protected attach point", defined_and_not_used: "'{a}' is defined but not used.", do_not_use_dummy: "'{a}' is named as dummy but is in use. Please remove dummy.", i_do_not_copy_context: "you are trying to copy the context, please use lang.hitch instead", use_context_with_query: "query is used without context", missing_inherited: "the function {a} must contain this.inherited(arguments)", no_inherited: "the function {a} must never use this.inherited(arguments)", missing_started_test: "the function {a} must test if this._started is true", should_use_inherited: "the function {a} should use this.inherited(arguments)", expect_no_arg: "getters can't have any arguments, maybe you should rename your function byXXX (like byId, byNode, ...)", expect_one_arg: "setters must have only one argument", expect_arg_named_as_setter: "The arguments '{a}' should be renamed '{b}'", must_return: "the function {a} must return a value", declare_on_one_line: "declare() must be on one signle line", cc_code: "Do not use comments starting by '//" + "@'. This can raise JS error on IE due to Conditional Compilation (http://en.wikipedia.org/wiki/Conditional_comment#Conditional_comments_in_JScript)", dojo_protected_name: "Take care, this function is part of Dojo, please be sure overriding it is not a mistake", dojo_test_arguments: "Argument(s) '{a}' should be checked in an if before using them/it in {b}", i_jslint_version: "version '{a}'", duplicated_string: "The string is duplicated, please use a constant", get_or_set_is_missing: "the setters and getters must all be defined, the corresponding one is missing for this function", hitch_loop: "hitch/partial should not be used in a loop.", i_jslint_global: "This line is deprecated, please remove it", i_itrf: "DojoCommonLibrary is deprecated. Please upgrade to DojoCommon.", i_selection: "SelectionTypes is deprecated. Please upgrade to DojoCommon ing/ui/form/*.", i_deprecated: "'{a}' is deprecated. Please upgrade to '{b}'", i_uncommented_function: "Functions should have comments (At least: line 1: '//<space>summary:', line 2: '//<tab><tab><explanation>')", i_uncommented_package: "Packages should have comments (At least: line 1: '//<space>summary:', line 2: '//<tab><tab><explanation>')", only_inherited: "Functions with only this.inherited() should be deleted", function_anonymous: "Functions must be anonymous", has_classname: "declare() should not have classname specified", use_absolute: "do not use relative path for class", used_before_a: "'{a}' was used before it was defined.", var_a_not: "Variable {a} was not declared correctly.", var_loop: "Don't declare variables in a loop.", weird_assignment: "Weird assignment.", weird_condition: "Weird condition.", weird_new: "Weird construction. Delete 'new'.", weird_program: "Weird program.", weird_relation: "Weird relation.", weird_ternary: "Weird ternary.", wrap_immediate: "Wrap an immediate function invocation in " + "parentheses to assist the reader in understanding that the " + "expression is the result of a function, and not the " + "function itself.", wrap_regexp: "Wrap the /regexp/ literal in parens to " + "disambiguate the slash operator.", write_is_wrong: "document.write can be a form of eval." }, closure = array_to_object([ 'goog' ], false), comments, comments_off, couch = array_to_object([ 'emit', 'getRow', 'isArray', 'log', 'provides', 'registerType', 'require', 'send', 'start', 'sum', 'toJSON' ], false), descapes = { 'b': '\b', 't': '\t', 'n': '\n', 'f': '\f', 'r': '\r', '"': '"', '/': '/', '\\': '\\', '!': '!' }, devel = array_to_object([ 'alert', 'confirm', 'console', 'Debug', 'opera', 'prompt', 'WSH' ], false), directive, escapes = { '\b': '\\b', '\t': '\\t', '\n': '\\n', '\f': '\\f', '\r': '\\r', '\'': '\\\'', '"' : '\\"', '/' : '\\/', '\\': '\\\\' }, funct, // The current function functions, // All of the functions global_funct, // The global body global_scope, // The global scope in_block, // Where function statements are not allowed indent, itself, // JSLINT itself json_mode, lex, // the tokenizer lines, lookahead, node = array_to_object([ 'Buffer', 'clearImmediate', 'clearInterval', 'clearTimeout', 'console', 'exports', 'global', 'module', 'process', 'require', 'setImmediate', 'setInterval', 'setTimeout', '__dirname', '__filename' ], false), node_js, numbery = array_to_object(['indexOf', 'lastIndexOf', 'search'], true), next_token, option, predefined, // Global variables defined by option prereg, prev_token, property, protosymbol, regexp_flag = array_to_object(['g', 'i', 'm'], true), return_this = function return_this() { return this; }, rhino = array_to_object([ 'defineClass', 'deserialize', 'gc', 'help', 'load', 'loadClass', 'print', 'quit', 'readFile', 'readUrl', 'runCommand', 'seal', 'serialize', 'spawn', 'sync', 'toint32', 'version' ], false), scope, // An object containing an object for each variable in scope semicolon_coda = array_to_object([';', '"', '\'', ')'], true), // standard contains the global names that are provided by the // ECMAScript standard. standard = array_to_object([ 'Array', 'Boolean', 'Date', 'decodeURI', 'decodeURIComponent', 'encodeURI', 'encodeURIComponent', 'Error', 'eval', 'EvalError', 'Function', 'isFinite', 'isNaN', 'JSON', 'Map', 'Math', 'Number', 'Object', 'parseInt', 'parseFloat', 'Promise', 'Proxy', 'RangeError', 'ReferenceError', 'Reflect', 'RegExp', 'Set', 'String', 'Symbol', 'SyntaxError', 'System', 'TypeError', 'URIError', 'WeakMap', 'WeakSet' ], false), strict_mode, syntax = Object.create(null), token, tokens, var_mode, warnings, // Regular expressions. Some of these are stupidly long. // carriage return, carriage return linefeed, or linefeed crlfx = /\r\n?|\n/, // unsafe characters that are silently deleted by one or more browsers cx = /[\u0000-\u0008\u000a-\u001f\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/, // identifier ix = /^([a-zA-Z_$][a-zA-Z0-9_$]*)$/, // javascript url jx = /^(?:javascript|jscript|ecmascript|vbscript)\s*:/i, // star slash lx = /\*\/|\/\*/, // characters in strings that need escapement nx = /[\u0000-\u001f'\\\u007f-\u009f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g, // sync syx = /Sync$/, // comment todo tox = /^\W*to\s*do(?:\W|$)/i, // token tx = /^\s*([(){}\[\]\?.,:;'"~#@`]|={1,3}|\/(\*(jslint|properties|property|members?|globals?)?|=|\/)?|\*[\/=]?|\+(?:=|\++)?|-(?:=|-+)?|[\^%]=?|&[&=]?|\|[|=]?|>{1,3}=?|<(?:[\/=!]|\!(\[|--)?|<=?)?|\!(\!|==?)?|[a-zA-Z_$][a-zA-Z0-9_$]*|[0-9]+(?:[xX][0-9a-fA-F]+|\.[0-9]*)?(?:[eE][+\-]?[0-9]+)?)/; if (typeof String.prototype.entityify !== 'function') { String.prototype.entityify = function () { return this .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;'); }; } if (typeof String.prototype.isAlpha !== 'function') { String.prototype.isAlpha = function () { return (this >= 'a' && this <= 'z\uffff') || (this >= 'A' && this <= 'Z\uffff'); }; } if (typeof String.prototype.isDigit !== 'function') { String.prototype.isDigit = function () { return (this >= '0' && this <= '9'); }; } if (typeof String.prototype.supplant !== 'function') { String.prototype.supplant = function (o) { return this.replace(/\{([^{}]*)\}/g, function (a, b) { var replacement = o[b]; return typeof replacement === 'string' || typeof replacement === 'number' ? replacement : a; }); }; } function sanitize(a) { // Escapify a troublesome character. return escapes[a] || '\\u' + ('0000' + a.charCodeAt().toString(16)).slice(-4); } function add_to_predefined(group) { Object.keys(group).forEach(function (name) { predefined[name] = group[name]; }); } function assume() { if (option.browser) { add_to_predefined(browser); option.browser = false; } if (option.closure) { add_to_predefined(closure); } if (option.couch) { add_to_predefined(couch); option.couch = false; } if (option.devel) { add_to_predefined(devel); option.devel = false; } if (option.node) { add_to_predefined(node); option.node = false; node_js = true; } if (option.rhino) { add_to_predefined(rhino); option.rhino = false; } if (!option.dojo_getset) { option.dojo_getset = false; } if (!option.dojo_define_force_absolute) { option.dojo_define_force_absolute = false; } if (!option.dojo_inheritedgetset) { option.dojo_inheritedgetset = false; } if (option.camelcase === undefined) { option.camelcase = true; } if (option.unquote === undefined) { option.unquote = true; } if (option.anonymousFunctions === undefined) { option.anonymousFunctions = true; } if (option.preventStringDuplication === undefined) { option.preventStringDuplication = true; } if (option.dojo_comments === undefined) { option.dojo_comments = true; } if (option.dojo === undefined) { option.dojo = true; } if (!option.quote) { option.quote = "single"; } if (!option.camelcase_deviations) { option.camelcase_deviations = {}; } } // Produce an error warning. function artifact(tok) { if (!tok) { tok = next_token; } return tok.id === '(number)' ? tok.number : tok.string; } function quit(message, line, character) { throw { name: 'JSLintError', line: line, character: character, message: bundle.scanned_a_b.supplant({ a: bundle[message] || message, b: Math.floor((line / lines.length) * 100) }) }; } function foundBundleName(msg) { var i; for(i in bundle) { if(bundle.hasOwnProperty(i)) { if(bundle[i] === msg) { return i; } } } return msg; } function warn(code, line, character, a, b, c, d) { var strLine, ignore, s = 'jslintignore:'; strLine = lines[line - 1]; if(!bundle[code]) { code = foundBundleName(code); } if(strLine) { strLine = strLine.replace(/\s/g, '').toLowerCase(); //no space, all lower //seach for JSLint ignore: xxx, yyy (converted to lower with no space) ignore = strLine.indexOf(s); if (ignore !== -1) { strLine = ',' + strLine.substr(ignore + s.length) + ','; if(strLine.indexOf(',' + code.toLowerCase() + ',') !== -1) { //the code is in ignore list, so return... return null; } } } var raw = bundle[code] + (code.indexOf('i_') === 0 ? '' : ' [code: ' + code + ']'); var warning = { // ~~ id: '(error)', // raw: bundle[code] || code, raw: raw || code, code: code, evidence: lines[line - 1] || '', line: line, character: character, a: a || artifact(this), b: b, c: c, d: d }; warning.reason = warning.raw.supplant(warning); itself.errors.push(warning); //if (option.passfail) { //quit('stopping', line, character); //} warnings += 1; //if (warnings >= option.maxerr) { //quit('too_many', line, character); //} return warning; } function stop(code, line, character, a, b, c, d) { var warning = warn(code, line, character, a, b, c, d); quit('stopping', warning.line, warning.character); return warning; } function expected_at(at) { if (!option.white && next_token.from !== at) { next_token.warn('expected_a_at_b_c', '', at, next_token.from); } } // lexical analysis and token construction lex = (function lex() { var character, c, from, length, line, pos, source_row; // Private lex methods function next_line() { var at; character = 1; source_row = lines[line]; line += 1; if (source_row === undefined) { return false; } //at = source_row.search(/\t/); at = source_row.search(/( )|(\t )|( \t)/); if (at >= 0) { //if (option.white) { //source_row = source_row.replace(/\t/g, ' '); //} else { //warn('use_spaces', line, at + 1); warn('mixed_tab', line, at + 1); //} } at = source_row.search(/\/\/@/); if (at >= 0) { warn('cc_code', line, at + 1); } source_row = source_row.replace(/\t/g, Array(+option.indent).join(' ') + ' '); at = source_row.search(cx); if (at >= 0) { warn('unsafe', line, at); } if (option.maxlen && option.maxlen < source_row.length) { warn('too_long', line, source_row.length); } return true; } // Produce a token object. The token inherits from a syntax symbol. function it(type, value) { var id, the_token; if (type === '(string)') { if (jx.test(value)) { warn('url', line, from); } } the_token = Object.create(syntax[( type === '(punctuator)' || (type === '(identifier)' && Object.prototype.hasOwnProperty.call(syntax, value)) ? value : type )] || syntax['(error)']); if (type === '(identifier)') { the_token.identifier = true; if (value === '__iterator__' || value === '__proto__') { stop('reserved_a', line, from, value); } else if (!option.nomen && (value.charAt(0) === '_' || value.charAt(value.length - 1) === '_')) { warn('dangling_a', line, from, value); } } if (type === '(number)') { the_token.number = +value; } else if (value !== undefined) { the_token.string = String(value); } the_token.line = line; the_token.from = from; the_token.thru = character; if (comments.length) { the_token.comments = comments; comments = []; } id = the_token.id; prereg = id && ( ('(,=:[!&|?{};~+-*%^<>'.indexOf(id.charAt(id.length - 1)) >= 0) || id === 'return' || id === 'case' ); return the_token; } function match(x) { var exec = x.exec(source_row), first; if (exec) { length = exec[0].length; first = exec[1]; c = first.charAt(0); source_row = source_row.slice(length); from = character + length - first.length; character += length; return first; } for (;;) { if (!source_row) { if (!option.white) { warn('unexpected_char_a', line, character - 1, '(space)'); } return; } c = source_row.charAt(0); if (c !== ' ') { break; } source_row = source_row.slice(1); character += 1; } stop('unexpected_char_a', line, character, c); } function string(x) { var ch, at = 0, r = '', result; function hex(n) { var i = parseInt(source_row.substr(at + 1, n), 16); at += n; if (i >= 32 && i <= 126 && i !== 34 && i !== 92 && i !== 39) { warn('unexpected_a', line, character, '\\'); } character += n; ch = String.fromCharCode(i); } if (json_mode && x !== '"') { warn('expected_a_b', line, character, '"', x); } else if (option.quote === 'single' && x !== "'") { warn('use_single_quote', line, character); } else if (option.quote === 'double' && x !== '"') { warn('use_double_quote', line, character); } for (;;) { while (at >= source_row.length) { at = 0; if (!next_line()) { stop('unclosed', line - 1, from); } } ch = source_row.charAt(at); if (ch === x) { character += 1; source_row = source_row.slice(at + 1); result = it('(string)', r); result.quote = x; if(r && dojo.stringsInCode[r] !== undefined && option.preventStringDuplication && dojo.stringsInCode[r] >= option.preventStringDuplication) { warn('duplicated_string', line, character); } dojo.stringsInCode[r] = dojo.stringsInCode[r] ? dojo.stringsInCode[r] + 1 : 1; return result; } if (ch < ' ') { if (ch === '\n' || ch === '\r') { break; } warn('control_a', line, character + at, source_row.slice(0, at)); } else if (ch === '\\') { at += 1; character += 1; ch = source_row.charAt(at); switch (ch) { case '': warn('unexpected_a', line, character, '\\'); next_line(); at = -1; break; case '\'': if (json_mode) { warn('unexpected_a', line, character, '\\\''); } break; case 'u': hex(4); break; case 'v': if (json_mode) { warn('unexpected_a', line, character, '\\v'); } ch = '\v'; break; case 'x': if (json_mode) { warn('unexpected_a', line, character, '\\x'); } hex(2); break; default: if (typeof descapes[ch] !== 'string') { warn(ch >= '0' && ch <= '7' ? 'octal_a' : 'unexpected_a', line, character, '\\' + ch); } else { ch = descapes[ch]; } } } r += ch; character += 1; at += 1; } } function number(snippet) { var digit; if (source_row.charAt(0).isAlpha()) { warn('expected_space_a_b', line, character, c, source_row.charAt(0)); } if (c === '0') { digit = snippet.charAt(1); if (digit.isDigit()) { if (token.id !== '.') { warn('unexpected_a', line, character, snippet); } } else if (json_mode && (digit === 'x' || digit === 'X')) { warn('unexpected_a', line, character, '0x'); } } if (snippet.slice(snippet.length - 1) === '.') { warn('trailing_decimal_a', line, character, snippet); } digit = +snippet; if (!isFinite(digit)) { warn('bad_number', line, character, snippet); } snippet = digit; return it('(number)', snippet); } function comment(snippet, type) { if (comments_off) { warn('unexpected_comment', line, character); } else if (!option.todo && tox.test(snippet)) { warn('todo_comment', line, character); } comments.push({ id: type, from: from, thru: character, line: line, string: snippet }); } function regexp() { var at = 0, b, bit, depth = 0, flag = '', high, letter, low, potential, quote, result; for (;;) { b = true; c = source_row.charAt(at); at += 1; switch (c) { case '': stop('unclosed_regexp', line, from); return; case '/': if (depth > 0) { warn('unescaped_a', line, from + at, '/'); } c = source_row.slice(0, at - 1); potential = Object.create(regexp_flag); for (;;) { letter = source_row.charAt(at); if (potential[letter] !== true) { break; } potential[letter] = false; at += 1; flag += letter; } if (source_row.charAt(at).isAlpha()) { stop('unexpected_a', line, from, source_row.charAt(at)); } character += at; source_row = source_row.slice(at); quote = source_row.charAt(0); if (quote === '/' || quote === '*') { stop('confusing_regexp', line, from); } result = it('(regexp)', c); result.flag = flag; return result; case '\\': c = source_row.charAt(at); if (c < ' ') { warn('control_a', line, from + at, String(c)); } else if (c === '<') { warn('unexpected_a', line, from + at, '\\'); } at += 1; break; case '(': depth += 1; b = false; if (source_row.charAt(at) === '?') { at += 1; switch (source_row.charAt(at)) { case ':': case '=': case '!': at += 1; break; default: warn('expected_a_b', line, from + at, ':', source_row.charAt(at)); } } break; case '|': b = false; break; case ')': if (depth === 0) { warn('unescaped_a', line, from + at, ')'); } else { depth -= 1; } break; case ' ': pos = 1; while (source_row.charAt(at) === ' ') { at += 1; pos += 1; } if (pos > 1) { warn('use_braces', line, from + at, pos); } break; case '[': c = source_row.charAt(at); if (c === '^') { at += 1; if (!option.regexp) { warn('insecure_a', line, from + at, c); } else if (source_row.charAt(at) === ']') { stop('unescaped_a', line, from + at, '^'); } } bit = false; if (c === ']') { warn('empty_class', line, from + at - 1); bit = true; } klass: do { c = source_row.charAt(at); at += 1; switch (c) { case '[': case '^': warn('unescaped_a', line, from + at, c); bit = true; break; case '-': if (bit) { bit = false; } else { warn('unescaped_a', line, from + at, '-'); bit = true; } break; case ']': if (!bit) { warn('unescaped_a', line, from + at - 1, '-'); } break klass; case '\\': c = source_row.charAt(at); if (c < ' ') { warn('control_a', line, from + at, String(c)); } else if (c === '<') { warn('unexpected_a', line, from + at, '\\'); } at += 1; bit = true; break; case '/': warn('unescaped_a', line, from + at - 1, '/'); bit = true; break; default: bit = true; } } while (c); break; case '.': if (!option.regexp) { warn('insecure_a', line, from + at, c); } break; case ']': case '?': case '{': case '}': case '+': case '*': warn('unescaped_a', line, from + at, c); break; } if (b) { switch (source_row.charAt(at)) { case '?': case '+': case '*': at += 1; if (source_row.charAt(at) === '?') { at += 1; } break; case '{': at += 1; c = source_row.charAt(at); if (c < '0' || c > '9') { warn('expected_number_a', line, from + at, c); } at += 1; low = +c; for (;;) { c = source_row.charAt(at); if (c < '0' || c > '9') { break; } at += 1; low = +c + (low * 10); } high = low; if (c === ',') { at += 1; high = Infinity; c = source_row.charAt(at); if (c >= '0' && c <= '9') { at += 1; high = +c; for (;;) { c = source_row.charAt(at); if (c < '0' || c > '9') { break; } at += 1; high = +c + (high * 10); } } } if (source_row.charAt(at) !== '}') { warn('expected_a_b', line, from + at, '}', c); } else { at += 1; } if (source_row.charAt(at) === '?') { at += 1; } if (low > high) { warn('not_greater', line, from + at, low, high); } break; } } } c = source_row.slice(0, at - 1); character += at; source_row = source_row.slice(at); return it('(regexp)', c); } // Public lex methods return { init: function (source) { if (typeof source === 'string') { lines = source.split(crlfx); } else { lines = source; } line = 0; next_line(); from = 1; }, // token -- this is called by advance to get the next token. token: function () { var first, i, snippet; for (;;) { while (!source_row) { if (!next_line()) { return it('(end)'); } } snippet = match(tx); if (snippet) { // identifier first = snippet.charAt(0); if (first.isAlpha() || first === '_' || first === '$') { return it('(identifier)', snippet); } // number if (first.isDigit()) { return number(snippet); } switch (snippet) { // string case '"': case "'": return string(snippet); // // comment case '//': comment(source_row, '//'); source_row = ''; break; // /* comment case '/*': for (;;) { i = source_row.search(lx); if (i >= 0) { break; } character = source_row.length; comment(source_row); from = 0; if (!next_line()) { stop('unclosed_comment', line, character); } } comment(source_row.slice(0, i), '/*'); character += i + 2; if (source_row.charAt(i) === '/') { stop('nested_comment', line, character); } source_row = source_row.slice(i + 2); break; case '': break; // / case '/': if (token.id === '/=') { stop('slash_equal', line, from); } return prereg ? regexp() : it('(punctuator)', snippet); // punctuator default: return it('(punctuator)', snippet); } } } } }; }()); function define(kind, token) { // Define a name. var name = token.string, master = scope[name]; // The current definition of the name if (option.camelcase && token.string.indexOf('$') === -1 && token.string.replace(/^_+/, "").indexOf("_") > -1 && !token.string.match(/^[A-Z0-9_]*$/)) { if(!option.camelcase_deviations[token.string]) { token.warn('use_camel_case', token.string); } } // vars are created with a deadzone, so that the expression that initializes // the var cannot access the var. Functions are not writeable. token.dead = false; token.init = false; token.kind = kind; token.master = master; token.used = 0; token.writeable = true; // Global variables are a little weird. They can be defined multiple times. // Some predefined global vars are (or should) not be writeable. if (kind === 'var' && funct === global_funct) { if (!master) { if (predefined[name] === false) { token.writeable = false; } global_scope[name] = token; } } else { // It is an error if the name has already been defined in this scope, except // when reusing an exception variable name. if (master) { if (master.function === funct) { if (master.kind !== 'exception' || kind !== 'exception' || !master.dead) { token.warn('already_defined', name); } } else if (master.function !== global_funct) { if (kind === 'var') { token.warn('redefinition_a_b', name, master.line); } } } scope[name] = token; if (kind === 'var') { block_var.push(name); } } } function peek(distance) { // Peek ahead to a future token. The distance is how far ahead to look. The // default is the next token. var found, slot = 0; distance = distance || 0; while (slot <= distance) { found = lookahead[slot]; if (!found) { found = lookahead[slot] = lex.token(); } slot += 1; } return found; } function advance(id, match) { // Produce the next token, also looking for programming errors. if (indent) { // If indentation checking was requested, then inspect all of the line breakings. // The var statement is tricky because the names might be aligned or not. We // look at the first line break after the var to determine the programmer's // intention. if (var_mode && next_token.line !== token.line) { if ((var_mode !== indent || !next_token.edge) && next_token.from === indent.at - (next_token.edge ? option.indent : 0)) { var dent = indent; for (;;) { dent.at -= option.indent; if (dent === var_mode) { break; } dent = dent.was; } dent.open = false; } var_mode = null; } if (next_token.id === '?' && indent.mode === ':' && token.line !== next_token.line) { indent.at -= option.indent; } if (indent.open) { // If the token is an edge. if (next_token.edge) { if (next_token.edge === 'label') { expected_at(1); } else if (next_token.edge === 'case' || indent.mode === 'statement') { expected_at(indent.at - option.indent); } else if (indent.mode !== 'array' || next_token.line !== token.line) { expected_at(indent.at); } // If the token is not an edge, but is the first token on the line. } else if (next_token.line !== token.line) { if (next_token.from < indent.at + (indent.mode === 'expression' ? 0 : option.indent)) { expected_at(indent.at + option.indent); } indent.wrap = true; } } else if (next_token.line !== token.line) { if (next_token.edge) { expected_at(indent.at); } else { indent.wrap = true; if (indent.mode === 'statement' || indent.mode === 'var') { expected_at(indent.at + option.indent); } else if (next_token.from < indent.at + (indent.mode === 'expression' ? 0 : option.indent)) { expected_at(indent.at + option.indent); } } } } switch (token.id) { case '(number)': if (next_token.id === '.') { next_token.warn('trailing_decimal_a'); } break; case '-': if (next_token.id === '-' || next_token.id === '--') { next_token.warn('confusing_a'); } break; case '+': if (next_token.id === '+' || next_token.id === '++') { next_token.warn('confusing_a'); } break; } if (token.id === '(string)' || token.identifier) { anonname = token.string; } var line = lines[token.line - 1]; var idep; if(option.customRules && typeof option.customRules === 'function') { option.customRules(id, token, line); } if(option.dojo && id && token.line > 0) { for(idep in dojo.deprecated) { if(line.indexOf('\''+idep) !== -1 || line.indexOf('"'+idep) !== -1) { token.warn('i_deprecated', idep, dojo.deprecated[idep]); } } } if(option.dojo && line && token.line > 0) { dojo.alreadyWarnedForDeprecated = dojo.alreadyWarnedForDeprecated || [] dojo.alreadyWarnedForDeprecated[token.line] = dojo.alreadyWarnedForDeprecated[token.line] || '' for(idep in dojo.deprecatedCode) { if(line.indexOf(idep) !== -1 && dojo.alreadyWarnedForDeprecated[token.line].indexOf(']"[' + idep + ']"[') === -1) { dojo.alreadyWarnedForDeprecated[token.line] += ']"[' + idep + ']"['; token.warn('i_deprecated', idep, dojo.deprecatedCode[idep]); } } if(token.string === 'declare' && /declare\s*\(\s*('|")[^',"]*('|")\s*,\s*/.test(line)) { token.warn('has_classname'); } } if(option.dojo_define_force_absolute && line) { if(/define\s*\(/.test(line) || /require\s*\(/.test(line)) { dojo.isInDefine = true; } if(dojo.isInDefine && /('|")\.+\//.test(line)) { token.warn('use_absolute'); } if(/function\s*\(/.test(line)) { dojo.isInDefine = false; } } if(option.dojo && token.line > 0 && ( token.string === "_connects" || ( (/[a-zA-Z0-9_]+Node$/.test(token.string) && next_token.string !== "(" && next_token.string !== ":" && token.string.indexOf("domNode") === -1 && token.string.indexOf("parentNode")) ) )) { //search for X.Y to check if Y is a private var attachpointError = false; if (token.string.indexOf('_connects') === 0 && line.indexOf('this.'+token.string) === -1 && (new RegExp('\\.+'+token.string)).test(line)) { //private call token.warn('maybe_illegal_private_call', 'this.'+token.string); } else if(/[a-zA-Z0-9_]+Node$/.test(token.string) && (/\.[a-zA-Z0-9_]+Node$/.test(line) || (new RegExp("\\." + token.string + '[\),;\}]')).test(line)) && line.indexOf('this.'+token.string) === -1){ token.warn('maybe_illegal_attach_point_call', 'this.'+token.string); } } if (id && next_token.id !== id) { if (match) { next_token.warn('expected_a_b_from_c_d', id, match.id, match.line, artifact()); } else if (!next_token.identifier || next_token.string !== id) { next_token.warn('expected_a_b', id, artifact()); } } prev_token = token; token = next_token; next_token = lookahead.shift() || lex.token(); next_token.function = funct; tokens.push(next_token); } function do_globals() { var name, writeable; for (;;) { if (next_token.id !== '(string)' && !next_token.identifier) { return; } name = next_token.string; advance(); writeable = false; if (next_token.id === ':') { advance(':'); switch (next_token.id) { case 'true': writeable = predefined[name] !== false; advance('true'); break; case 'false': advance('false'); break; default: next_token.stop('unexpected_a'); } } predefined[name] = writeable; if (next_token.id !== ',') { return; } advance(','); } } function do_jslint() { var name, value; while (next_token.id === '(string)' || next_token.identifier) { //name = next_token.string; //if (!allowed_option[name]) { //next_token.stop('unexpected_a'); //} advance(); //if (next_token.id !== ':') { //next_token.stop('expected_a_b', ':', artifact()); //} advance(':'); //if (typeof allowed_option[name] === 'number') { //value = next_token.number; //if (value > allowed_option[name] || value <= 0 || //Math.floor(value) !== value) { //next_token.stop('expected_small_a'); //} //option[name] = value; //} else { //if (next_token.id === 'true') { //option[name] = true; //} else if (next_token.id === 'false') { //option[name] = false; //} else { //next_token.stop('unexpected_a'); //} //} advance(); if (next_token.id === ',') { advance(','); } } assume(); } function do_properties() { var name; option.properties = true; for (;;) { if (next_token.id !== '(string)' && !next_token.identifier) { return; } name = next_token.string; advance(); if (next_token.id === ':') { for (;;) { advance(); if (next_token.id !== '(string)' && !next_token.identifier) { break; } } } property[name] = 0; if (next_token.id !== ',') { return; } advance(','); } } directive = function directive() { var command = this.id, old_comments_off = comments_off, old_indent = indent; comments_off = true; indent = null; if (next_token.line === token.line && next_token.from === token.thru) { next_token.warn('missing_space_a_b', artifact(token), artifact()); } if (lookahead.length > 0) { // this.warn('unexpected_a'); this.stop('unexpected_a'); } switch (command) { case '/*properties': case '/*property': case '/*members': case '/*member': do_properties(); break; case '/*jslint': token.warn('i_jslint_global'); do_jslint(); break; case '/*globals': case '/*global': do_globals(); break; default: this.stop('unexpected_a'); } comments_off = old_comments_off; advance('*/'); indent = old_indent; }; // Indentation intention function edge(mode) { next_token.edge = indent ? indent.open && (mode || 'edge') : ''; } function step_in(mode) { var open; if (typeof mode === 'number') { indent = { at: +mode, open: true, was: indent }; } else if (!indent) { indent = { at: 1, mode: 'statement', open: true }; } else if (mode === 'statement') { indent = { at: indent.at, open: true, was: indent }; } else { open = mode === 'var' || next_token.line !== token.line; indent = { at: (open || mode === 'control' ? indent.at + option.indent : indent.at) + (indent.wrap ? option.indent : 0), mode: mode, open: open, was: indent }; if (mode === 'var' && open) { var_mode = indent; } } } function step_out(id, symbol) { if (id) { if (indent && indent.open) { indent.at -= option.indent; edge(); } advance(id, symbol); } if (indent) { indent = indent.was; } } // Functions for conformance of whitespace. function one_space(left, right) { left = left || token; right = right || next_token; if (right.id !== '(end)' && !option.white && (token.line !== right.line || token.thru + 1 !== right.from)) { right.warn('expected_space_a_b', artifact(token), artifact(right)); } } function one_space_only(left, right) { left = left || token; right = right || next_token; if (right.id !== '(end)' && (left.line !== right.line || (!option.white && left.thru + 1 !== right.from))) { right.warn('expected_space_a_b', artifact(left), artifact(right)); } } function no_space(left, right) { left = left || token; right = right || next_token; //if ((!option.white) && if ((!option.white) && !right.comments && left.thru !== right.from && left.line === right.line) { right.warn('unexpected_space_a_b', artifact(left), artifact(right)); } } function no_space_only(left, right) { left = left || token; right = right || next_token; if (right.id !== '(end)' && (left.line !== right.line || (!option.white && left.thru !== right.from))) { right.warn('unexpected_space_a_b', artifact(left), artifact(right)); } } function spaces(left, right) { if (!option.white) { left = left || token; right = right || next_token; if (left.thru === right.from && left.line === right.line) { right.warn('missing_space_a_b', artifact(left), artifact(right)); } } } function comma() { if (next_token.id !== ',') { warn('expected_a_b', token.line, token.thru, ',', artifact()); } else { if (!option.white) { no_space_only(); } advance(','); spaces(); } } function semicolon() { if (next_token.id !== ';') { warn('expected_a_b', token.line, token.thru, ';', artifact()); } else { if (!option.white) { no_space_only(); } advance(';'); if (semicolon_coda[next_token.id] !== true) { spaces(); } } } function use_strict() { if (next_token.string === 'use strict') { if (strict_mode) { next_token.warn('unnecessary_use'); } edge(); advance(); semicolon(); strict_mode = true; return true; } return false; } function are_similar(a, b) { if (a === b) { return true; } if (Array.isArray(a)) { if (Array.isArray(b) && a.length === b.length) { var i; for (i = 0; i < a.length; i += 1) { if (!are_similar(a[i], b[i])) { return false; } } return true; } return false; } if (Array.isArray(b)) { return false; } if (a.id === '(number)' && b.id === '(number)') { return a.number === b.number; } if (a.arity === b.arity && a.string === b.string) { switch (a.arity) { case undefined: return a.string === b.string; case 'prefix': case 'suffix': return a.id === b.id && are_similar(a.first, b.first) && a.id !== '{' && a.id !== '['; case 'infix': return are_similar(a.first, b.first) && are_similar(a.second, b.second); case 'ternary': return are_similar(a.first, b.first) && are_similar(a.second, b.second) && are_similar(a.third, b.third); case 'function': case 'regexp': return false; default: return true; } } if (a.id === '.' && b.id === '[' && b.arity === 'infix') { return a.second.string === b.second.string && b.second.id === '(string)'; } if (a.id === '[' && a.arity === 'infix' && b.id === '.') { return a.second.string === b.second.string && a.second.id === '(string)'; } return false; } // This is the heart of JSLINT, the Pratt parser. In addition to parsing, it // is looking for ad hoc lint patterns. We add .fud to Pratt's model, which is // like .nud except that it is only used on the first token of a statement. // Having .fud makes it much easier to define statement-oriented languages like // JavaScript. I retained Pratt's nomenclature. // .nud Null denotation // .fud First null denotation // .led Left denotation // lbp Left binding power // rbp Right binding power // They are elements of the parsing method called Top Down Operator Precedence. function expression(rbp, initial) { // rbp is the right binding power. // initial indicates that this is the first expression of a statement. var left; if (next_token.id === '(end)') { token.stop('unexpected_a', next_token.id); } advance(); if (initial) { anonname = 'anonymous'; } if (initial === true && token.fud) { left = token.fud(); } else { if (token.nud) { left = token.nud(); } else { if (next_token.id === '(number)' && token.id === '.') { token.warn('leading_decimal_a', artifact()); advance(); return token; } token.stop('expected_identifier_a', artifact(token)); } while (rbp < next_token.lbp) { advance(); left = token.led(left); } } if (left && left.assign && !initial) { if (!option.ass) { left.warn('assignment_expression'); } if (left.id !== '=' && left.first.master) { left.first.master.used = true; } } return left; } protosymbol = { nud: function () { this.stop('unexpected_a'); }, led: function () { this.stop('expected_operator_a'); }, warn: function (code, a, b, c, d) { if (!this.warning) { this.warning = warn(code, this.line || 0, this.from || 0, a || artifact(this), b, c, d); } }, stop: function (code, a, b, c, d) { this.warning = undefined; this.warn(code, a, b, c, d); return quit('stopping', this.line, this.character); }, lbp: 0 }; // Functional constructors for making the symbols that will be inherited by // tokens. function symbol(s, bp) { var x = syntax[s]; if (!x) { x = Object.create(protosymbol); x.id = x.string = s; x.lbp = bp || 0; syntax[s] = x; } return x; } function postscript(x) { x.postscript = true; return x; } function ultimate(s) { var x = symbol(s, 0); x.from = 1; x.thru = 1; x.line = 0; x.edge = 'edge'; x.string = s; return postscript(x); } function reserve_name(x) { var c = x.id.charAt(0); if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) { reservedPropertyName['_' + x.string] = x.string; x.identifier = x.reserved = true; } return x; } function stmt(s, f) { var x = symbol(s); x.fud = f; return reserve_name(x); } function disrupt_stmt(s, f) { var x = stmt(s, f); x.disrupt = true; } function labeled_stmt(s, f) { var x = stmt(s, function labeled() { var the_statement; if (funct.breakage) { funct.breakage.push(this); } else { funct.breakage = [this]; } the_statement = f.apply(this); if (funct.breakage.length > 1) { funct.breakage.pop(); } else { delete funct.breakage; } return the_statement; }); x.labeled = true; } function prefix(s, f) { var x = symbol(s, 150); reserve_name(x); x.nud = function () { var that = this; that.arity = 'prefix'; if (typeof f === 'function') { that = f(that); if (that.arity !== 'prefix') { return that; } } else { if (s === 'typeof') { one_space(); } else { no_space_only(); } that.first = expression(150); } switch (that.id) { case '++': case '--': if (!option.plusplus) { // that.warn('unexpected_a'); that.stop('unexpected_a'); } else if ((!that.first.identifier || that.first.reserved) && that.first.id !== '.' && that.first.id !== '[') { that.warn('bad_operand'); } break; default: if (that.first.arity === 'prefix' || that.first.arity === 'function') { // that.warn('unexpected_a'); that.stop('unexpected_a'); } } return that; }; return x; } function type(s, t, nud) { var x = symbol(s); x.arity = t; if (nud) { x.nud = nud; } return x; } function isReserved(s) { return reservedPropertyName['_' + s] !== undefined; } function reserve(s, f) { var x = symbol(s); reservedPropertyName['_' + s] = s; x.identifier = x.reserved = true; if (typeof f === 'function') { x.nud = f; } return x; } function constant(name) { var x = reserve(name); x.string = name; x.nud = return_this; return x; } function reservevar(s, v) { return reserve(s, function () { if (typeof v === 'function') { v(this); } return this; }); } function infix(s, p, f, w) { var x = symbol(s, p); reserve_name(x); x.led = function (left) { this.arity = 'infix'; if (!w) { spaces(prev_token, token); spaces(); } if (!option.bitwise && this.bitwise) { this.warn('unexpected_a'); //this.stop('unexpected_a'); } if (typeof f === 'function') { return f(left, this); } this.first = left; this.second = expression(p); return this; }; return x; } function expected_relation(node, message) { if (node.assign) { node.warn(message || 'conditional_assignment'); } return node; } function expected_condition(node, message) { switch (node.id) { case '[': case '-': if (node.arity !== 'infix') { node.warn(message || 'weird_condition'); } break; case 'false': case 'function': case 'Infinity': case 'NaN': case 'null': case 'true': case 'undefined': case 'void': case '(number)': case '(regexp)': case '(string)': case '{': case '?': case '~': node.warn(message || 'weird_condition'); break; case '(': if (node.first.id === 'new' || (node.first.string === 'Boolean') || (node.first.id === '.' && numbery[node.first.second.string] === true)) { node.warn(message || 'weird_condition'); } break; } return node; } function check_relation(node) { switch (node.arity) { case 'prefix': switch (node.id) { case '{': case '[': // node.warn('unexpected_a'); node.stop('unexpected_a'); break; case '!': node.warn('confusing_a'); break; } break; case 'function': case 'regexp': // node.warn('unexpected_a'); node.stop('unexpected_a'); break; default: if (node.id === 'NaN') { node.warn('isNaN'); } else if (node.relation) { node.warn('weird_relation'); } } return node; } function relation(s, eqeq) { var x = infix(s, 100, function (left, that) { check_relation(left); if (eqeq && !option.eqeq) { that.warn('expected_a_b', eqeq, that.id); } var right = expression(100); if (are_similar(left, right) || ((left.id === '(string)' || left.id === '(number)') && (right.id === '(string)' || right.id === '(number)'))) { that.warn('weird_relation'); } else if (left.id === 'typeof') { if (right.id !== '(string)') { right.warn("expected_string_a", artifact(right)); } else if (right.string === 'undefined' || right.string === 'null') { left.warn("unexpected_typeof_a", right.string); } } else if (right.id === 'typeof') { if (left.id !== '(string)') { left.warn("expected_string_a", artifact(left)); } else if (left.string === 'undefined' || left.string === 'null') { right.warn("unexpected_typeof_a", left.string); } } that.first = left; that.second = check_relation(right); return that; }); x.relation = true; return x; } function lvalue(that, s) { var master; if (that.identifier) { master = scope[that.string]; if (master) { if (scope[that.string].writeable !== true) { that.warn('read_only'); } master.used -= 1; if (s === '=') { master.init = true; } } else if (that.reserved) { that.warn('expected_identifier_a_reserved'); } } else if (that.id === '.' || that.id === '[') { if (!that.first || that.first.string === 'arguments') { that.warn('bad_assignment'); } } else { that.warn('bad_assignment'); } } function assignop(s, op) { var x = infix(s, 20, function (left, that) { var next; that.first = left; lvalue(left, s); that.second = expression(20); if (that.id === '=' && are_similar(that.first, that.second)) { that.warn('weird_assignment'); } next = that; while (next_token.id === '=') { lvalue(next.second, '='); next_token.first = next.second; next.second = next_token; next = next_token; advance('='); next.second = expression(20); } return that; }); x.assign = true; if (op) { if (syntax[op].bitwise) { x.bitwise = true; } } return x; } function bitwise(s, p) { var x = infix(s, p, 'number'); x.bitwise = true; return x; } function suffix(s) { var x = symbol(s, 150); x.led = function (left) { no_space_only(prev_token, token); if (!option.plusplus) { // this.warn('unexpected_a'); this.stop('unexpected_a'); } else if ((!left.identifier || left.reserved) && left.id !== '.' && left.id !== '[') { this.warn('bad_operand'); } this.first = left; this.arity = 'suffix'; return this; }; return x; } function optional_identifier(variable) { if (next_token.identifier) { advance(); if (token.reserved && variable) { token.warn('expected_identifier_a_reserved'); } return token.string; } } function identifier(variable) { var i = optional_identifier(variable); if (!i) { next_token.stop(token.id === 'function' && next_token.id === '(' ? 'name_function' : 'expected_identifier_a'); } return i; } function statement() { var label, preamble, the_statement; // We don't like the empty statement. if (next_token.id === ';') { // next_token.warn('unexpected_a'); next_token.stop('unexpected_a'); semicolon(); return; } // Is this a labeled statement? if (next_token.identifier && !next_token.reserved && peek().id === ':') { edge('label'); label = next_token; advance(); advance(':'); define('label', label); if (next_token.labeled !== true || funct === global_funct) { label.stop('unexpected_label_a'); } else if (jx.test(label.string + ':')) { label.warn('url'); } next_token.label = label; label.init = true; label.statement = next_token; } // Parse the statement. preamble = next_token; if (token.id !== 'else') { edge(); } step_in('statement'); the_statement = expression(0, true); if (the_statement) { // Look for the final semicolon. if (the_statement.arity === 'statement') { if (the_statement.id === 'switch' || (the_statement.block && the_statement.id !== 'do')) { spaces(); } else { semicolon(); } } else { // If this is an expression statement, determine if it is acceptable. // We do not like // new Blah; // statements. If it is to be used at all, new should only be used to make // objects, not side effects. The expression statements we do like do // assignment or invocation or delete. if (the_statement.id === '(') { if (the_statement.first.id === 'new') { next_token.warn('bad_new'); } } else if (the_statement.id === '++' || the_statement.id === '--') { lvalue(the_statement.first); } else if (!the_statement.assign && the_statement.id !== 'delete') { if (!option.closure || !preamble.comments) { preamble.warn('assignment_function_expression'); } } semicolon(); } } step_out(); if (label) { label.dead = true; } return the_statement; } function statements() { var array = [], disruptor, the_statement; // A disrupt statement may not be followed by any other statement. // If the last statement is disrupt, then the sequence is disrupt. while (next_token.postscript !== true) { if (next_token.id === ';') { // next_token.warn('unexpected_a'); next_token.stop('unexpected_a'); semicolon(); } else { if (next_token.string === 'use strict') { if ((!node_js) || funct !== global_funct || array.length > 0) { next_token.warn('function_strict'); } use_strict(); } if (disruptor) { next_token.warn('unreachable_a_b', next_token.string, disruptor.string); disruptor = null; } the_statement = statement(); if (the_statement) { array.push(the_statement); if (the_statement.disrupt) { disruptor = the_statement; array.disrupt = true; } } } } return array; } function block(kind) { // A block is a sequence of statements wrapped in braces. var array, curly = next_token, old_block_var = block_var, old_in_block = in_block, isDojoLoop = false, old_strict_mode = strict_mode; if(option.dojo && kind === 'function' && (/\.forEach\(/.test(lines[token.line - 1]) || /\.some\(/.test(lines[token.line - 1]) || /array\.filter\(/.test(lines[token.line - 1]) || /array\.map\(/.test(lines[token.line - 1]) || /\.every\(/.test(lines[token.line - 1])) ) { isDojoLoop = true; funct.loopage += 1; funct.dojoloop = funct.loopage; } in_block = kind !== 'function' && kind !== 'try' && kind !== 'catch'; block_var = []; if (curly.id === '{') { spaces(); advance('{'); step_in(); if (kind === 'function' && !use_strict() && !old_strict_mode && !option.sloppy && funct.level === 1) { next_token.warn('missing_use_strict'); } array = statements(); strict_mode = old_strict_mode; step_out('}', curly); } else if (in_block) { curly.stop('expected_a_b', '{', artifact()); } else { curly.warn('expected_a_b', '{', artifact()); array = [statement()]; array.disrupt = array[0].disrupt; } if (kind !== 'catch' && array.length === 0 && !option.debug) { curly.warn('empty_block'); } var mteststarted = ',' + dojo.mustTestStarted.join(",") + ','; var fncSepName = ',' + funct['name'].replace(/'/g,'') + ','; if (option.dojo && kind === 'function' && ((array.length === 1) || (array.length === 2 && funct['hasStartedIf'] === true && mteststarted.indexOf(fncSepName) !== -1))) { for(var lineIndex = 0; lineIndex < array.length; lineIndex++) { //if there is only one line in a function, check if it's not an inherited call var line = lines[array[lineIndex].line - 1]; if (/^\s*(return)?\s*this\.inherited\(arguments\);\s*$/.test(line)) { //function with just an inherited call curly.warn('only_inherited'); } } } block_var.forEach(function (name) { scope[name].dead = true; }); block_var = old_block_var; in_block = old_in_block; if(isDojoLoop) { funct.loopage -= 1; funct.dojoloop = null; } return array; } function tally_property(name) { if (option.properties && typeof property[name] !== 'number') { token.warn('unexpected_property_a', name); } if (property[name]) { property[name] += 1; } else { property[name] = 1; } } // ECMAScript parser (function () { var x = symbol('(identifier)'); x.nud = function () { var name = this.string, master = scope[name], writeable; if (option.camelcase && name.indexOf('$') === -1 && name.replace(/^_+/, "").indexOf("_") > -1 && !name.match(/^[A-Z0-9_]*$/)) { if(!option.camelcase_deviations[name]) { token.warn('use_camel_case', name); } } if (option.dojo && token.string === 'query' && next_token.string === '(') { var line = lines[token.line - 1]; if (/query\s*\([^,]+,/.test(line)) { //2 args } else { //1 args token.warn('use_context_with_query'); } } // If the master is not in scope, then we may have an undeclared variable. // Check the predefined list. If it was predefined, create the global // variable. if (!master) { writeable = predefined[name]; if (typeof writeable === 'boolean') { global_scope[name] = master = { dead: false, function: global_funct, kind: 'var', string: name, writeable: writeable }; // But if the variable is not in scope, and is not predefined, and if we are not // in the global scope, then we have an undefined variable error. } else { token.warn('used_before_a'); } } else { this.master = master; } // Annotate uses that cross scope boundaries. if (master) { if (master.kind === 'label') { this.warn('a_label'); } else { if (master.dead === true || master.dead === funct) { this.warn('a_scope'); } master.used += 1; if (master.function !== funct) { if (master.function === global_funct) { funct.global.push(name); } else { master.function.closure.push(name); funct.outer.push(name); } } } } return this; }; x.identifier = true; }()); // Build the syntax table by declaring the syntactic elements. type('(array)', 'array'); type('(function)', 'function'); type('(number)', 'number', return_this); type('(object)', 'object'); type('(string)', 'string', return_this); type('(boolean)', 'boolean', return_this); type('(regexp)', 'regexp', return_this); ultimate('(begin)'); ultimate('(end)'); ultimate('(error)'); postscript(symbol('}')); symbol(')'); symbol(']'); postscript(symbol('"')); postscript(symbol('\'')); symbol(';'); symbol(':'); symbol(','); symbol('#'); symbol('@'); symbol('*/'); postscript(reserve('case')); reserve('catch'); postscript(reserve('default')); reserve('else'); reserve('finally'); reservevar('arguments', function (x) { if (strict_mode && funct === global_funct) { x.warn('strict'); } funct.arguments = true; }); reservevar('eval'); constant('false', 'boolean'); constant('Infinity', 'number'); constant('NaN', 'number'); constant('null', ''); reservevar('boolean'); //because of IE8 reservevar('float'); //because of phantomJS reservevar('this', function (x) { if (strict_mode && funct.statement && funct.name.charAt(0) > 'Z') { x.warn('strict'); } }); constant('true', 'boolean'); constant('undefined', ''); infix('?', 30, function (left, that) { step_in('?'); that.first = expected_condition(expected_relation(left)); that.second = expression(0); spaces(); step_out(); var colon = next_token; advance(':'); step_in(':'); spaces(); that.third = expression(10); that.arity = 'ternary'; if (are_similar(that.second, that.third)) { colon.warn('weird_ternary'); } else if (are_similar(that.first, that.second)) { that.warn('use_or'); } step_out(); return that; }); infix('||', 40, function (left, that) { function paren_check(that) { if (that.id === '&&' && !that.paren) { that.warn('and'); } return that; } that.first = paren_check(expected_condition(expected_relation(left))); that.second = paren_check(expected_relation(expression(40))); if (are_similar(that.first, that.second)) { that.warn('weird_condition'); } return that; }); infix('&&', 50, function (left, that) { that.first = expected_condition(expected_relation(left)); that.second = expected_relation(expression(50)); if (are_similar(that.first, that.second)) { that.warn('weird_condition'); } return that; }); prefix('void', function (that) { that.first = expression(0); that.warn('expected_a_b', 'undefined', 'void'); return that; }); bitwise('|', 70); bitwise('^', 80); bitwise('&', 90); relation('==', '==='); relation('==='); relation('!=', '!=='); relation('!=='); relation('<'); relation('>'); relation('<='); relation('>='); bitwise('<<', 120); bitwise('>>', 120); bitwise('>>>', 120); infix('in', 120, function (left, that) { that.warn('infix_in'); that.left = left; that.right = expression(130); return that; }); infix('instanceof', 120); infix('+', 130, function (left, that) { if (left.id === '(number)') { if (left.number === 0) { // left.warn('unexpected_a', '0'); left.stop('unexpected_a', '0'); } } else if (left.id === '(string)') { if (left.string === '') { left.warn('expected_a_b', 'String', '\'\''); } } var right = expression(130); if (right.id === '(number)') { if (right.number === 0) { // right.warn('unexpected_a', '0'); right.stop('unexpected_a', '0'); } } else if (right.id === '(string)') { if (right.string === '') { right.warn('expected_a_b', 'String', '\'\''); } } if (left.id === right.id) { if (left.id === '(string)' || left.id === '(number)') { if (left.id === '(string)') { left.string += right.string; if (jx.test(left.string)) { left.warn('url'); } } else { left.number += right.number; } left.thru = right.thru; return left; } } that.first = left; that.second = right; return that; }); prefix('+'); prefix('+++', function () { token.warn('confusing_a'); this.first = expression(150); this.arity = 'prefix'; return this; }); infix('+++', 130, function (left) { token.warn('confusing_a'); this.first = left; this.second = expression(130); return this; }); infix('-', 130, function (left, that) { if ((left.id === '(number)' && left.number === 0) || left.id === '(string)') { // left.warn('unexpected_a'); left.stop('unexpected_a'); } var right = expression(130); if ((right.id === '(number)' && right.number === 0) || right.id === '(string)') { // right.warn('unexpected_a'); right.stop('unexpected_a'); } if (left.id === right.id && left.id === '(number)') { left.number -= right.number; left.thru = right.thru; return left; } that.first = left; that.second = right; return that; }); prefix('-'); prefix('---', function () { token.warn('confusing_a'); this.first = expression(150); this.arity = 'prefix'; return this; }); infix('---', 130, function (left) { token.warn('confusing_a'); this.first = left; this.second = expression(130); return this; }); infix('*', 140, function (left, that) { if ((left.id === '(number)' && (left.number === 0 || left.number === 1)) || left.id === '(string)') { // left.warn('unexpected_a'); left.stop('unexpected_a'); } var right = expression(140); if ((right.id === '(number)' && (right.number === 0 || right.number === 1)) || right.id === '(string)') { // right.warn('unexpected_a'); right.stop('unexpected_a'); } if (left.id === right.id && left.id === '(number)') { left.number *= right.number; left.thru = right.thru; return left; } that.first = left; that.second = right; return that; }); infix('/', 140, function (left, that) { if ((left.id === '(number)' && left.number === 0) || left.id === '(string)') { // left.warn('unexpected_a'); left.stop('unexpected_a'); } var right = expression(140); if ((right.id === '(number)' && (right.number === 0 || right.number === 1)) || right.id === '(string)') { // right.warn('unexpected_a'); right.stop('unexpected_a'); } if (left.id === right.id && left.id === '(number)') { left.number /= right.number; left.thru = right.thru; return left; } that.first = left; that.second = right; return that; }); infix('%', 140, function (left, that) { if ((left.id === '(number)' && (left.number === 0 || left.number === 1)) || left.id === '(string)') { // left.warn('unexpected_a'); left.stop('unexpected_a'); } var right = expression(140); if ((right.id === '(number)' && right.number === 0) || right.id === '(string)') { // right.warn('unexpected_a'); right.stop('unexpected_a'); } if (left.id === right.id && left.id === '(number)') { left.number %= right.number; left.thru = right.thru; return left; } that.first = left; that.second = right; return that; }); suffix('++'); prefix('++'); suffix('--'); prefix('--'); prefix('delete', function (that) { one_space(); var p = expression(0); if (!p || (p.id !== '.' && p.id !== '[')) { next_token.warn('deleted'); } that.first = p; return that; }); prefix('~', function (that) { no_space_only(); var line = lines[token.line - 1] || ''; //if (!option.bitwise) { if (!option.bitwise && !/\~[a-zA-Z0-9_\[\]\"\']+\.indexOf/.test(line)) { that.warn('unexpected_a'); } that.first = expression(150); return that; }); function banger(that) { no_space_only(); that.first = expected_condition(expression(150)); if (bang[that.first.id] === that || that.first.assign) { that.warn('confusing_a'); } return that; } prefix('!', banger); prefix('!!', banger); prefix('typeof'); prefix('new', function (that) { one_space(); var c = expression(160), n, p, v; that.first = c; if (c.id !== 'function') { if (c.identifier) { switch (c.string) { case 'Object': token.warn('use_object'); break; case 'Array': if (next_token.id === '(') { p = next_token; p.first = this; advance('('); if (next_token.id !== ')') { n = expression(0); p.second = [n]; if (n.id === '(string)' || next_token.id === ',') { p.warn('use_array'); } while (next_token.id === ',') { advance(','); p.second.push(expression(0)); } } else { token.warn('use_array'); } advance(')', p); return p; } token.warn('use_array'); break; case 'Number': case 'String': case 'Boolean': case 'Math': case 'JSON': c.warn('not_a_constructor'); break; case 'Function': if (!option.evil) { next_token.warn('function_eval'); } break; case 'Date': case 'RegExp': case 'this': break; default: if (c.id !== 'function') { v = c.string.charAt(0); if (!option.newcap && (v < 'A' || v > 'Z')) { token.warn('constructor_name_a'); } } } } else { if (c.id !== '.' && c.id !== '[' && c.id !== '(') { token.warn('bad_constructor'); } } } else { that.warn('weird_new'); } if (next_token.id !== '(') { next_token.warn('missing_a', '()'); } return that; }); infix('(', 160, function (left, that) { var e, p; if (indent && indent.mode === 'expression') { no_space(prev_token, token); } else { no_space_only(prev_token, token); } if (!left.immed && left.id === 'function') { next_token.warn('wrap_immediate'); } p = []; if (left.identifier) { if (left.string.match(/^[A-Z]([A-Z0-9_$]*[a-z][A-Za-z0-9_$]*)?$/)) { if (left.string !== 'Number' && left.string !== 'String' && left.string !== 'Boolean' && left.string !== 'Date') { if (left.string === 'Math') { left.warn('not_a_function'); } else if (left.string === 'Object') { token.warn('use_object'); } else if (left.string === 'Array' || !option.newcap) { left.warn('missing_a', 'new'); } } } else if (left.string === 'JSON') { left.warn('not_a_function'); } } else if (left.id === '.') { if (left.second.string === 'split' && left.first.id === '(string)') { left.second.warn('use_array'); } } step_in(); if (next_token.id !== ')') { no_space(); for (;;) { edge(); e = expression(10); if (left.string === 'Boolean' && (e.id === '!' || e.id === '~')) { e.warn('weird_condition'); } p.push(e); if (next_token.id !== ',') { break; } comma(); } } no_space(); step_out(')', that); if (typeof left === 'object') { if (left.string === 'parseInt' && p.length === 1) { left.warn('radix'); } else if (left.string === 'String' && p.length >= 1 && p[0].id === '(string)') { // left.warn('unexpected_a'); left.stop('unexpected_a'); } if (!option.evil) { if (left.string === 'eval' || left.string === 'Function' || left.string === 'execScript') { left.warn('evil'); } else if (p[0] && p[0].id === '(string)' && (left.string === 'setTimeout' || left.string === 'setInterval')) { left.warn('implied_evil'); } } if (!left.identifier && left.id !== '.' && left.id !== '[' && left.id !== '(' && left.id !== '&&' && left.id !== '||' && left.id !== '?') { left.warn('bad_invocation'); } if (left.id === '.') { if (p.length > 0 && left.first && left.first.first && are_similar(p[0], left.first.first)) { if (left.second.string === 'call' || (left.second.string === 'apply' && (p.length === 1 || (p[1].arity === 'prefix' && p[1].id === '[')))) { // left.second.warn('unexpected_a'); left.second.stop('unexpected_a'); } } if (left.second.string === 'toString') { if (left.first.id === '(string)' || left.first.id === '(number)') { // left.second.warn('unexpected_a'); left.second.stop('unexpected_a'); } } } } that.first = left; that.second = p; return that; }, true); prefix('(', function (that) { step_in('expression'); no_space(); edge(); if (next_token.id === 'function') { next_token.immed = true; } var value = expression(0); value.paren = true; no_space(); step_out(')', that); if (value.id === 'function') { switch (next_token.id) { case '(': next_token.warn('move_invocation'); break; case '.': case '[': // next_token.warn('unexpected_a'); next_token.stop('unexpected_a'); break; default: that.warn('bad_wrap'); } } else if (!value.arity) { if (!option.closure || !that.comments) { // that.warn('unexpected_a', that); that.stop('unexpected_a', that); } } return value; }); infix('.', 170, function (left, that) { no_space(prev_token, token); no_space(); var name = identifier(); if (typeof name === 'string') { tally_property(name); if (isReserved(name) && next_token.string !== '(') { token.warn('braket_notation', name); } } if(typeof name === 'string' && anonname === 'this' && name === 'inherited') { funct['hasInherited'] = true; } var line = lines[token.line - 1] || ''; if(typeof name === 'string' && anonname === 'this' && name === '_started' && ~line.indexOf('if(')) { funct['hasStartedIf'] = true; } if(typeof name === 'string' && option.dojo && (name === 'hitch' || name === 'partial') && funct['loopage']) { token.warn('hitch_loop'); } that.first = left; that.second = token; if (left && left.string === 'arguments' && (name === 'callee' || name === 'caller')) { left.warn('avoid_a', 'arguments.' + name); } else if (!option.evil && left && left.string === 'document' && (name === 'write' || name === 'writeln')) { left.warn('write_is_wrong'); } else if (!option.stupid && syx.test(name)) { token.warn('sync_a'); } else if (left && left.id === '{') { that.warn('unexpected_a'); } if (!option.evil && (name === 'eval' || name === 'execScript')) { next_token.warn('evil'); } return that; }, true); infix('[', 170, function (left, that) { var e, s; no_space_only(prev_token, token); no_space(); step_in(); edge(); e = expression(0); switch (e.id) { case '(number)': if (e.id === '(number)' && left.id === 'arguments') { left.warn('use_param'); } break; case '(string)': if (!option.evil && (e.string === 'eval' || e.string === 'execScript')) { e.warn('evil'); } else if (!option.sub && ix.test(e.string)) { s = syntax[e.string]; if (!s || !s.reserved) { e.warn('subscript'); } } tally_property(e.string); break; } if (left && (left.id === '{' || (left.id === '[' && left.arity === 'prefix'))) { that.warn('unexpected_a'); } step_out(']', that); no_space(prev_token, token); that.first = left; that.second = e; return that; }, true); prefix('[', function (that) { no_space(); that.first = []; step_in('array'); while (next_token.id !== '(end)') { while (next_token.id === ',') { // next_token.warn('unexpected_a'); next_token.stop('unexpected_a'); advance(','); } if (next_token.id === ']') { break; } indent.wrap = false; edge(); that.first.push(expression(10)); if (next_token.id === ',') { comma(); if (next_token.id === ']') { // token.warn('unexpected_a'); token.stop('unexpected_a'); break; } } else { break; } } no_space(); step_out(']', that); return that; }, 170); function property_name() { var id = optional_identifier(); if (!id) { if (next_token.id === '(string)') { id = next_token.string; advance(); } else if (next_token.id === '(number)') { id = next_token.number.toString(); advance(); } } return id; } assignop('='); assignop('+=', '+'); assignop('-=', '-'); assignop('*=', '*'); assignop('/=', '/').nud = function () { next_token.stop('slash_equal'); }; assignop('%=', '%'); assignop('&=', '&'); assignop('|=', '|'); assignop('^=', '^'); assignop('<<=', '<<'); assignop('>>=', '>>'); assignop('>>>=', '>>>'); function function_parameters() { var id, parameters = [], paren = next_token; advance('('); token.function = funct; step_in(); no_space(); if (next_token.id !== ')') { for (;;) { edge(); id = identifier(); if (token.reserved) { token.warn('expected_identifier_a_reserved'); } define('parameter', token); parameters.push(id); token.init = true; token.writeable = true; if (next_token.id !== ',') { break; } comma(); } } no_space(); step_out(')', paren); return parameters; } function search_vars(f) { var s = []; if(f.id === '&&' || f.id === '||' || f.id === '!') { if(f.first) { s = s.concat(search_vars(f.first)); if(f.second) { s = s.concat(search_vars(f.second)); } } } else if(!f.arity) { s.push(f.string); } return s; } function get_function_args(f) { var i, r = []; f = f || funct; for(i = 0; i < f['parameter'].length; i++) { r.push(f['parameter'][i].string || f['parameter'][i]); } return r; } function do_function(func, name) { var filter, if_var, ok, i; var old_funct = funct, old_option = option, old_scope = scope; scope = Object.create(old_scope); anonname = prev_token.id !== ':' && prev_token.id !== '=' ? '' : anonname; funct = { closure: [], global: [], level: old_funct.level + 1, line: next_token.line, loopage: 0, name: name || '\'' + (anonname || '').replace(nx, sanitize) + '\'', outer: [], scope: scope }; funct.parameter = function_parameters(); func.function = funct; option = Object.create(old_option); functions.push(funct); if (name) { func.name = name; func.string = name; define('function', func); func.init = true; func.used += 1; } func.writeable = false; one_space(); func.block = block('function'); if (option.dojo) { if(func.block.length > 0 && typeof func.block[0] === 'object' && func.block[0].string === 'if' && !func.block[0].else) { filter = func.block[0].first; if_var = search_vars(filter); var fncArgs = ',' + get_function_args(funct).join(',') + ','; ok = 0; for(i = 0; i < if_var.length; i++) { if(fncArgs.indexOf(',' + if_var[i] + ',') !== -1) { ok++; } } funct['all_arguments_tested'] = ok === funct['parameter'].length; } else if(funct['parameter'].length > 0) { funct['all_arguments_tested'] = false; } } Object.keys(scope).forEach(function (name) { var master = scope[name]; if (!master.used && master.kind !== 'exception' && (master.kind !== 'parameter' || !option.unparam)) { // master.warn('unused_a'); if (name.toLowerCase().indexOf('dummy') === -1 && name !== 'require') { master.warn('use_dummy', 0, name); } } else if (!master.init) { master.warn('uninitialized_a'); } if (master.used && name.toLowerCase().indexOf('dummy') !== -1) { master.warn('do_not_use_dummy', 0, name); } }); funct = old_funct; option = old_option; scope = old_scope; } prefix('{', function (that) { var get, i, j, name, set, seen = Object.create(null); that.first = []; step_in(); while (next_token.id !== '}') { indent.wrap = false; // JSLint recognizes the ES5 extension for get/set in object literals, // but requires that they be used in pairs. edge(); if (next_token.string === 'get' && peek().id !== ':') { get = next_token; advance('get'); one_space_only(); name = next_token; i = property_name(); if (!i) { next_token.stop('missing_property'); } get.string = ''; do_function(get); if (funct.loopage) { get.warn('function_loop'); } if (get.function.parameter.length) { get.warn('parameter_a_get_b', get.function.parameter[0], i); } comma(); set = next_token; spaces(); edge(); advance('set'); set.string = ''; one_space_only(); j = property_name(); if (i !== j) { token.stop('expected_a_b', i, j || next_token.string); } do_function(set); if (set.block.length === 0) { token.warn('missing_a', 'throw'); } if (set.function.parameter.length === 0) { set.stop('parameter_set_a', 'value'); } else if (set.function.parameter[0] !== 'value') { set.stop('expected_a_b', 'value', set.function.parameter[0]); } name.first = [get, set]; } else { name = next_token; i = property_name(); if (typeof i !== 'string') { next_token.stop('missing_property'); } no_space_only(); advance(':'); spaces(); name.first = expression(10); } if (option.camelcase && name.string.indexOf('$') === -1 && name.string.replace(/^_+/, "").indexOf("_") > -1 && !name.string.match(/^[A-Z0-9_]*$/)) { if(!option.camelcase_deviations[name.string]) { token.warn('use_camel_case', name.string); } } if (option.unquote && name.quote && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(name.string) && !isReserved(name.string)) { token.warn('remove_quote', name.string); } if (isReserved(name.string) && !name.quote) { token.warn('expected_identifier_a_reserved', name.string); } that.first.push(name); if (seen[i] === true) { next_token.warn('duplicate_a', i); } seen[i] = true; tally_property(i); if (next_token.id !== ',') { break; } for (;;) { comma(); if (next_token.id !== ',') { break; } // next_token.warn('unexpected_a'); next_token.stop('unexpected_a'); } if (next_token.id === '}') { // token.warn('unexpected_a'); token.stop('unexpected_a'); } } step_out('}', that); return that; }); stmt('{', function () { next_token.warn('statement_block'); this.arity = 'statement'; this.block = statements(); this.disrupt = this.block.disrupt; advance('}', this); return this; }); stmt('jslint_version', function () { stop('i_jslint_version', token, itself.edition); this.arity = 'statement'; return this; }); //stmt('/*global', directive); //stmt('/*globals', directive); //stmt('/*jslint', directive); //stmt('/*member', directive); //stmt('/*members', directive); //stmt('/*property', directive); //stmt('/*properties', directive); stmt('var', function () { // JavaScript does not have block scope. It only has function scope. So, // declaring a variable in a block can have unexpected consequences. // var.first will contain an array, the array containing name tokens // and assignment tokens. var assign, id, name; //if (funct.loopage) { if (funct.loopage && funct.dojoloop !== funct.loopage) { next_token.warn('var_loop'); } else if (funct.varstatement && !option.vars) { next_token.warn('combine_var'); } if (funct !== global_funct) { funct.varstatement = true; } this.arity = 'statement'; this.first = []; step_in('var'); for (;;) { name = next_token; id = identifier(true); define('var', name); name.dead = funct; if (next_token.id === '=') { if (funct === global_funct && !name.writeable) { name.warn('read_only'); } assign = next_token; assign.first = name; spaces(); advance('='); spaces(); assign.ben_next = next_token.string; if (next_token.id === 'undefined') { token.warn('unnecessary_initialize', id); } if (peek(0).id === '=' && next_token.identifier) { next_token.stop('var_a_not'); } if(option.dojo && (peek(0).id === ',' || peek(0).id === ';') && assign.ben_next === 'this') { token.warn('i_do_not_copy_context', id); } assign.second = expression(0); assign.arity = 'infix'; name.init = true; this.first.push(assign); } else { this.first.push(name); } name.dead = false; name.writeable = true; if (next_token.id !== ',') { break; } comma(); indent.wrap = false; if (var_mode && next_token.line === token.line && this.first.length === 1) { var_mode = null; indent.open = false; indent.at -= option.indent; } spaces(); edge(); } var_mode = null; step_out(); return this; }); stmt('function', function () { one_space(); if (in_block) { token.warn('function_block'); } var name = next_token, id = identifier(true); define('var', name); if (!name.writeable) { name.warn('read_only'); } name.init = true; name.statement = true; no_space(); this.arity = 'statement'; do_function(this, id); if (next_token.id === '(' && next_token.line === token.line) { next_token.stop('function_statement'); } return this; }); prefix('function', function (that) { if(next_token.id === '(') { no_space_only(); } var id = optional_identifier(true), name; if (id) { name = token; // no_space(); no_space_only(); } else { id = ''; // one_space(); no_space_only(); } var lineIndex = token.line, line = lines[token.line - 1] || '', nextline = lines[lineIndex] || '', nextnextline = lines[token.line + 1] || '', hasNoComment = function(a, b) { return (/\/\/[ ]summary:$/.test(a) === false || /\/\/\t\t.*/.test(b) === false); }; //check if it's a function defined in an object //and if the next line is a dojo comment: //summary //and if next next line repect the dojo comment model: // description if(option.dojo_comments && option.dojo && /[a-zA-Z0-9\-_]:[ ]function/.test(line) && hasNoComment(nextline, nextnextline)) { //check only public (and not lifeCycle) var lmatch = line.match(/\s+([a-z-A-Z0-9][a-zA-Z0-9\-_]*):[ ]function/), lcycle = ',' + dojo.lifecycle.join(',') + ','; if(lmatch !== null && lmatch[1] && lcycle.indexOf(',' + lmatch[1] + ',') === -1) { token.warn('i_uncommented_function'); } } if(option.anonymousFunctions && /: function/.test(line) === true && /function\(/.test(line) === false) { token.warn('function_anonymous'); } itself.functionCount = itself.functionCount || 0; if(option.dojo_comments && option.dojo && itself.functionCount === 0) { if(line.indexOf('{') === -1) { //first go to the line where the function start, then search for comments while(line.indexOf('{') === -1) { line = lines[lineIndex++] || false; if(line === false) { break; } } nextline = lines[lineIndex] || '' } while(nextline.replace(/\s/g, '') === '') { nextline = lines[++lineIndex] || false; if(nextline === false) { break; } } nextnextline = lines[++lineIndex]; if(hasNoComment(nextline, nextnextline)) { token.warn('i_uncommented_package'); } } itself.functionCount++; do_function(that, id); if (name) { name.function = that.function; } if (funct.loopage) { that.warn('function_loop'); } switch (next_token.id) { case ';': case '(': case ')': case ',': case ']': case '}': case ':': case '(end)': break; case '.': if (peek().string !== 'bind' || peek(1).id !== '(') { // next_token.warn('unexpected_a'); next_token.stop('unexpected_a'); } break; default: next_token.stop('unexpected_a'); } that.arity = 'function'; return that; }); stmt('if', function () { var paren = next_token; //one_space(); no_space_only(); advance('('); step_in('control'); no_space(); edge(); this.arity = 'statement'; this.first = expected_condition(expected_relation(expression(0))); no_space(); step_out(')', paren); one_space(); this.block = block('if'); if (next_token.id === 'else') { if (this.block.disrupt) { next_token.warn(this.elif ? 'use_nested_if' : 'unnecessary_else'); } one_space(); advance('else'); one_space(); if (next_token.id === 'if') { next_token.elif = true; this.else = statement(true); } else { this.else = block('else'); } if (this.else.disrupt && this.block.disrupt) { this.disrupt = true; } } return this; }); stmt('try', function () { // try.first The catch variable // try.second The catch clause // try.third The finally clause // try.block The try block var exception_variable, paren; one_space(); //no_space(); this.arity = 'statement'; this.block = block('try'); if (next_token.id === 'catch') { // one_space(); advance('catch'); // one_space(); no_space_only(); paren = next_token; advance('('); step_in('control'); no_space(); edge(); exception_variable = next_token; this.first = identifier(); define('exception', exception_variable); exception_variable.init = true; no_space(); step_out(')', paren); one_space(); this.second = block('catch'); if (this.second.length) { if (this.first === 'ignore') { exception_variable.warn('unexpected_a'); } } else { if (this.first !== 'ignore') { exception_variable.warn('expected_a_b', 'ignore', exception_variable.string); } } exception_variable.dead = true; } if (next_token.id === 'finally') { one_space(); advance('finally'); one_space(); this.third = block('finally'); } else if (!this.second) { next_token.stop('expected_a_b', 'catch', artifact()); } return this; }); labeled_stmt('while', function () { //one_space(); no_space_only(); var paren = next_token; funct.loopage += 1; advance('('); step_in('control'); no_space(); edge(); this.arity = 'statement'; this.first = expected_relation(expression(0)); if (this.first.id !== 'true') { expected_condition(this.first, 'unexpected_a'); } no_space(); step_out(')', paren); one_space(); this.block = block('while'); if (this.block.disrupt) { prev_token.warn('strange_loop'); } funct.loopage -= 1; return this; }); reserve('with'); labeled_stmt('switch', function () { // switch.first the switch expression // switch.second the array of cases. A case is 'case' or 'default' token: // case.first the array of case expressions // case.second the array of statements // If all of the arrays of statements are disrupt, then the switch is disrupt. var cases = [], old_in_block = in_block, particular, that = token, the_case = next_token; function find_duplicate_case(value) { if (are_similar(particular, value)) { value.warn('duplicate_a'); } } //one_space(); no_space_only(); advance('('); no_space(); step_in(); this.arity = 'statement'; this.first = expected_condition(expected_relation(expression(0))); no_space(); step_out(')', the_case); one_space(); advance('{'); step_in(); in_block = true; this.second = []; if (that.from !== next_token.from && !option.white) { next_token.warn('expected_a_at_b_c', next_token.string, that.from, next_token.from); } while (next_token.id === 'case') { the_case = next_token; the_case.first = []; the_case.arity = 'case'; for (;;) { spaces(); edge('case'); advance('case'); one_space(); particular = expression(0); cases.forEach(find_duplicate_case); cases.push(particular); the_case.first.push(particular); if (particular.id === 'NaN') { // particular.warn('unexpected_a'); particular.stop('unexpected_a'); } no_space_only(); advance(':'); if (next_token.id !== 'case') { break; } } spaces(); the_case.second = statements(); if (the_case.second && the_case.second.length > 0) { if (!the_case.second[the_case.second.length - 1].disrupt) { next_token.warn('missing_a_after_b', 'break', 'case'); } } else { next_token.warn('empty_case'); } this.second.push(the_case); } if (this.second.length === 0) { next_token.warn('missing_a', 'case'); } if (next_token.id === 'default') { spaces(); the_case = next_token; the_case.arity = 'case'; edge('case'); advance('default'); no_space_only(); advance(':'); spaces(); the_case.second = statements(); if (the_case.second && the_case.second.length > 0) { this.disrupt = the_case.second[the_case.second.length - 1].disrupt; } else { the_case.warn('empty_case'); } this.second.push(the_case); } if (this.break) { this.disrupt = false; } spaces(); step_out('}', this); in_block = old_in_block; return this; }); prefix("this", function (that) { if(option.dojo) { //search for this.X.Y to check if Y is a private var line = lines[token.line - 1], attachpointError = false, txt = '', rFunction = /\.[a-zA-Z0-9_]+\.(_[a-zA-Z0-9]+)/, rAttachPoint1 = /\.[a-zA-Z0-9_]+\.([a-zA-Z0-9_]+Node)\s*[^a-zA-Z0-9\(]/, rAttachPoint2 = /\.[a-zA-Z0-9_]+\.([a-zA-Z0-9_]+Node)\s*$/; if (rFunction.test(line) && line.indexOf('._destroyed') === -1 && line.indexOf('._beingDestroyed') === -1) { //private call txt = line.match(rFunction)[1]; that.warn('illegal_private_call', txt); } else if(rAttachPoint1.test(line)){ txt = line.match(rAttachPoint1)[1]; attachpointError = true; } else if(rAttachPoint2.test(line)){ txt = line.match(rAttachPoint2)[1]; attachpointError = true; } if(attachpointError && line.indexOf(".domNode") === -1 && line.indexOf(".parentNode") === -1 && line.indexOf("this.containerNode") === -1 ) { that.warn('illegal_attach_point_call', txt); } } that.arity = 'ben'; return that; }); stmt('debugger', function () { if (!option.debug) { // this.warn('unexpected_a'); this.stop('unexpected_a'); } this.arity = 'statement'; return this; }); labeled_stmt('do', function () { funct.loopage += 1; one_space(); this.arity = 'statement'; this.block = block('do'); if (this.block.disrupt) { prev_token.warn('strange_loop'); } one_space(); advance('while'); var paren = next_token; one_space(); advance('('); step_in(); no_space(); edge(); this.first = expected_condition(expected_relation(expression(0)), 'unexpected_a'); no_space(); step_out(')', paren); funct.loopage -= 1; return this; }); labeled_stmt('for', function () { var blok, filter, master, ok = false, paren = next_token, value; this.arity = 'statement'; funct.loopage += 1; advance('('); if (next_token.id === ';') { no_space(); advance(';'); no_space(); advance(';'); no_space(); advance(')'); blok = block('for'); } else { step_in('control'); //spaces(this, paren); no_space_only(this, paren); no_space(); if (next_token.id === 'var') { next_token.stop('move_var'); } edge(); if (peek(0).id === 'in') { this.forin = true; value = expression(1000); master = value.master; if (!master) { value.stop('bad_in_a'); } if (master.kind !== 'var' || master.function !== funct || !master.writeable || master.dead) { value.warn('bad_in_a'); } master.init = true; master.used -= 1; this.first = value; advance('in'); this.second = expression(20); step_out(')', paren); blok = block('for'); if (!option.forin) { if (blok.length === 1 && typeof blok[0] === 'object') { if (blok[0].id === 'if' && !blok[0].else) { filter = blok[0].first; while (filter.id === '&&') { filter = filter.first; } switch (filter.id) { case '===': case '!==': ok = filter.first.id === '[' ? are_similar(filter.first.first, this.second) && are_similar(filter.first.second, this.first) : filter.first.id === 'typeof' && filter.first.first.id === '[' && are_similar(filter.first.first.first, this.second) && are_similar(filter.first.first.second, this.first); break; case '(': ok = filter.first.id === '.' && (( are_similar(filter.first.first, this.second) && filter.first.second.string === 'hasOwnProperty' && are_similar(filter.second[0], this.first) ) || ( filter.first.first.id === '.' && filter.first.first.first.first && filter.first.first.first.first.string === 'Object' && filter.first.first.first.id === '.' && filter.first.first.first.second.string === 'prototype' && filter.first.first.second.string === 'hasOwnProperty' && filter.first.second.string === 'call' && are_similar(filter.second[0], this.second) && are_similar(filter.second[1], this.first) )); break; } } else if (blok[0].id === 'switch') { ok = blok[0].id === 'switch' && blok[0].first.id === 'typeof' && blok[0].first.first.id === '[' && are_similar(blok[0].first.first.first, this.second) && are_similar(blok[0].first.first.second, this.first); } } if (!ok) { this.warn('for_if'); } } } else { edge(); this.first = []; for (;;) { this.first.push(expression(0, 'for')); if (next_token.id !== ',') { break; } comma(); } semicolon(); edge(); this.second = expected_relation(expression(0)); if (this.second.id !== 'true') { expected_condition(this.second, 'unexpected_a'); } semicolon(token); if (next_token.id === ';') { next_token.stop('expected_a_b', ')', ';'); } this.third = []; edge(); for (;;) { this.third.push(expression(0, 'for')); if (next_token.id !== ',') { break; } comma(); } no_space(); step_out(')', paren); one_space(); blok = block('for'); } } if (blok.disrupt) { prev_token.warn('strange_loop'); } this.block = blok; funct.loopage -= 1; return this; }); function optional_label(that) { var label = next_token.string, master; that.arity = 'statement'; if (!funct.breakage || (!option.continue && that.id === 'continue')) { // that.warn('unexpected_a'); that.stop('unexpected_a'); } else if (next_token.identifier && token.line === next_token.line) { one_space_only(); master = scope[label]; if (!master || master.kind !== 'label') { next_token.warn('not_a_label'); } else if (master.dead || master.function !== funct) { next_token.warn('not_a_scope'); } else { master.used += 1; if (that.id === 'break') { master.statement.break = true; } if (funct.breakage[funct.breakage.length - 1] === master.statement) { // next_token.warn('unexpected_a'); next_token.stop('unexpected_a'); } } that.first = next_token; advance(); } else { if (that.id === 'break') { funct.breakage[funct.breakage.length - 1].break = true; } } return that; } disrupt_stmt('break', function () { return optional_label(this); }); disrupt_stmt('continue', function () { return optional_label(this); }); disrupt_stmt('return', function () { if (funct === global_funct) { // this.warn('unexpected_a'); this.stop('unexpected_a'); } this.arity = 'statement'; if (next_token.id !== ';' && next_token.line === token.line) { if (option.closure) { spaces(); } else { one_space_only(); } if (next_token.id === '/' || next_token.id === '(regexp)') { next_token.warn('wrap_regexp'); } this.first = expression(0); if (this.first.assign) { // this.first.warn('unexpected_a'); this.first.stop('unexpected_a'); } } funct['hasReturn'] = true; return this; }); disrupt_stmt('throw', function () { this.arity = 'statement'; one_space_only(); this.first = expression(20); return this; }); // Superfluous reserved words reserve('class'); reserve('const'); reserve('enum'); reserve('export'); reserve('extends'); reserve('import'); reserve('super'); // Harmony reserved words reserve('implements'); reserve('interface'); reserve('let'); reserve('package'); reserve('private'); reserve('protected'); reserve('public'); reserve('static'); reserve('yield'); // Parse JSON function json_value() { function json_object() { var brace = next_token, object = Object.create(null); advance('{'); if (next_token.id !== '}') { while (next_token.id !== '(end)') { while (next_token.id === ',') { // next_token.warn('unexpected_a'); next_token.stop('unexpected_a'); advance(','); } if (next_token.id !== '(string)') { next_token.warn('expected_string_a'); } if (object[next_token.string] === true) { next_token.warn('duplicate_a'); } else if (next_token.string === '__proto__') { next_token.warn('dangling_a'); } else { object[next_token.string] = true; } no_space_only(); advance(); advance(':'); json_value(); if (next_token.id !== ',') { break; } advance(','); if (next_token.id === '}') { // token.warn('unexpected_a'); token.stop('unexpected_a'); break; } } } advance('}', brace); } function json_array() { var bracket = next_token; advance('['); if (next_token.id !== ']') { while (next_token.id !== '(end)') { while (next_token.id === ',') { // next_token.warn('unexpected_a'); next_token.stop('unexpected_a'); advance(','); } json_value(); if (next_token.id !== ',') { break; } advance(','); if (next_token.id === ']') { // token.warn('unexpected_a'); token.stop('unexpected_a'); break; } } } advance(']', bracket); } switch (next_token.id) { case '{': json_object(); break; case '[': json_array(); break; case 'true': case 'false': case 'null': case '(number)': case '(string)': advance(); break; case '-': advance('-'); no_space_only(); advance('(number)'); break; default: next_token.stop('unexpected_a'); } } // The actual JSLINT function itself. itself = function JSLint(the_source, the_option) { //force using custom set of options : the_option = true; itself.functionCount = 0; dojo.alreadyWarnedForDeprecated = null; dojo.stringsInCode = {}; var i, predef, tree; itself.errors = []; itself.tree = ''; itself.properties = ''; begin = prev_token = token = next_token = Object.create(syntax['(begin)']); tokens = []; predefined = Object.create(null); add_to_predefined(standard); property = Object.create(null); if (the_option) { // option = Object.create(the_option); option = OPTIONS; predef = option.predef; if (predef) { if (Array.isArray(predef)) { for (i = 0; i < predef.length; i += 1) { predefined[predef[i]] = true; } } else if (typeof predef === 'object') { add_to_predefined(predef); } } } else { option = Object.create(null); } option.indent = +option.indent || 4; option.maxerr = +option.maxerr || 50; global_scope = scope = Object.create(null); global_funct = funct = { scope: scope, loopage: 0, level: 0 }; functions = [funct]; block_var = []; comments = []; comments_off = false; in_block = false; indent = null; json_mode = false; lookahead = []; node_js = false; prereg = true; strict_mode = false; var_mode = null; warnings = 0; lex.init(the_source); assume(); try { advance(); if (next_token.id === '(number)') { next_token.stop('unexpected_a'); } else { switch (next_token.id) { case '{': case '[': comments_off = true; json_mode = true; json_value(); break; default: // If the first token is a semicolon, ignore it. This is sometimes used when // files are intended to be appended to files that may be sloppy. A sloppy // file may be depending on semicolon insertion on its last line. step_in(1); if (next_token.id === ';' && !node_js) { next_token.edge = true; advance(';'); } tree = statements(); begin.first = tree; itself.tree = begin; if (tree.disrupt) { prev_token.warn('weird_program'); } } } indent = null; advance('(end)'); itself.property = property; itself.warnUnused(); } catch (e) { if (e) { // ~~ itself.errors.push({ reason : e.message, line : e.line || next_token.line, character : e.character || next_token.from }, null); } } return itself.errors.length === 0; }; itself.warnUnused = function() { var function_data, i, j, kind, name, the_function, set_list = [], get_list = []; for (i = 1; i < functions.length; i += 1) { the_function = functions[i]; function_data = { name: [], line: [], label: [], parameter: [] }; //for (j = 0; j < functionicity.length; j += 1) { // function_data[functionicity[j]] = []; //} if(option.dojo) { var minherits = dojo.mustInherits.concat(option.mustInherits || []); minherits = ',' + minherits.join(",") + ','; var ninherits = ',' + dojo.neverInherits.join(",") + ','; var mteststarted = ',' + dojo.mustTestStarted.join(",") + ','; var dojoProtected = ',' + dojo.dojoProtected.join(",") + ','; var mustcheckargs = ',' + dojo.mustcheckargs.join(",") + ','; var fncRealName = the_function['name'].replace(/'/g,''); var fncSepName = ',' + fncRealName + ','; if(the_function.all_arguments_tested === false && mustcheckargs.indexOf(fncSepName) !== -1 ) { warn('dojo_test_arguments', the_function['line'], 0, get_function_args(the_function).join(', '), fncRealName); } if(!the_function.hasInherited && minherits.indexOf(fncSepName) !== -1 ) { warn('missing_inherited', the_function['line'], 0, fncRealName); } if(the_function.hasInherited && ninherits.indexOf(fncSepName) !== -1 ) { warn('no_inherited', the_function['line'], 0, fncRealName); } if(!the_function.hasStartedIf && mteststarted.indexOf(fncSepName) !== -1 ) { warn('missing_started_test', the_function['line'], 0, fncRealName); } if(dojoProtected.indexOf(fncSepName) !== -1 ) { warn('dojo_protected_name', the_function['line'], 0, fncRealName); } //in case of getter/setter if(/_[gs]et[a-zA-Z0-9_]+Attr/.test(fncRealName)) { if(option.dojo_inheritedgetset && !the_function.hasInherited) { warn('should_use_inherited', the_function['line'], 0, fncRealName); } if(!the_function.hasReturn) { warn('must_return', the_function['line'], 0, fncRealName); } if(the_function['parameter'].length !== 0 && /_get[a-zA-Z0-9_]+Attr/.test(fncRealName) ) { warn('expect_no_arg', the_function['line'], 0); } if(the_function['parameter'].length !== 1 && /_set[a-zA-Z0-9_]+Attr/.test(fncRealName) ) { warn('expect_one_arg', the_function['line'], 0); } if(the_function['parameter'].length === 1 && /_set[a-zA-Z0-9_]+Attr/.test(fncRealName) ) { var propertyToSet = fncRealName.replace('_set', '').replace('Attr', ''); propertyToSet = propertyToSet.charAt(0).toLowerCase() + propertyToSet.substr(1); if(the_function['parameter'][0] !== propertyToSet) { warn('expect_arg_named_as_setter', the_function['line'], 0, the_function['parameter'][0], propertyToSet); } } } if(option.dojo_getset) { if(/_set[a-zA-Z0-9_]+Attr/.test(fncRealName)) { set_list.push({root:fncRealName.replace(/_set|_get/, '') ,name: fncRealName, line: the_function['line']}); } if(/_get[a-zA-Z0-9_]+Attr/.test(fncRealName)) { get_list.push({root:fncRealName.replace(/_set|_get/, '') ,name: fncRealName, line: the_function['line']}); } } } } if(option.dojo_getset && option.dojo) { var s = function(a, b) { if(a.root > b.root) { return 1; } if(a.root < b.root) { return -1; } return 0; }, c = set_list.concat(get_list); c = c.sort(s); var i; for(i = 0; i < c.length - 1; i++) { if(c[i].root === c[i+1].root) { i++; continue; } warn('get_or_set_is_missing', c[i].line, 0); } } }; function unique(array) { array = array.sort(); var i, length = 0, previous, value; for (i = 0; i < array.length; i += 1) { value = array[i]; if (value !== previous) { array[length] = value; previous = value; length += 1; } } array.length = length; return array; } // Data summary. itself.data = function () { var data = {functions: []}, function_data, i, the_function, the_scope; data.errors = itself.errors; data.json = json_mode; data.global = unique(Object.keys(global_scope)); function selects(name) { var kind = the_scope[name].kind; switch (kind) { case 'var': case 'exception': case 'label': function_data[kind].push(name); break; } } for (i = 1; i < functions.length; i += 1) { the_function = functions[i]; function_data = { name: the_function.name, line: the_function.line, level: the_function.level, parameter: the_function.parameter, var: [], exception: [], closure: unique(the_function.closure), outer: unique(the_function.outer), global: unique(the_function.global), label: [] }; the_scope = the_function.scope; Object.keys(the_scope).forEach(selects); function_data.var.sort(); function_data.exception.sort(); function_data.label.sort(); data.functions.push(function_data); } data.tokens = tokens; return data; }; itself.error_report = function (data) { var evidence, i, output = [], warning; if (data.errors.length) { if (data.json) { output.push('<cite>JSON: bad.</cite><br>'); } for (i = 0; i < data.errors.length; i += 1) { warning = data.errors[i]; if (warning) { evidence = warning.evidence || ''; output.push('<cite>'); if (isFinite(warning.line)) { output.push('<address>line ' + String(warning.line) + ' character ' + String(warning.character) + '</address>'); } output.push(warning.reason.entityify() + '</cite>'); if (evidence) { output.push('<pre>' + evidence.entityify() + '</pre>'); } } } } return output.join(''); }; itself.report = function (data) { var dl, i, j, names, output = [], the_function; function detail(h, array) { var comma_needed = false; if (array.length) { output.push("<dt>" + h + "</dt><dd>"); array.forEach(function (item) { output.push((comma_needed ? ', ' : '') + item); comma_needed = true; }); output.push("</dd>"); } } output.push('<dl class=level0>'); if (data.global.length) { detail('global', data.global); dl = true; } else if (data.json) { if (!data.errors.length) { output.push("<dt>JSON: good.</dt>"); } } else { output.push("<dt><i>No new global variables introduced.</i></dt>"); } if (dl) { output.push("</dl>"); } else { output[0] = ''; } if (data.functions) { for (i = 0; i < data.functions.length; i += 1) { the_function = data.functions[i]; names = []; if (the_function.params) { for (j = 0; j < the_function.params.length; j += 1) { names[j] = the_function.params[j].string; } } output.push('<dl class=level' + the_function.level + '><address>line ' + String(the_function.line) + '</address>' + the_function.name.entityify()); detail('parameter', the_function.parameter); detail('variable', the_function.var); detail('exception', the_function.exception); detail('closure', the_function.closure); detail('outer', the_function.outer); detail('global', the_function.global); detail('label', the_function.label); output.push('</dl>'); } } return output.join(''); }; itself.properties_report = function (property) { if (!property) { return ''; } var i, key, keys = Object.keys(property).sort(), mem = ' ', name, not_first = false, output = ['/*properties']; for (i = 0; i < keys.length; i += 1) { key = keys[i]; if (property[key] > 0) { if (not_first) { mem += ','; } name = ix.test(key) ? key : '\'' + key.replace(nx, sanitize) + '\''; if (mem.length + name.length >= 80) { output.push(mem); mem = ' '; } else { mem += ' '; } mem += name; not_first = true; } } output.push(mem, '*/\n'); return output.join('\n'); }; itself.color = function (data) { var from, i = 1, level, line, result = [], thru, data_token = data.tokens[0]; while (data_token && data_token.id !== '(end)') { from = data_token.from; line = data_token.line; thru = data_token.thru; level = data_token.function.level; do { thru = data_token.thru; data_token = data.tokens[i]; i += 1; } while (data_token && data_token.line === line && data_token.from - thru < 5 && level === data_token.function.level); result.push({ line: line, level: level, from: from, thru: thru }); } return result; }; itself.jslint = itself; itself.edition = '2014-07-08'; return itself; }()); try { module.exports = JSLINT; } catch(e) {}
ben8p/smallEditor
res/linter/jslint.js
JavaScript
gpl-2.0
176,648
<?php global $wpdb; $deleghe = $wpdb->get_results( $wpdb->prepare("select descrizione from wp_cm_deleghe", ARRAY_A) ); ?> <a href="#" id="selectComplessaFiltro" class="selectComplessa"><div class="divLinkSelectEvoluta" id="divLinkSelectEvoluta" nome="divLinkSelectEvoluta">Deleghe</div> <div class="contentFrecciaSelectFiltri contentFrecciaSelectDeleghe" id="contentFrecciaSelectFiltri" nome="contentFrecciaSelectFiltri"><img src="http://localhost/ComunichereteV3/wp-content/plugins/wp-wg-ricerca-utente/img/freccia.png" class="freccia"></div> </a> <div class="cm_deleghe" id="cm_deleghe" name="cm_deleghe"> <div id="cm_apriDelegheGov" class="cm_apriDelegheGov"> <ol class="facet-valuesDeleghe"> <?php foreach ( $deleghe as $chiave => $valore) : ?> <li class="facet-value"><input type="checkbox" name="deleghe[]" value="<?php echo esc_attr( $valore -> descrizione ); ?>" /> <div class="label-container"> <label class="facet-label" title="<?php echo esc_attr( $valore-> descrizione ); ?>" ><?php echo esc_attr( $valore-> descrizione ); ?></label> </div> </li> <?php endforeach; ?> </ol> </div> <div class="footerComboFiltro" id="footerComboFiltro"><a href="#" id="avviaRicercaDiv" class="avviaRicercaDiv">Affina Ricerca </a></div> </div>
fabrizio22/ComunichereteV3
wp-content/plugins/wp-wg-ricerca-utente/inc/qualifiche/comuni/cm_deleghe.php
PHP
gpl-2.0
1,409
<?php /** * The template for displaying archive pages. * * Learn more: http://codex.wordpress.org/Template_Hierarchy * * @package CorporateBusiness */ get_header(); ?> <div id="primary" class="content-area"> <main id="main" class="site-main" role="main"> <?php if ( have_posts() ) : ?> <header class="page-header"> <?php corporatebusiness_archive_title( '<h1 class="page-title">', '</h1>' ); corporatebusiness_archive_description( '<div class="taxonomy-description">', '</div>' ); ?> </header><!-- .page-header --> <?php /* Start the Loop */ ?> <?php while ( have_posts() ) : the_post(); ?> <?php /* Include the Post-Format-specific template for the content. * If you want to override this in a child theme, then include a file * called content-___.php (where ___ is the Post Format name) and that will be used instead. */ if ( get_theme_mod ( 'blog_view', '1' ) ) { get_template_part( 'content', 'blog' ); } else { get_template_part( 'content', get_post_format() );} ?> <?php endwhile; ?> <?php corporatebusiness_posts_navigation(); ?> <?php else : ?> <?php get_template_part( 'content', 'none' ); ?> <?php endif; ?> </main><!-- #main --> </div><!-- #primary --> <?php get_sidebar(); ?> <?php get_footer(); ?>
huraaa/stylo
wp-content/themes/corporatebusiness/archive.php
PHP
gpl-2.0
1,325
/** * @Copyright 2015 firefreak11 * * This file is part of PowderInJava. * * PowderInJava is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PowderInJava is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with PowderInJava. If not, see <http://www.gnu.org/licenses/>. **/ package powderinjava.elements; import powderinjava.Particle; import powderinjava.State; public class OXGN extends Element{ public OXGN(){ super(OXGN.class,State.GAS,0x7FE5D7,0,3.42f,true,false,"Oxygen. Creates water with hydrogen."); } public int update(int x,int y,Particle p){ if(elementAt(x,y)==HYGN&&(p.temp+Particle.particleAt(x,y).temp)/2>=400.0f){ changeType(p,WATR); changeType(Particle.particleAt(x,y),NONE); return 1; } return 0; } }
daveyognaught/powderinjava
src/powderinjava/elements/OXGN.java
Java
gpl-2.0
1,200
<?php /** * SunOS System Class * * PHP version 5 * * @category PHP * @package PSI_OS * @author Michael Cramer <BigMichi1@users.sourceforge.net> * @copyright 2009 phpSysInfo * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @version SVN: $Id: class.SunOS.inc.php 687 2012-09-06 20:54:49Z namiltd $ * @link http://phpsysinfo.sourceforge.net */ /** * SunOS sysinfo class * get all the required information from SunOS systems * * @category PHP * @package PSI_OS * @author Michael Cramer <BigMichi1@users.sourceforge.net> * @copyright 2009 phpSysInfo * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @version Release: 3.0 * @link http://phpsysinfo.sourceforge.net */ class SunOS extends OS { /** * add warning to errors */ public function __construct() { } /** * Extract kernel values via kstat() interface * * @param string $key key for kstat programm * * @return string */ private function _kstat($key) { if (CommonFunctions::executeProgram('kstat', '-p d '.$key, $m, PSI_DEBUG)) { list($key, $value) = preg_split("/\t/", trim($m), 2); return $value; } else { return ''; } } /** * Virtual Host Name * * @return void */ private function _hostname() { if (PSI_USE_VHOST === true) { $this->sys->setHostname(getenv('SERVER_NAME')); } else { if (CommonFunctions::executeProgram('uname', '-n', $result, PSI_DEBUG)) { $ip = gethostbyname($result); if ($ip != $result) { $this->sys->setHostname(gethostbyaddr($ip)); } } } } /** * IP of the Virtual Host Name * * @return void */ private function _ip() { if (PSI_USE_VHOST === true) { $this->sys->setIp(gethostbyname($this->sys->getHostname())); } else { if (!($result = getenv('SERVER_ADDR'))) { $this->sys->setIp(gethostbyname($this->sys->getHostname())); } else { $this->sys->setIp($result); } } } /** * Kernel Version * * @return void */ private function _kernel() { if (CommonFunctions::executeProgram('uname', '-s', $os, PSI_DEBUG)) { if (CommonFunctions::executeProgram('uname', '-r', $version, PSI_DEBUG)) { $this->sys->setKernel($os.' '.$version); } else { $this->sys->setKernel($os); } } } /** * UpTime * time the system is running * * @return void */ private function _uptime() { $this->sys->setUptime(time() - $this->_kstat('unix:0:system_misc:boot_time')); } /** * Number of Users * * @return void */ private function _users() { if (CommonFunctions::executeProgram('who', '-q', $buf, PSI_DEBUG)) { $who = preg_split('/=/', $buf); $this->sys->setUsers($who[1]); } } /** * Processor Load * optionally create a loadbar * * @return void */ private function _loadavg() { $load1 = $this->_kstat('unix:0:system_misc:avenrun_1min'); $load5 = $this->_kstat('unix:0:system_misc:avenrun_5min'); $load15 = $this->_kstat('unix:0:system_misc:avenrun_15min'); $this->sys->setLoad(round($load1 / 256, 2).' '.round($load5 / 256, 2).' '.round($load15 / 256, 2)); } /** * CPU information * * @return void */ private function _cpuinfo() { $dev = new CpuDevice(); if (CommonFunctions::executeProgram('uname', '-i', $buf, PSI_DEBUG)) { $dev->setModel(trim($buf)); } $dev->setCpuSpeed($this->_kstat('cpu_info:0:cpu_info0:clock_MHz')); $dev->setCache($this->_kstat('cpu_info:0:cpu_info0:cpu_type') * 1024); $this->sys->setCpus($dev); } /** * Network devices * * @return void */ private function _network() { if (CommonFunctions::executeProgram('netstat', '-ni | awk \'(NF ==10){print;}\'', $netstat, PSI_DEBUG)) { $lines = preg_split("/\n/", $netstat, -1, PREG_SPLIT_NO_EMPTY); foreach ($lines as $line) { $ar_buf = preg_split("/\s+/", $line); if (! empty($ar_buf[0]) && $ar_buf[0] !== 'Name') { $dev = new NetDevice(); $dev->setName($ar_buf[0]); $results[$ar_buf[0]]['errs'] = $ar_buf[5] + $ar_buf[7]; preg_match('/^(\D+)(\d+)$/', $ar_buf[0], $intf); $prefix = $intf[1].':'.$intf[2].':'.$intf[1].$intf[2].':'; $cnt = $this->_kstat($prefix.'drop'); if ($cnt > 0) { $dev->setDrops($cnt); } $cnt = $this->_kstat($prefix.'obytes64'); if ($cnt > 0) { $dev->setTxBytes($cnt); } $cnt = $this->_kstat($prefix.'rbytes64'); if ($cnt > 0) { $dev->setRxBytes($cnt); } $this->sys->setNetDevices($dev); } } } } /** * Physical memory information and Swap Space information * * @return void */ private function _memory() { $pagesize = $this->_kstat('unix:0:seg_cache:slab_size'); $this->sys->setMemTotal($this->_kstat('unix:0:system_pages:pagestotal') * $pagesize); $this->sys->setMemUsed($this->_kstat('unix:0:system_pages:pageslocked') * $pagesize); $this->sys->setMemFree($this->_kstat('unix:0:system_pages:pagesfree') * $pagesize); $dev = new DiskDevice(); $dev->setName('SWAP'); $dev->setFsType('swap'); $dev->setTotal($this->_kstat('unix:0:vminfo:swap_avail') / 1024); $dev->setUsed($this->_kstat('unix:0:vminfo:swap_alloc') / 1024); $dev->setFree($this->_kstat('unix:0:vminfo:swap_free') / 1024); $this->sys->setSwapDevices($dev); } /** * filesystem information * * @return void */ private function _filesystems() { if (CommonFunctions::executeProgram('df', '-k', $df, PSI_DEBUG)) { $mounts = preg_split("/\n/", $df, -1, PREG_SPLIT_NO_EMPTY); foreach ($mounts as $mount) { $ar_buf = preg_split('/\s+/', $mount, 6); $dev = new DiskDevice(); $dev->setName($ar_buf[0]); $dev->setTotal($ar_buf[1] * 1024); $dev->setUsed($ar_buf[2] * 1024); $dev->setFree($ar_buf[3] * 1024); $dev->setMountPoint($ar_buf[5]); if (CommonFunctions::executeProgram('df', '-n', $dftypes, PSI_DEBUG)) { $mounttypes = preg_split("/\n/", $dftypes, -1, PREG_SPLIT_NO_EMPTY); foreach ($mounttypes as $type) { $ty_buf = preg_split('/:/', $type, 2); if ($ty_buf == $dev->getName()) { $dev->setFsType($ty_buf[1]); break; } } } $this->sys->setDiskDevices($dev); } } } /** * Distribution Icon * * @return void */ private function _distro() { $this->sys->setDistribution('SunOS'); $this->sys->setDistributionIcon('SunOS.png'); } /** * get the information * * @see PSI_Interface_OS::build() * * @return Void */ function build() { $this->error->addError("WARN", "The SunOS version of phpSysInfo is work in progress, some things currently don't work"); $this->_hostname(); $this->_ip(); $this->_distro(); $this->_kernel(); $this->_uptime(); $this->_users(); $this->_loadavg(); $this->_cpuinfo(); $this->_network(); $this->_memory(); $this->_filesystems(); } } ?>
PieVo/power-meter
www/phpsysinfo/includes/os/class.SunOS.inc.php
PHP
gpl-2.0
8,440
using System; using System.IO; using Server; using Server.Commands; namespace Server.Misc { public class AutoSave : Timer { private static TimeSpan m_Delay = TimeSpan.FromMinutes( 1.0 ); private static TimeSpan m_Warning = TimeSpan.Zero; //private static TimeSpan m_Warning = TimeSpan.FromSeconds( 15.0 ); public static void Initialize() { new AutoSave().Start(); CommandSystem.Register( "SetSaves", AccessLevel.Administrator, new CommandEventHandler( SetSaves_OnCommand ) ); } private static bool m_SavesEnabled = true; public static bool SavesEnabled { get{ return m_SavesEnabled; } set{ m_SavesEnabled = value; } } [Usage( "SetSaves <true | false>" )] [Description( "Enables or disables automatic shard saving." )] public static void SetSaves_OnCommand( CommandEventArgs e ) { if ( e.Length == 1 ) { m_SavesEnabled = e.GetBoolean( 0 ); e.Mobile.SendMessage( "Saves have been {0}.", m_SavesEnabled ? "enabled" : "disabled" ); } else { e.Mobile.SendMessage( "Format: SetSaves <true | false>" ); } } public AutoSave() : base( m_Delay - m_Warning, m_Delay ) { Priority = TimerPriority.OneMinute; } protected override void OnTick() { if ( !m_SavesEnabled || AutoRestart.Restarting ) return; if ( m_Warning == TimeSpan.Zero ) { Save( true ); } else { int s = (int)m_Warning.TotalSeconds; int m = s / 60; s %= 60; if ( m > 0 && s > 0 ) World.Broadcast( 0x35, true, "The world will save in {0} minute{1} and {2} second{3}.", m, m != 1 ? "s" : "", s, s != 1 ? "s" : "" ); else if ( m > 0 ) World.Broadcast( 0x35, true, "The world will save in {0} minute{1}.", m, m != 1 ? "s" : "" ); else World.Broadcast( 0x35, true, "The world will save in {0} second{1}.", s, s != 1 ? "s" : "" ); Timer.DelayCall( m_Warning, new TimerCallback( Save ) ); } } public static void Save() { AutoSave.Save( false ); } public static void Save( bool permitBackgroundWrite ) { if ( AutoRestart.Restarting ) return; World.WaitForWriteCompletion(); try{ Backup(); } catch ( Exception e ) { Console.WriteLine("WARNING: Automatic backup FAILED: {0}", e); } World.Save( true, permitBackgroundWrite ); } private static string[] m_Backups = new string[] { "Third Backup", "Second Backup", "Most Recent" }; private static void Backup() { if ( m_Backups.Length == 0 ) return; string root = Path.Combine( Core.BaseDirectory, "Backups/Automatic" ); if ( !Directory.Exists( root ) ) Directory.CreateDirectory( root ); string[] existing = Directory.GetDirectories( root ); for ( int i = 0; i < m_Backups.Length; ++i ) { DirectoryInfo dir = Match( existing, m_Backups[i] ); if ( dir == null ) continue; if ( i > 0 ) { string timeStamp = FindTimeStamp( dir.Name ); if ( timeStamp != null ) { try{ dir.MoveTo( FormatDirectory( root, m_Backups[i - 1], timeStamp ) ); } catch{} } } else { try{ dir.Delete( true ); } catch{} } } string saves = Path.Combine( Core.BaseDirectory, "Saves" ); if ( Directory.Exists( saves ) ) Directory.Move( saves, FormatDirectory( root, m_Backups[m_Backups.Length - 1], GetTimeStamp() ) ); } private static DirectoryInfo Match( string[] paths, string match ) { for ( int i = 0; i < paths.Length; ++i ) { DirectoryInfo info = new DirectoryInfo( paths[i] ); if ( info.Name.StartsWith( match ) ) return info; } return null; } private static string FormatDirectory( string root, string name, string timeStamp ) { return Path.Combine( root, String.Format( "{0} ({1})", name, timeStamp ) ); } private static string FindTimeStamp( string input ) { int start = input.IndexOf( '(' ); if ( start >= 0 ) { int end = input.IndexOf( ')', ++start ); if ( end >= start ) return input.Substring( start, end-start ); } return null; } private static string GetTimeStamp() { DateTime now = DateTime.UtcNow; return String.Format( "{0}-{1}-{2} {3}-{4:D2}-{5:D2}", now.Day, now.Month, now.Year, now.Hour, now.Minute, now.Second ); } } }
mikedevita/server.ultimaonlineshard.com
Scripts/Misc/AutoSave.cs
C#
gpl-2.0
4,480
var model = (function () { var self = {}; self.Job = function() {//{{{ this.id = 0; this.index = 0; this.name = ''; this.parent = null; this.skill = {}; this.numskill = 0; };//}}} self.Skill = function() {//{{{ this.id = 0; this.job = null; this.name = ''; this.icon = 0; this.req_slevel = []; this.req_sp = []; this.index = 0; this.level = {}; this.numlevel = 0; this.ultimate = false; };//}}} self.SkillLevel = function() {//{{{ this.id = 0; this.level = 0; this.description_pve = ''; this.description_pvp = ''; this.req_level = 0; this.skill = null; this.sp_cost = 0; this.sp_cost_cumulative = 0; this.mp_cost_pve = 0; this.mp_cost_pvp = 0; this.cooldown_pve = 0; this.cooldown_pvp = 0; };//}}} self.job_byid = {}; self.job_byindx = []; self.skill_byid = {}; self.slevel_byid = {}; self.parse =function(response, char_level) {//{{{ console.debug("model.parse - enter"); var description = {}; var parent = []; var parse_job = function(obj) {//{{{ console.debug("model.parse.parse_job - enter"); var job = new self.Job(); job.id = obj.pk; job.name = obj.fields.name; job.index = obj.fields.number; // assumes jobs are sent __in_order__ job.parent = obj.fields.parent === null ? null : self.job_byid[obj.fields.parent]; self.job_byid[job.id] = job; self.job_byindx[job.index] = job; console.debug("model.parse.parse_job - exit"); };//}}} var parse_skill = function(obj) {//{{{ console.debug("model.parse.parse_skill - enter"); description[obj.pk] = obj.fields.description; for (var n=1; n<4; n++) { if (obj.fields['parent_'+n] !== null) { parent.push({ 'skill': obj.pk, 'slevel':obj.fields['parent_'+n] }); } } var skill = new self.Skill(); skill.id = obj.pk; skill.job = self.job_byid[obj.fields.job]; skill.name = obj.fields.name; skill.icon = obj.fields.icon; skill.index = obj.fields.tree_index; skill.ultimate = obj.fields.ultimate; for (n=0; obj.fields.hasOwnProperty('sp_required_'+n); n++) { skill.req_sp.push(obj.fields['sp_required_'+n]); } skill.job.skill[skill.index] = skill; skill.job.numskill += 1; self.skill_byid[skill.id] = skill; console.debug("model.parse.parse_skill - exit"); };//}}} var parse_slevel = function(obj, char_level) {//{{{ console.debug("model.parse.parse_slevel - enter"); var slevel = new self.SkillLevel(); var pve_description = description[obj.fields.skill]; var pvp_description = description[obj.fields.skill]; var pve_params = obj.fields.description_params_pve.split(','); var pvp_params = obj.fields.description_params_pvp.split(','); for (var n in pve_params) { pve_description = pve_description.replace('{'+n+'}', pve_params[n]); pvp_description = pvp_description.replace('{'+n+'}', pvp_params[n]); } slevel.id = obj.pk; slevel.level = obj.fields.level; slevel.description_pve = pve_description; slevel.description_pvp = pvp_description; slevel.req_level = obj.fields.required_level; slevel.skill = self.skill_byid[obj.fields.skill]; slevel.sp_cost = obj.fields.sp_cost; slevel.sp_cost_cumulative = obj.fields.sp_cost_cumulative; slevel.mp_cost_pve = obj.fields.mp_cost_pve; slevel.mp_cost_pvp = obj.fields.mp_cost_pvp; slevel.cooldown_pve = obj.fields.cooldown_pve; slevel.cooldown_pvp = obj.fields.cooldown_pvp; slevel.skill.level[slevel.level] = slevel; if (slevel.req_level <= char_level) { slevel.skill.numlevel += 1; } self.slevel_byid[slevel.id] = slevel; console.debug("model.parse.parse_slevel - exit"); };//}}} for (n in response) { var obj = response[n]; switch (obj.model) { case "skills.job": parse_job(obj); break; case "skills.skill": parse_skill(obj); break; case "skills.skilllevel": parse_slevel(obj, char_level); break; default: break; } } for (n in parent) { var skill = self.skill_byid[parent[n].skill]; skill.req_slevel.push(self.slevel_byid[parent[n].slevel]); } console.debug("model.parse - exit"); };//}}} return self; })();
kalhartt/yadnss
client-polymer/js/model.js
JavaScript
gpl-2.0
5,107
<?php /** * Element: Categoies Zoo * DEPRECATED! * * @package NoNumber Framework * @version 13.11.11 * * @author Peter van Westen <peter@nonumber.nl> * @link http://www.nonumber.nl * @copyright Copyright © 2013 NoNumber All Rights Reserved * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL */ defined('_JEXEC') or die; // For backwards compatibility require_once __DIR__ . '/zoo.php'; class JFormFieldNN_CategoriesZOO extends JFormFieldNN_ZOO { }
alons182/3monkiescr
tmp/install_527dce65a41c7/framework/framework/j2/plugins/system/nnframework/fields/categorieszoo.php
PHP
gpl-2.0
521
<?php $disable_switcher = theme_get_setting('judy_disable_switch', 'judy'); if(empty($disable_switcher)) $disable_switcher = 'on'; if(!empty($disable_switcher) && $disable_switcher=='on'){ ?> <?php global $base_url;?> <div id="style-selector"> <div class="style-selector-wrapper"><span class="title"><?php print t('Choose Theme Options');?></span> <div> <br /><br /> <span class="title-sub2"><?php print t('Predefined Color Skins');?></span> <ul class="styles" id="styles_switcher_color"> <li><a href="#" title="Default" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/default.css'?>"><span class="pre-color-skin1"></span></a></li> <li><a href="#" title="Red" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/red.css'?>"><span class="pre-color-skin2"></span></a></li> <li><a href="#" title="Green" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/green.css'?>"><span class="pre-color-skin3"></span></a></li> <li><a href="#" title="Cyan" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/cyan.css'?>"><span class="pre-color-skin4"></span></a></li> <li><a href="#" title="Orange" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/orange.css'?>"><span class="pre-color-skin5"></span></a></li> <li><a href="#" title="Light Blue" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/lightblue.css'?>"><span class="pre-color-skin6"></span></a></li> <li><a href="#" title="Pink" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/pink.css'?>"><span class="pre-color-skin7"></span></a></li> <li><a href="#" title="Purple" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/purple.css'?>"><span class="pre-color-skin8"></span></a></li> <li><a href="#" title="Bridge" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/bridge.css'?>"><span class="pre-color-skin9"></span></a></li> <li><a href="#" title="Slate" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/slate.css'?>"><span class="pre-color-skin10"></span></a></li> <li><a href="#" title="Yellow" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/yellow.css'?>"><span class="pre-color-skin11"></span></a></li> <li><a href="#" title="Dark Red" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/darkred.css'?>"><span class="pre-color-skin12"></span></a></li> <li><a href="#" title="Dark Red" rel="<?php print $base_url.'/'.path_to_theme().'/css/color-scheme/blue.css'?>"><span class="pre-color-skin13"></span></a></li> </ul> <!-- end Predefined Color Skins --> <a href="#" class="close icon-chevron-right"></a></div> </div> </div> <!-- end style switcher --> <script> (function($) { $(document).ready(function(){ $('ul#styles_switcher_color li a').click(function(){ var rel = ($(this).attr('rel')); $('link[id="skin"]').attr('href',rel); return false; }); }); })(this.jQuery); </script> <?php } ?>
drupalviking/drupalviking
sites/all/themes/judy/tpl/switcher.tpl.php
PHP
gpl-2.0
3,090
showWord(["n. ","Moun ki ap bay yon konferans. <br>"])
georgejhunt/HaitiDictionary.activity
data/words/konferansye.js
JavaScript
gpl-2.0
54
""" Wilson - Implemet the Wilson model for stratified and heterogeneous regimes, and a 'framework' that takes the lesser of the two results """
rcriii42/DHLLDV
src/Wilson/__init__.py
Python
gpl-2.0
145
export default (function (window,document,$,undefined) { $('.js-input-date').each(function(){ let $el = $(this); let restrict = $el.data('restrict'); let picker = new Pikaday({ field: this, format: 'MM/DD/YYYY', }); switch(restrict) { case 'max': picker.setMaxDate(new Date()); break; case 'min': picker.setMinDate(new Date()); break; } $el.attr('type','text'); }); })(window,document,jQuery);
massgov/mayflower
packages/patternlab/styleguide/source/assets/js/modules/pikaday.js
JavaScript
gpl-2.0
512
<?php /* WARNING! DO NOT EDIT THIS FILE! BizzThemes theme framework is built with hooks and advanced conditional logic for containers, grids and widgets, which you may control from your theme template Builder. Do not modify any theme files and only make changes through theme administration or via 'custom' folder files. */ do_action('footer_html_build');
pereiracruz2002/vaniaSalgados
wp-content/themes/restaurant/footer.php
PHP
gpl-2.0
393
namespace TrueMount.Forms { partial class PasswordDialog { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(PasswordDialog)); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.panel1 = new System.Windows.Forms.Panel(); this.label2 = new System.Windows.Forms.Label(); this.labelVolumeName = new System.Windows.Forms.Label(); this.buttonCancel = new System.Windows.Forms.Button(); this.buttonOk = new System.Windows.Forms.Button(); this.textBoxPassword = new System.Windows.Forms.TextBox(); this.labelMessage = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // pictureBox1 // resources.ApplyResources(this.pictureBox1, "pictureBox1"); this.pictureBox1.Image = global::TrueMount.Properties.Resources._1276718799_application_pgp_signature; this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.TabStop = false; // // panel1 // resources.ApplyResources(this.panel1, "panel1"); this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.labelVolumeName); this.panel1.Controls.Add(this.buttonCancel); this.panel1.Controls.Add(this.buttonOk); this.panel1.Controls.Add(this.textBoxPassword); this.panel1.Controls.Add(this.labelMessage); this.panel1.Name = "panel1"; // // label2 // resources.ApplyResources(this.label2, "label2"); this.label2.Name = "label2"; // // labelVolumeName // resources.ApplyResources(this.labelVolumeName, "labelVolumeName"); this.labelVolumeName.AutoEllipsis = true; this.labelVolumeName.Name = "labelVolumeName"; // // buttonCancel // resources.ApplyResources(this.buttonCancel, "buttonCancel"); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.UseVisualStyleBackColor = true; this.buttonCancel.Click += new System.EventHandler(this.buttonCancel_Click); // // buttonOk // resources.ApplyResources(this.buttonOk, "buttonOk"); this.buttonOk.Name = "buttonOk"; this.buttonOk.UseVisualStyleBackColor = true; this.buttonOk.Click += new System.EventHandler(this.buttonOk_Click); // // textBoxPassword // resources.ApplyResources(this.textBoxPassword, "textBoxPassword"); this.textBoxPassword.Name = "textBoxPassword"; // // labelMessage // resources.ApplyResources(this.labelMessage, "labelMessage"); this.labelMessage.Name = "labelMessage"; // // PasswordDialog // this.AcceptButton = this.buttonOk; resources.ApplyResources(this, "$this"); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.CancelButton = this.buttonCancel; this.Controls.Add(this.pictureBox1); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "PasswordDialog"; this.ShowIcon = false; this.ShowInTaskbar = false; this.TopMost = true; this.Activated += new System.EventHandler(this.PasswordDialog_Activated); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.Button buttonOk; private System.Windows.Forms.TextBox textBoxPassword; private System.Windows.Forms.Label labelMessage; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label labelVolumeName; } }
nefarius/TrueMount-2
TrueMount/Forms/PasswordDialog.Designer.cs
C#
gpl-2.0
5,744
package admiciones.web.controlador; import hcdigital.presentacion.util.Pintor; import java.io.Serializable; import org.zkoss.zk.ui.Component; import org.zkoss.zk.ui.Sessions; import org.zkoss.zk.ui.util.GenericForwardComposer; import org.zkoss.zkplus.spring.SpringUtil; import org.zkoss.zul.Textbox; import admiciones.db.dto.modelo.Profesional; import admisiones.servicio.EntidadServicio; public class NuevaEntidadCtl extends GenericForwardComposer implements Serializable{ /** * Id Serializable */ private static final long serialVersionUID = 1L; private Textbox nombre; private Textbox codigo; private Textbox tipoUsuario; /** * Al cargar el zul */ public void doAfterCompose(Component comp) throws Exception{ super.doAfterCompose(comp); } public void onClick$cancelar(){ Pintor pintor=(Pintor)Sessions.getCurrent().getAttribute("pintor"); pintor.cerrarVentana(); } public void onClick$guardar(){ Profesional profesional=(Profesional)Sessions.getCurrent().getAttribute("profesional"); String usuarioConectado=profesional.getUsuario(); EntidadServicio entidadServicio = (EntidadServicio) SpringUtil.getBean("entidadServicio"); try { entidadServicio.guardar( nombre.getText(), codigo.getText(), tipoUsuario.getText(), usuarioConectado ); Pintor pintor=(Pintor)Sessions.getCurrent().getAttribute("pintor"); if(pintor!=null ){ pintor.abrirVentana("admisiones/web/vista/ListaEntidades.zul","contenidoPosicion",null); } } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
saalejo/medico
medicoAdmiciones/src/admiciones/web/controlador/NuevaEntidadCtl.java
Java
gpl-2.0
1,670
<?php // // ZoneMinder web HU Hungarian language file, $Date$, $Revision$ // Copyright (C) 2001-2008 Philip Coombes // // This program is free software; you can redistribute it and/or // modify it under the terms of the GNU General Public License // as published by the Free Software Foundation; either version 2 // of the License, or (at your option) any later version. // // This program is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // // You should have received a copy of the GNU General Public License // along with this program; if not, write to the Free Software // Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. // // ZoneMinder Hungarian Translation by szimszon at oregpreshaz dot eu, robi // version: 0.8 - 2013.08.15. - frissítés 1.26.0-hoz (robi) // version: 0.7 - 2013.05.12. - frissítés 1.25.0-hoz (robi) // version: 0.6 - 2009.06.21. - frissítés 1.24.2-höz (robi) // version: 0.5 - 2007.12.30. - frissítés 1.23.1-hez (robi) // version: 0.4 - 2007.12.30. - frissítés 1.23.0-hoz (robi) // version: 0.3 - 2006.04.27. - fordítás befejezése, elrendezése elféréshez (robi) // version: 0.2 - 2006.12.05. - par javitas // version: 0.1 - 2006.11.27. - sok typoval es par leforditatlan resszel // Notes for Translators // 0. Get some credit, put your name in the line above (optional) // 1. When composing the language tokens in your language you should try and keep to roughly the // same length text if possible. Abbreviate where necessary as spacing is quite close in a number of places. // 2. There are four types of string replacement // a) Simple replacements are words or short phrases that are static and used directly. This type of // replacement can be used 'as is'. // b) Complex replacements involve some dynamic element being included and so may require substitution // or changing into a different order. The token listed in this file will be passed through sprintf as // a formatting string. If the dynamic element is a number you will usually need to use a variable // replacement also as described below. // c) Variable replacements are used in conjunction with complex replacements and involve the generation // of a singular or plural noun depending on the number passed into the zmVlang function. See the // the zmVlang section below for a further description of this. // d) Optional strings which can be used to replace the prompts and/or help text for the Options section // of the web interface. These are not listed below as they are quite large and held in the database // so that they can also be used by the zmconfig.pl script. However you can build up your own list // quite easily from the Config table in the database if necessary. // 3. The tokens listed below are not used to build up phrases or sentences from single words. Therefore // you can safely assume that a single word token will only be used in that context. // 4. In new language files, or if you are changing only a few words or phrases it makes sense from a // maintenance point of view to include the original language file and override the old definitions rather // than copy all the language tokens across. To do this change the line below to whatever your base language // is and uncomment it. // require_once( 'zm_lang_en_gb.php' ); // You may need to change the character set here, if your web server does not already // do this by default, uncomment this if required. // // Example //header( "Content-Type: text/html; charset=iso8859-2" ); header( "Content-Type: text/html; charset=utf-8" ); // You may need to change your locale here if your default one is incorrect for the // language described in this file, or if you have multiple languages supported. // If you do need to change your locale, be aware that the format of this function // is subtlely different in versions of PHP before and after 4.3.0, see // http://uk2.php.net/manual/en/function.setlocale.php for details. // Also be aware that changing the whole locale may affect some floating point or decimal // arithmetic in the database, if this is the case change only the individual locale areas // that don't affect this rather than all at once. See the examples below. // Finally, depending on your setup, PHP may not enjoy have multiple locales in a shared // threaded environment, if you get funny errors it may be this. // // Examples // setlocale( 'LC_ALL', 'en_GB' ); All locale settings pre-4.3.0 // setlocale( LC_ALL, 'hu_HU' ); //All locale settings 4.3.0 and after //setlocale( LC_CTYPE, 'hu_HU'); //Character class settings 4.3.0 and after //setlocale( LC_TIME, 'hu_HU'); //Date and time formatting 4.3.0 and after setlocale( LC_CTYPE, 'hu_HU'); setlocale( LC_TIME, 'hu_HU' ); // Simple String Replacements $SLANG = array( '24BitColour' => '24 bites szín', '8BitGrey' => '8 bit szürkeárnyalat', 'Action' => 'Művelet', 'Actual' => 'Valós', 'AddNewControl' => 'Új vezérlés', 'AddNewMonitor' => 'Új kamera', 'AddNewUser' => 'Új felhasználó', 'AddNewZone' => 'Új zóna', 'Alarm' => 'Riadó', 'AlarmBrFrames' => 'Riasztó<br/>képek', 'AlarmFrame' => 'Riasztó kép', 'AlarmFrameCount' => 'Riasztáshoz szükséges képkockák száma', 'AlarmLimits' => 'Riasztási határok', 'AlarmMaximumFPS' => 'Maximális FPS riasztott állapotban', 'AlarmPx' => 'Riasztó képpont', 'AlarmRGBUnset' => 'Be kell állítani egy RGB színt a riasztáshoz', 'Alert' => 'Figyelem', 'All' => 'Mind', 'Apply' => 'Alkalmaz', 'ApplyingStateChange' => 'Állapot váltása...', 'ArchArchived' => 'Csak archivált', 'ArchUnarchived' => 'Csak archiválatlan', 'Archive' => 'Archiválás', 'Archived' => 'Archívum', 'Area' => 'Terület', 'AreaUnits' => 'Terület (képpont / %)', 'AttrAlarmFrames' => 'Riadó képkockák', 'AttrArchiveStatus' => 'Archivált állapot', 'AttrAvgScore' => 'Átlagérték', 'AttrCause' => 'Okozó', 'AttrDate' => 'Dátum', 'AttrDateTime' => 'Dátum/Idő', 'AttrDiskBlocks' => 'Tárhely blokk', 'AttrDiskPercent' => 'Tárhely százalék', 'AttrDuration' => 'Időtartam', 'AttrFrames' => 'Képkocka', 'AttrId' => 'Azonosító', 'AttrMaxScore' => 'Max. érték', 'AttrMonitorId' => 'Kamera azonosító', 'AttrMonitorName' => 'Kamera név', 'AttrName' => 'Név', 'AttrNotes' => 'Megjegyzés', 'AttrSystemLoad' => 'Rendszerterhelés', 'AttrTime' => 'Idő', 'AttrTotalScore' => 'Összérték', 'AttrWeekday' => 'Hétköznap', 'Auto' => 'Auto', 'AutoStopTimeout' => 'Auto megállási idő túllépés', 'Available' => 'Elérhető', 'AvgBrScore' => 'Átlag<br/>érték', 'Background' => 'Háttérben', 'BackgroundFilter' => 'Szűrő automatikus futtatása a háttérben', 'BadAlarmFrameCount' => 'Riasztáshoz szükséges képkockák száma legyen legalább 1', 'BadAlarmMaxFPS' => 'Maximális FPS riasztott állapotban legyen megadva', 'BadChannel' => 'A csatorna száma legyen legalább 0', 'BadDevice' => 'Az eszköz elérése valós legyen', 'BadFPSReportInterval' => 'Az FPS naplózásának gyakorisága legyen legalább 0', 'BadFormat' => 'A típus 0 vagy nagyobb egész szám legyen', 'BadFrameSkip' => 'Az eldobott képkockák száma legyen legalább 0', 'BadHeight' => 'A képmagasság legyen érvényes érték képpontban megadva', 'BadHost' => 'A hoszt legyen valós IP cím vagy hosztnév http:// nélkül', 'BadImageBufferCount' => 'A képkockák száma a pufferben legyen legalább 10', 'BadLabelX' => 'A cimke X koordinátája legyen legalább 0', 'BadLabelY' => 'A cimke Y koordinátája legyen legalább 0', 'BadMaxFPS' => 'Maximális FPS nyugalmi állapotban legyen megadva', 'BadNameChars' => 'A név csak betűket, számokat, plusz-, kötő-, és aláhúzásjelet tartalmazhat', 'BadPalette' => 'A szín-palettának válasszin egy helyes értéket', 'BadPath' => 'A kép elérési útvonala helytelen', 'BadPort' => 'A portszám helytelen', 'BadPostEventCount' => 'Az esemény utáni képkockák száma legyen legalább 0', 'BadPreEventCount' => 'Az esemény előtti képkockák száma legyen legalább 0', 'BadRefBlendPerc' => 'Változás a referenciaképtől legyen legalább 1', 'BadSectionLength' => 'Fix időtartamú esemény hossza legyen legalább 30', 'BadSignalCheckColour' => 'Szín a jel kimaradásakor legyen egy érvényes HTML szín-kód', 'BadStreamReplayBuffer'=> 'Folyam visszajátszó puffer legyen legalább 0', 'BadWarmupCount' => 'Bemelegítő képkockák száma legyen legalább 0', 'BadWebColour' => 'Szín az idővonal ablakban legyen egy érvényes HTML szín-kód', 'BadWidth' => 'A képszélesség legyen érvényes érték képpontban megadva', 'Bandwidth' => 'sávszélességre', 'BlobPx' => 'Blob képpont', 'BlobSizes' => 'Blob méretek', 'Blobs' => 'Blob-ok', 'Brightness' => 'Fényerő', 'Buffers' => 'Pufferek', 'CanAutoFocus' => 'Van autofókusza', 'CanAutoGain' => 'Van AGC-je', 'CanAutoIris' => 'Van autoírisze', 'CanAutoWhite' => 'Van autómata fehér egyensúlya', 'CanAutoZoom' => 'Van auto-zoomja', 'CanFocus' => 'Tud fókuszálni', 'CanFocusAbs' => 'Tud abszolút fókuszt', 'CanFocusCon' => 'Tud folyamatos fókuszt', 'CanFocusRel' => 'Tud relatív fókuszt', 'CanGain' => 'Tud erősíteni', 'CanGainAbs' => 'Tud abszolút erősítést', 'CanGainCon' => 'Tud folyamatos erősítést', 'CanGainRel' => 'Tud relatív erősítést', 'CanIris' => 'Tud íriszt változtatni', 'CanIrisAbs' => 'Tud abszolut íriszt', 'CanIrisCon' => 'Folyamatosan tud íriszt változtatni', 'CanIrisRel' => 'Relatíven tud íriszt változtatni', 'CanMove' => 'Tud mozogni', 'CanMoveAbs' => 'Tud abszolult mozgást', 'CanMoveCon' => 'Folyamatosan tud mozogni', 'CanMoveDiag' => 'Diagonálban tud mozogni', 'CanMoveMap' => 'Útvonalon tud mozogni', 'CanMoveRel' => 'Relatíven tud mozogni', 'CanPan' => 'Tud jobb-bal mozgást' , 'CanReset' => 'Tud alaphelyzetbe jönni', 'CanSetPresets' => 'Tud menteni profilokat', 'CanSleep' => 'Tud phihenő üzemmódot', 'CanTilt' => 'Tud fel-le mozgást', 'CanWake' => 'Tud feléledni', 'CanWhite' => 'Van fehér szintje', 'CanWhiteAbs' => 'Van abszolut fehér szintje', 'CanWhiteBal' => 'Van fehér egyensúlya', 'CanWhiteCon' => 'Van folyamatos fehér egyensúlya', 'CanWhiteRel' => 'Van relatív fehér egyensúlya', 'CanZoom' => 'Tud zoom-olni', 'CanZoomAbs' => 'Tud abszolut zoom-ot', 'CanZoomCon' => 'Tud folyamatos zoom-ot', 'CanZoomRel' => 'Tud relatív zoom-ot', 'Cancel' => 'Mégsem', 'CancelForcedAlarm' => 'Kézi riasztás megszűntetése', 'CaptureHeight' => 'Képmagasság', 'CaptureMethod' => 'Digitalizálás módszere', 'CapturePalette' => 'Digitalizálás szín-palettája', 'CaptureWidth' => 'Képszélesség', 'Cause' => 'Okozó', 'CheckMethod' => 'A riasztás figyelésének módja', 'ChooseDetectedCamera' => 'Válasszon érzékelt kamerát', 'ChooseFilter' => 'Válasszon szűrőt', 'ChooseLogFormat' => 'Válasszon napló formátumot', 'ChooseLogSelection' => 'Válasszon naplót', 'ChoosePreset' => 'Válasszon profilt', 'Clear' => 'Törlés', 'Close' => 'Bezárás', 'Colour' => 'Szín', 'Command' => 'Parancs', 'Component' => 'Komponens', 'Config' => 'Beállítás', 'ConfiguredFor' => 'Beállítva', 'ConfirmDeleteEvents' => 'Biztos benne, hogy törli a kiválasztott eseményeket?', 'ConfirmPassword' => 'Jelszó megerősítés', 'ConjAnd' => 'és', 'ConjOr' => 'vagy', 'Console' => 'Konzol', 'ContactAdmin' => 'Kérem vegye fel a kapcsolatot a rendszergazdával a részletekért.', 'Continue' => 'Folytatás', 'Contrast' => 'Kontraszt', 'Control' => 'Vezérlés', 'ControlAddress' => 'Vezérlési jogok', 'ControlCap' => 'Vezérlési lehetőség', 'ControlCaps' => 'Vezérlési lehetőségek', 'ControlDevice' => 'Vezérlő eszköz', 'ControlType' => 'Vezérlés típusa', 'Controllable' => 'Vezérelhető', 'Cycle' => 'Ciklikus nézet', 'CycleWatch' => 'Ciklikus nézet', 'DateTime' => 'Dátum/Idő', 'Day' => 'Napon', 'Debug' => 'Hibakeresés', 'DefaultRate' => 'Alapértelmezett sebesség', 'DefaultScale' => 'Alapértelmezett méret', 'DefaultView' => 'Alapértelmezett nézet', 'Delete' => 'Törlés', 'DeleteAndNext' => 'Törlés &amp;<br>következő', 'DeleteAndPrev' => 'Törlés &amp;<br>előző', 'DeleteSavedFilter' => 'Mentett szűrő törlése', 'Description' => 'Leírás', 'DetectedCameras' => 'Érzékelt kamerák', 'Device' => 'Eszköz', 'DeviceChannel' => 'Eszköz csatornája', 'DeviceFormat' => 'Eszköz formátuma', 'DeviceNumber' => 'Eszköz szám', 'DevicePath' => 'Eszköz elérési útvonala', 'Devices' => 'Eszközök', 'Dimensions' => 'Méretek', 'DisableAlarms' => 'Riasztások tiltása', 'Disk' => 'Tárhely', 'Display' => 'Megjelenés', 'Displaying' => 'Megjelenítés', 'Donate' => 'Kérem támogasson', 'DonateAlready' => 'Nem, én már támogattam', 'DonateEnticement' => 'Ön már jó ideje használja a ZoneMindert, és reméljük hasznos eszköznek tartja háza vagy munkahelye biztonságában. Bár a ZoneMinder egy szabad, nyílt forráskódú termék és az is marad, a fejlesztése pénzbe kerül. Ha van lehetősége támogatni a jövőbeni fejlesztéseket és az új funkciókat kérem, tegye meg. A támogatás teljesen önkéntes, de nagyon megbecsült és mértéke is tetszőleges.<br><br>Ha támogatni szertne, kérem, válasszon az alábbi lehetőségekből vagy látogassa meg a http://www.zoneminder.com/donate.html oldalt.<br><br>Köszönjük, hogy használja a ZoneMinder-t és ne felejtse el meglátogatni a fórumokat a ZoneMinder.com oldalon támogatásért és ötletekért, hogy a jövőben is még jobban ki tudja használni a ZoneMinder lehetőségeit.', 'DonateRemindDay' => 'Nem most, figyelmeztessen egy nap múlva', 'DonateRemindHour' => 'Nem most, figyelmeztessen egy óra múlva', 'DonateRemindMonth' => 'Nem most, figyelmeztessen egy hónap múlva', 'DonateRemindNever' => 'Nem szeretném támogatni, ne is emlékeztessen', 'DonateRemindWeek' => 'Nem most, figyelmeztessen egy hét múlva', 'DonateYes' => 'Igen, most szeretném támogatni', 'Download' => 'Letöltés', 'DuplicateMonitorName' => 'Kameranév duplikálás', 'Duration' => 'Időtartam', 'Edit' => 'Szerkesztés', 'Email' => 'E-mail', 'EnableAlarms' => 'Riasztások engedélyezése', 'Enabled' => 'Engedélyezve', 'EnterNewFilterName' => 'Adja meg az új szűrő nevét', 'Error' => 'Hiba', 'ErrorBrackets' => 'Hiba: kérem ellenőrizze, hogy a zárójel-párok rendben vannak-e', 'ErrorValidValue' => 'Hiba: kérem ellenőrizze, hogy minden beállításnak érvényes értéke van-e', 'Etc' => 'stb', 'Event' => 'Esemény', 'EventFilter' => 'Esemény szűrő', 'EventId' => 'Esemény azonosító', 'EventName' => 'Esemény neve', 'EventPrefix' => 'Eseménynév előtag', 'Events' => 'Események', 'Exclude' => 'Kizárás', 'Execute' => 'Végrehajtás', 'Export' => 'Exportálás', 'ExportDetails' => 'Esemény adatainak exportálása', 'ExportFailed' => 'Az exportálás sikertelen', 'ExportFormat' => 'Tömörített exportfájl formátuma', 'ExportFormatTar' => 'TAR', 'ExportFormatZip' => 'ZIP', 'ExportFrames' => 'Képkockák adatainak exportálása', 'ExportImageFiles' => 'Képkockák exportálása', 'ExportLog' => 'Naplók exportálása', 'ExportMiscFiles' => 'Egyéb fájlok exportálása (ha vannak)', 'ExportOptions' => 'Exportálás beállításai', 'ExportSucceeded' => 'Az exportálás sikerült', 'ExportVideoFiles' => 'Videófájlok exportálása (ha vannak)', 'Exporting' => 'Exportálás folyamatban', 'FPS' => 'fps', 'FPSReportInterval' => 'FPS naplózásának gyakorisága', 'FTP' => 'FTP', 'Far' => 'Távol', 'FastForward' => 'Előre tekerés', 'Feed' => 'Folyam', 'Ffmpeg' => 'ffmpeg', 'File' => 'Fájl', 'FilterArchiveEvents' => 'Minden találat archiválása', 'FilterDeleteEvents' => 'Minden találat törlése', 'FilterEmailEvents' => 'Minden találat adatainak küldése E-mailben', 'FilterExecuteEvents' => 'Parancs futtatása minden találaton', 'FilterMessageEvents' => 'Minden találat adatainak üzenése', 'FilterPx' => 'Szűrt képkockák', 'FilterUnset' => 'Meg kell adnod a szűrő szélességét és magasságát', 'FilterUploadEvents' => 'Minden találat feltöltése', 'FilterVideoEvents' => 'Videó készítése minden találatról', 'Filters' => 'Szűrők', 'First' => 'Első', 'FlippedHori' => 'Vízszintes tükrözés', 'FlippedVert' => 'Függőleges tükrözés', 'Focus' => 'Fókusz', 'ForceAlarm' => 'Kézi riasztás', 'Format' => 'Formátum', 'Frame' => 'Képkocka', 'FrameId' => 'Képkocka azonosító', 'FrameRate' => 'FPS', 'FrameSkip' => 'Képkocka kihagyás', 'Frames' => 'Képkocka', 'Func' => 'Funk.', 'Function' => 'Funkció', 'Gain' => 'Erősítés', 'General' => 'Általános', 'GenerateVideo' => 'Videó készítés', 'GeneratingVideo' => 'Videó készítése folyamatban', 'GoToZoneMinder' => 'Ellenőrzés a ZoneMinder.com-on', 'Grey' => 'Szürke', 'Group' => 'Csoport', 'Groups' => 'Csoportok', 'HasFocusSpeed' => 'Van fókusz sebesség', 'HasGainSpeed' => 'Van AGC sebesség', 'HasHomePreset' => 'Van alapállás profilja', 'HasIrisSpeed' => 'Van írisz sebesség', 'HasPanSpeed' => 'Van jobb-bal sebesség', 'HasPresets' => 'Vannak profiljai', 'HasTiltSpeed' => 'Van le-fel sebesség', 'HasTurboPan' => 'Van gyors jobb-bal', 'HasTurboTilt' => 'Van gyors le-fel', 'HasWhiteSpeed' => 'Van fehér egyensúly sebesség', 'HasZoomSpeed' => 'Van zoom sebesség', 'High' => 'Magas', 'HighBW' => 'Magas<br>sávszél', 'Home' => 'Alapba', 'Hour' => 'Órában', 'Hue' => 'Színárnyalat', 'Id' => 'Az.', 'Idle' => 'Nyugalom', 'Ignore' => 'Figyelmen kívül hagyás', 'Image' => 'Kép', 'ImageBufferSize' => 'Képkockák száma a pufferben', 'Images' => 'Kép', 'In' => 'In', 'Include' => 'Beágyaz', 'Inverted' => 'Invertálva', 'Iris' => 'Írisz', 'KeyString' => 'Kulcs karaktersor', 'Label' => 'Cimke', 'Language' => 'Nyelv', 'Last' => 'Utolsó', 'Layout' => 'Elrendezés', 'Level' => 'Szint', 'LimitResultsPost' => 'találatra', // This is used at the end of the phrase 'Limit to first N results only' 'LimitResultsPre' => 'Csak az első', // This is used at the beginning of the phrase 'Limit to first N results only' 'Line' => 'Sor', 'LinkedMonitors' => 'Összefüggés más kamerákkal<br>(jelölés Ctrl+kattintással)', 'List' => 'Lista', 'Load' => 'Terhelés', 'Local' => 'Helyi', 'Log' => 'Napló', 'LoggedInAs' => 'Bejelentkezve mint', 'Logging' => 'Naplózás', 'LoggingIn' => 'Bejelentkezés folyamatban', 'Login' => 'Bejelentkezés', 'Logout' => 'Kilépés', 'Logs' => 'Naplók', 'Low' => 'Alacsony', 'LowBW' => 'Alacsony<br>sávszél', 'Main' => 'Fő', 'Man' => 'Man', 'Manual' => 'Kézikönyv', 'Mark' => 'Jelölő', 'Max' => 'Max.', 'MaxBandwidth' => 'Max. sávszélesség', 'MaxBrScore' => 'Max.<br/>érték', 'MaxFocusRange' => 'Max. fókusz tartomány', 'MaxFocusSpeed' => 'Max. fókusz sebesség', 'MaxFocusStep' => 'Max. fókusz lépték', 'MaxGainRange' => 'Max. AGC tartomány', 'MaxGainSpeed' => 'Max. AGC sebesség', 'MaxGainStep' => 'Max. AGC lépték', 'MaxIrisRange' => 'Max. írisz tartomány', 'MaxIrisSpeed' => 'Max. írisz sebesség', 'MaxIrisStep' => 'Max. írisz lépték', 'MaxPanRange' => 'Max. jobb-bal tartomány', 'MaxPanSpeed' => 'Max. jobb-bal sebesség', 'MaxPanStep' => 'Max. jobb-bal lépték', 'MaxTiltRange' => 'Max. fel-le tartomány', 'MaxTiltSpeed' => 'Max. fel-le sebesség', 'MaxTiltStep' => 'Max. fel-le lépték', 'MaxWhiteRange' => 'Max. fehér egyensúly tartomány', 'MaxWhiteSpeed' => 'Max. fehér egyensúly sebesség', 'MaxWhiteStep' => 'Max. fehér egyensúly lépték', 'MaxZoomRange' => 'Max. zoom tartomány', 'MaxZoomSpeed' => 'Max. zoom sebesség', 'MaxZoomStep' => 'Max. zoom lépték', 'MaximumFPS' => 'Maximális FPS nyugalmi állapotban', 'Medium' => 'Közepes', 'MediumBW' => 'Közepes<br>sávszél', 'Message' => 'Üzenet', 'MinAlarmAreaLtMax' => 'A minimum riasztott területnek kisebbnek kell lennie mint a maximumnak', 'MinAlarmAreaUnset' => 'Meg kell adnod a minimum képpont számot, ami riasztást okoz', 'MinBlobAreaLtMax' => 'A minimum blob területnek kisebbnek kell lennie mint a maximumnak', 'MinBlobAreaUnset' => 'Meg kell adnod a minimum blob képpont számot, ami riasztást okoz', 'MinBlobLtMinFilter' => 'A minimum blob területnek kisebbnek vagy egyenlőnek kell lennie a megszűrt területtel', 'MinBlobsLtMax' => 'A minimum bloboknak kisebbeknek kell lenniük, mint a maximum', 'MinBlobsUnset' => 'Meg kell adnod a blobok számát', 'MinFilterAreaLtMax' => 'A minimum megszűrt területnek kisebbnek kell lennie mint a maximum', 'MinFilterAreaUnset' => 'Meg kell adnod a megszűrt terület képpontjainak számát', 'MinFilterLtMinAlarm' => 'A megszűrt területnek kisebbnek vagy ugyanakkorának kell lennie mint a riasztott terület', 'MinFocusRange' => 'Min. fókusz terület', 'MinFocusSpeed' => 'Min. fókusz sebesség', 'MinFocusStep' => 'Min. fókusz lépték', 'MinGainRange' => 'Min. AGC tartomány', 'MinGainSpeed' => 'Min AGC sebesség', 'MinGainStep' => 'Min. AGC lépték', 'MinIrisRange' => 'Min. írisz terület', 'MinIrisSpeed' => 'Min. írisz sebesség', 'MinIrisStep' => 'Min. írisz lépték', 'MinPanRange' => 'Min. jobb-bal tartomány', 'MinPanSpeed' => 'Min. jobb-bal sebesség', 'MinPanStep' => 'Min. jobb-bal lépték', 'MinPixelThresLtMax' => 'A képpont minimum eltérési küszöbének kisebbnek kell lennie, mint a maximum', 'MinPixelThresUnset' => 'Meg kell adnod a képpont minimum eltérési küszöbét', 'MinTiltRange' => 'Min. fel-le tartomány', 'MinTiltSpeed' => 'Min. fel-le sebesség', 'MinTiltStep' => 'Min. fel-le lépték', 'MinWhiteRange' => 'Min. fehér egyensúly terület', 'MinWhiteSpeed' => 'Min. fehér egyensúly sebesség', 'MinWhiteStep' => 'Min. fehér egyensúly lépték', 'MinZoomRange' => 'Min. zoom terület', 'MinZoomSpeed' => 'Min. zoom sebesség', 'MinZoomStep' => 'Min. zoom lépték', 'Misc' => 'Egyéb', 'Monitor' => 'Kamera', 'MonitorIds' => 'Kamera&nbsp;azonosítók', 'MonitorPreset' => 'Előre beállított kameraprofilok', 'MonitorPresetIntro' => 'Kérem, válasszon egy kész kameraprofilt az alábbiak közül.<br>Figyelem: ez felülírja a korábban már beállított értékeket.<br><br>', 'MonitorProbe' => 'Kamerajel észlelés', 'MonitorProbeIntro' => 'Az alábbi listában találhatók az automatikusan érzékelt analóg és hálózati kamerákat, illetve azt, hogy közülük melyik van használatban, vagy kiválasztható.<br/><br/>Válasszon egyet az alábbi listából.<br/><br/>Figyelem: nem biztos, hogy minden kamerát lehet automatikusan érzékelni. Az itt kiválasztott kamara adatai felülírhatják azokat, amelyeket már ehhez a monitorhoz beállított.<br/><br/>', 'Monitors' => 'Kamerák', 'Montage' => 'Többkamerás nézet', 'Month' => 'Hónapban', 'More' => 'Több', 'Move' => 'Mozgás', 'MustBeGe' => 'nagyobbnak vagy egyenlőnek kell lennie', 'MustBeLe' => 'kisebbnek vagy egyenlőnek kell lennie', 'MustConfirmPassword' => 'Meg kell erősítenie a jelszót', 'MustSupplyPassword' => 'Meg kell adnia a jelszót', 'MustSupplyUsername' => 'Meg kell adnia felhasználói nevet', 'Name' => 'Név', 'Near' => 'Közel', 'Network' => 'Hálózat', 'New' => 'Uj', 'NewGroup' => 'Új csoport', 'NewLabel' => 'Új cimke', 'NewPassword' => 'Új jelszó', 'NewState' => 'Új állapot neve', 'NewUser' => 'Új felhasználó', 'Next' => 'Következő', 'No' => 'Nem', 'NoDetectedCameras' => 'Nem érzékelhetőek kamerák', 'NoFramesRecorded' => 'Nincs rögzített képkocka ehhez az eseményhez', 'NoGroup' => 'Nincs csoport', 'NoSavedFilters' => 'Nincs mentett szűrő', 'NoStatisticsRecorded' => 'Nincs mentett statisztika ehhez az eseményhez/képkockához', 'None' => 'Nincs kiválasztva', 'NoneAvailable' => 'Nem elérhető', 'Normal' => 'Normál', 'Notes' => 'Megjegyzések', 'NumPresets' => 'Profilok száma', 'Off' => 'Ki', 'On' => 'Be', 'OpEq' => 'egyenlő', 'OpGt' => 'nagyobb mint', 'OpGtEq' => 'nagyobb van egyenlő', 'OpIn' => 'beállítva', 'OpLt' => 'kisebb mint', 'OpLtEq' => 'kisebb vagy egyenlő', 'OpMatches' => 'találatok', 'OpNe' => 'nem egyenlő', 'OpNotIn' => 'nincs beállítva', 'OpNotMatches' => 'nincs találat', 'Open' => 'Megnyitás', 'OptionHelp' => 'Beállítási segítség', 'OptionRestartWarning' => 'Ez a beállítás nem tud érvénybe lépni miközben az élő rendszer fut.\nHa végzett minden beállítással, kérem, indítsa újra a ZoneMinder szolgáltatást.', 'Options' => 'Beállítások', 'OrEnterNewName' => 'vagy új néven:', 'Order' => 'Sorrend', 'Orientation' => 'Orientáció', 'Out' => 'Kifelé', 'OverwriteExisting' => 'Meglévő felülírása', 'Paged' => 'Lapozva', 'Pan' => 'Jobb-bal mozgatás', 'PanLeft' => 'Mozgatás balra', 'PanRight' => 'Mozgatás jobbra', 'PanTilt' => 'Mozgat', 'Parameter' => 'Paraméter', 'Password' => 'Jelszó', 'PasswordsDifferent' => 'Az új és a megerősített jelszó különböznek!', 'Paths' => 'Útvonalak', 'Pause' => 'Szünet', 'Phone' => 'Telefonon betárcsázva', 'PhoneBW' => 'Mobil<br>sávszél', 'Pid' => 'PID', 'PixelDiff' => 'Képpont eltérés', 'Pixels' => 'képpont', 'Play' => 'Lejátszás', 'PlayAll' => 'Mind lejátszása', 'PleaseWait' => 'Kérlek várj...', 'Point' => 'Pont', 'PostEventImageBuffer' => 'Esemény utáni képkockák a pufferben', 'PreEventImageBuffer' => 'Esemény elötti képkockák a pufferben', 'PreserveAspect' => 'Méretarány megtartása', 'Preset' => 'Előre beállított profil', 'Presets' => 'Előre beállított profilok', 'Prev' => 'Előző', 'Probe' => 'Érzékelés', 'Protocol' => 'Protocol', 'Rate' => 'FPS', 'Real' => 'Valós', 'Record' => 'Felvétel', 'RefImageBlendPct' => 'Változás a referenciaképtől %-ban', 'Refresh' => 'Frissítés', 'Remote' => 'Hálózati', 'RemoteHostName' => 'Hálózati IP cím/hosztnév', 'RemoteHostPath' => 'A kép elérési útvonala', 'RemoteHostPort' => 'Hálózati portszám', 'RemoteHostSubPath' => 'A kép elérési al-útvonala', 'RemoteImageColours' => 'A kép színe', 'RemoteMethod' => 'Hálózati cím mód', 'RemoteProtocol' => 'Hálózati protokoll', 'Rename' => 'Átnevezés', 'Replay' => 'Esemény visszajátszás', 'ReplayAll' => 'Mindet', 'ReplayGapless' => 'Szünet nélkülieket', 'ReplaySingle' => 'Egyenként', 'Reset' => 'Alapértékre', 'ResetEventCounts' => 'Eseményszámláló nullázása', 'Restart' => 'A szolgáltatás újraindítása', 'Restarting' => 'Újraindítás', 'RestrictedCameraIds' => 'Korlátozott kamerák azonosítói', 'RestrictedMonitors' => 'Korlátozott kamerák', 'ReturnDelay' => 'Visszaérkezés késleltetése', 'ReturnLocation' => 'Visszaérkezés helye', 'Rewind' => 'Visszatekerés', 'RotateLeft' => 'Balra forgatás', 'RotateRight' => 'Jobbra forgatás', 'RunLocalUpdate' => 'Kérem, futtassa le a zmupdate.pl szkriptet a frissítéshez.', 'RunMode' => 'Futási mód', 'RunState' => 'A ZoneMinder állapota', 'Running' => 'Élő', 'Save' => 'Mentés', 'SaveAs' => 'Mentés erre:', 'SaveFilter' => 'Szűrő mentése', 'Scale' => 'Méret', 'Score' => 'Pontszám', 'Secs' => 'mp.', 'Sectionlength' => 'Fix időtartamú esemény hossza', 'Select' => 'Kiválasztás', 'SelectFormat' => 'Válasszon formátumot', 'SelectLog' => 'Válasszon naplót', 'SelectMonitors' => 'Kamerák kiválasztása', 'SelfIntersecting' => 'A sokszög szélei nem kereszteződhetnek', 'Set' => 'Beállít', 'SetNewBandwidth' => 'Sávszélességi profil választása a böngészöhöz', 'SetPreset' => 'Profil beállítása', 'Settings' => 'Beállítások', 'ShowFilterWindow' => 'Szűrőablak megjelenítése', 'ShowTimeline' => 'Idővonal megjelenítése', 'SignalCheckColour' => 'Szín a jel kimaradásakor', 'Size' => 'Fájlméret', 'SkinDescription' => 'Alapértelmezett felület ebben a böngészőben', 'Sleep' => 'Alvás', 'SortAsc' => 'Növekvő', 'SortBy' => 'Sorbarendezés:', 'SortDesc' => 'Csökkenő', 'Source' => 'Jelforrás', 'SourceColours' => 'A kép színe', 'SourcePath' => 'A kép elérési útvonala', 'SourceType' => 'Jelforrás típusa', 'Speed' => 'Sebesség', 'SpeedHigh' => 'Nagy sebsség', 'SpeedLow' => 'Alacsony sebesség', 'SpeedMedium' => 'Közepes sebesség', 'SpeedTurbo' => 'Turbó sebesség', 'Start' => 'Indít', 'State' => 'Állapot', 'Stats' => 'Statisztikák', 'Status' => 'Státusz', 'Step' => 'Ugrás', 'StepBack' => 'Visszalépés', 'StepForward' => 'Előrelépés', 'StepLarge' => 'Nagy ugrás', 'StepMedium' => 'Közepes ugrás', 'StepNone' => 'Nincs ugrás', 'StepSmall' => 'Kis ugrás', 'Stills' => 'Állóképek', 'Stop' => 'A szolgáltatás leállítása', 'Stopped' => 'Leállítva', 'Stream' => 'Élő folyam', 'StreamReplayBuffer' => 'Képkockák száma a pufferben visszajátszáskor', 'Submit' => 'Küldés', 'System' => 'Rendszer', 'SystemLog' => 'Rendszernapló', 'Tele' => 'Táv', 'Thumbnail' => 'Előnézet', 'Tilt' => 'Fel-le mozgás', 'Time' => 'Időpont', 'TimeDelta' => 'Idő változás', 'TimeStamp' => 'Időbélyeg', 'Timeline' => 'Idővonal', 'Timestamp' => 'Időbélyeg', 'TimestampLabelFormat' => 'Időbélyeg formátuma', 'TimestampLabelX' => 'Elhelyezés X pozició', 'TimestampLabelY' => 'Elhelyezés Y pozició', 'Today' => 'Ma', 'Tools' => 'Eszközök', 'Total' => 'Összes', 'TotalBrScore' => 'Össz.<br/>pontszám', 'TrackDelay' => 'Késleltetés követése', 'TrackMotion' => 'Mozgás követése', 'Triggers' => 'Egyéb előidézők', 'TurboPanSpeed' => 'Jobb-bal gyorssebesség', 'TurboTiltSpeed' => 'Fel-le gyorssebesség', 'Type' => 'Típus', 'Unarchive' => 'Archívumból ki', 'Undefined' => 'Nincs megadva', 'Units' => 'Egység', 'Unknown' => 'Ismeretlen', 'Update' => 'Frissítés', 'UpdateAvailable' => 'Elérhető ZoneMinder frissítés.', 'UpdateNotNecessary' => 'Nem szükséges a frissítés.', 'Updated' => 'Frissítve', 'Upload' => 'Feltöltés', 'UseFilter' => 'Szűrőt használ', 'UseFilterExprsPost' => '&nbsp;szürés&nbsp; használata', // This is used at the end of the phrase 'use N filter expressions' 'UseFilterExprsPre' => '&nbsp;', // This is used at the beginning of the phrase 'use N filter expressions' 'User' => 'Felhasználó', 'Username' => 'Felhasználónév', 'Users' => 'Felhasználók', 'Value' => 'Érték', 'Version' => 'Verzió', 'VersionIgnore' => 'Ezen verzió figyelmen kívül hagyása', 'VersionRemindDay' => 'Egy nap múlva emlékeztessen', 'VersionRemindHour' => 'Egy óra múlva emlékeztessen', 'VersionRemindNever' => 'Ne emlékeztessen az új verzióról', 'VersionRemindWeek' => 'Egy hét múlva emlékeztessen', 'Video' => 'Videó', 'VideoFormat' => 'Videó formátum', 'VideoGenFailed' => 'A videó készítése sikertelen.', 'VideoGenFiles' => 'Létező videók', 'VideoGenNoFiles' => 'Nem találhatók videók', 'VideoGenParms' => 'Videó készítési paraméterek', 'VideoGenSucceeded' => 'A videó elkészült.', 'VideoSize' => 'Képméret', 'View' => 'Megtekintés', 'ViewAll' => 'Az összes listázása', 'ViewEvent' => 'Események nézet', 'ViewPaged' => 'Oldal nézet', 'Wake' => 'Ébresztés', 'WarmupFrames' => 'Bemelegítő képkockák', 'Watch' => 'Figyelés', 'Web' => 'Web', 'WebColour' => 'Szín az idővonal skálán', 'Week' => 'Héten', 'White' => 'Fehér', 'WhiteBalance' => 'Fehér egyensúly', 'Wide' => 'Széles', 'X' => 'X', 'X10' => 'X10', 'X10ActivationString' => 'X10 élesítő karaktersor', 'X10InputAlarmString' => 'X10 bemeneti riadó karaktersor', 'X10OutputAlarmString' => 'X10 kimeneti riadó karaktersor', 'Y' => 'Y', 'Yes' => 'Igen', 'YouNoPerms' => 'Nincs joga az erőforrás eléréséhez.', 'Zone' => 'Zóna:', 'ZoneAlarmColour' => 'Riasztott terület<br>színezése (R/G/B)', 'ZoneArea' => 'Zóna lefedettsége', 'ZoneFilterSize' => 'Szélesség és magasság<br>szűrés képpontban', 'ZoneMinMaxAlarmArea' => 'Min/Max riasztó terület', 'ZoneMinMaxBlobArea' => 'Min/Max Blob terület', 'ZoneMinMaxBlobs' => 'Min/Max Blobok', 'ZoneMinMaxFiltArea' => 'Min/Max szűrt terület', 'ZoneMinMaxPixelThres' => 'Min/Max képpont változási<br>küszöb (0-255)', 'ZoneMinderLog' => 'ZoneMinder Napló', 'ZoneOverloadFrames' => 'Túlterhelés esetén<br>ennyi képkocka hagyható ki', 'Zones' => 'Zónák', 'Zoom' => 'Zoom', 'ZoomIn' => 'Zoom be', 'ZoomOut' => 'Zoom ki', ); // Complex replacements with formatting and/or placements, must be passed through sprintf $CLANG = array( 'CurrentLogin' => 'Jelenleg belépve mint \'%1$s\'', 'EventCount' => '%1$s %2$s', // For example '37 Events' (from Vlang below) 'LastEvents' => 'Utolsó %1$s %2$s', // For example 'Last 37 Events' (from Vlang below) 'LatestRelease' => 'Az utolsó kiadás verziószáma v%1$s, ami itt fent van v%2$s.', 'MonitorCount' => '%1$s %2$s', // For example '4 Monitors' (from Vlang below) 'MonitorFunction' => 'Kamerafunkció: %1$s', 'RunningRecentVer' => 'A legfrissebb ZoneMinder verziót használja: v%s.', 'VersionMismatch' => 'Verziószám eltérés: rendszerverzió %1$s, adatbázis %2$s.', ); // The next section allows you to describe a series of word ending and counts used to // generate the correctly conjugated forms of words depending on a count that is associated // with that word. // This intended to allow phrases such a '0 potatoes', '1 potato', '2 potatoes' etc to // conjugate correctly with the associated count. // In some languages such as English this is fairly simple and can be expressed by assigning // a count with a singular or plural form of a word and then finding the nearest (lower) value. // So '0' of something generally ends in 's', 1 of something is singular and has no extra // ending and 2 or more is a plural and ends in 's' also. So to find the ending for '187' of // something you would find the nearest lower count (2) and use that ending. // // So examples of this would be // $zmVlangPotato = array( 0=>'Potatoes', 1=>'Potato', 2=>'Potatoes' ); // $zmVlangSheep = array( 0=>'Sheep' ); // // where you can have as few or as many entries in the array as necessary // If your language is similar in form to this then use the same format and choose the // appropriate zmVlang function below. // If however you have a language with a different format of plural endings then another // approach is required . For instance in Russian the word endings change continuously // depending on the last digit (or digits) of the numerator. In this case then zmVlang // arrays could be written so that the array index just represents an arbitrary 'type' // and the zmVlang function does the calculation about which version is appropriate. // // So an example in Russian might be (using English words, and made up endings as I // don't know any Russian!!) // $zmVlangPotato = array( 1=>'Potati', 2=>'Potaton', 3=>'Potaten' ); // // and the zmVlang function decides that the first form is used for counts ending in // 0, 5-9 or 11-19 and the second form when ending in 1 etc. // // Variable arrays expressing plurality, see the zmVlang description above $VLANG = array( 'Event' => array( 0=>'esemény', 1=>'esemény', 2=>'esemény' ), 'Monitor' => array( 0=>'kamera', 1=>'kamera', 2=>'kamera' ), ); // You will need to choose or write a function that can correlate the plurality string arrays // with variable counts. This is used to conjugate the Vlang arrays above with a number passed // in to generate the correct noun form. // // In languages such as English this is fairly simple // Note this still has to be used with printf etc to get the right formating function zmVlang( $langVarArray, $count ) { krsort( $langVarArray ); foreach ( $langVarArray as $key=>$value ) { if ( abs($count) >= $key ) { return( $value ); } } die( 'Error, unable to correlate variable language string' ); } // This is an version that could be used in the Russian example above // The rules are that the first word form is used if the count ends in // 0, 5-9 or 11-19. The second form is used then the count ends in 1 // (not including 11 as above) and the third form is used when the // count ends in 2-4, again excluding any values ending in 12-14. // // function zmVlang( $langVarArray, $count ) // { // $secondlastdigit = substr( $count, -2, 1 ); // $lastdigit = substr( $count, -1, 1 ); // // or // // $secondlastdigit = ($count/10)%10; // // $lastdigit = $count%10; // // // Get rid of the special cases first, the teens // if ( $secondlastdigit == 1 && $lastdigit != 0 ) // { // return( $langVarArray[1] ); // } // switch ( $lastdigit ) // { // case 0 : // case 5 : // case 6 : // case 7 : // case 8 : // case 9 : // { // return( $langVarArray[1] ); // break; // } // case 1 : // { // return( $langVarArray[2] ); // break; // } // case 2 : // case 3 : // case 4 : // { // return( $langVarArray[3] ); // break; // } // } // die( 'Error, unable to correlate variable language string' ); // } // This is an example of how the function is used in the code which you can uncomment and // use to test your custom function. //$monitors = array(); //$monitors[] = 1; // Choose any number //echo sprintf( $zmClangMonitorCount, count($monitors), zmVlang( $zmVlangMonitor, count($monitors) ) ); // In this section you can override the default prompt and help texts for the options area // These overrides are in the form show below where the array key represents the option name minus the initial ZM_ // So for example, to override the help text for ZM_LANG_DEFAULT do $OLANG = array( // 'LANG_DEFAULT' => array( // 'Prompt' => "This is a new prompt for this option", // 'Help' => "This is some new help for this option which will be displayed in the popup window when the ? is clicked" // ), ); ?>
martonmiklos/ZoneMinder
web/lang/hu_hu.php
PHP
gpl-2.0
46,814
/* * (C) 2007-2013 Alibaba Group Holding Limited. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 as * published by the Free Software Foundation. * * * Version: $Id: ss_define.h 344 2013-08-29 11:17:38Z duanfei@taobao.com $ * * Authors: * duanfei <duanfei@taobao.com> * - initial release */ #include "common/define.h" #include "common/atomic.h" #include "ms_define.h" #include "common/error_msg.h" #include "common/parameter.h" using namespace tfs::common; namespace tfs { namespace migrateserver { MsRuntimeGlobalInformation::MsRuntimeGlobalInformation(): is_destroy_(false) { } void MsRuntimeGlobalInformation::dump(const int32_t level, const char* file, const int32_t line, const char* function, const pthread_t thid, const char* format, ...) { char msgstr[256] = {'\0'};/** include '\0'*/ va_list ap; va_start(ap, format); vsnprintf(msgstr, 256, NULL == format ? "" : format, ap); va_end(ap); TBSYS_LOGGER.logMessage(level, file, line, function, thid, "%s", msgstr); } MsRuntimeGlobalInformation& MsRuntimeGlobalInformation::instance() { static MsRuntimeGlobalInformation instance; return instance; } }/** migrateserver **/ }/** tfs **/
nosqldb/tfs
src/migrateserver/ms_define.cpp
C++
gpl-2.0
1,359
<?php // Get ID $ID = $client; // DB global $wpdb; $table_db_name = $wpdb->prefix . "webinarignition"; $findstat = $wpdb->get_row("SELECT * FROM $table_db_name WHERE id = '$ID'", OBJECT); $full_path = get_site_url(); $assets = WEBINARIGNITION_URL . "inc/"; ?> <script src="<?php echo $assets; ?>lp/js/jquery.js"></script> <script src="<?php echo $assets; ?>lp/js/cookie.js"></script> <script type="text/javascript"> $(document).ready(function () { // Check If Cookie Is Set -- Get ID $getCookieID = $.cookie('we-trk-<?php echo $ID; ?>'); // Track Order For User var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>'; var data = {action: 'webinarignition_track_order', id: "<?php echo $client; ?>", lead: "" + $getCookieID + ""}; $.post(ajaxurl, data, function (results) { }); }); </script>
TakenCdosG/chcact.org
wp-content/plugins/webinarignition/inc/lp/ordertrk.php
PHP
gpl-2.0
866
<?php /** Aramaic (ܐܪܡܝܐ) * * See MessagesQqq.php for message documentation incl. usage of parameters * To improve a translation please visit http://translatewiki.net * * @ingroup Language * @file * * @author 334a * @author A2raya07 * @author Amire80 * @author Basharh * @author Man2fly2002 * @author Michaelovic * @author The Thadman */ $rtl = true; $namespaceNames = array( NS_MEDIA => 'ܡܝܕܝܐ', NS_SPECIAL => 'ܕܝܠܢܝܐ', NS_MAIN => '', NS_TALK => 'ܡܡܠܠܐ', NS_USER => 'ܡܦܠܚܢܐ', NS_USER_TALK => 'ܡܡܠܠܐ_ܕܡܦܠܚܢܐ', NS_PROJECT_TALK => 'ܡܡܠܠܐ_ܕ$1', NS_FILE => 'ܠܦܦܐ', NS_FILE_TALK => 'ܡܡܠܠܐ_ܕܠܦܦܐ', NS_MEDIAWIKI => 'ܡܝܕܝܐܘܝܩܝ', NS_MEDIAWIKI_TALK => 'ܡܡܠܠܐ_ܕܡܝܕܝܐܘܝܩܝ', NS_TEMPLATE => 'ܩܠܒܐ', NS_TEMPLATE_TALK => 'ܡܡܠܠܐ_ܕܩܠܒܐ', NS_HELP => 'ܥܘܕܪܢܐ', NS_HELP_TALK => 'ܡܡܠܠܐ_ܕܥܘܕܪܢܐ', NS_CATEGORY => 'ܣܕܪܐ', NS_CATEGORY_TALK => 'ܡܡܠܠܐ_ܕܣܕܪܐ', ); $namespaceAliases = array( 'ܡܬܚܫܚܢܐ' => NS_USER, 'ܡܡܠܠܐ_ܕܡܬܚܫܚܢܐ' => NS_USER_TALK, ); $specialPageAliases = array( 'Allmessages' => array( 'ܟܠ_ܐܓܪ̈ܬܐ' ), 'Allpages' => array( 'ܟܠ_ܦܐܬܬ̈ܐ' ), 'Blankpage' => array( 'ܦܐܬܐ_ܣܦܝܩܬܐ' ), 'Categories' => array( 'ܣܕܪ̈ܐ' ), 'Contributions' => array( 'ܫܘܬܦܘܝܬ̈ܐ' ), 'CreateAccount' => array( 'ܒܪܝ_ܚܘܫܒܢܐ' ), 'DeletedContributions' => array( 'ܫܘܬܦܘܝܬ̈ܐ_ܫܝܦܬ̈ܐ' ), 'Filepath' => array( 'ܫܒܝܠܐ_ܕܦܐܬܐ' ), 'Log' => array( 'ܣܓܠ̈ܐ' ), 'Longpages' => array( 'ܦܐܬܬ̈ܐ_ܐܪ̈ܝܟܬܐ' ), 'Movepage' => array( 'ܫܢܝ_ܦܐܬܐ' ), 'Mycontributions' => array( 'ܫܘܬܦܘܝܬ̈ܝ' ), 'Newpages' => array( 'ܦܐܬܬ̈ܐ_ܚܕ̈ܬܬܐ' ), 'Preferences' => array( 'ܓܒܝܬ̈ܐ' ), 'Protectedpages' => array( 'ܦܐܬܬ̈ܐ_ܢܛܝܪ̈ܬܐ' ), 'Protectedtitles' => array( 'ܟܘܢܝ̈ܐ_ܢܛܝܪ̈ܐ' ), 'Recentchanges' => array( 'ܫܘܚܠܦ̈ܐ_ܚܕ̈ܬܐ' ), 'Search' => array( 'ܒܨܝܐ' ), 'Shortpages' => array( 'ܦܐܬܬ̈ܐ_ܟܪ̈ܝܬܐ' ), 'Specialpages' => array( 'ܦܐܬܬ̈ܐ_ܕ̈ܝܠܢܝܬܐ' ), 'Upload' => array( 'ܐܣܩ' ), 'Watchlist' => array( 'ܪ̈ܗܝܬܐ' ), 'Whatlinkshere' => array( 'ܡܐ_ܐܣܪ_ܠܗܪܟܐ' ), ); $magicWords = array( 'redirect' => array( '0', '#ܨܘܝܒܐ', '#REDIRECT' ), 'numberofpages' => array( '1', 'ܡܢܝܢܐ_ܕܦܐܬܬ̈ܐ', 'NUMBEROFPAGES' ), 'numberofarticles' => array( '1', 'ܡܢܝܢܐ_ܕܡܠܘܐ̈ܐ', 'NUMBEROFARTICLES' ), 'numberoffiles' => array( '1', 'ܡܢܝܢܐ_ܕܠܦܦ̈ܐ', 'NUMBEROFFILES' ), 'pagename' => array( '1', 'ܫܡܐ_ܕܦܐܬܐ', 'PAGENAME' ), 'pagenamee' => array( '1', 'ܟܘܢܝܐ_ܕܦܐܬܐ', 'PAGENAMEE' ), 'namespace' => array( '1', 'ܚܩܠܐ', 'NAMESPACE' ), 'msg' => array( '0', 'ܐܓܪܬܐ:', 'MSG:' ), 'img_thumbnail' => array( '1', 'ܙܥܘܪܬܐ', 'thumbnail', 'thumb' ), 'img_manualthumb' => array( '1', 'ܙܥܘܪܬܐ=$1', 'thumbnail=$1', 'thumb=$1' ), 'img_right' => array( '1', 'ܝܡܝܢܐ', 'right' ), 'img_left' => array( '1', 'ܣܡܠܐ', 'left' ), 'img_none' => array( '1', 'ܠܐ_ܡܕܡ', 'none' ), 'img_center' => array( '1', 'ܡܨܥܐ', 'center', 'centre' ), 'img_page' => array( '1', 'ܦܐܬܐ=$1', 'ܦܐܬܐ $1', 'page=$1', 'page $1' ), 'img_border' => array( '1', 'ܬܚܘܡܐ', 'border' ), 'img_baseline' => array( '1', 'ܣܪܛܐ_ܫܪܫܝܐ', 'baseline' ), 'img_sub' => array( '1', 'ܦܪܥܝܐ', 'sub' ), 'grammar' => array( '0', 'ܬܘܪܨ_ܡܡܠܠܐ:', 'GRAMMAR:' ), 'gender' => array( '0', 'ܓܢܣܐ:', 'GENDER:' ), 'language' => array( '0', '#ܠܫܢܐ:', '#LANGUAGE:' ), 'special' => array( '0', 'ܕܝܠܢܝܐ', 'special' ), 'url_path' => array( '0', 'ܫܒܝܠܐ', 'PATH' ), 'url_wiki' => array( '0', 'ܘܝܩܝ', 'WIKI' ), ); $messages = array( # User preference toggles 'tog-underline' => 'ܪܫܘܡ ܣܪܛܐ ܬܚܝܬ ܐܣܪܐ:', 'tog-justify' => 'ܫܘܐ ܦܬܓܡ̈ܐ', 'tog-hideminor' => 'ܛܫܝ ܫܘܚܠܦ̈ܐ ܙܥܘܪ̈ܐ ܒܫܘܚܠܦ̈ܐ ܚܕ̈ܬܐ', 'tog-hidepatrolled' => 'ܛܫܝ ܫܘܚܠܦ̈ܐ ܟܪ̈ܝܟܐ ܒܫܘܚܠܦ̈ܐ ܚܕ̈ܬܐ', 'tog-newpageshidepatrolled' => 'ܛܫܝ ܦܐܬܬ̈ܐ ܟܪ̈ܝܟܬܐ ܡܢ ܡܟܬܒܘܬܐ ܕܦܐܬܐ ܚܕܬܐ', 'tog-extendwatchlist' => 'ܐܪܘܚ ܪ̈ܗܝܬܐ ܠܚܘܘܝܐ ܕܟܠܗܘܢ ܫܘܚܠܦ̈ܐ، ܠܐ ܚܕ̈ܬܐ ܒܠܚܘܕ', 'tog-editondblclick' => 'ܫܚܠܦ ܦܐܬ̈ܐ ܬܪ ܢܩܪܐ ܙܘܓܢܝܐ (ܣܢܝܩܬ ܠ JavaScript)', 'tog-editsection' => 'ܡܫܟܚ ܫܘܚܠܦܐ ܕܦܘܣܩ̈ܐ ܒܐܘܪܚܐ ܕܐܝܨܘܪ̈ܐ [ܫܚܠܦ]', 'tog-rememberpassword' => 'ܕܟܘܪ ܥܠܠܬܝ ܥܠ ܡܦܐܬܢܐ ܗܢܐ (ܠܡܬܚܐ ܥܠܝܐ ܕ $1 {{PLURAL:$1|ܝܘܡܐ|ܝܘܡܬ̈ܐ}})', 'tog-watchcreations' => 'ܐܘܣܦ ܦܐܬܬ̈ܐ ܕܒܪܐ ܐܢܐ ܘܠܠܦ̈ܐ ܕܐܣܩ ܐܢܐ ܠܪ̈ܗܝܬܝ', 'tog-watchdefault' => 'ܐܘܣܦ ܦܐܬܬ̈ܐ ܘܠܦܦ̈ܐ ܕܫܚܠܦ ܐܢܐ ܠܪ̈ܗܝܬܝ', 'tog-watchmoves' => 'ܐܘܣܦ ܦܐܬܬ̈ܐ ܘܠܦܦ̈ܐ ܕܫܢܐ ܐܢܐ ܠܪ̈ܗܝܬܝ', 'tog-watchdeletion' => 'ܐܘܣܦ ܦܐܬܬ̈ܐ ܘܠܦܦ̈ܐ ܕܫܐܦ ܐܢܐ ܠܪ̈ܗܝܬܝ', 'tog-oldsig' => 'ܪܡܝ ܐܝܕܐ ܗܫܝܐ:', 'tog-watchlisthideown' => 'ܛܫܝ ܫܘܚܠܦ̈ܝ ܡܢ ܪ̈ܗܝܬܐ', 'tog-watchlisthidebots' => 'ܛܫܝ ܫܘܚܠܦ̈ܐ ܕܒܘܬ ܡܢ ܪ̈ܗܝܬܐ', 'tog-watchlisthideminor' => 'ܛܫܝ ܫܘܚܠܦ̈ܐ ܙܥܘܪ̈ܐ ܡܢ ܪ̈ܗܝܬܐ', 'tog-watchlisthideliu' => 'ܛܫܝ ܫܘܚܠܦ̈ܐ ܕܡܦܠܚܢ̈ܐ ܥܠܝܠ̈ܐ ܡܢ ܪ̈ܗܝܬܐ', 'tog-watchlisthideanons' => 'ܛܫܝ ܫܘܚܠܦ̈ܐ ܕܡܦܠܚܢ̈ܐ ܠܐ ܝܕ̈ܝܥܐ ܡܢ ܪ̈ܗܝܬܐ', 'tog-ccmeonemails' => 'ܫܕܪ ܠܝ ܨܚܚ̈ܐ ܕܒܝܠܕܪ̈ܐ ܐܠܩܛܪ̈ܘܢܝܐ ܕܫܕܪ ܐܢܐ ܠܡܦܠܚܢ̈ܐ ܐܚܪ̈ܢܐ', 'tog-showhiddencats' => 'ܚܘܝ ܣܕܪ̈ܐ ܛܘܫܝ̈ܐ', 'underline-always' => 'ܐܡܝܢ', 'underline-never' => 'ܠܐ ܡܡܬܘܡ', # Dates 'sunday' => 'ܚܕܒܫܒܐ', 'monday' => 'ܬܪܝܢܒܫܒܐ', 'tuesday' => 'ܬܠܬܒܫܒܐ', 'wednesday' => 'ܐܪܒܥܒܫܒܐ', 'thursday' => 'ܚܡܫܒܫܒܐ', 'friday' => 'ܥܪܘܒܬܐ', 'saturday' => 'ܫܒܬܐ', 'sun' => 'ܚܕܒܫܒܐ', 'mon' => 'ܬܪܝܢܒܫܒܐ', 'tue' => 'ܬܠܬܒܫܒܐ', 'wed' => 'ܐܪܒܥܒܫܒܐ', 'thu' => 'ܚܡܫܒܫܒܐ', 'fri' => 'ܥܪܘܒܬܐ', 'sat' => 'ܫܒܬܐ', 'january' => 'ܒܟܢܘܢ ܐܚܪܝ', 'february' => 'ܒܫܒܛ', 'march' => 'ܒܐܕܪ', 'april' => 'ܒܢܝܣܢ', 'may_long' => 'ܒܐܝܪ', 'june' => 'ܒܚܙܝܪܢ', 'july' => 'ܒܬܡܘܙ', 'august' => 'ܒܐܒ', 'september' => 'ܒܐܝܠܘܠ', 'october' => 'ܒܬܫܪܝܢ ܩܕܡ', 'november' => 'ܒܬܫܪܝܢ ܐܚܪܝ', 'december' => 'ܒܟܢܘܢ ܩܕܡ', 'january-gen' => 'ܟܢܘܢ ܐܚܪܝ', 'february-gen' => 'ܫܒܛ', 'march-gen' => 'ܐܕܪ', 'april-gen' => 'ܢܝܣܢ', 'may-gen' => 'ܐܝܪ', 'june-gen' => 'ܚܙܝܪܢ', 'july-gen' => 'ܬܡܘܙ', 'august-gen' => 'ܐܒ', 'september-gen' => 'ܐܝܠܘܠ', 'october-gen' => 'ܬܫܪܝܢ ܩܕܡ', 'november-gen' => 'ܬܫܪܝܢ ܐܚܪܝ', 'december-gen' => 'ܟܢܘܢ ܩܕܡ', 'jan' => 'ܟܢܘܢ ܐܚܪܝ', 'feb' => 'ܫܒܛ', 'mar' => 'ܐܕܪ', 'apr' => 'ܢܝܣܢ', 'may' => 'ܐܝܪ', 'jun' => 'ܚܙܝܪܢ', 'jul' => 'ܬܡܘܙ', 'aug' => 'ܐܒ', 'sep' => 'ܐܝܠܘܠ', 'oct' => 'ܬܫܪܝܢ ܩܕܡ', 'nov' => 'ܬܫܪܝܢ ܐܚܪܝ', 'dec' => 'ܟܢܘܢ ܩܕܡ', # Categories related messages 'pagecategories' => '{{PLURAL:$1|ܣܕܪܐ|ܣܕܪ̈ܐ}}', 'category_header' => 'ܦܐܬܬ̈ܐ ܒܣܕܪܐ ܕ "$1"', 'subcategories' => 'ܣܕܪ̈ܐ ܦܪ̈ܥܝܐ', 'category-media-header' => 'ܡܝܕܝܐ ܒܣܕܪܐ ܕ "$1"', 'category-empty' => "''ܗܢܐ ܣܕܪܐ ܗܫܐܝܬ ܠܝܬ ܒܗ ܦܐܬܬ̈ܐ ܐܘ ܡܝܕܝܐ.''", 'hidden-categories' => '{{PLURAL:$1|ܣܕܪܐ ܛܘܫܝܐ|ܣܕܪ̈ܐ ܛܘܫܝܐ}}', 'hidden-category-category' => 'ܣܕܪ̈ܐ ܛܘܫܝ̈ܐ', 'category-subcat-count' => '{{PLURAL:$2|ܣܕܪܐ ܗܢܐ ܐܝܬ ܒܗ ܗܢܐ ܣܕܪܐ ܦܪܥܝܐ ܕܐܬܐ ܒܠܚܘܕ.|ܣܕܪܐ ܗܢܐ ܐܝܬ ܒܗ {{PLURAL:$1|ܣܕܪܐ ܦܪܥܝܐ ܕܐܬܐ|$1 ܣܕܪ̈ܐ ܦܪ̈ܥܝܐ ܕܐܬܝܢ}}، ܡܢ ܣܘܝܟܐ ܕ $2.}}', 'category-subcat-count-limited' => 'ܣܕܪܐ ܗܢܐ ܐܝܬ ܒܗ {{PLURAL:$1|ܣܕܪܐ ܦܪܥܝܐ ܗܢܐ|$1 ܣܕܪ̈ܐ ܦܪ̈ܥܝܐ ܗܠܝܢ}}.', 'category-article-count' => '{{PLURAL:$2|ܣܕܪܐ ܗܢܐ ܠܝܬ ܒܗ ܦܐܬܐ.|{{PLURAL:$1||ܣܕܪܐ ܗܢܐ ܐܝܬ ܒܗ ܦܐܬܐ ܗܕܐ ܒܠܚܘܕ|ܣܕܪܐ ܗܢܐ ܐܝܬ ܒܗ ܗܠܝܢ $1 ܦܐܬܬ̈ܐ}} ܡܢ ܣܘܝܟܐ ܕ $2.}}', 'category-article-count-limited' => '{{PLURAL:$1|ܦܐܬܐ ܗܕܐ|$1 ܦܐܬܬ̈ܐ ܗܠܝܢ}} ܒܣܕܪܐ ܗܢܐ.', 'category-file-count' => '{{PLURAL:$2|ܣܕܪܐ ܗܢܐ ܐܝܬ ܒܗ ܠܦܦܐ ܕܐܬܐ ܒܠܚܘܕ.|{{PLURAL:$1|ܠܦܦܐ ܕܐܬܐ ܐܝܬܘܗܝ|$1 ܠܦܦ̈ܐ ܕܐܬܝܢ ܐܝܬܝܗܘܢ}} ܒܣܕܪܐ ܗܢܐ، ܡܢ ܣܘܝܟܐ ܕ $2.}}', 'category-file-count-limited' => 'ܐܝܬ {{PLURAL:$1|ܠܦܦܐ ܕܐܬܐ|$1 ܠܦܦ̈ܐ ܕܐܬܝܢ}} ܒܣܕܪܐ ܗܫܝܐ.', 'listingcontinuesabbrev' => '(ܫܘܠܡܐ)', 'about' => 'ܡܢܘ', 'article' => 'ܡܓܠܬܐ', 'newwindow' => '(ܦܬܚ ܒܟܘܬܐ ܚܕܬܐ)', 'cancel' => 'ܒܛܘܠ', 'moredotdotdot' => 'ܝܬܝܪ...', 'mypage' => 'ܦܐܬܐ', 'mytalk' => 'ܡܡܠܠܐ', 'anontalk' => 'ܡܡܠܠܐ ܕܗܢܐ ܐܝ ܦܝ (IP)', 'navigation' => 'ܐܠܦܪܘܬܐ', 'and' => '&#32;ܘ', # Cologne Blue skin 'qbfind' => 'ܐܫܟܚ', 'qbbrowse' => 'ܡܦܐܬ', 'qbedit' => 'ܫܚܠܦ', 'qbpageoptions' => 'ܗܕܐ ܦܐܬܐ', 'qbmyoptions' => 'ܦܐܬܬ̈ܐ ܕܝܠܝ', 'qbspecialpages' => 'ܦܐܬܬ̈ܐ ܕ̈ܝܠܢܝܬܐ', 'faq' => 'ܫܘܐܠ̈ܐ ܬܢܝ̈ܐ', 'faqpage' => 'Project:ܫܘܐܠ̈ܐ ܬܢܝ̈ܐ', # Vector skin 'vector-action-addsection' => 'ܐܘܣܦ ܡܠܘܐܐ', 'vector-action-delete' => 'ܫܘܦ', 'vector-action-move' => 'ܫܢܝ', 'vector-action-protect' => 'ܛܪ', 'vector-action-undelete' => 'ܠܐ ܫܘܦ', 'vector-action-unprotect' => 'ܫܚܠܦ ܢܛܝܪܘܬܐ', 'vector-view-create' => 'ܒܪܝ', 'vector-view-edit' => 'ܫܚܠܦ', 'vector-view-history' => 'ܚܙܝ ܬܫܥܝܬܐ', 'vector-view-view' => 'ܩܪܝ', 'vector-view-viewsource' => 'ܚܙܝ ܡܒܘܥܐ', 'actions' => 'ܥܒܕ̈ܐ', 'namespaces' => 'ܚܩܠܬ̈ܐ', 'variants' => 'ܡܫܬܚܠܦܢܘ̈ܬܐ', 'errorpagetitle' => 'ܦܘܕܐ', 'returnto' => 'ܕܥܘܪ ܠ$1.', 'tagline' => 'ܡܢ {{SITENAME}}', 'help' => 'ܥܘܕܪܢܐ', 'search' => 'ܒܨܝܐ', 'searchbutton' => 'ܒܨܝ', 'go' => 'ܙܠ', 'searcharticle' => 'ܙܠ', 'history' => 'ܬܫܥܝܬܐ ܕܦܐܬܐ', 'history_short' => 'ܬܫܥܝܬܐ', 'updatedmarker' => 'ܐܬܚܕܬ ܗܐ ܡܢ ܙܒܢܐ ܕܣܘܥܪܢܝ ܐܚܪܝܐ', 'printableversion' => 'ܨܚܚܐ ܡܬܛܒܥܢܐ', 'permalink' => 'ܐܣܘܪܐ ܦܝܘܫܐ', 'print' => 'ܛܒܘܥ', 'view' => 'ܚܘܝ', 'edit' => 'ܫܚܠܦ', 'create' => 'ܒܪܝ', 'editthispage' => 'ܫܚܠܦ ܦܐܬܐ ܗܕܐ', 'create-this-page' => 'ܒܪܝ ܗܕܐ ܦܐܬܐ', 'delete' => 'ܫܘܦ', 'deletethispage' => 'ܫܘܦ ܦܐܬܐ ܗܕܐ', 'undelete_short' => 'ܠܐ ܫܘܦ {{PLURAL:$1|ܚܕ ܫܘܚܠܦܐ|$1 ܫܘܚܠܦ̈ܐ}}', 'viewdeleted_short' => 'ܚܙܝ {{PLURAL:$1|ܚܕ ܫܘܚܠܦܐ ܫܝܦܐ|$1 ܫܘܚܠܦ̈ܐ ܫܝܦ̈ܐ}}', 'protect' => 'ܛܪ', 'protect_change' => 'ܫܚܠܦ', 'protectthispage' => 'ܛܪ ܠܗܕܐ ܦܐܬܐ', 'unprotect' => 'ܫܚܠܦ ܢܛܝܪܘܬܐ', 'unprotectthispage' => 'ܫܚܠܦ ܢܛܝܪܘܬܐ ܕܗܕܐ ܦܐܬܐ', 'newpage' => 'ܦܐܬܐ ܚܕܬܐ', 'talkpage' => 'ܕܪܘܫ ܗܕܐ ܦܐܬܐ', 'talkpagelinktext' => 'ܡܡܠܠܐ', 'specialpage' => 'ܦܐܬܐ ܕܝܠܢܝܬܐ', 'personaltools' => 'ܡܐܢ̈ܐ ܦܪ̈ܨܘܦܝܐ', 'postcomment' => 'ܡܢܬܐ ܚܕܬܐ', 'articlepage' => 'ܚܘܝܝܐ ܕܦܐܬܐ ܕܚܒܝܫܬ̈ܐ', 'talk' => 'ܡܡܠܠܐ', 'views' => 'ܚܙܝܬ̈ܐ', 'toolbox' => 'ܣܢܕܘܩܐ ܕܡܐܢ̈ܐ', 'userpage' => 'ܚܙܝ ܦܐܬܐ ܕܡܦܠܚܢܐ', 'projectpage' => 'ܚܙܝ ܦܐܬܐ ܕܬܪܡܝܬܐ', 'imagepage' => 'ܚܙܝ ܦܐܬܐ ܕܠܦܦܐ', 'mediawikipage' => 'ܚܙܝ ܦܐܬܐ ܕܐܓܪܬܐ', 'templatepage' => 'ܚܙܝ ܦܐܬܐ ܕܩܠܒܐ', 'viewhelppage' => 'ܚܙܝ ܦܐܬܐ ܕܥܘܕܪܢܐ', 'categorypage' => 'ܚܙܝ ܦܐܬܐ ܕܣܕܪܐ', 'viewtalkpage' => 'ܚܙܝ ܡܡܠܠܐ', 'otherlanguages' => 'ܠܫܢ̈ܐ ܐܚܪ̈ܢܐ', 'redirectedfrom' => '(ܨܝܒ ܡܢ $1)', 'redirectpagesub' => 'ܦܐܬܐ ܕܨܘܝܒܐ', 'lastmodifiedat' => 'ܫܘܚܠܦܐ ܐܚܪܝܐ ܕܦܐܬܐ ܗܕܐ ܗܘܐ ܒܣܝܩܘܡ $1, $2.', 'viewcount' => 'ܐܬܓܠܚܬ ܗܕܐ ܦܐܬܐ {{PLURAL:$1|ܙܒܢܬܐ ܚܕ|$1 ܙܒܢܝ̈ܢ}}.', 'protectedpage' => 'ܦܐܬܐ ܢܛܝܪܬܐ', 'jumpto' => 'ܫܘܪ ܠ:', 'jumptonavigation' => 'ܐܠܦܪܘܬܐ', 'jumptosearch' => 'ܒܨܝܐ', 'view-pool-error' => 'ܫܘܒܩܢܐ، ܬܫܡܫܬ̈ܐ ܐܢܘܢ ܠܐ̈ܝܐ ܗܫܐܝܬ ܣܓܝ ܡܦܠܚܢ̈ܐ ܢܣܝܢ ܠܚܙܝܐ ܕܦܐܬܐ ܗܕܐ ܦܝܣܐ ܡܢܟ ܣܟܝ ܩܠܝܠ ܡܢ ܩܕܡ ܕܬܢܣܐ ܠܡܛܝܐ ܠܦܐܬܐ ܗܕܐ ܙܒܢܬܐ ܐܚܪܬܐ. $1', 'pool-timeout' => 'ܫܠܡ ܥܕܢܐ ܣܒܪܬܐ ܠܚܠܩܐ', 'pool-queuefull' => 'ܣܕܪܐ ܕܦܘܣܣܐ ܡܠܝܐ', 'pool-errorunknown' => 'ܦܘܕܐ ܠܐ ܝܕܝܥܐ', # All link text and link target definitions of links into project namespace that get used by other message strings, with the exception of user group pages (see grouppage) and the disambiguation template definition (see disambiguations). 'aboutsite' => 'ܡܢܘ {{SITENAME}}', 'aboutpage' => 'Project:ܡܢܘ', 'copyright' => 'ܚܒܝܫܬ̈ܐ ܐܝܬ ܬܚܝܬ $1.', 'copyrightpage' => '{{ns:project}}:ܙܕ̈ܩܐ ܕܚܬܡܐ', 'currentevents' => 'ܓܕ̈ܫܐ ܗܫܝ̈ܐ', 'currentevents-url' => 'Project:ܓܕ̈ܫܐ ܗܫܝ̈ܐ', 'disclaimers' => 'ܠܐ ܡܫܬܐܠܢܘܬܐ', 'disclaimerpage' => 'Project:ܠܐ ܡܫܬܐܠܢܘܬܐ ܓܘܢܝܬܐ', 'edithelp' => 'ܥܘܕܪܢܐ ܠܫܚܠܦܬܐ', 'edithelppage' => 'Help:ܫܚܠܦܬܐ', 'helppage' => 'Help:ܚܒܝܫܬ̈ܐ', 'mainpage' => 'ܦܐܬܐ ܪܝܫܝܬܐ', 'mainpage-description' => 'ܦܐܬܐ ܪܝܫܝܬܐ', 'policy-url' => 'Project:ܦܘܪܢܣܐ', 'portal' => 'ܬܪܥܐ ܕܟܢܫܐ', 'portal-url' => 'Project:ܬܪܥܐ ܕܟܢܫܐ', 'privacy' => 'ܦܘܪܢܣܐ ܕܕܝܠܢܝܘܬܐ', 'privacypage' => 'Project:ܦܘܪܢܣܐ ܕܕܝܠܢܝܘܬܐ', 'badaccess' => 'ܦܘܕܐ ܒܦܣܣܐ', 'badaccess-group0' => 'ܠܬ ܠܟ ܦܣܣܐ ܠܚܘܩܩܐ ܕܥܒܕܐ ܕܐܢܬ ܫܐܠܬܝ.', 'ok' => 'ܛܒ', 'youhavenewmessages' => 'ܐܝܬ ܠܟ $1 ($2).', 'newmessageslink' => 'ܐܓܪ̈ܬܐ ܚܕ̈ܬܬܐ', 'newmessagesdifflink' => 'ܫܘܚܠܦܐ ܐܚܪܝܐ', 'youhavenewmessagesmulti' => 'ܐܝܬ ܠܟ ܐܓܪ̈ܬܐ ܚܕ̈ܬܬܐ ܒ $1', 'editsection' => 'ܫܚܠܦ', 'editold' => 'ܫܚܠܦ', 'viewsourceold' => 'ܚܙܝ ܡܒܘܥܐ', 'editlink' => 'ܫܚܠܦ', 'viewsourcelink' => 'ܚܙܝ ܡܒܘܥܐ', 'editsectionhint' => 'ܫܚܠܦ ܡܢܬܐ: $1', 'toc' => 'ܚܒܝܫܬ̈ܐ', 'showtoc' => 'ܚܘܝ', 'hidetoc' => 'ܛܫܝ', 'collapsible-collapse' => 'ܐܟܪܟ', 'collapsible-expand' => 'ܪܘܚ', 'viewdeleted' => 'ܚܙܝ $1؟', 'restorelink' => '{{PLURAL:$1|ܚܕ ܫܘܚܠܦܐ ܫܝܦܐ|$1 ܫܘܚܠܦ̈ܐ ܫܝܦ̈ܐ}}', 'site-atom-feed' => '$1 ܛܥܝܡܘܬܐ ܕܐܛܘܡ', 'page-atom-feed' => '"$1" ܛܥܝܡܘܬܐ ܕܐܛܘܡ', 'feed-atom' => 'ܐܛܘܡ', 'red-link-title' => '$1 (ܦܐܬܐ ܗܕܐ ܠܝܬ)', 'sort-descending' => 'ܣܘܕܪܐ ܡܚܬܐܝܬ', 'sort-ascending' => 'ܣܘܕܪܐ ܡܣܩܐܝܬ', # Short words for each namespace, by default used in the namespace tab in monobook 'nstab-main' => 'ܦܐܬܐ', 'nstab-user' => 'ܦܐܬܐ ܕܡܦܠܚܢܐ', 'nstab-media' => 'ܦܐܬܐ ܕܡܝܕܝܐ', 'nstab-special' => 'ܦܐܬܐ ܕܝܠܢܝܬܐ', 'nstab-project' => 'ܦܐܬܐ ܕܬܪܡܝܬܐ', 'nstab-image' => 'ܠܦܦܐ', 'nstab-mediawiki' => 'ܐܓܪܬܐ', 'nstab-template' => 'ܩܠܒܐ', 'nstab-help' => 'ܦܐܬܐ ܕܥܘܕܪܢܐ', 'nstab-category' => 'ܣܕܪܐ', # Main script and global functions 'nosuchaction' => 'ܠܝܬ ܗܟܘܬ ܥܒܕܐ', 'nosuchspecialpage' => 'ܠܝܬ ܗܟܘܬ ܦܐܬܐ ܕܝܠܢܝܬܐ', # General errors 'error' => 'ܦܘܕܐ', 'databaseerror' => 'ܦܘܕܐ ܒܐܣ ܝܕ̈ܥܬܐ', 'missingarticle-rev' => '(ܡܢܝܢܐ ܕܬܢܝܬܐ: $1)', 'missingarticle-diff' => '(ܦܘܪܫܐ: $1, $2)', 'internalerror' => 'ܦܘܕܐ ܓܘܝܐ', 'internalerror_info' => 'ܦܘܕܐ ܓܘܝܐ: $1', 'badtitle' => 'ܟܘܢܝܐ ܠܐ ܛܒܐ', 'perfcached' => 'ܓܠܝܬ̈ܐ ܗܠܝܢ ܐܣܢܝܢ ܐܢܘܢ ܘܡܬܡܨܝܢܬܐ ܐܝܬܝܗܝ ܕܠܐ ܢܗܘܢ ܚܘ̈ܕܬܐ. ܡܬܚܐ ܥܠܝܐ ܕ {{PLURAL:$1|ܚܕ ܦܠܛܐ|$1 ܦܠܛ̈ܐ}} ܐܝܬ ܒܐܣܢܐ.', 'perfcachedts' => 'ܓܠܝܬ̈ܐ ܗܠܝܢ ܐܣܢܝܢ ܐܢܘܢ ܘܚܘܕܬܐ ܐܚܪܝܐ ܗܘܐ ܒ $1. ܡܬܚܐ ܥܠܝܐ ܕ {{PLURAL:$4|ܚܕ ܦܠܛܐ|$4 ܦܠܛ̈ܐ}} ܐܝܬ ܒܐܣܢܐ.', 'querypage-no-updates' => 'ܚܘܕ̈ܬܐ ܕܗܕܐ ܦܐܬܐ ܠܐ ܙܪ̈ܝܙܐ ܐܢܘܢ. ܝܕ̈ܥܬܐ ܗܪܟܐ ܠܐ ܡܬܚܕܬܝܢ ܗܫܐ.', 'viewsource' => 'ܚܙܝ ܡܒܘܥܐ', 'viewsource-title' => 'ܚܙܝ ܡܒܘܥܐ ܕ $1', 'actionthrottled' => 'ܠܐ ܡܬܡܨܝܢܬܐ ܐܝܬܝܗܝ ܠܡܥܒܕ ܝܬܝܪ ܡܢ ܗܢܐ ܥܒܕܐ', 'viewsourcetext' => 'ܡܨܐ ܐܢܬ ܕܬܚܙܐ ܘܬܢܣܚ ܠܡܒܘ̈ܥܐ ܕܗܕܐ ܦܐܬܐ:', 'protectedinterface' => 'ܗܕܐ ܦܐܬܐ ܡܘܬܪܐ ܟܬܝܒܬܐ ܕܦܐܬܐ ܠܚܘܪܙܐ ܒܗܢܐ ܘܝܩܝ, ܘܐܝܬܝܗܝ ܢܛܪܬܐ ܠܡܘܢܥ ܚܘܒܠܐ. ܠܡܘܣܦ ܐܘ ܫܘܚܠܦ ܬܘܪ̈ܓܡܐ ܕܟܠܗܘܢ ܘܝܩܝ، ܐܦܠܚ [//translatewiki.net/ translatewiki.net]، ܬܪܡܝܬܐ ܕܬܘܪܓܡܐ ܕܡܝܕܝܐܘܝܩܝ.', 'editinginterface' => "'''ܙܘܗܪܐ:''' ܐܢܬ ܬܫܚܠܦ ܦܐܬܐ ܕܡܬܦܠܚܬ ܒܚܙܝܐ ܟܬܝܒܝܐ ܕܬܚܪܙܬܐ. ܟܠ ܫܘܚܠܦܐ ܒܦܐܬܐ ܗܕܐ ܢܗܘܐ ܠܗ ܡܥܒܕܢܘܬܐ ܥܠ ܐܣܟܡܐ ܕܦܐܬܐ ܕܡܦܠܚܢܐ ܕܡܦܠܚܢ̈ܐ ܐܚܪ̈ܢܐ ܒܘܝܩܝ ܗܢܐ. ܠܡܘܣܦ ܐܘ ܫܘܚܠܦ ܬܘܪ̈ܓܡܐ ܕܟܠܗܘܢ ܘܝܩܝ، ܐܦܠܚ [//translatewiki.net/ translatewiki.net]، ܬܪܡܝܬܐ ܕܬܘܪܓܡܐ ܕܡܝܕܝܐܘܝܩܝ.", 'sqlhidden' => '(ܒܘܬܬܐ SQL ܛܫܝܐ)', 'namespaceprotected' => "ܠܝܬ ܠܟ ܦܣܣܐ ܠܫܚܠܦܬܐ ܕܦܐܬܬ̈ܐ ܒܚܩܠܐ ܕ'''$1'''.", # Login and logout pages 'logouttext' => "'''ܗܫܐ ܦܠܛܠܟ ܡܢ ܚܘܫܒܢܟ.''' ܡܨܬ ܐܦܠܚܬ {{SITENAME}} ܐܝܟ ܡܦܠܚܢܐ ܠܐ ܝܕܝܥܐ ܐܘ ܡܨܬ ܕ[[Special:UserLogin|ܬܥܘܠ]] ܒܚܘܫܒܢܐ ܥܝܢܗ ܐܘ ܐܝܟ ܡܦܠܚܢܐ ܐܚܪܢܐ. ܚܕ ܟܡܐ ܡܢ ܦܐܬܬ̈ܐ ܡܬܚܙܝܢ ܐܝܟ ܕܗܘ ܐܢܬ ܥܠܝܠܐ ܐܝܬܝܟ ܥܕܡܐ ܕܐܣܦܩܬ ܠܦܐܬܬ̈ܐ ܠܒܝܟܬ̈ܐ ܕܡܦܐܬܢܐ ܕܝܠܟ", 'welcomecreation' => '== ܒܫܝܢܐ, $1! == ܐܬܒܪܝ ܚܘܫܒܢܟ. ܠܐ ܢܫܐ ܐܢܬ ܠܫܚܠܦܬܐ ܕ[[Special:Preferences|ܨܒܝܢܝܘܬ̈ܐ ܒ {{SITENAME}}]].', 'yourname' => 'ܫܡܐ ܕܡܦܠܚܢܐ:', 'yourpassword' => 'ܡܠܬܐ ܕܥܠܠܐ:', 'yourpasswordagain' => 'ܟܬܘܒ ܡܠܬܐ ܕܥܠܠܐ ܙܒܢܬܐ ܐܚܪܬܐ:', 'remembermypassword' => 'ܕܟܘܪ ܥܠܠܬܝ ܥܠ ܡܦܐܬܢܐ ܗܢܐ (ܠܡܬܚܐ ܥܠܝܐ ܕ $1 {{PLURAL:$1|ܝܘܡܐ|ܝܘܡܬ̈ܐ}})', 'login' => 'ܥܘܠ', 'nav-login-createaccount' => 'ܥܘܠ / ܒܪܝ ܚܘܫܒܢܐ', 'loginprompt' => 'ܐܠܨܐ ܠܡܦܐܬܢܐ ܕܝܠܟ ܕܣܡܟ ܠܩܘܩܝܙ (cookies) ܠܥܠܠܬܐ ܒ {{SITENAME}}.', 'userlogin' => 'ܥܘܠ / ܒܪܝ ܚܘܫܒܢܐ', 'userloginnocreate' => 'ܥܘܠ', 'logout' => 'ܦܠܘܛ', 'userlogout' => 'ܦܠܘܛ', 'notloggedin' => 'ܠܝܬܝܟ ܥܠܝܠܐ', 'nologin' => "ܠܝܬ ܠܟ ܚܘܫܒܢܐ؟ '''$1'''.", 'nologinlink' => 'ܒܪܝ ܚܘܫܒܢܐ', 'createaccount' => 'ܒܪܝ ܚܘܫܒܢܐ', 'gotaccount' => "ܐܝܬ ܠܟ ܚܘܫܒܢܐ؟ '''$1'''.", 'gotaccountlink' => 'ܥܘܠ', 'userlogin-resetlink' => 'ܐܬܢܫܝܬ ܝܕ̈ܥܬܐ ܕܥܠܠܐ؟', 'createaccountmail' => 'ܒܝܕ ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ', 'createaccountreason' => 'ܥܠܬܐ', 'badretype' => 'ܡܠܬܐ ܕܥܠܠܐ ܟܬܒܬ ܐܢܬ ܠܐ ܐܘܝܢܬܐ.', 'userexists' => 'ܫܡܐ ܕܡܦܠܚܢܐ ܕܐܥܠܬ ܫܩܝܠܐ ܐܝܬܘܗܝ. ܫܦܝܪܐܝܬ ܓܒܝ ܫܡܐ ܐܚܪܢܐ.', 'loginerror' => 'ܦܘܕܐ ܒܥܠܠܐ', 'createaccounterror' => 'ܠܐ ܡܫܟܚ ܠܒܪܝܐ ܚܘܫܒܢܐ: $1', 'noname' => 'ܠܐ ܦܪܫ ܐܢܬ ܫܡܐ ܕܡܦܠܚܢܐ ܬܪܝܨܐ', 'loginsuccesstitle' => 'ܥܠܠܐ ܓܡܪ', 'loginsuccess' => "'''ܗܫܐ ܥܠܝܠܐ ܐܢܬ ܒ{{SITENAME}} ܒܫܡ \"\$1\".'''", 'nouserspecified' => 'ܘܠܐ ܠܟ ܕܬܚܡ ܫܡܐ ܕܡܦܠܚܢܐ', 'wrongpassword' => 'ܡܠܬܐ ܕܥܠܠܐ ܠܐ ܬܪܝܨܬܐ ܐܥܠܬ. ܒܒܥܘ ܡܢܟ ܕܬܢܣܐ ܙܒܢ ܐܚܪܝܢ.', 'wrongpasswordempty' => 'ܡܠܬܐ ܕܥܠܠܐ ܕܐܥܠܬ ܣܦܝܩܬܐ ܐܝܬܝܗ. ܒܒܥܘ ܡܢܟ ܕܬܢܣܐ ܙܒܢ ܐܚܪܝܢ.', 'passwordtooshort' => 'ܡܠܬܐ ܕܥܠܠܐ ܘܠܐ ܕܬܗܘܐ ܕܠܐ ܒܨܪ ܡܢ{{PLURAL:$1|ܐܬܘܬܐ ܚܕ|$1 ܐܬܘ̈ܬܐ}}.', 'mailmypassword' => 'ܫܕܪ ܠܝ ܡܠܬܐ ܚܕܬܐ ܕܥܠܠܐ', 'passwordremindertitle' => 'ܡܠܬܐ ܕܥܠܠܐ ܙܒܢܢܝܬܐ ܚܕܬܐ ܠ{{SITENAME}}', 'noemail' => 'ܠܝܬ ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ ܠܡܦܠܚܢܐ "$1".', 'mailerror' => 'ܦܘܕܐ ܒܫܘܕܪܐ ܕܒܝܠܕܪܐ: $1', 'emailconfirmlink' => 'ܫܪܪ ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ ܕܝܠܟ', 'accountcreated' => 'ܚܘܫܒܢܐ ܒܪܐ', 'accountcreatedtext' => 'ܐܬܒܪܝ ܚܘܫܒܢܐ ܕܡܦܠܚܢܐ ܠ $1.', 'createaccount-title' => 'ܒܪܝܐ ܕܚܘܫܒܢܐ ܒ {{SITENAME}}', 'loginlanguagelabel' => 'ܠܫܢܐ: $1', # Change password dialog 'resetpass' => 'ܫܚܠܦ ܡܠܬܐ ܕܥܠܠܐ', 'resetpass_header' => 'ܫܚܠܦ ܡܠܬܐ ܕܥܠܠܐ ܕܚܘܫܒܢܐ', 'oldpassword' => 'ܡܠܬܐ ܕܥܠܠܐ ܥܬܝܩܬܐ:', 'newpassword' => 'ܡܠܬܐ ܕܥܠܠܐ ܚܕܬܐ:', 'retypenew' => 'ܟܬܘܒ ܡܠܬܐ ܕܥܠܠܐ ܙܒܢܬܐ ܐܚܪܬܐ:', 'resetpass_submit' => 'ܛܝܒ ܡܠܬܐ ܕܥܠܠܐ ܘܥܘܠ', 'resetpass-submit-loggedin' => 'ܫܚܠܦ ܡܠܬܐ ܕܥܠܠܐ', 'resetpass-submit-cancel' => 'ܒܛܘܠ', 'resetpass-temp-password' => 'ܡܠܬܐ ܕܥܠܠܐ ܙܒܢܢܝܬܐ:', # Special:PasswordReset 'passwordreset' => 'ܣܘܡ ܡܠܬܐ ܕܥܠܠܐ ܙܒܢ ܐܚܪܝܢ', 'passwordreset-legend' => 'ܣܘܡ ܡܠܬܐ ܕܥܠܠܐ ܙܒܢ ܐܚܪܝܢ', 'passwordreset-pretext' => '{{PLURAL:$1||ܐܥܠ ܚܕ ܡܢ ܡܢܘܬ̈ܐ ܕܝܕ̈ܥܬܐ ܠܬܬܚܬ}}', 'passwordreset-username' => 'ܫܡܐ ܕܡܦܠܚܢܐ:', 'passwordreset-domain' => 'ܪܘܚܬܐ:', 'passwordreset-email' => 'ܡܘܢܥܐ ܕܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ:', # Special:ChangeEmail 'changeemail' => 'ܫܚܠܦ ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ', # Edit page toolbar 'bold_sample' => 'ܟܬܒܬܐ ܥܒܝܬܐ', 'bold_tip' => 'ܟܬܒܬܐ ܥܒܝܬܐ', 'italic_sample' => 'ܟܬܒܬܐ ܦܠܝܡܬܐ', 'italic_tip' => 'ܟܬܒܬܐ ܦܠܝܡܬܐ', 'link_sample' => 'ܟܘܢܝܐ ܕܐܣܘܪܐ', 'link_tip' => 'ܐܣܘܪܐ ܓܘܝܐ', 'extlink_tip' => 'ܐܣܘܪܐ ܒܪܝܐ (ܕܟܘܪ http:// ܩܕܡܝܬܐ)', 'headline_sample' => 'ܨܚܚܐ ܕܦܪܫܓܢܐ ܪܫܝܐ', 'nowiki_sample' => 'ܣܢܘܦ ܟܬܒܬܐ ܕܠܐ ܣܕܝܪܘܬܐ ܗܪܟܐ', 'nowiki_tip' => 'ܒܣܝ ܣܕܝܪܘܬܐ ܕܘܝܩܝ', 'image_tip' => 'ܠܦܦܐ ܛܡܝܪܐ', 'media_tip' => 'ܐܣܘܪܐ ܕܠܦܦܐ', 'sig_tip' => 'ܪܡܝ ܐܝܕܟ ܥܡ ܙܒܢܐ ܘܣܝܩܘܡܐ', # Edit pages 'summary' => 'ܦܣܝܩܬ̈ܐ ܕܫܘܚܠܦܐ:', 'subject' => 'ܡܠܘܐܐ/ܡܘܢܥܐ ܪܫܝܐ:', 'minoredit' => 'ܗܢܐ ܗܘ ܫܘܚܠܦܐ ܙܥܘܪܐ', 'watchthis' => 'ܪܗܝ ܦܐܬܐ ܗܕܐ', 'savearticle' => 'ܠܒܘܟ ܦܐܬܐ', 'preview' => 'ܚܝܪܐ ܩܕܡܝܐ', 'showpreview' => 'ܚܘܝ ܚܝܪܐ ܩܕܡܝܐ', 'showlivepreview' => 'ܚܝܪܐ ܩܕܡܝܐ ܚܝܐ', 'showdiff' => 'ܚܘܝ ܫܘܚܠܦ̈ܐ', 'anoneditwarning' => "'''ܙܘܗܪܐ:''' ܠܐ ܐܝܬܝܟ ܥܠܝܠܐ. ܐܝ ܦܝ (IP) ܕܝܠܟ ܢܬܟܬܒ ܒܬܫܥܝܬܐ ܕܦܐܬܐ.", 'anonpreviewwarning' => '"ܠܐ ܐܝܬܝܟ ܥܠܝܠܐ. ܠܒܟܬܐ ܕܦܐܬܐ ܢܬܟܬܒ ܐܝ ܦܝ (IP) ܕܝܠܟ ܒܬܫܥܝܬܐ ܕܫܘܚܠܦܐ ܕܦܐܬܐ."', 'summary-preview' => 'ܚܝܪܐ ܩܕܡܝܐ ܕܦܣܝܩܬ̈ܐ :', 'blockedtitle' => 'ܡܦܠܚܢܐ ܗܘ ܡܚܪܡܐ', 'blockednoreason' => 'ܠܝܬ ܥܠܬܐ ܝܗܝܒܬܐ', 'nosuchsectiontitle' => 'ܠܐ ܡܨܐ ܐܫܟܚ ܡܢܬܐ', 'loginreqlink' => 'ܥܘܠ', 'accmailtitle' => 'ܡܠܬܐ ܕܥܠܠܐ ܫܕܪܬ', 'newarticle' => '(ܚܕܬܐ)', 'newarticletext' => "ܐܬܬ ܒܬܪ ܐܣܪܐ ܕܦܐܬܐ ܕܠܐ ܐܬܬܣܝܡܬ ܥܕܡܫ. ܠܣܘܝܡܐ ܕܦܐܬܐ ܗܕܐ, ܫܪܝ ܠܟܬܒܬܐ ܒܣܢܕܘܩܐ ܠܬܚܬ (ܚܙܝ [[{{MediaWiki:Helppage}}|ܦܐܬܐ ܕܥܘܕܪܢܐ]] ܠܐܚܪܢܐ ܝܕ̈ܥܬܐ). ܐܢ ܐܬܬ ܠܗܪܟܐ ܦܘܕܐܝܬ, ܕܘܫ ܠܦܪܡܝܬܐ ܕ '''ܠܒܣܬܪ back''' ܒܡܦܐܬܢܐ ܕܝܠܟ.", 'updated' => '(ܐܬܚܕܬ)', 'note' => "'''ܡܥܝܪܢܘܬܐ:'''", 'previewnote' => "'''ܕܟܪ ܕܗܢܘ ܚܝܪܐ ܩܕܡܝܐ ܒܠܚܘܕ'''. ܫܘܚܠܦ̈ܐ ܕܝܠܟ ܠܐ ܐܬܠܒܟܘ ܥܕܡܐ ܠܗܫܐ!", 'editing' => 'ܫܚܠܦܬܐ ܕ $1', 'editingsection' => 'ܫܚܠܦܬܐ ܕ $1 (ܡܢܬܐ)', 'editingcomment' => 'ܫܚܠܦܬܐ ܕ $1 (ܡܢܬܐ ܚܕܬܐ)', 'yourtext' => 'ܟܬܒܬܐ ܕܝܠܟ', 'storedversion' => 'ܬܢܝܬ̈ܐ ܐܣܝܢ̈ܐ', 'editingold' => "'''ܙܘܗܪܐ: ܫܚܠܦ ܐܢܬ ܬܢܝܬܐ ܥܬܝܩܬܐ ܕܦܐܬܐ ܗܕܐ.''' ܐܢ ܠܒܟ ܐܢܬ ܦܐܬܐ ܗܕܐ, ܟܠ ܫܘ̈ܚܠܦܐ ܕܐܬܥܒܕܘ ܒܬܪ ܗܕܐ ܬܢܝܬܐ ܢܬܛܠܩܘܢ.", 'yourdiff' => 'ܦܪ̈ܝܫܘܝܬܐ', 'templatesused' => '{{PLURAL:$1|ܩܠܒܐ|ܩܠܒ̈ܐ}} ܒܦܐܬܐ ܗܕܐ:', 'template-protected' => '(ܢܛܝܪܐ)', 'template-semiprotected' => '(ܕܡܘܬ ܢܛܝܪܐ)', 'nocreate-loggedin' => 'ܠܝܬ ܠܟ ܦܣܣܐ ܕܒܪܝܐ ܕܦܐܬܐ ܗܕܐ.', 'permissionserrors' => 'ܦܘܕ̈ܐ ܕܦܣܣ̈ܐ', 'permissionserrorstext-withaction' => 'ܠܝܬ ܠܟ ܦܣܣܐ ܠ$2, ܒ{{PLURAL:$1|ܥܠܬܐ|ܥܠܬ̈ܐ}} ܕ:', 'log-fulllog' => 'ܚܙܝ ܣܓܠܐ ܓܡܝܪܐ', 'edit-already-exists' => 'ܒܪܝܐ ܕܦܐܬܐ ܚܕܬܐ ܠܐ ܡܬܡܨܝܢܐ. ܗܕܐ ܦܐܬܐ ܐܝܬ ܡܢ ܟܕܘ.', # "Undo" feature 'undo-summary' => 'ܠܐ ܬܥܒܕ $1 ܒܝܕ [[Special:Contributions/$2|$2]] ([[User talk:$2|ܡܡܠܠܐ]])', # Account creation failure 'cantcreateaccounttitle' => 'ܒܪܝܐ ܕܚܘܫܒܢܐ ܠܐ ܡܬܡܨܝܢܐ', # History pages 'viewpagelogs' => 'ܚܙܝ ܣܓܠ̈ܐ ܕܦܐܬܐ ܗܕܐ', 'nohistory' => 'ܠܝܬ ܬܫܥܝܬܐ ܕܫܘܚܠܦ̈ܐ ܠܦܐܬܐ ܗܕܐ', 'currentrev' => 'ܬܢܝܬܐ ܗܫܝܬܐ', 'currentrev-asof' => 'ܬܢܝܬܐ ܗܫܝܬܐ ܒܣܝܩܘܡ $1', 'revisionasof' => 'ܬܢܝܬܐ ܒܣܝܩܘܡ $1', 'revision-info' => 'ܬܢܝܬܐ ܒܣܝܩܘܡ $1 ܒܝܕ $2', 'previousrevision' => '← ܬܢܝܬܐ ܕܩܕܡ', 'nextrevision' => 'ܬܢܝܬܐ ܕܒܬܪ →', 'currentrevisionlink' => 'ܬܢܝܬܐ ܗܫܝܬܐ', 'cur' => 'ܗܫܝܐ', 'next' => 'ܕܒܬܪ', 'last' => 'ܕܩܕܡ', 'page_first' => 'ܩܕܡܝܐ', 'page_last' => 'ܐܚܪܝܐ', 'histlegend' => "ܓܒܝܐ ܕܦܘܪܫܐ: ܓܒܝ ܣܢܕ̈ܘܩܐ ܕܬܢܝܬ̈ܐ ܠܦܘܚܡܐ ܘܕܘܫ '''Enter''' ܐܘ '''ܦܚܘܡ ܒܝܢܝ ܬܪܝܢ ܬܢܝܬ̈ܐ ܓܒܝܬ̈ܐ'''.<br /> ܩܠܝܕܐ: '''({{int:cur}})''' = ܦܘܪܫܐ ܥܡ ܬܢܝܬܐ ܗܫܝܬܐ, '''({{int:last}})''' = ܦܘܪܫܐ ܥܡ ܬܢܝܬܐ ܩܕܝܡܬܐ, '''{{int:minoreditletter}}''' = ܫܘܚܠܦܐ ܙܥܘܪܐ.", 'history-fieldset-title' => 'ܡܦܐܬ ܬܫܥܝܬܐ', 'history-show-deleted' => 'ܫܝܦܬ̈ܐ ܒܠܚܘܕ', 'histfirst' => 'ܩܕܝܡ ܟܠ', 'histlast' => 'ܐܚܪܝ ܟܠ', 'historyempty' => '(ܣܦܝܩܐ)', # Revision feed 'history-feed-title' => 'ܬܫܥܝܬܐ ܕܬܢܝܬܐ', 'history-feed-description' => 'ܬܫܥܝܬܐ ܕܬܢܝܬܐ ܕܗܕܐ ܦܐܬܐ ܥܠ ܘܝܩܝ', 'history-feed-item-nocomment' => '$1 ܒ $2', # Revision deletion 'rev-delundel' => 'ܚܘܝ/ܛܫܝ', 'rev-showdeleted' => 'ܚܘܝ', 'revisiondelete' => 'ܫܘܦ/ܠܐ ܫܘܦ ܬܢܝܬ̈ܐ', 'revdelete-show-file-submit' => 'ܐܝܢ', 'revdelete-selected' => "'''{{PLURAL:$2|ܬܢܝܬܐ ܓܒܝܬܐ|ܬܢܝܬ̈ܐ ܓܒܝܬܐ}} ܕ [[:$1]]:'''", 'revdelete-hide-text' => 'ܛܫܝ ܟܬܒܬܐ ܕܬܢܝܬܐ', 'revdelete-hide-image' => 'ܛܫܝ ܚܒܝܫܬ̈ܐ ܕܠܦܦܐ', 'revdelete-hide-name' => 'ܛܫܝ ܥܒܕܐ ܘܢܘܦܐ', 'revdelete-hide-comment' => 'ܛܫܝ ܟܪܝܘܬܐ ܕܫܘܚܠܦܐ', 'revdelete-hide-user' => 'ܛܫܝ ܫܡܐ/ܐܝ ܦܝ (IP) ܕܡܦܠܚܢܐ', 'revdelete-radio-same' => '(ܠܐ ܬܫܚܠܦ)', 'revdelete-radio-set' => 'ܐܝܢ', 'revdelete-radio-unset' => 'ܠܐ', 'revdelete-log' => 'ܥܠܬܐ:', 'revdel-restore' => 'ܫܚܠܦ ܚܙܝܬܐ', 'revdel-restore-deleted' => 'ܬܢܝܬ̈ܐ ܫܝܦ̈ܐ', 'revdel-restore-visible' => 'ܬܢܝܬ̈ܐ ܡܬܚܙܝܢܝܬ̈ܐ', 'pagehist' => 'ܬܫܥܝܬܐ ܕܦܐܬܐ', 'deletedhist' => 'ܬܫܥܝܬܐ ܫܝܦܬܐ', 'revdelete-otherreason' => 'ܥܠܬܐ ܐܚܪܬܐ/ܢܩܝܦܬܐ:', 'revdelete-reasonotherlist' => 'ܥܠܬܐ ܐܚܪܬܐ', 'revdelete-edit-reasonlist' => 'ܫܚܠܦ ܥܠܠܬ̈ܐ ܕܫܝܦܐ', 'revdelete-offender' => 'ܣܝܘܡܐ ܕܬܢܝܬܐ:', # History merging 'mergehistory' => 'ܚܒܘܛ ܬܫܥܝܬ̈ܐ ܕܦܐܬܐ', 'mergehistory-box' => 'ܚܒܘܛ ܬܢܝܬ̈ܐ ܕܬܪܬܝܢ ܦܐܬܬ̈ܐ', 'mergehistory-from' => 'ܦܐܬܐ ܕܡܒܘܥܐ:', 'mergehistory-into' => 'ܦܐܬܐ ܕܢܘܦܐ:', 'mergehistory-submit' => 'ܚܒܘܛ ܬܢܝܬ̈ܐ', 'mergehistory-no-source' => 'ܦܐܬܐ ܕܡܒܘܥܐ $1 ܠܝܬ.', 'mergehistory-autocomment' => 'ܚܒܛ [[:$1]] ܒ [[:$2]]', 'mergehistory-comment' => 'ܚܒܛ [[:$1]] ܒ [[:$2]]: $3', 'mergehistory-reason' => 'ܥܠܬܐ:', # Merge log 'mergelog' => 'ܣܓܠܐ ܕܚܒܛܐ', 'pagemerge-logentry' => 'ܚܒܛ [[$1]] ܒ [[$2]] (ܬܢܝܬ̈ܐ ܥܕܡܐ ܠ $3)', 'revertmerge' => 'ܒܛܘܠ ܚܒܛܐ', # Diffs 'history-title' => '"$1": ܬܫܥܝܬܐ ܕܬܢܝܬܐ', 'difference' => '(ܦܘܪܫܐ ܒܝܢܝ ܬܢܝܬ̈ܐ)', 'difference-multipage' => '(ܦܘܪܫܐ ܒܝܢܝ ܦܐܬܬ̈ܐ)', 'lineno' => 'ܣܪܛܐ $1:', 'compareselectedversions' => 'ܦܚܘܡ ܒܝܢܝ ܬܪܝܢ ܬܢܝܬ̈ܐ ܓܒܝܬ̈ܐ', 'showhideselectedversions' => 'ܚܘܝ/ܛܫܝ ܬܢܝܬ̈ܐ ܓܒܝܬ̈ܐ', 'editundo' => 'ܠܐ ܬܥܒܕ', 'diff-multi' => '({{PLURAL:$1|ܚܕܐ ܬܢܝܬܐ ܡܨܥܝܬܐ|$1 ܬܢܝܬ̈ܐ ܡܨܥܝܬ̈ܐ}} ܒܝܕ {{PLURAL:$2|ܚܕ ܡܦܠܚܢܐ ܠܐ ܓܠܝܚܬܐ|$2 ܡܦܠܚܢ̈ܐ ܠܐ ܓܠܝܚܬ̈ܐ}})', 'diff-multi-manyusers' => '({{PLURAL:$1|ܚܕܐ ܬܢܝܬܐ ܡܨܥܝܬܐ ܠܐ ܓܠܝܚܬܐ|$1 ܬܢܝܬ̈ܐ ܡܨܥܝܬ̈ܐ ܠܐ ܓܠܝܚܬ̈ܐ}} ܒܝܕ ܝܬܝܪ ܡܢ $2 {{PLURAL:$2|ܚܕ ܡܦܠܚܢܐ|ܡܦܠܚܢ̈ܐ}})', # Search results 'searchresults' => 'ܦܠܛ̈ܐ ܕܒܨܝܐ', 'searchresults-title' => 'ܦܠܛ̈ܐ ܕܒܨܝܐ ܥܠ "$1"', 'searchresulttext' => 'ܠܝܬܝܪ ܝܕ̈ܥܬܐ ܥܠ ܒܨܝܐ ܒ {{SITENAME}}, ܚܙܝ [[{{MediaWiki:Helppage}}|{{int:help}}]].', 'searchsubtitle' => 'ܒܨܐ ܐܢܬ ܥܠ \'\'\'[[:$1]]\'\'\' ([[Special:Prefixindex/$1|ܟܠ ܦܐܬܬ̈ܐ ܕܫܪܝܢ ܒ"$1"]]{{int:pipe-separator}}[[Special:WhatLinksHere/$1|ܟܠ ܦܐܬܬ̈ܐ ܕܐܣܪܝܢ ܥܡ "$1"]])', 'searchsubtitleinvalid' => "ܒܨܐ ܐܢܬ ܥܠ '''$1'''", 'titlematches' => 'ܫܡܐ ܕܦܐܬܐ ܐܘܝܢܐ', 'notitlematches' => 'ܠܝܬ ܫܡܐ ܕܦܐܬܐ ܐܘܝܢܐ', 'textmatches' => 'ܟܬܒܬܐ ܐܘܝܢܬܐ', 'notextmatches' => 'ܠܝܬ ܟܬܒܬܐ ܐܘܝܢܬܐ', 'prevn' => '{{PLURAL:$1|$1}} ܕܩܕܡ', 'nextn' => '{{PLURAL:$1|$1}} ܕܒܬܪ', 'prevn-title' => '$1 {{PLURAL:$1|ܦܠܛܐ|ܦܠܛ̈ܐ}} ܕܩܕܡ', 'nextn-title' => '$1 {{PLURAL:$1|ܦܠܛܐ|ܦܠܛ̈ܐ}} ܕܒܬܪ', 'shown-title' => 'ܚܘܝ $1 {{PLURAL:$1|ܦܠܛܐ|ܦܠܛ̈ܐ}} ܠܟܠ ܦܐܬܐ', 'viewprevnext' => 'ܚܘܝ ($1 {{int:pipe-separator}} $2) ($3)', 'searchmenu-legend' => 'ܓܒܝܬ̈ܐ ܕܒܨܝܐ', 'searchmenu-exists' => "'''ܐܝܬ ܦܐܬܐ ܒܫܡ \"[[:\$1]]\" ܥܠ ܗܢܐ ܘܝܩܝ'''", 'searchmenu-new' => "'''ܒܪܝ ܦܐܬܐ \"[[:\$1]]\" ܥܠ ܗܢܐ ܘܝܩܝ!'''", 'searchhelp-url' => 'Help:ܚܒܝܫܬ̈ܐ', 'searchprofile-articles' => 'ܦܐܬܬ̈ܐ ܕܚܒܝܫܬ̈ܐ', 'searchprofile-project' => 'ܦܐܬܬ̈ܐ ܕܬܪ̈ܡܝܬܐ ܘܕܥܘܕܪܢܐ', 'searchprofile-images' => 'ܡܝܕ̈ܝܐ ܣܓܝܐ̈ܐ (Multimedia)', 'searchprofile-everything' => 'ܟܠ ܡܕܡ', 'searchprofile-advanced' => 'ܡܬܩܕܡܢܐ', 'searchprofile-articles-tooltip' => 'ܒܨܝ ܒܓܘ $1', 'searchprofile-project-tooltip' => 'ܒܨܝ ܒ $1', 'searchprofile-images-tooltip' => 'ܒܨܝ ܥܠ ܠܦܦ̈ܐ', 'search-result-size' => '$1 ({{PLURAL:$2|1 ܡܠܬܐ|$2 ܡܠ̈ܐ}})', 'search-redirect' => '(ܨܝܒ $1)', 'search-section' => '(ܡܢܬܐ $1)', 'search-suggest' => 'ܐܪܐ ܣܟܠܬ ܗܘܐ: $1', 'search-interwiki-caption' => 'ܬܪ̈ܡܝܬܐ ܐܚܘܬ̈ܐ', 'search-interwiki-default' => 'ܦܠܛ̈ܐ ܕ $1:', 'search-interwiki-more' => '(ܝܬܝܪ)', 'search-mwsuggest-enabled' => 'ܥܡ ܡܚܫܚܬ̈ܐ', 'search-mwsuggest-disabled' => 'ܠܐ ܡܚܫܚܬ̈ܐ', 'search-relatedarticle' => 'ܐܚܝܢܝ̈ܐ', 'mwsuggest-disable' => 'ܒܛܘܠ ܬܘܦܥܠܐ ܕܡܚܫܚܬ̈ܐ ܕܒܨܝܐ', 'searcheverything-enable' => 'ܒܨܝ ܒܟܠ ܚܩܠܬ̈ܐ', 'searchrelated' => 'ܐܚܝܢܝ̈ܐ', 'searchall' => 'ܟܠ', 'showingresults' => "ܚܘܘܝܐ ܠܬܚܬ {{PLURAL:$1|'''1''' ܦܠܛܐ|'''$1''' ܦܠܛ̈ܐ}} ܫܪܐ ܡܢ ܡܢܝܢܐ '''$2'''.", 'showingresultsnum' => "ܚܘܘܝܐ ܠܬܚܬ {{PLURAL:$3|'''ܚܕ ܦܠܛܐ'''|'''$3''' ܦܠܛ̈ܐ}} ܫܪܐ ܡܢ ܡܢܝܢܐ '''$2'''.", 'showingresultsheader' => "{{PLURAL:$5|ܦܠܛܐ '''$1''' ܡܢ '''$3'''|ܦܠܛ̈ܐ '''$1 - $2''' ܡܢ '''$3'''}} ܠ'''$4'''", 'search-nonefound' => 'ܠܝܬ ܦܠܛ̈ܐ ܐܘܝܢ̈ܐ ܠܗܢܐ ܒܨܝܐ.', 'powersearch' => 'ܒܨܝܐ ܡܬܩܕܡܢܐ', 'powersearch-legend' => 'ܒܨܝܐ ܡܬܩܕܡܢܐ', 'powersearch-ns' => 'ܒܨܝ ܒܚܩܠܬ̈ܐ:', 'powersearch-redir' => 'ܚܘܝ ܨܘܝܒ̈ܐ', 'powersearch-field' => 'ܒܨܝ ܥܠ', 'powersearch-togglelabel' => 'ܓܒܝ:', 'powersearch-toggleall' => 'ܟܠ', 'powersearch-togglenone' => 'ܠܐ ܡܕܡ', 'search-external' => 'ܒܨܝܐ ܒܪܝܐ', # Quickbar 'qbsettings-none' => 'ܠܐ ܡܕܡ', # Preferences page 'preferences' => 'ܨܒܝܢܝܘܬ̈ܐ', 'mypreferences' => 'ܨܒܝܢܝܘܬ̈ܐ', 'prefs-edits' => 'ܡܢܝܢܐ ܕܫܘܚܠܦ̈ܐ:', 'prefsnologin' => 'ܠܝܬܝܟ ܥܠܝܠܐ', 'changepassword' => 'ܫܚܠܦ ܡܠܬܐ ܕܥܠܠܐ', 'prefs-skin' => 'ܓܠܕܐ', 'skin-preview' => 'ܚܝܪܐ ܩܕܡܝܐ', 'datedefault' => 'ܠܐ ܨܒܝܢܝܘܬܐ', 'prefs-datetime' => 'ܣܝܩܘܡܐ ܘܙܒܢܐ', 'prefs-personal' => 'ܦܘܓܪܦܐ ܕܡܦܠܚܢܐ', 'prefs-rc' => 'ܫܘܚܠܦ̈ܐ ܚܕ̈ܬܐ', 'prefs-watchlist' => 'ܪ̈ܗܝܬܐ', 'prefs-watchlist-days' => 'ܝܘܡܬ̈ܐ ܠܚܙܝܐ ܒܪ̈ܗܝܬܐ:', 'prefs-watchlist-days-max' => 'ܠܡܬܚܐ ܥܠܝܐ ܕ $1 {{PLURAL:$1|ܝܘܡܐ|ܝܘܡܬ̈ܐ}}', 'prefs-misc' => 'ܦܪ̈ܝܫܬܐ', 'prefs-resetpass' => 'ܫܚܠܦ ܡܠܬܐ ܕܥܠܠܐ', 'prefs-changeemail' => 'ܫܚܠܦ ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ', 'prefs-email' => 'ܓܒܝܬ̈ܐ ܕܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ', 'prefs-rendering' => 'ܐܣܟܝܡܐ', 'saveprefs' => 'ܠܒܘܟ', 'resetprefs' => 'ܡܫܝ ܫܘܚܠܦ̈ܐ ܠܐ ܠܒܝܟ̈ܐ', 'prefs-editing' => 'ܫܚܠܦܬܐ', 'rows' => 'ܨ̈ܦܐ', 'columns' => 'ܥܡܘܕ̈ܐ:', 'searchresultshead' => 'ܒܨܝ', 'resultsperpage' => 'ܡܢܝܢܐ ܕܦܠܛ̈ܐ ܒܦܐܬܐ:', 'recentchangesdays' => 'ܝܘܡܬ̈ܐ ܠܚܙܝܐ ܒܫܘܚܠܦ̈ܐ ܚܕ̈ܬܐ:', 'recentchangescount' => 'ܡܢܝܢܐ ܕܫܘܚܠܦ̈ܐ ܠܚܙܝܐ ܪܫܐܝܬ:', 'savedprefs' => 'ܨܒܝܢܝܘܬ̈ܟ ܐܬܠܒܟܘ.', 'timezonelegend' => 'ܙܘܢܐ ܙܒܢܝܐ:', 'localtime' => 'ܥܕܢܐ ܕܘܟܬܝܐ:', 'timezoneregion-africa' => 'ܐܦܪܝܩܐ', 'timezoneregion-america' => 'ܐܡܪܝܩܐ', 'timezoneregion-antarctica' => 'ܐܢܛܐܪܩܛܝܩܐ', 'timezoneregion-asia' => 'ܐܣܝܐ', 'timezoneregion-atlantic' => 'ܐܘܩܝܢܘܣ ܐܛܠܢܛܝܐ', 'timezoneregion-australia' => 'ܐܘܣܛܪܠܝܐ', 'timezoneregion-europe' => 'ܐܘܪܘܦܐ', 'timezoneregion-indian' => 'ܐܘܩܝܢܘܣ ܗܢܕܘܝܐ', 'timezoneregion-pacific' => 'ܐܘܩܝܢܘܣ ܫܩܛܝܐ', 'prefs-searchoptions' => 'ܒܨܝܐ', 'prefs-namespaces' => 'ܚܩܠܬ̈ܐ', 'defaultns' => 'ܐܘ ܒܨܝ ܒܚܩܠܬ̈ܐ ܗܢܝܢ', 'prefs-files' => 'ܠܦܦ̈ܐ', 'prefs-emailconfirm-label' => 'ܫܘܪܪܐ ܕܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ:', 'youremail' => 'ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ:', 'username' => 'ܫܡܐ ܕܡܦܠܚܢܐ:', 'uid' => 'ܗܝܝܘܬܐ ܕܡܦܠܚܢܐ:', 'prefs-memberingroups' => 'ܗܕܡܐ ܕ{{PLURAL:$1|ܟܢܘܫܬܐ|ܟܢܘܫܬ̈ܐ}}:', 'prefs-registration' => 'ܙܒܢܐ ܕܣܘܓܠܐ:', 'yourrealname' => 'ܫܡܐ ܫܪܝܪܐ:', 'yourlanguage' => 'ܠܫܢܐ:', 'yournick' => 'ܪܡܝ ܐܝܕܐ:', 'badsiglength' => 'ܪܡܝ ܐܝܕܟ ܣܓܝ ܐܪܝܟܬܐ. ܐܠܨܐ ܠܟ ܠܐ ܝܬܝܪ ܡܢ $1 {{PLURAL:$1|ܐܬܘܬܐ|ܐܬܘܬ̈ܐ}} ܐܪܝܟܬܐ ܗܘܬ.', 'yourgender' => 'ܓܢܣܐ:', 'gender-unknown' => 'ܠܐ ܦܣܝܩܐ', 'gender-male' => 'ܕܟܪܐ', 'gender-female' => 'ܢܩܒܐ', 'prefs-help-gender' => 'ܨܒܝܢܝܐ: ܐܬܦܠܚ ܠܡܬܡܠܠ ܒܓܢܣܐ ܬܪܝܨܐ ܒܝܕ ܬܚܪܙܬܐ. ܝܕܥܬܐ ܗܕܐ ܬܗܘܐ ܓܠܝܬܐ ܠܥܠܡܐ.', 'email' => 'ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ', 'prefs-info' => 'ܝܕ̈ܥܬܐ ܪ̈ܫܝܬܐ', 'prefs-i18n' => 'ܬܘܪܓܡܐ', 'prefs-signature' => 'ܪܡܝ ܐܝܕܐ', 'prefs-dateformat' => 'ܚܫܠܬܐ ܕܣܝܩܘܡܐ', 'prefs-advancedediting' => 'ܓܒܝܬ̈ܐ ܡܬܩܕ̈ܡܢܐ', 'prefs-advancedrc' => 'ܓܒܝܬ̈ܐ ܡܬܩܕ̈ܡܢܐ', 'prefs-advancedrendering' => 'ܓܒܝܬ̈ܐ ܡܬܩܕ̈ܡܢܐ', 'prefs-advancedsearchoptions' => 'ܓܒܝܬ̈ܐ ܡܬܩܕ̈ܡܢܐ', 'prefs-advancedwatchlist' => 'ܓܒܝܬ̈ܐ ܡܬܩܕ̈ܡܢܐ', 'prefs-displayrc' => 'ܓܒܝܬ̈ܐ ܕܚܘܘܝܐ', 'prefs-displaysearchoptions' => 'ܓܒܝܬ̈ܐ ܕܚܘܘܝܐ', 'prefs-displaywatchlist' => 'ܓܒܝܬ̈ܐ ܕܚܘܘܝܐ', 'prefs-diffs' => 'ܦܪ̈ܝܫܘܝܬܐ', # User rights 'userrights' => 'ܡܕܒܪܢܘܬܐ ܕܙܕ̈ܩܐ ܕܡܦܠܚܢܐ', 'userrights-lookup-user' => 'ܕܒܪ ܟܢܘܫܝ̈ܐ ܕܡܦܠܚܢܐ', 'userrights-user-editname' => 'ܐܥܠ ܫܡܐ ܕܡܦܠܚܢܐ:', 'editusergroup' => 'ܫܚܠܦ ܟܢܘܫܝ̈ܐ ܕܡܦܠܚܢܐ', 'userrights-editusergroup' => 'ܫܚܠܦ ܟܢܘܫܝ̈ܐ ܕܡܦܠܚܢܐ', 'saveusergroups' => 'ܠܒܘܟ ܟܢܘܫܝ̈ܐ ܕܡܦܠܚܢܐ', 'userrights-groupsmember' => 'ܗܕܡܐ ܒ:', 'userrights-reason' => 'ܥܠܬܐ:', # Groups 'group' => 'ܟܢܘܫܬܐ:', 'group-user' => 'ܡܦܠܚܢ̈ܐ', 'group-autoconfirmed' => 'ܡܦܠܚܢ̈ܐ ܡܫܪܪ̈ܐ ܝܬܐܝܬ', 'group-bot' => 'ܒܘܬ̈ܐ', 'group-sysop' => 'ܡܕܒܪ̈ܢܐ', 'group-bureaucrat' => 'ܒܝܪܘܩܪ̈ܛܐ', 'group-suppress' => 'ܚܝܘܪ̈ܐ', 'group-all' => '(ܟܠ)', 'group-user-member' => '{{GENDER:$1|ܡܦܠܚܢܐ|ܡܦܠܚܢܬܐ}}', 'group-autoconfirmed-member' => '{{GENDER:$1|ܡܦܠܚܢܐ ܡܫܪܪܐ ܝܬܐܝܬ|ܡܦܠܚܢܬܐ ܡܫܪܪܬܐ ܝܬܐܝܬ}}', 'group-bot-member' => '{{GENDER:$1|ܒܘܬ (Bot)}}', 'group-sysop-member' => '{{GENDER:$1|ܡܕܒܪܢܐ|ܡܕܒܪܢܬܐ}}', 'group-bureaucrat-member' => '{{GENDER:$1|ܒܝܪܘܩܪܛܐ}}', 'group-suppress-member' => '{{GENDER:$1|ܚܝܘܪܐ|ܚܝܘܪܬܐ}}', 'grouppage-user' => '{{ns:project}}:ܡܦܠܚܢ̈ܐ', 'grouppage-autoconfirmed' => '{{ns:project}}:ܡܦܠܚܢ̈ܐ ܡܫܪܪ̈ܐ ܝܬܐܝܬ', 'grouppage-bot' => '{{ns:project}}:ܒܘܬ̈ܐ', 'grouppage-sysop' => '{{ns:project}}:ܡܕܒܪ̈ܢܐ', 'grouppage-bureaucrat' => '{{ns:project}}:ܒܝܪܘܩܪ̈ܛܐ', 'grouppage-suppress' => '{{ns:project}}:ܚܝܘܪܐ', # Rights 'right-read' => 'ܩܪܝ ܦܐܬܬ̈ܐ', 'right-edit' => 'ܫܚܠܦ ܦܐܬܬ̈ܐ', 'right-createtalk' => 'ܒܪܝ ܦܐܬܬ̈ܐ ܕܡܡܠܠܐ', 'right-createaccount' => 'ܒܪܝ ܚܘܫܒܢ̈ܐ ܕܡܦܠܚܢܐ ܚܕܬܐ', 'right-minoredit' => 'ܫܘܕܥ ܥܠ ܫܘܚܠܦ̈ܐ ܐܝܟ ܙܥܘܪܐ', 'right-move' => 'ܫܢܝ ܦܐܬܬ̈ܐ', 'right-move-subpages' => 'ܫܢܝ ܦܐܬܬ̈ܐ ܥܡ ܦܐܬܬ̈ܐ ܦܪ̈ܥܝܐ ܕܝܠܗܘܢ', 'right-movefile' => 'ܫܢܝ ܠܦܦ̈ܐ', 'right-upload' => 'ܐܣܩ ܠܦܦ̈ܐ', 'right-delete' => 'ܫܘܦ ܦܐܬܬ̈ܐ', 'right-bigdelete' => 'ܫܘܦ ܦܐܬܬ̈ܐ ܥܡ ܬܫܥܝܬ̈ܐ ܪ̈ܒܬܐ', 'right-browsearchive' => 'ܒܨܝ ܦܐܬܬ̈ܐ ܫܝܦܬ̈ܐ', 'right-undelete' => 'ܠܐ ܫܘܦ ܦܐܬܬ̈ܐ', 'right-suppressionlog' => 'ܚܙܝ ܣܓܠ̈ܐ ܦܪ̈ܨܘܦܝܐ', 'right-block' => 'ܚܪܘܡ ܡܦܠܚܢ̈ܐ ܐܚܪ̈ܢܐ ܡܢ ܫܚܠܦܬܐ', 'right-mergehistory' => 'ܚܒܘܛ ܬܫܥܝܬܐ ܕܦܐܬܬ̈ܐ', 'right-userrights' => 'ܫܚܠܦ ܟܠ ܙܕ̈ܩܐ ܕܡܦܠܚܢܐ', # User rights log 'rightslog' => 'ܣܓܠܐ ܕܙܕ̈ܩܐ ܕܡܦܠܚܢܐ', 'rightslogtext' => 'ܗܢܘ ܣܓܠܐ ܕܫܘܚܠܦ̈ܐ ܕܙܕ̈ܩܐ ܕܡܦܠܚܢܐ.', 'rightsnone' => '(ܠܐ ܡܕܡ)', # Associated actions - in the sentence "You do not have permission to X" 'action-read' => 'ܩܪܝ ܦܐܬܐ ܗܕܐ', 'action-edit' => 'ܫܚܠܦܬܐ ܕܦܐܬܐ ܗܕܐ', 'action-createpage' => 'ܒܪܝܬܐ ܕܦܐܬܬ̈ܐ', 'action-createtalk' => 'ܒܪܝܬܐ ܕܦܐܬܬ̈ܐ ܕܡܡܠܠܐ', 'action-createaccount' => 'ܒܪܝܬܐ ܕܚܘܫܒܢܐ ܕܗܢܐ ܡܦܠܚܢܐ', 'action-minoredit' => 'ܫܘܕܥܬܐ ܥܠ ܫܘܚܠܦܐ ܗܢܐ ܐܝܟ ܙܥܘܪܐ', 'action-move' => 'ܫܢܝܬܐ ܕܦܐܬܐ ܗܕܐ', 'action-move-rootuserpages' => 'ܫܢܝܬܐ ܕܦܐܬܬ̈ܐ ܫܪ̈ܫܝܬܐ ܕܡܦܠܚܢܐ', 'action-movefile' => 'ܫܢܝܬܐ ܕܗܢܐ ܠܦܦܐ', 'action-upload' => 'ܐܣܩܬܐ ܕܗܢܐ ܠܦܦܐ', 'action-delete' => 'ܫܝܦܬܐ ܕܦܐܬܐ ܗܕܐ', 'action-deleterevision' => 'ܫܝܦܬܐ ܕܬܢܝܬܐ ܗܕܐ', 'action-deletedhistory' => 'ܚܙܝܬܐ ܕܬܫܥܝܬܐ ܫܝܦܬܐ ܕܦܐܬܐ ܗܕܐ', 'action-browsearchive' => 'ܒܨܝܐ ܥܠ ܦܐܬܬ̈ܐ ܫܝܦܬ̈ܐ', 'action-undelete' => 'ܠܐ ܫܘܦ ܦܐܬܐ ܗܕܐ', 'action-suppressionlog' => 'ܚܙܝܬܐ ܕܗܢܐ ܣܓܠܐ ܦܪܨܘܦܝܐ', 'action-block' => 'ܚܪܡܬܐ ܕܡܦܠܚܢܐ ܗܢܐ ܡܢ ܫܚܠܦܬܐ', 'action-mergehistory' => 'ܚܒܛܬܐ ܕܬܫܥܝܬܐ ܕܦܐܬܐ ܗܕܐ', 'action-userrights' => 'ܫܚܠܦܬܐ ܕܟܠ ܙܕ̈ܩܐ ܕܡܦܠܚܢܐ', # Recent changes 'nchanges' => '$1 {{PLURAL:$1|ܫܘܚܠܦܐ|ܫܘܚܠܦ̈ܐ}}', 'recentchanges' => 'ܫܘܚܠܦ̈ܐ ܚܕ̈ܬܐ', 'recentchanges-legend' => 'ܓܒܝܬ̈ܐ ܕܫܘܚܠܦ̈ܐ ܚܕ̈ܬܐ', 'recentchangestext' => 'ܥܩܒ ܫܘܚܠܦ̈ܐ ܕܘܝܩܝ ܚܕܬ ܡܢ ܟܠ ܒܦܐܬܐ ܗܕܐ.', 'recentchanges-feed-description' => 'ܥܩܒ ܫܘܚܠܦ̈ܐ ܚܕܬ ܡܢ ܟܠ ܕܘܝܩܝ ܒܝܕ ܗܕܐ ܬܪܣܝܬܐ.', 'recentchanges-label-newpage' => 'ܫܘܚܠܦܐ ܗܢܐ ܐܬܬܣܝܡ ܦܐܬܐ ܚܕܬܐ', 'recentchanges-label-minor' => 'ܗܢܘ ܫܘܚܠܦܐ ܙܥܘܪܐ', 'recentchanges-label-bot' => 'ܒܘܬ (bot) ܥܒܕ ܗܢܐ ܫܘܚܠܦܐ', 'recentchanges-label-unpatrolled' => 'ܫܘܚܠܦܐ ܗܢܐ ܠܐ ܗܘ ܟܪܝܟܐ ܠܗܫܐ', 'rcnotefrom' => "ܠܬܚܬ ܫܘܚܠܦ̈ܐ ܕܡܢ '''$2''' (ܥܕ '''$1''' ܡܬܚܙܝܢ̈ܐ).", 'rclistfrom' => 'ܚܘܝ ܫܘܚܠܦ̈ܐ ܚܕ̈ܬܐ ܡܢ $1', 'rcshowhideminor' => '$1 ܫܘܚܠܦ̈ܐ ܙܥܘܪ̈ܐ', 'rcshowhidebots' => '$1 ܒܘܬ̈ܐ (Bots)', 'rcshowhideliu' => '$1 ܡܦܠܚܢ̈ܐ ܥܠܝܠ̈ܐ', 'rcshowhideanons' => '$1 ܡܦܠܚܢܐ ܠܐ ܝܕܝܥܐ', 'rcshowhidepatr' => '$1 ܫܘܚܠܦ̈ܐ ܬܢܝ̈ܐ', 'rcshowhidemine' => '$1 ܫܘܚܠܦ̈ܝ', 'rclinks' => 'ܚܘܝ $1 ܫܘܚܠܦ̈ܐ ܐܚܪ̈ܝܐ ܒ $2 ܝܘܡܬ̈ܐ ܐܚܪ̈ܝܐ<br />$3', 'diff' => 'ܦܘܪܫܐ', 'hist' => 'ܬܫܥܝܬܐ', 'hide' => 'ܛܫܝ', 'show' => 'ܚܘܝ', 'minoreditletter' => 'ܙ', 'newpageletter' => 'ܚ', 'boteditletter' => 'ܒ', 'rc_categories_any' => 'ܐܝܢܐ ܕܗܘ', 'rc-change-size-new' => '$1 {{PLURAL:$1|ܒܐܝܛ|ܒܐܝܛ̈ܐ}} ܒܬܪ ܫܘܚܠܦܐ', 'newsectionsummary' => '/* $1 */ ܡܢܬܐ ܚܕܬܐ', 'rc-enhanced-expand' => 'ܚܘܝ ܐܪ̈ܝܟܬܐ (ܒܥܐ ܠܟ JavaScript)', 'rc-enhanced-hide' => 'ܛܫܝ ܐܪ̈ܝܟܬܐ', 'rc-old-title' => 'ܐܬܒܪܝ ܫܪܫܐܝܬ ܐܝܟ "$1"', # Recent changes linked 'recentchangeslinked' => 'ܫܘܚܠܦ̈ܐ ܕ̈ܡܝܐ', 'recentchangeslinked-feed' => 'ܫܘܚܠܦ̈ܐ ܕ̈ܡܝܐ', 'recentchangeslinked-toolbox' => 'ܫܘܚܠܦ̈ܐ ܕ̈ܡܝܐ', 'recentchangeslinked-page' => 'ܫܡܐ ܕܦܐܬܐ:', # Upload 'upload' => 'ܐܣܩ ܠܦܦܐ', 'uploadbtn' => 'ܐܣܩ ܠܦܦܐ', 'uploadnologin' => 'ܠܝܬܝܟ ܥܠܝܠܐ', 'uploaderror' => 'ܦܘܕܐ ܒܡܣܩܬܐ', 'uploadlog' => 'ܣܓܠܐ ܕܣܠܩܐ', 'uploadlogpage' => 'ܣܓܠܐ ܕܣܠܩܐ', 'filename' => 'ܫܡܐ ܕܠܦܦܐ', 'filedesc' => 'ܦܣܝܩܬ̈ܐ', 'fileuploadsummary' => 'ܦܣܝܩܬ̈ܐ:', 'filereuploadsummary' => 'ܫܘܚܠܦ̈ܐ ܕܠܦܦܐ:', 'filestatus' => 'ܐܝܟܢܝܘܬܐ ܕܙܕ̈ܩܐ ܕܛܒܥܐ', 'filesource' => 'ܡܒܘܥܐ:', 'minlength1' => 'ܫܡܗ̈ܐ ܕܠܦܦܐ ܘܠܐ ܕܢܗܘܐ ܒܪܝܐ ܡܢ ܐܬܘܬܐ ܚܕܐ ܟܕ ܙܥܘܪ', 'uploadwarning' => 'ܐܣܩ ܙܘܗܪܐ', 'savefile' => 'ܠܒܘܟ ܠܦܦܐ', 'uploadedimage' => 'ܐܣܩ "[[$1]]"', 'uploadvirus' => 'ܠܦܦܐ ܐܝܬ ܒܗ ܒܝܪܘܣ! ܐܪ̈ܝܟܬܐ: $1', 'upload-source' => 'ܡܒܘܥܐ ܕܠܦܦܐ', 'sourcefilename' => 'ܫܡܐ ܕܠܦܦܐ ܡܒܘܥܐ', 'sourceurl' => 'URL ܡܒܘܥܐ:', 'upload-maxfilesize' => 'ܡܬܚܐ ܥܠܝܐ ܕܥܓܪܐ ܕܠܦܦܐ: $1', 'upload-description' => 'ܫܘܡܗܐ ܕܠܦܦܐ', 'upload-options' => 'ܓܒܝܬ̈ܐ ܕܐܣܩܬܐ ܕܠܦܦܐ', 'watchthisupload' => 'ܪܗܝ ܗܢܐ ܠܦܦܐ', 'upload-success-subj' => 'ܠܦܦܐ ܐܣܩܬ ܢܨܝܚܐܝܬ', 'upload-failure-subj' => 'ܩܛܪܐ ܒܐܣܩܬܐ ܕܠܦܦܐ', 'upload-failure-msg' => 'ܐܝܬ ܗܘܐ ܩܛܪܐ ܒܠܦܦܐ ܕܐܣܩܬ ܡܢ [$2]: $1', 'upload-warning-subj' => 'ܙܘܗܪܐ ܥܠ ܐܣܩܬܐ ܕܠܦܦܐ', 'upload-proto-error' => 'ܦܪܘܛܘܩܘܠ ܠܐ ܬܪܝܨܐ', 'upload-file-error' => 'ܦܘܕܐ ܓܘܝܐ', 'upload-misc-error' => 'ܦܘܕܐ ܠܐ ܝܕܝܥܐ ܒܐܣܩܬܐ ܕܠܦܦܐ', 'upload-unknown-size' => 'ܥܓܪܐ ܠܐ ܝܕܝܥܐ', # img_auth script messages 'img-auth-nofile' => 'ܠܦܦܐ "$1" ܠܝܬ ܠܗ ܐܝܬܘܬܐ.', # HTTP errors 'http-read-error' => 'HTTP ܦܘܕܐ ܒܩܪܝܬܐ.', 'http-curl-error' => 'ܦܘܕܐ ܒܫܟܚܐ ܕURL: $1', 'license' => 'ܦܣܣܐ:', 'license-header' => 'ܦܣܣܐ', 'license-nopreview' => '(ܠܝܬ ܚܝܪܐ ܩܕܡܝܐ)', 'upload_source_file' => ' (ܠܦܦܐ ܥܠ ܚܫܘܒܬܐ ܕܝܠܟ)', # Special:ListFiles 'listfiles-summary' => 'ܦܐܬܐ ܕܝܠܢܝܬܐ ܗܕܐ ܬܓܠܚ ܟܠ ܠܦܦ̈ܐ ܡܣܩ̈ܐ. ܐܡܬܝ ܕܬܨܦܐ ܒܝܕ ܡܦܠܚܢܐ ܬܓܠܚ ܨܚܚܐ ܐܚܪܝܐ ܒܠܚܘܕ ܕܠܦܦ̈ܐ ܡܣܩ̈ܐ ܒܝܕ ܗܢܐ ܡܦܠܚܢܐ.', 'listfiles_search_for' => 'ܒܨܝ ܥܠ ܫܡܐ ܕܡܝܕܝܐ:', 'imgfile' => 'ܠܦܦܐ', 'listfiles' => 'ܡܟܬܒܘܬܐ ܕܠܦܦ̈ܐ', 'listfiles_thumb' => 'ܙܘܥܪܐ', 'listfiles_date' => 'ܣܝܩܘܡܐ', 'listfiles_name' => 'ܫܡܐ', 'listfiles_user' => 'ܡܦܠܚܢܐ', 'listfiles_size' => 'ܥܓܪܐ', 'listfiles_description' => 'ܫܘܡܗܐ', 'listfiles_count' => 'ܨܚܚ̈ܐ', # File description page 'file-anchor-link' => 'ܠܦܦܐ', 'filehist' => 'ܬܫܥܝܬܐ ܕܠܦܦܐ', 'filehist-deleteall' => 'ܫܘܦ ܟܠ', 'filehist-deleteone' => 'ܫܘܦ', 'filehist-revert' => 'ܐܦܢܝ', 'filehist-current' => 'ܗܫܝܐ', 'filehist-datetime' => 'ܣܝܩܘܡܐ/ܙܒܢܐ', 'filehist-thumb' => 'ܨܘܪܬܐ ܙܥܘܪܬܐ', 'filehist-nothumb' => 'ܠܐ ܙܥܘܪܬܐ', 'filehist-user' => 'ܡܦܠܚܢܐ', 'filehist-dimensions' => 'ܩܝܡ̈ܐ', 'filehist-filesize' => 'ܥܓܪܐ ܕܠܦܦܐ', 'filehist-comment' => 'ܥܘܩܒܐ', 'imagelinks' => 'ܡܦܠܚܬܐ ܕܠܦܦܐ', 'linkstoimage' => '{{PLURAL:$1|ܦܐܬܐ ܗܕܐ ܐܣܪ|$1 ܦܐܬܬ̈ܐ ܗܠܝܢ ܐܣܪܝܢ}} ܥܡ ܗܢܐ ܠܦܦܐ:', 'nolinkstoimage' => 'ܠܝܬ ܦܐܬܐ ܕܐܣܪ ܠܗܢܐ ܠܦܦܐ.', 'uploadnewversion-linktext' => 'ܐܣܩ ܨܚܚܐ ܚܕܬܐ ܡܢ ܗܢܐ ܠܦܦܐ', 'shared-repo-from' => 'ܡܢ $1', # File reversion 'filerevert-comment' => 'ܥܠܬܐ:', # File deletion 'filedelete' => 'ܫܘܦ $1', 'filedelete-legend' => 'ܫܘܦ ܠܦܦܐ', 'filedelete-comment' => 'ܥܠܬܐ:', 'filedelete-submit' => 'ܫܘܦ', 'filedelete-success' => "'''$1''' ܐܫܬܝܦ.", 'filedelete-nofile' => "'''$1''' ܠܝܬ.", 'filedelete-otherreason' => 'ܥܠܬܐ ܐܚܪܬܐ:', 'filedelete-reason-otherlist' => 'ܥܠܬܐ ܐܚܪܬܐ', 'filedelete-edit-reasonlist' => 'ܫܚܠܦ ܥܠܠܬ̈ܐ ܕܫܝܦܐ', # MIME search 'mimesearch' => 'MIME ܒܨܝܐ', 'mimetype' => 'MIME ܐܕܫܐ:', 'download' => 'ܐܚܬ', # Unwatched pages 'unwatchedpages' => 'ܦܐܬܬ̈ܐ ܠܐ ܪ̈ܗܝܬܐ', # List redirects 'listredirects' => 'ܡܟܬܒܘܬܐ ܕܨܘܝܒ̈ܐ', # Unused templates 'unusedtemplates' => 'ܩܠܒ̈ܐ ܠܐ ܦܠܝܚ̈ܐ', 'unusedtemplateswlh' => 'ܐܣܘܪ̈ܐ ܐܚܪ̈ܢܐ', # Random page 'randompage' => 'ܡܓܠܬܐ ܚܘܝܚܬܐ', 'randompage-nopages' => 'ܠܝܬ ܦܐܬܬ̈ܐ ܒ{{PLURAL:$2|ܚܩܠܐ ܕ|ܚܩܠܬ̈ܐ ܕ}}: $1.', # Random redirect 'randomredirect' => 'ܨܘܝܒ̈ܐ ܚܘܝܚ̈ܐ', 'randomredirect-nopages' => 'ܠܝܬ ܨܘܝܒ̈ܐ ܒܚܩܠܐ ܕ"$1".', # Statistics 'statistics' => 'ܚܒܝܫܘܬ ܡܢܝܢܐ', 'statistics-header-pages' => 'ܚܒܝܫܘܬ ܡܢܝܢ̈ܐ ܕܦܐܬܐ', 'statistics-header-edits' => 'ܚܒܝܫܘܬ ܡܢܝܢܐ ܕܫܘܚܠܦ̈ܐ', 'statistics-header-views' => 'ܚܒܝܫܘܬ ܡܢܝܢܐ ܕܚܙܝܐ', 'statistics-header-users' => 'ܚܒܝܫܘܬ ܡܢܝܢܐ ܕܡܦܠܚܢܐ', 'statistics-header-hooks' => 'ܚܒܝܫܘܬ ܡܢܝܢܐ ܐܚܪܢܐ', 'statistics-articles' => 'ܦܐܬܬ̈ܐ ܕܚܒܝܫܬ̈ܐ', 'statistics-pages' => 'ܦܐܬܬ̈ܐ', 'statistics-edits' => 'ܫܘܚܠܦ̈ܐ ܕܦܐܬܬ̈ܐ ܡܢ ܫܘܪܝܐ ܕ {{SITENAME}}', 'statistics-edits-average' => 'ܡܨܥܐ ܕܫܘܚܠܦ̈ܐ ܠܟܠ ܦܐܬܐ', 'statistics-views-total' => 'ܣܘܝܟܐ ܕܚܙܝܐ', 'statistics-views-peredit' => 'ܚܘܘܝ̈ܐ ܠܟܠ ܫܘܚܠܦܐ', 'statistics-users' => '[[Special:ListUsers|ܡܦܠܚܢ̈ܐ]] ܡܣܓܠ̈ܐ', 'statistics-users-active' => 'ܡܦܠܚܢ̈ܐ ܙܪ̄ܝܙܐ', 'statistics-mostpopular' => 'ܦܐܬܬ̈ܐ ܚܙܝ̈ܐ ܝܬܝܪ ܡܢ ܟܠ', 'disambiguations' => 'ܦܐܬܬ̈ܐ ܐܣܝܪ̈ܬܐ ܒܦܐܬܬ̈ܐ ܕܬܘܚܡܐ ܐܚܪܢܐ', 'disambiguationspage' => 'Template:ܬܘܚܡܐ ܐܚܪܢܐ', 'doubleredirects' => 'ܨܘܝܒ̈ܐ ܥܦܝܦ̈ܐ', 'double-redirect-fixed-move' => '[[$1]] ܐܫܬܢܝܬ. ܗܫܐ ܐܝܬܝܗܝ ܨܘܝܒܐ ܠ [[$2]].', 'brokenredirects' => 'ܨܘܝܒ̈ܐ ܬܒܝܪ̈ܐ', 'brokenredirectstext' => 'ܨܘ̈ܝܒܐ ܗܠܝܢ ܡܛܝܢ ܠܦܐܬܬ̈ܐ ܕܠܝܬܠܗܝܢ ܐܝܬܘܬܐ:', 'brokenredirects-edit' => 'ܫܚܠܦ', 'brokenredirects-delete' => 'ܫܘܦ', 'withoutinterwiki' => 'ܦܐܬܬ̈ܐ ܕܠܐ ܐܣܘܪ̈ܐ ܕܠܫܢ̈ܐ ܐܚܪ̈ܢܐ', 'withoutinterwiki-summary' => 'ܦܐܬܬ̈ܐ ܗܠܝܢ ܠܐ ܡܛܝܢ ܠܨ̈ܚܚܐ ܕܠܫܢ̈ܐ ܐܚܪ̈ܢܐ.', 'withoutinterwiki-legend' => 'ܫܪܘܝܐ', 'withoutinterwiki-submit' => 'ܚܘܝ', 'fewestrevisions' => 'ܦܐܬܬ̈ܐ ܥܡ ܬܢܝܬ̈ܐ ܒܨܝܪ ܡܢ ܟܠ', # Miscellaneous special pages 'nbytes' => '$1 {{PLURAL:$1|ܒܐܝܛ|ܒܐܝܛ̈ܐ}}', 'ncategories' => '$1 {{PLURAL:$1|ܣܕܪܐ|ܣܕܪ̈ܐ}}', 'nlinks' => '$1 {{PLURAL:$1|ܐܣܘܪܐ|ܐܣܘܪ̈ܐ}}', 'nmembers' => '$1 {{PLURAL:$1|ܗܕܡܐ|ܗܕ̈ܡܐ}}', 'nrevisions' => '$1 {{PLURAL:$1|ܬܢܝܬܐ|ܬܢܝܬ̈ܐ }}', 'nviews' => '$1 {{PLURAL:$1|ܚܘܘܝܐ|ܚܘܘܝ̈ܐ}}', 'specialpage-empty' => 'ܠܝܬ ܦܠܛ̈ܐ ܒܬܫܪܪܐ ܗܢܐ.', 'lonelypages' => 'ܦܐܬܬ̈ܐ ܝܬܡܬ̈ܐ', 'uncategorizedpages' => 'ܦܐܬܬ̈ܐ ܠܐ ܣܕܝܪ̈ܬܐ', 'uncategorizedcategories' => 'ܣܕܪ̈ܐ ܠܐ ܣܕܝܪ̈ܐ', 'uncategorizedimages' => 'ܠܦܦ̈ܐ ܠܐ ܣܕܝܪ̈ܐ', 'uncategorizedtemplates' => 'ܩܠܒ̈ܐ ܠܐ ܣܕܝܪ̈ܐ', 'unusedcategories' => 'ܣܕܪ̈ܐ ܠܐ ܦܠܝܚ̈ܐ', 'unusedimages' => 'ܠܦܦ̈ܐ ܠܐ ܦܠܝܚ̈ܐ', 'popularpages' => 'ܦܐܬܬ̈ܐ ܡܫܡܗܬ̈ܐ', 'wantedcategories' => 'ܣܕܪ̈ܐ ܒܥܝ̈ܐ', 'wantedpages' => 'ܦܐܬܬ̈ܐ ܣܢܝܩܬ̈ܐ', 'wantedfiles' => 'ܠܦܦ̈ܐ ܣܢܝܩ̈ܐ', 'wantedtemplates' => 'ܩܠܒ̈ܐ ܣܢܝܩ̈ܐ', 'mostlinked' => 'ܦܐܬܬ̈ܐ ܐܣܝܪ̈ܬܐ ܝܬܝܪ ܡܢ ܟܠ', 'mostlinkedcategories' => 'ܣܕܪ̈ܐ ܐܣܝܪ̈ܐ ܝܬܝܪ ܡܢ ܟܠ', 'mostlinkedtemplates' => 'ܩܠܒ̈ܐ ܐܣܝܪ̈ܐ ܝܬܝܪ ܡܢ ܟܠ', 'mostcategories' => 'ܦܐܬܬ̈ܐ ܣܕܝܪ̈ܬܐ ܝܬܝܪ ܡܢ ܟܠ', 'mostimages' => 'ܠܦܦ̈ܐ ܐܣܝܪ̈ܐ ܝܬܝܪ ܡܢ ܟܠ', 'mostrevisions' => 'ܦܐܬܬ̈ܐ ܥܡ ܫܘܚܠܦ̈ܐ ܝܬܝܪ ܡܢ ܟܠ', 'prefixindex' => 'ܟܠ ܦܐܬܬ̈ܐ ܥܡ ܫܪܘܝܐ', 'prefixindex-namespace' => 'ܟܠ ܦܐܬܬ̈ܐ ܥܡ ܫܪܘܝܐ ($1 ܚܩܠܐ)', 'shortpages' => 'ܦܐܬܬ̈ܐ ܟܪ̈ܝܬܐ', 'longpages' => 'ܦܐܬܬ̈ܐ ܐܪ̈ܝܟܬܐ', 'deadendpages' => 'ܦܐܬܬ̈ܐ ܥܡ ܚܪܬܐ ܡܝܬܬܐ', 'protectedpages' => 'ܦܐܬܬ̈ܐ ܢܛܝܪ̈ܬܐ', 'protectedtitles' => 'ܟܘܢܝ̈ܐ ܢܛܝܪ̈ܐ', 'protectedtitlestext' => 'ܟܘܢܝ̈ܐ ܗܠܝܢ ܢܛܝܪ̈ܐ ܐܢܘܢ ܠܘܩܒܠ ܒܪܝܐ', 'protectedtitlesempty' => 'ܠܝܬ ܟܘܢܝ̈ܐ ܢܛܝܪ̈ܐ ܗܫܐܝܬ ܥܡ ܗܠܝܢ ܦܪ̈ܘܫܝܐ', 'listusers' => 'ܡܟܬܒܘܬܐ ܕܗܕ̈ܡܐ', 'listusers-editsonly' => 'ܚܘܝ ܡܦܠܚܢ̈ܐ ܥܡ ܫܘܚܠܦ̈ܐ ܒܠܚܘܕ', 'listusers-creationsort' => 'ܛܟܣ ܐܝܟ ܣܝܩܘܡܐ ܕܒܪܝܐ', 'usereditcount' => '$1 {{PLURAL:$1|ܫܘܚܠܦܐ|ܫܘܚܠܦ̈ܐ}}', 'usercreated' => '{{ܓܢܣܐ:$3|ܒܪܐ}} ܒܣܝܩܘܡ $1 ܒܫܥܬܐ $2', 'newpages' => 'ܦܐܬܬ̈ܐ ܚܕ̈ܬܬܐ', 'newpages-username' => 'ܫܡܐ ܕܡܦܠܚܢܐ:', 'ancientpages' => 'ܦܐܬܬ̈ܐ ܥܬܝܩ ܡܢ ܟܠ', 'move' => 'ܫܢܝ', 'movethispage' => 'ܫܢܝ ܦܐܬܐ ܗܕܐ', 'notargettitle' => 'ܕܠܐ ܢܘܦܐ', 'nopagetitle' => 'ܠܝܬ ܗܟܘܬ ܦܐܬܐ ܕܢܘܦܐ', 'nopagetext' => 'ܦܐܬܐ ܕܢܘܦܐ ܕܬܬܚܡܬ ܠܝܬ ܠܗ ܐܝܬܘܬܐ.', 'pager-newer-n' => '{{PLURAL:$1|1 1 ܚܕܬܐ|$1 ܚܕ̈ܬܐ}}', 'pager-older-n' => '{{PLURAL:$1|1 ܥܬܝܩܐ|$1 ܥܬܝܩ̈ܐ}}', 'suppress' => 'ܚܝܘܪܐ', # Book sources 'booksources' => 'ܙܠ', 'booksources-search-legend' => 'ܒܨܝ ܥܠ ܡܒܘܥ̈ܐ ܕܟܬܒ̈ܐ', 'booksources-go' => 'ܙܠ', # Special:Log 'specialloguserlabel' => 'ܡܦܩܢܐ:', 'speciallogtitlelabel' => 'ܢܘܦܐ (ܟܘܢܝܐ ܐܘ ܡܦܠܚܢܐ):', 'log' => 'ܣܓܠ̈ܐ', 'all-logs-page' => 'ܟܠ ܣܓܠ̈ܐ ܓܘܢܝ̈ܐ', 'alllogstext' => 'ܓܠܚܐ ܟܠܢܝܐ ܠܟܠ ܣܓܠ̈ܐ ܡܪ ܐܝܬܘܬܐ ܒ{{SITENAME}}. ܡܨܬ ܕܬܙܥܪ ܠܦܠܛܐ ܒܓܒܝܬܐ ܕܐܕܫܐ ܕܣܓܠܐ ܐܘ ܫܡܐ ܕܡܦܠܚܢܐ (ܪܓܫܬܢܐ ܠܐܕܫܐ ܕܐܬܘܬܐ) ܐܘ ܦܐܬܐ ܬܘܥܒܕܬܐ (ܐܦ ܪܓܫܬܢܐ ܠܐܕܫܐ ܕܐܬܘܬܐ).', 'logempty' => 'ܠܝܬ ܡܠܘܐ̈ܐ ܠܐ̈ܝܡܐ ܒܣܓܠܐ ܗܢܐ.', 'log-title-wildcard' => 'ܒܨܝ ܥܠ ܟܘܢܝ̈ܐ ܕܫܪܝܢ ܥܡ ܟܬܒܬܐ ܗܕܐ', # Special:AllPages 'allpages' => 'ܟܠ ܦܐܬܬ̈ܐ', 'alphaindexline' => '$1 ܠ $2', 'nextpage' => 'ܦܐܬܐ ܕܒܬܪ ($1)', 'prevpage' => 'ܦܐܬܐ ܕܩܕܡ ($1)', 'allpagesfrom' => 'ܚܘܝ ܦܐܬܬ̈ܐ ܕܫܪܐ ܥܡ:', 'allpagesto' => 'ܚܘܝ ܦܐܬܬ̈ܐ ܕܫܠܡ ܥܡ:', 'allarticles' => 'ܟܠ ܡܓܠ̈ܐ', 'allinnamespace' => 'ܟܠ ܦܐܬܬ̈ܐ (ܚܩܠܐ ܕ $1)', 'allnotinnamespace' => 'ܟܠ ܦܐܬܬ̈ܐ (ܕܠܝܬ ܒܚܩܠܐ ܕ $1)', 'allpagesprev' => 'ܕܩܕܡ', 'allpagesnext' => 'ܕܒܬܪ', 'allpagessubmit' => 'ܙܠ', 'allpagesprefix' => 'ܚܘܝ ܦܐܬܬ̈ܐ ܕܫܪܝܢ ܒ:', 'allpages-bad-ns' => '{{SITENAME}} ܠܝܬ ܠܗ ܚܩܠܐ "$1".', # Special:Categories 'categories' => 'ܣܕܪ̈ܐ', 'categoriesfrom' => 'ܚܘܝ ܣܕܪ̈ܐ ܕܫܪܝܢ ܒ:', 'special-categories-sort-count' => 'ܛܟܣ ܒܡܢܝܢܐ', 'special-categories-sort-abc' => 'ܛܟܣ ܗܓܝܢܐܝܬ', # Special:DeletedContributions 'deletedcontributions' => 'ܫܘܬܦܘ̈ܬܐ ܫܝ̈ܦܬܐ ܕܡܦܠܚܢܐ', 'deletedcontributions-title' => 'ܫܘܬܦܘ̈ܬܐ ܫܝ̈ܦܬܐ ܕܡܦܠܚܢܐ', 'sp-deletedcontributions-contribs' => 'ܫܘܬܦܘ̈ܬܐ', # Special:LinkSearch 'linksearch' => 'ܐܣܘܪ̈ܐ ܒܪ̈ܝܐ ܒܨܝܐ', 'linksearch-pat' => 'ܙܢܐ ܕܒܨܝܐ:', 'linksearch-ns' => 'ܚܩܠܐ:', 'linksearch-ok' => 'ܒܨܝ', 'linksearch-line' => '$1 ܝܨܝܪܐ ܡܢ $2', # Special:ListUsers 'listusersfrom' => 'ܚܘܝ ܡܦܠܚܢ̈ܐ ܕܫܪܝܢ ܒ:', 'listusers-submit' => 'ܚܘܝ', 'listusers-noresult' => 'ܠܐ ܐܫܬܟܚ ܡܦܠܚܢܐ ܚܕ.', 'listusers-blocked' => '(ܚܪܝܡܐ)', # Special:ActiveUsers 'activeusers' => 'ܡܟܬܒܘܬܐ ܕܗܕ̈ܡܐ ܙܪ̄ܝܙܐ', 'activeusers-count' => '$1 {{PLURAL:$1|ܥܒܕܐ|ܥܒܕ̈ܐ}} ܒ {{PLURAL:$3|ܝܘܡܐ ܐܚܪܝܐ|$3 ܝܘܡܬ̈ܐ ܐܚܪ̈ܝܐ}}', 'activeusers-from' => 'ܚܘܝ ܡܦܠܚܢ̈ܐ ܕܫܪܐ ܥܡ:', 'activeusers-hidebots' => 'ܛܫܝ ܒܘܬ̈ܐ (bots)', 'activeusers-hidesysops' => 'ܛܫܝ ܡܕܒܪ̈ܢܐ', 'activeusers-noresult' => 'ܠܐ ܐܫܬܟܚ ܡܦܠܚܢ̈ܐ ܐܢܫ̈ܝܢ.', # Special:Log/newusers 'newuserlogpage' => 'ܣܓܠܐ ܕܒܪܝܬܐ ܕܡܦܠܚܢܐ', 'newuserlogpagetext' => 'ܗܢܘ ܣܓܠܐ ܕܒܪܝܐ ܕܡܦܠܚܢ̈ܐ', # Special:ListGroupRights 'listgrouprights' => 'ܙܕ̈ܩܐ ܕܟܢܘܫܬܐ ܕܡܦܠܚܢ̈ܐ', 'listgrouprights-group' => 'ܟܢܘܫܬܐ', 'listgrouprights-rights' => 'ܙܕ̈ܩܐ', 'listgrouprights-helppage' => 'Help:ܙܕ̈ܩܐ ܕܟܢܘܫܬܐ', 'listgrouprights-members' => '(ܡܟܬܒܘܬܐ ܕܗܕ̈ܡܐ)', 'listgrouprights-addgroup' => 'ܐܘܣܦ {{PLURAL:$2|ܟܢܘܫܬܐ|ܟܢܘܫܬ̈ܐ}}: $1', 'listgrouprights-removegroup' => 'ܠܚܝ {{PLURAL:$2|ܟܢܘܫܬܐ|ܟܢܘܫܬ̈ܐ}}: $1', 'listgrouprights-addgroup-all' => 'ܐܘܣܦ ܟܠ ܟܢܘܫܬ̈ܐ', 'listgrouprights-removegroup-all' => 'ܠܚܝ ܟܠ ܟܢܘܫܬ̈ܐ', 'listgrouprights-removegroup-self' => 'ܠܚܝ {{PLURAL:$2|ܟܢܘܫܬܐ|ܟܢܘܫܬ̈ܐ}} ܡܢ ܚܘܫܒܢܗ ܕܝܠܢܝܐ: $1', 'listgrouprights-removegroup-self-all' => 'ܠܚܝ ܟܠ ܟܢܘܫܬ̈ܐ ܡܢ ܚܘܫܒܢܗ ܕܝܠܢܝܐ', # Email user 'mailnologin' => 'ܠܝܬ ܡܘܢܥܐ ܠܫܘܕܪܐ', 'emailuser' => 'ܫܕܪ ܐܓܪܬܐ ܠܗܢܐ ܡܦܠܚܢܐ', 'emailpage' => 'ܫܕܪ ܐܓܪܬܐ ܒܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ ܠܡܦܠܚܢܐ', 'defemailsubject' => 'ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ ܡܢ ܡܦܠܚܢܐ "$1"', 'noemailtitle' => 'ܠܝܬ ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ', 'emailusername' => 'ܫܡܐ ܕܡܦܠܚܢܐ:', 'emailusernamesubmit' => 'ܫܕܪ', 'email-legend' => 'ܫܕܪ ܐܓܪܬܐ ܠܡܦܠܚܢܐ ܕ {{SITENAME}} ܐܚܪܢܐ', 'emailfrom' => 'ܡܢ:', 'emailto' => 'ܠ:', 'emailsubject' => 'ܡܠܘܐܐ:', 'emailmessage' => 'ܐܓܪܬܐ:', 'emailsend' => 'ܫܕܪ', 'emailccme' => 'ܫܕܪ ܠܝ ܨܚܚܐ ܡܢ ܐܓܪ̈ܬܐ ܕܝܠܝ.', 'emailccsubject' => 'ܨܚܚܐ ܕܐܓܪܬܟ ܠ $1: $2', 'emailsent' => 'ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ ܐܫܬܕܪ', # User Messenger 'usermessage-summary' => 'ܫܒܩܐ ܐܓܪܬܐ ܕܛܟܣܐ', 'usermessage-editor' => 'ܡܫܕܪܢܐ ܕܛܟܣܐ', # Watchlist 'watchlist' => 'ܪ̈ܗܝܬܐ', 'mywatchlist' => 'ܪ̈ܗܝܬܐ', 'watchlistfor2' => 'ܕ $1 $2', 'nowatchlist' => 'ܠܝܬ ܠܟ ܡܕܡ ܒܪ̈ܗܝܬܐ ܕܝܠܟ', 'watchlistanontext' => '$1 ܠܚܙܝܐ ܐܘ ܫܚܠܦܬܐ ܕܦܐܬܬ̈ܐ ܒܪ̈ܗܝܬܟ.', 'watchnologin' => 'ܠܝܬܝܟ ܥܠܝܠܐ', 'watchnologintext' => 'ܐܠܨܐ ܕܬܗܘܐ [[Special:UserLogin|ܥܠܝܠܐ]] ܠܫܚܠܦܬܐ ܕܪ̈ܗܝܬܟ.', 'addwatch' => 'ܐܘܣܦ ܥܠ ܪ̈ܗܝܬܝ', 'addedwatchtext' => 'ܦܐܬܐ ܕ"[[:$1]]" ܐܬܬܘܣܦܬ ܠ[[Special:Watchlist|ܪ̈ܗܝܬܟ]]. ܐܝܢܐ ܫܘܚܠܦܐ ܥܠ ܦܐܬܐ ܗܕܐ ܒܕܥܬܝܕ ܬܬܓܠܚ ܥܡ ܦܐܬܐ ܕܡܡܠܠܐ ܕܝܠܗ ܬܡܢ.', 'removewatch' => 'ܫܩܘܠ ܡܢ ܪ̈ܗܝܬܝ', 'removedwatchtext' => 'ܦܐܬܐ ܕ "[[:$1]]" ܐܫܬܩܠܬ ܡܢ [[Special:Watchlist|ܪ̈ܗܝܬܟ]].', 'watch' => 'ܪܗܝ', 'watchthispage' => 'ܪܗܝ ܗܕܐ ܦܐܬܐ', 'unwatch' => 'ܠܐ ܪܗܝ', 'unwatchthispage' => 'ܟܠܝ ܪܗܝܐ', 'watchnochange' => 'ܐܦܠܐ ܚܕ ܡܢ ܦܐܬܬ̈ܐ ܒܪ̈ܗܝܬܟ ܐܫܬܚܠܦܬ ܒܡܬܚܐ ܕܙܒܢܐ ܓܠܝܚܐ.', 'watchlist-details' => '{{PLURAL:$1|$1 ܦܐܬܐ|$1 ܦܐܬܬ̈ܐ}} ܒܪ̈ܗܝܬܟ, ܫܒܘܩ ܡܢ ܦܐܬܬ̈ܐ ܕܡܡܠܠܐ.', 'wlheader-showupdated' => "* ܦܐܬܬ̈ܐ ܕܐܫܬܚܠܦܢ ܡܢ ܒܬܪ ܣܘܥܪܢܟ ܐܚܪܝܐ ܡܬܓܠܚܢ ܒܣܪܛܐ '''ܚܠܝܡܐ'''", 'wlnote' => "ܠܬܚܬ {{PLURAL:$1|ܫܘܚܠܦܐ ܐܚܪܝܐ| '''$1''' ܫܘܚܠܦ̈ܐ ܐܚܪ̈ܝܐ}} {{PLURAL:$2|ܒܫܥܬܐ ܐܚܪܝܬܐ|'''$2''' ܒܫܥܬ̈ܐ ܐܚܪ̈ܝܬܐ}}, ܠܦܘܬ $3, $4.", 'wlshowlast' => 'ܚܘܝ $1 ܫܥܬ̈ܐ $2 ܝܘܡܬ̈ܐ ܐܚܪ̈ܝܐ $3', 'watchlist-options' => 'ܨܒܝܢܝܘܬ̈ܐ ܕܪ̈ܗܝܬܐ', # Displayed when you click the "watch" button and it is in the process of watching 'watching' => 'ܪܗܝܐ...', 'unwatching' => 'ܠܚܝ ܪܗܝܐ...', 'enotif_reset' => 'ܫܘܕܥ ܟܠ ܦܐܬܬ̈ܐ ܐܝܟ ܣܥܝܪ̈ܬܐ', 'enotif_newpagetext' => 'ܗܕܐ ܗܝ ܦܐܬܐ ܚܕܬܐ', 'enotif_impersonal_salutation' => 'ܡܦܠܚܢܐ {{SITENAME}}', 'changed' => 'ܐܫܬܚܠܦܬ', 'created' => 'ܒܪܐ', 'enotif_lastvisited' => 'ܚܙܝ $1 ܠܟܠ ܫܘܚܠܦ̈ܐ ܡܢ ܐܡܬܝ ܕܣܘܥܪܢܐ ܐܚܪܝܐ ܕܝܠܟ.', 'enotif_lastdiff' => 'ܚܙܝ $1 ܠܚܙܝܐ ܕܫܘܚܠܦܐ ܗܢܐ.', 'enotif_anon_editor' => 'ܡܦܠܚܢܐ ܠܐ ܝܕܝܥܐ $1', # Delete 'deletepage' => 'ܫܘܦ ܦܐܬܐ', 'confirm' => 'ܫܪܪ', 'excontent' => "ܚܒܝܫܬ̈ܐ ܗܘ̈ܝ: '$1'", 'excontentauthor' => "ܚܒܝܫܬ̈ܐ ܗܘ̈ܝ: '$1' (ܘܫܘܬܦܢܐ ܝܚܝܕܝܐ ܗܘܐ '[[Special:Contributions/$2|$2]]')", 'exblank' => 'ܦܐܬܐ ܣܦܝܩܬܐ ܗܘܐ', 'delete-confirm' => 'ܫܘܦ "$1"', 'delete-legend' => 'ܫܘܦ', 'actioncomplete' => 'ܥܡܠܝܬܐ ܓܡܪܬ', 'actionfailed' => 'ܥܡܠܝܬܐ ܠܐ ܢܨܚܬ', 'dellogpage' => 'ܣܓܠܐ ܕܫܝܦܐ', 'dellogpagetext' => 'ܠܬܚܬ ܡܟܬܒܘܬܐ ܕܦܐܬܬ̈ܐ ܫܝܦܬ̈ܐ ܚܕ̈ܬܬܐ.', 'deletionlog' => 'ܣܓܠܐ ܕܫܝܦܐ', 'deletecomment' => 'ܥܠܬܐ:', 'deleteotherreason' => 'ܥܠܬܐ ܐܚܪܬܐ/ܝܬܝܪܬܐ:', 'deletereasonotherlist' => 'ܥܠܬܐ ܐܚܪܬܐ', 'delete-edit-reasonlist' => 'ܫܚܠܦ ܥܠܠܬ̈ܐ ܕܫܝܦܐ', # Rollback 'rollbacklink' => 'ܐܦܢܝ', 'editcomment' => "ܦܣܝܩܬ̈ܐ ܕܫܘܚܠܦܐ ܗܘܐ: \"''\$1''\".", 'revertpage' => 'ܐܗܦܟ ܫܘܚܠܦ̈ܐ ܒܝܕ [[Special:Contributions/$2|$2]] ([[User talk:$2|ܡܡܠܠܐ]]) ܠܬܢܝܬܐ ܐܚܪܝܬܐ ܒܝܕ [[User:$1|$1]]', # Edit tokens 'sessionfailure-title' => 'ܡܘܬܒܐ ܠܐ ܢܨܚܬ', # Protect 'protectlogpage' => 'ܣܓܠܐ ܕܢܛܪܐ', 'protectedarticle' => 'ܢܛܪ "[[$1]]"', 'modifiedarticleprotection' => 'ܫܚܠܦ ܫܘܝܐ ܕܢܛܪܐ ܕ"[[$1]]"', 'unprotectedarticle' => 'ܫܩܘܠ ܢܛܝܪܘܬܐ ܡܢ "[[$1]]"', 'movedarticleprotection' => 'ܫܢܐ ܛܘܝܒ̈ܐ ܕܢܛܪܐ ܡܢ "[[$2]]" ܠ "[[$1]]"', 'protect-title' => 'ܫܚܠܦ ܫܘܝܐ ܕܢܛܪܐ ܕ"$1"', 'protect-title-notallowed' => 'ܚܘܝ ܫܘܝܐ ܕܢܛܪܐ ܕ"$1"', 'prot_1movedto2' => '[[$1]] ܐܬܫܢܝܬ ܠ [[$2]]', 'protect-legend' => 'ܫܪܪ ܢܘܛܪܐ', 'protectcomment' => 'ܥܠܬܐ:', 'protect-default' => 'ܦܣܣܐ ܠܟܠ ܡܦܠܚܢ̈ܐ', 'protect-fallback' => 'ܦܣܣ ܠܡܦܠܚܢ̈ܐ ܥܡ "$1" ܦܣܣܐ ܒܠܚܘܕ', 'protect-level-autoconfirmed' => 'ܦܣܣ ܠܡܦܠܚܢ̈ܐ ܚܬܝܬ̈ܐ ܝܬܐܝܬ ܒܠܚܘܕ', 'protect-level-sysop' => 'ܦܣܣ ܠܡܕܒܪ̈ܢܐ ܒܠܚܘܕ', 'protect-expiring' => 'ܬܦܪܘܩ ܒ $1 (UTC)', 'protect-expiring-local' => 'ܬܦܪܘܩ ܒ $1', 'protect-expiry-indefinite' => 'ܠܥܠܡ', 'protect-othertime' => 'ܥܕܢܐ ܐܚܪܢܐ:', 'protect-othertime-op' => 'ܥܕܢܐ ܐܚܪܢܐ', 'protect-otherreason' => 'ܥܠܬܐ ܐܚܪܬܐ/ܢܩܝܦܬܐ:', 'protect-otherreason-op' => 'ܥܠܬܐ ܐܚܪܬܐ', 'protect-edit-reasonlist' => 'ܫܚܠܦ ܥܠܬܐ ܕܢܛܪܐ', 'protect-expiry-options' => '1 ܫܥܐ:1 hour,1 ܝܘܡ:1 day,1 ܫܒܘܥ:1 week,2 ܫܒܘܥ̈ܝܢ:2 weeks,1 ܝܪܚ:1 month,3 ܝܪ̈ܚܝܢ:3 months,6 ܝܪ̈ܚܝܢ:6 months,1 ܫܢܐ:1 year,ܠܥܠܡ:infinite', 'restriction-type' => 'ܦܣܣܐ:', 'restriction-level' => 'ܫܘܝܐ ܕܣܘܝܟܐ:', 'minimum-size' => 'ܡܬܚܐ ܬܚܬܝܐ ܕܥܓܪܐ', 'maximum-size' => 'ܡܬܚܐ ܥܠܝܐ ܕܥܓܪܐ', 'pagesize' => '(ܒܐܝܛ)', # Restrictions (nouns) 'restriction-edit' => 'ܫܚܠܦ', 'restriction-move' => 'ܫܢܝ', 'restriction-create' => 'ܒܪܝ', 'restriction-upload' => 'ܐܣܩ', # Restriction levels 'restriction-level-sysop' => 'ܢܛܝܪܘܬܐ ܓܡܝܪܬܐ', 'restriction-level-autoconfirmed' => 'ܕܡܘܬ ܢܛܝܪܘܬܐ', 'restriction-level-all' => 'ܐܝܢܐ ܫܘܝܐ', # Undelete 'undelete' => 'ܚܙܝ ܦܐܬܬ̈ܐ ܫܝܦܬ̈ܐ', 'undeletepage' => 'ܚܙܝ ܘܐܦܢܝ ܦܐܬܬ̈ܐ ܫܝܦܬ̈ܐ', 'viewdeletedpage' => 'ܚܙܝ ܦܐܬܬ̈ܐ ܫܝܦܬ̈ܐ', 'undelete-fieldset-title' => 'ܐܦܢܝ ܬܢܝܬ̈ܐ', 'undelete-revision' => 'ܫܦ ܬܢܝܬܐ ܕ $1 (ܒܣܝܩܘܡ $4, ܒ $5) ܒܝܕ $3:', 'undelete-nodiff' => 'ܠܝܬ ܬܢܝܬܐ ܥܬܝܩܬܐ.', 'undeletebtn' => 'ܐܦܢܝ', 'undeletelink' => 'ܚܙܝ/ܐܦܢܝ', 'undeleteviewlink' => 'ܚܙܝ', 'undeleteinvert' => 'ܐܗܦܟ ܠܓܘܒܝܐ', 'undeletecomment' => 'ܥܠܬܐ:', 'undeletedrevisions' => '{{PLURAL:$1|1 ܬܢܝܬܐ|$1 ܬܢܝܬ̈ܐ}} ܐܦܢܝܬ', 'undeletedrevisions-files' => '{{PLURAL:$1|1 ܬܢܝܬܐ|$1 ܬܢܝܬ̈ܐ}} and {{PLURAL:$2|1 ܠܦܦܐ|$2 ܠܦܦܐ}} ܐܦܢܝܬ', 'undeletedfiles' => '{{PLURAL:$1|1 ܠܦܦܐ|$1 ܠܦܦ̈ܐ}} ܐܦܢܝܬ', 'undelete-header' => 'ܚܙܝ [[Special:Log/delete|ܣܓܠܐ ܕܫܝܦܐ]] ܠܚܙܝܐ ܕܦܐܬܬ̈ܐ ܫܝܦܬ̈ܐ ܚܕ̈ܬܬܐ.', 'undelete-search-title' => 'ܒܨܝ ܦܐܬܬ̈ܐ ܫܝܦܬ̈ܐ', 'undelete-search-box' => 'ܒܨܝ ܦܐܬܬ̈ܐ ܫܝܦܬ̈ܐ', 'undelete-search-prefix' => 'ܚܘܝ ܦܐܬܬ̈ܐ ܫܪܝܢ ܒ:', 'undelete-search-submit' => 'ܒܨܝ', 'undelete-error-short' => 'ܦܘܕܐ ܒܦܢܝܐ ܕܠܦܦܐ: $1', 'undelete-show-file-submit' => 'ܐܝܢ', # Namespace form on various pages 'namespace' => 'ܚܩܠܐ:', 'invert' => 'ܐܗܦܟ ܠܓܘܒܝܐ', 'namespace_association' => 'ܚܩܠܐ ܠܐܝܡܐ', 'blanknamespace' => '(ܪܫܝܬܐ)', # Contributions 'contributions' => 'ܫܘܬܦܘܝܬ̈ܐ ܕܡܦܠܚܢܐ', 'contributions-title' => 'ܫܘܬܦܘ̈ܬܐ ܕܡܦܠܚܢܐ ܠ$1', 'mycontris' => 'ܫܘܬܦܘ̈ܬܐ', 'contribsub2' => 'ܕ $1 ($2)', 'uctop' => '(ܥܠܝܐ)', 'month' => 'ܡܢ ܝܪܚܐ ܕ (ܘܡܢ ܩܕܡ ܗܝܕܝܢ):', 'year' => 'ܡܢ ܫܢܬ (ܘܡܢ ܩܕܡ ܗܝܕܝܢ):', 'sp-contributions-newbies' => 'ܚܘܝ ܫܘܬܦܘ̈ܬܐ ܕܚܘܫܒܢ̈ܐ ܚܕ̈ܬܐ ܒܠܚܘܕ', 'sp-contributions-newbies-sub' => 'ܠܚܘܫܒܢ̈ܐ ܚܕ̈ܬܐ', 'sp-contributions-newbies-title' => 'ܫܘܬܦܘ̈ܬܐ ܕܡܦܠܚܢܐ ܠܚܘܫܒܢ̈ܐ ܚܕ̈ܬܐ', 'sp-contributions-blocklog' => 'ܣܓܠܐ ܕܚܪܡܐ', 'sp-contributions-deleted' => 'ܫܘܬܦܘ̈ܬܐ ܫܝ̈ܦܬܐ ܕܡܦܠܚܢܐ', 'sp-contributions-uploads' => 'ܡܣܩܬ̈ܐ', 'sp-contributions-logs' => 'ܣܓܠ̈ܐ', 'sp-contributions-talk' => 'ܡܡܠܠܐ', 'sp-contributions-userrights' => 'ܕܘܒܪܐ ܕܙܕ̈ܩܐ ܕܡܦܠܚܢܐ', 'sp-contributions-search' => 'ܒܨܝ ܫܘܬܦܘ̈ܬܐ', 'sp-contributions-username' => 'ܐܝ ܦܝ (IP) ܐܘ ܫܡܐ ܕܡܦܠܚܢܐ:', 'sp-contributions-toponly' => 'ܚܘܝ ܫܘܚܠܦ̈ܐ ܕܗܢܘܢ ܬܢܝܬ̈ܐ ܐܚܪ̈ܝܬܐ ܒܠܚܘܕ', 'sp-contributions-submit' => 'ܒܨܝ', # What links here 'whatlinkshere' => 'ܡܐ ܐܣܪ ܠܗܪܟܐ', 'whatlinkshere-title' => 'ܦܐܬܬ̈ܐ ܕܐܣܝܪܝܢ ܥܡ "$1"', 'whatlinkshere-page' => 'ܦܐܬܐ:', 'linkshere' => "ܦܐܬܬ̈ܐ ܗܠܝܢ ܐܣܝܪܝܢ ܥܡ '''[[:$1]]''':", 'nolinkshere' => "ܠܝܬ ܦܐܬܬ̈ܐ ܐܣܪܝܢ ܥܡ '''[[:$1]]'''.", 'nolinkshere-ns' => "ܠܝܬ ܦܐܬܬ̈ܐ ܐܣܪܝܢ ܥܡ '''[[:$1]]''' ܒܚܩܠܐ ܓܒܝܐ.", 'isredirect' => 'ܦܐܬܐ ܕܨܘܝܒܐ', 'istemplate' => 'ܚܒܝܫܬܐ', 'isimage' => 'ܐܣܘܪܐ ܕܠܦܦܐ', 'whatlinkshere-prev' => '{{PLURAL:$1|ܕܩܕܡ|$1 ܕܩܕܡ}}', 'whatlinkshere-next' => '{{PLURAL:$1|ܕܒܬܪ|$1 ܕܒܬܪ}}', 'whatlinkshere-links' => '← ܐܣܘܪ̈ܐ', 'whatlinkshere-hideredirs' => '$1 ܨܘܝܒ̈ܐ', 'whatlinkshere-hidetrans' => '$1 ܡܬܚܪ̈ܙܢܘܬܐ', 'whatlinkshere-hidelinks' => '$1 ܐܣܘܪ̈ܐ', 'whatlinkshere-hideimages' => '$1 ܐܣܘܪܐ ܕܠܦܦܐ', 'whatlinkshere-filters' => 'ܡܨܦܝܢܝܬ̈ܐ', # Block/unblock 'autoblockid' => 'ܚܪܡܐ ܝܬܢܝܐ #$1', 'block' => 'ܚܪܘܡ ܡܦܠܚܢܐ', 'unblock' => 'ܫܩܘܠ ܚܪܡܐ ܡܢ ܡܦܠܚܢܐ', 'blockip' => 'ܚܪܘܡ ܡܦܠܚܢܐ', 'blockip-title' => 'ܚܪܘܡ ܡܦܠܚܢܐ', 'blockip-legend' => 'ܚܪܘܡ ܡܦܠܚܢܐ', 'ipadressorusername' => 'ܐܝ ܦܝ (IP) ܐܘ ܫܡܐ ܕܡܦܠܚܢܐ:', 'ipbexpiry' => 'ܡܬܚܐ ܕܚܪܡܐ:', 'ipbreason' => 'ܥܠܬܐ:', 'ipbreasonotherlist' => 'ܥܠܬܐ ܐܚܪܬܐ', 'ipbsubmit' => 'ܚܪܘܡ ܡܦܠܚܢܐ ܗܢܐ', 'ipbother' => 'ܥܕܢܐ ܐܚܪܢܐ', 'ipboptions' => '2 ܫܥ̈ܝܢ:2 hours,1 ܝܘܡ:1 day,3 ܝܘܡ̈ܝܢ:3 days,1 ܫܒܘܥ:1 week,2 ܫܒܘܥ̈ܝܢ:2 weeks,1 ܝܪܚ:1 month,3 ܝܪ̈ܚܝܢ:3 months,6 ܝܪ̈ܚܝܢ:6 months,1 ܫܢܐ:1 year,ܠܥܠܡ:infinite', 'ipbotheroption' => 'ܐܚܪܢܐ', 'ipbotherreason' => 'ܥܠܬܐ ܐܚܪܬܐ/ܢܩܝܦܬܐ:', 'ipbhidename' => 'ܛܫܝ ܫܡܐ ܕܡܦܠܚܢܐ ܡܢ ܫܘܚܠܦ̈ܐ ܘܡܟܬܒܘܬ̈ܐ', 'badipaddress' => 'ܐܝ ܦܝ (IP) ܠܐ ܬܪܝܨܐ:', 'blockipsuccesssub' => 'ܚܪܡܐ ܓܡܪ', 'ipb-edit-dropdown' => 'ܫܚܠܦ ܥܠܠܬ̈ܐ ܕܚܪܡܐ', 'ipb-unblock-addr' => 'ܫܩܘܠ ܚܪܡܐ ܡܢ $1', 'ipb-unblock' => 'ܫܩܘܠ ܚܪܡܐ ܡܢ ܐܝ ܦܝ (IP) ܐܘ ܫܡܐ ܕܡܦܠܚܢܐ', 'ipb-blocklist-contribs' => 'ܫܘܬܦܘ̈ܬܐ ܕ$1', 'unblockip' => 'ܫܩܘܠ ܚܪܡܐ ܡܢ ܡܦܠܚܢܐ', 'ipusubmit' => 'ܫܩܘܠ ܚܪܡܐ ܗܢܐ', 'unblocked' => 'ܐܫܬܩܠ ܚܪܡܐ ܡܢ [[User:$1|$1]]', 'blocklist' => 'ܡܦܠܚܢ̈ܐ ܡܚܪ̈ܡܐ', 'ipblocklist' => 'ܡܦܠܚܢ̈ܐ ܡܚܪ̈ܡܐ', 'ipblocklist-legend' => 'ܐܫܟܚ ܡܦܠܚܢܐ ܡܚܪܡܐ', 'blocklist-reason' => 'ܥܠܬܐ', 'ipblocklist-submit' => 'ܒܨܝ', 'ipblocklist-localblock' => 'ܚܪܡܐ ܕܘܟܬܢܝܐ', 'infiniteblock' => 'ܠܥܠܡ', 'anononlyblock' => 'ܠܐ ܝܕ̈ܝܥܐ ܒܠܚܘܕ', 'ipblocklist-empty' => 'ܣܓܠܐ ܕܚܪܡܐ ܣܦܝܩܐ.', 'blocklink' => 'ܚܪܘܡ', 'unblocklink' => 'ܫܩܘܠ ܚܪܡܐ', 'change-blocklink' => 'ܫܚܠܦ ܚܪܡܐ', 'contribslink' => 'ܫܘܬܦܘ̈ܬܐ', 'blocklogpage' => 'ܣܓܠܐ ܕܚܪܡܐ', 'blocklogentry' => 'ܚܪܡ [[$1]] ܠܡܬܚܐ ܕ $2 $3', 'blocklogtext' => 'ܗܢܘ ܣܓܠܐ ܕܥܡܠܝܬ̈ܐ ܕܚܪܡܐ ܘܫܩܠ ܚܪܡܐ. ܡܘܢܥ̈ܐ ܕܐܝ ܦܝ (IP) ܚܪ̈ܝܡܐ ܝܬܐܝܬ ܠܐ ܓܠܝܚܝܢ ܐܢܘܢ. ܚܙܝ [[Special:BlockList|ܡܟܬܒܘܬܐ ܕܚܪܡܐ ܕܐܝ ܦܝ (IP)]]ܠܚܙܝܐ ܕܥܡܠܝܬ̈ܐ ܕܚܪܡܐ ܬܘܦܥܠ̈ܐ ܗܫܐܝܬ.', 'unblocklogentry' => 'ܫܩܠ ܚܪܡܐ ܡܢ $1', 'block-log-flags-anononly' => 'ܡܦܠܚܢ̈ܐ ܠܐ ܝܕ̈ܝܥܐ ܒܠܚܘܕ', 'block-log-flags-nocreate' => 'ܒܪܝܬܐ ܕܚܘ̈ܫܒܢܐ ܠܐ ܐܝܬܝܗ ܡܬܩܒܠܢܐ', 'block-log-flags-hiddenname' => 'ܫܡܐ ܕܡܦܠܚܢܐ ܛܘܫܝܐ', 'ipb_already_blocked' => '"$1" ܡܚܪܡܐ ܗܘ ܡܢ ܟܕܘ', 'ipb-needreblock' => '"$1" ܡܚܪܡܐ ܗܘ ܡܢ ܟܕܘ Do you want to change the settings?', 'blockme' => 'ܚܪܘܡ ܠܝ', 'proxyblocksuccess' => 'ܒܪܐ', # Move page 'move-page' => 'ܫܢܝ $1', 'move-page-legend' => 'ܫܢܝ ܦܐܬܐ', 'movearticle' => 'ܫܢܝ ܦܐܬܐ:', 'movenologin' => 'ܠܝܬܝܟ ܥܠܝܠܐ', 'newtitle' => 'ܠܫܡܐ ܚܕܬܐ:', 'move-watch' => 'ܪܗܝ ܦܐܬܐ ܗܕܐ', 'movepagebtn' => 'ܫܢܝ ܦܐܬܐ', 'pagemovedsub' => 'ܫܘܢܝܐ ܓܡܪ', 'movepage-moved' => '\'\'\'"$1" ܐܫܬܢܝܬ ܠ "$2"\'\'\'', 'movepage-moved-redirect' => 'ܨܘܝܒܐ ܐܬܒܪܝ', 'movedto' => 'ܐܬܫܢܝ ܠ', 'move-subpages' => 'ܫܢܝ ܦܐܬܬ̈ܐ ܦܪ̈ܥܝܬ̈ܐ (ܥܕܡܐ ܠ $1)', 'move-talk-subpages' => 'ܫܢܝ ܦܐܬܬ̈ܐ ܦܪ̈ܥܝܬ̈ܐ ܕܦܐܬܐ ܕܕܘܪܫܐ (ܥܕܡܐ ܠ $1)', 'movelogpage' => 'ܣܓܠܐ ܕܫܘܢܝܐ', 'movereason' => 'ܥܠܬܐ:', 'revertmove' => 'ܐܦܢܝ', 'delete_and_move' => 'ܫܘܦ ܘܫܢܝ', 'delete_and_move_confirm' => 'ܐܝܢ, ܫܘܦ ܦܐܬܐ', 'move-leave-redirect' => 'ܫܒܘܩ ܨܘܝܒܐ ܒܬܪܟ', # Export 'export' => 'ܐܦܩ ܦܐܬܬ̈ܐ', 'exportall' => 'ܐܦܩ ܟܠ ܦܐܬܬ̈ܐ', 'export-submit' => 'ܐܦܩ', 'export-addcattext' => 'ܐܘܣܦ ܦܐܬܬ̈ܐ ܡܢ ܣܕܪܐ:', 'export-addcat' => 'ܐܘܣܦ', 'export-addnstext' => 'ܐܘܣܦ ܦܐܬܬ̈ܐ ܡܢ ܚܩܠܐ:', 'export-addns' => 'ܐܘܣܦ', 'export-download' => 'ܠܒܘܟ ܐܝܟ ܠܦܦܐ', # Namespace 8 related 'allmessages' => 'ܐܓܪ̈ܬܐ ܕܛܟܣܐ', 'allmessagesname' => 'ܫܡܐ', 'allmessagesdefault' => 'ܐܓܪܬܐ ܕܟܬܒܬܐ ܡܬܚܫܒܢܝܬܐ', 'allmessagescurrent' => 'ܟܬܒܬܐ ܗܫܝܬܐ ܕܐܓܪܬܐ', 'allmessages-filter-legend' => 'ܡܨܦܝܢܝܬܐ', 'allmessages-filter' => 'ܨܦܝ ܐܝܟ ܐܝܟܢܝܘܬܐ ܕܡܬܕܝܠܢܘܬܐ:', 'allmessages-filter-unmodified' => 'ܠܐ ܫܘܓܢܝܐ', 'allmessages-filter-all' => 'ܟܠ', 'allmessages-filter-modified' => 'ܫܘܓܢܝܐ', 'allmessages-prefix' => 'ܡܨܦܝܢܝܬܐ ܐܝܟ ܫܘܪܝܐ', 'allmessages-language' => 'ܠܫܢܐ:', 'allmessages-filter-submit' => 'ܙܠ', # Thumbnails 'thumbnail-more' => 'ܐܘܪܒ', 'thumbnail_error' => 'ܦܘܕܐ ܒܒܪܝܐ ܕܨܘܪܬܐ ܙܥܘܪܬܐ: $1', # Special:Import 'import' => 'ܐܥܠ ܦܐܬܬ̈ܐ', 'import-interwiki-submit' => 'ܐܥܠ', 'import-upload-filename' => 'ܫܡܐ ܕܠܦܦܐ:', 'import-revision-count' => '$1 {{PLURAL:$1|ܬܢܝܬܐ |ܬܢܝܬ̈ܐ}}', 'importnopages' => 'ܠܝܬ ܦܐܬܬ̈ܐ ܠܡܥܠܢܘܬܐ.', 'importnotext' => 'ܣܦܝܩܐ ܐܘ ܠܝܬ ܒܗ ܟܬܒܬܐ', 'importsuccess' => 'ܡܥܠܢܘܬܐ ܓܡܪܬ', 'import-noarticle' => 'ܠܝܬ ܦܐܬܬ̈ܐ ܠܡܥܠܢܘܬܐ!', 'import-upload' => 'ܐܣܩ ܓܠܝܬ̈ܐ ܕ XML', # Import log 'importlogpage' => 'ܣܓܠܐ ܕܡܥܠܢܘܬܐ', 'import-logentry-upload-detail' => '$1 {{PLURAL:$1|ܬܢܝܬܐ |ܬܢܝܬ̈ܐ}}', 'import-logentry-interwiki-detail' => '$1 {{PLURAL:$1|ܬܢܝܬܐ |ܬܢܝܬ̈ܐ}} ܡܢ $2', # Tooltip help for the actions 'tooltip-pt-userpage' => 'ܦܐܬܐ ܕܡܦܠܚܢܐ ܕܝܠܟ', 'tooltip-pt-mytalk' => 'ܦܐܬܐ ܕܡܡܠܠܐ ܕܝܠܟ', 'tooltip-pt-preferences' => 'Your preferences', 'tooltip-pt-watchlist' => 'ܡܟܬܒܢܘܬܐ ܕܦܐܬܬ̈ܐ ܕܬܪܗܝ ܐܢܬ ܫܘܚܠܦ̈ܐ ܕܬܗܘܐ ܒܗܘܢ', 'tooltip-pt-mycontris' => 'ܡܟܬܒܢܘܬܐ ܕܫܘܬܦܘܝܬ̈ܟ', 'tooltip-pt-login' => 'ܢܠܒܒ ܠܟ ܕܣܓܠ ܐܢܬ ܥܠܠܐ ܕܝܠܟ، ܐܠܐ ܗܢܐ ܠܐ ܐܝܬܝܗܝ ܐܠܨܝܐ', 'tooltip-pt-logout' => 'ܦܠܛܐ', 'tooltip-ca-talk' => 'ܡܡܠܠܐ ܥܠ ܚܒܝܫܬܐ ܕܦܐܬܐ', 'tooltip-ca-addsection' => 'ܫܪܝ ܡܢܬܐ ܚܕܬܐ', 'tooltip-ca-viewsource' => 'ܗܢܐ ܦܐܬܐ ܢܛܪܬܐ ܐܝܬܝܗܝ. ܡܨܐ ܐܢܬ ܕܬܚܙܐ ܡܒܘܥܐ ܕܝܠܗ', 'tooltip-ca-protect' => 'ܛܪ ܠܗܕܐ ܦܐܬܐ', 'tooltip-ca-delete' => 'ܫܘܦ ܦܐܬܐ ܗܕܐ', 'tooltip-ca-move' => 'ܫܢܝ ܦܐܬܐ ܗܕܐ', 'tooltip-search' => 'ܒܨܝ ܒܓܘ {{SITENAME}}', 'tooltip-search-fulltext' => 'ܒܨܝ ܒܓܘ ܦܐܬܬ̈ܐ ܥܠ ܗܢܐ ܟܬܝܒܬܐ', 'tooltip-p-logo' => 'ܦܐܬܐ ܪܝܫܝܬܐ', 'tooltip-n-mainpage' => 'ܣܥܪ ܦܐܬܐ ܪܝܫܝܬܐ', 'tooltip-n-mainpage-description' => 'ܬܪܘܩܬܐ ܕܦܐܬܐ ܪܝܫܝܬܐ', 'tooltip-n-portal' => 'ܚܕܪ ܬܪܡܝܬܐ، ܡܢܐ ܡܫܟܚ ܐܢܬ ܠܥܒܕܐ، ܐܝܟܐ ܬܚܙܝ ܟܠ ܡܐ ܕܣܢܝܩ ܐܢܬ ܠܗ', 'tooltip-n-recentchanges' => 'ܡܟܬܒܢܘܬܐ ܒܫܘܚܠܦ̈ܐ ܚܕ̈ܬܐ ܒܓܘ ܘܝܩܝ.', 'tooltip-n-randompage' => 'ܐܛܥܢ ܡܓܠܬܐ ܚܕ ܚܘܝܚܬܐ', 'tooltip-n-help' => 'ܕܘܟܐ ܠܥܘܕܪܢܐ', 'tooltip-feed-atom' => 'ܛܥܝܡܘܬܐ ܕܐܛܘܡ ܠܦܐܬܬܐ ܗܕܐ', 'tooltip-t-contributions' => 'ܡܟܬܒܢܘܬܐ ܒܫܘܬܦ̈ܐ ܕܗܢܐ ܡܦܠܚܢܐ', 'tooltip-t-emailuser' => 'ܫܕܪ ܐܓܪܬܐ ܠܗܢܐ ܡܦܠܚܢܐ', 'tooltip-t-upload' => 'ܐܣܩ ܠܦܦ̈ܐ', 'tooltip-t-specialpages' => 'ܡܟܬܒܢܘܬܐ ܒܟܠ ܦܐܬܬ̈ܐ ܕ̈ܝܠܢܝܬܐ', 'tooltip-ca-nstab-main' => 'ܚܘܝ ܦܐܬܐ ܕܚܒ̈ܝܫܬܐ', 'tooltip-ca-nstab-user' => 'ܚܘܝ ܦܐܬܐ ܕܡܦܠܚܢܐ', 'tooltip-ca-nstab-image' => 'ܚܘܝ ܦܐܬܐ ܕܠܦܦܐ', 'tooltip-ca-nstab-category' => 'ܚܘܝ ܦܐܬܐ ܕܣܕܪܐ', 'tooltip-save' => 'ܠܒܘܟ ܫܘܚܠܦܟ', 'tooltip-watch' => 'ܐܘܣܦ ܦܐܬܐ ܗܕܐ ܠܡܟܬܒܢܘܬܐ ܕܪ̈ܗܝܬܟ', # Attribution 'anonymous' => '{{PLURAL:$1|ܡܦܠܚܢܐ ܠܐ ܝܕܝܥܐ|ܡܦܠܚܢ̈ܐ ܠܐ ܝܕ̈ܝܥܐ}} ܕ {{SITENAME}}', 'siteuser' => '{{SITENAME}} ܡܦܠܚܢܐ $1', 'others' => 'ܐܚܪ̈ܢܐ', 'siteusers' => '{{SITENAME}} {{PLURAL:$2|ܡܦܠܚܢܐ|ܡܦܠܚܢ̈ܐ}} $1', 'anonusers' => '{{SITENAME}} {{PLURAL:$2|ܡܦܠܚܢܐ ܠܐ ܝܕܝܥܐ|ܡܦܠܚܢ̈ܐ ܠܐ ܝܕ̈ܝܥܐ}} $1', 'creditspage' => 'ܙܕ̈ܩܐ ܕܦܐܬܐ', # Info page 'pageinfo-title' => 'ܝܕ̈ܥܬܐ ܥܠ "$1"', 'pageinfo-header-edits' => 'ܬܫܥܝܬܐ ܕܫܘܚܠܦ̈ܐ', 'pageinfo-watchers' => 'ܡܢܝܢܐ ܕܪ̈ܗܝܐ', 'pageinfo-authors' => 'ܡܢܝܢܐ ܕܡܫܚܠܦܢ̈ܐ ܡܫܚܠܦ̈ܐ', 'pageinfo-views' => 'ܡܢܝܢܐ ܕܚܙܝܬ̈ܐ', # Patrolling 'markaspatrolleddiff' => 'ܫܘܕܥ ܐܝܟ ܟܪܝܟܬܐ', 'markaspatrolledtext' => 'ܫܘܕܥ ܦܐܬܐ ܗܕܐ ܐܝܟ ܟܪܝܟܬܐ', 'markedaspatrolled' => 'ܫܘܕܥܬ ܐܝܟ ܟܪܝܟܬܐ', # Patrol log 'patrol-log-page' => 'ܣܓܠܐ ܕܟܪܟܐ', 'log-show-hide-patrol' => '$1 ܣܓܠܐ ܕܟܪܟܐ', # Image deletion 'filedeleteerror-short' => 'ܦܘܕܐ ܒܫܝܦܐ ܕܠܦܦܐ: $1', 'filedeleteerror-long' => 'ܦܘܕ̈ܐ ܐܫܟܚܬ ܟܕ ܫܝܦܐ ܠܦܦܐ: $1', # Browsing diffs 'previousdiff' => '← ܫܘܚܠܦܐ ܕܩܕܡ', 'nextdiff' => 'ܫܘܚܠܦܐ ܕܒܬܪ →', # Media information 'thumbsize' => 'ܥܓܪܐ ܕܨܘܪܬܐ ܙܥܘܪܬܐ:', 'widthheightpage' => '$1 × $2, $3 {{PLURAL:$3|ܦܐܬܐ|ܦܐܬܬ̈ܐ}}', 'file-info' => 'ܥܓܪܐ ܕܠܦܦܐ: $1, MIME ܐܕܫܐ: $2', 'file-info-size' => '$1 × $2 ܦܩܣܠ، ܥܓܪܐ ܕܠܦܦܐ: $3، ܐܕܫܐ ܕ MIME: $4', 'file-info-size-pages' => '$1 × $2 ܦܩܣܠ, ܥܓܪܐ ܕܠܦܦܐ: $3, ܐܕܫܐ ܕ MIME: $4, $5 {{PLURAL:$5|ܦܐܬܐ|ܦܐܬܬ̈ܐ}}', 'file-nohires' => 'ܠܝܬ ܢܩܕܘܬܐ ܝܬܝܪ ܡܢ ܗܢܐ.', 'show-big-image' => 'ܢܩܕܘܬܐ ܓܡܝܪܬܐ', 'show-big-image-preview' => 'ܥܓܪܐ ܕܓܠܚܐ: $1.', 'show-big-image-size' => '$1 × $2 ܦܩܣܠ', # Special:NewFiles 'newimages' => 'ܒܝܬ ܓܠܚܐ ܕܠܦܦ̈ܐ ܚܕܬ̈ܐ', 'newimages-legend' => 'ܡܨܦܝܢܝܬܐ', 'newimages-label' => 'ܫܡܐ ܕܠܦܦܐ (ܐܘ ܡܢܬܐ ܡܢܗ)', 'showhidebots' => '($1 ܒܘܬ̈ܐ)', 'noimages' => 'ܠܝܬ ܡܕܡ ܠܚܙܝܐ.', 'ilsubmit' => 'ܒܨܝ', 'bydate' => 'ܒܣܝܩܘܡܐ', 'sp-newimages-showfrom' => 'ܚܘܝ ܠܦܦ̈ܐ ܚܕ̈ܬܐ ܕܫܪܝ ܡܢ $2, $1', # Video information, used by Language::formatTimePeriod() to format lengths in the above messages 'seconds' => '{{PLURAL:$1|$1 ܪܦܦܐ|$1 ܪ̈ܦܦܐ}}', 'minutes' => '{{PLURAL:$1|$1 ܩܛܝܢܬܐ|$1 ܩܛܝܢܬ̈ܐ}}', 'hours' => '{{PLURAL:$1|$1 ܫܥܬܐ|$1 ܫܥܬ̈ܐ}}', 'days' => '{{PLURAL:$1|$1 ܝܘܡܐ|$1 ܝܘܡܬ̈ܐ}}', 'ago' => 'ܩܕܡ $1', # Metadata 'metadata' => 'ܓܠܝܬ̈ܐ ܕܡܝܛܐ', 'metadata-expand' => 'ܚܘܝ ܐܪ̈ܝܟܬܐ ܪ̈ܘܝܚܬܐ', 'metadata-collapse' => 'ܛܫܝ ܐܪ̈ܝܟܬܐ ܪ̈ܘܝܚܬܐ', # EXIF tags 'exif-imagewidth' => 'ܦܬܘܐ', 'exif-imagelength' => 'ܐܘܪܟܐ', 'exif-xresolution' => 'ܢܩܕܘܬܐ ܐܘܦܩܝܬܐ', 'exif-yresolution' => 'ܢܩܕܘܬܐ ܥܡܘܕܝܬܐ', 'exif-imagedescription' => 'ܟܘܢܝܐ ܕܨܘܪܬܐ', 'exif-artist' => 'ܣܝܘܡܐ', 'exif-exposuretime-format' => '$1 ܪܦܦܐ ($2)', 'exif-filesource' => 'ܡܒܘܥܐ ܕܠܦܦܐ', 'exif-gpsspeedref' => 'ܚܕܝܘܬܐ ܕܩܠܘܠܘܬܐ', 'exif-gpstrack' => 'ܨܘܒܐ ܕܫܘܢܝܐ', 'exif-gpsimgdirectionref' => 'ܡܒܘܥܐ ܕܨܘܒܐ ܕܨܘܪܬܐ', 'exif-gpsimgdirection' => 'ܨܘܒܐ ܕܨܘܪܬܐ', 'exif-languagecode' => 'ܠܫܢܐ', 'exif-unknowndate' => 'ܣܝܩܘܡܐ ܠܐ ܝܕܝܥܐ', 'exif-orientation-1' => 'ܟܝܢܝܐ', 'exif-exposureprogram-1' => 'ܐܝܕܝܐ', 'exif-exposureprogram-2' => 'ܬܚܪܙܬܐ ܟܝܢܝܬܐ', 'exif-meteringmode-0' => 'ܠܐ ܝܕܝܥܐ', 'exif-meteringmode-255' => 'ܐܚܪܢܐ', 'exif-lightsource-0' => 'ܠܐ ܝܕܝܥܐ', 'exif-lightsource-9' => 'ܨܚܘܐ', 'exif-lightsource-10' => 'ܐܬܝܪܐ ܥܝܒܝܐ', 'exif-lightsource-11' => 'ܛܠܐ', 'exif-focalplaneresolutionunit-2' => 'ܐܝܢܟ̰', 'exif-customrendered-0' => 'ܥܡܠܝܬܐ ܟܝܢܝܬܐ', 'exif-gaincontrol-0' => 'ܠܐ ܡܕܡ', 'exif-contrast-0' => 'ܟܝܢܝܐ', 'exif-contrast-1' => 'ܪܟܝܟܐ', 'exif-contrast-2' => 'ܩܫܝܐ', 'exif-saturation-0' => 'ܟܝܢܝܐ', 'exif-sharpness-0' => 'ܟܝܢܝܐ', 'exif-sharpness-1' => 'ܪܟܝܟܐ', 'exif-sharpness-2' => 'ܩܫܝܐ', 'exif-subjectdistancerange-0' => 'ܠܐ ܝܕܝܥܐ', 'exif-subjectdistancerange-2' => 'ܚܝܪܐ ܩܪܝܒܐ', 'exif-subjectdistancerange-3' => 'ܚܝܪܐ ܪܚܘܩܐ', # Pseudotags used for GPSSpeedRef 'exif-gpsspeed-k' => 'ܟܝܠܘܡܬܪ ܒܫܥܬܐ', 'exif-gpsspeed-m' => 'ܡܝܠܐ ܒܫܥܬܐ', 'exif-gpsspeed-n' => 'ܩܛܪ̈ܐ', # Pseudotags used for GPSDestDistanceRef 'exif-gpsdestdistance-m' => 'ܡܝܠ̈ܐ', # Pseudotags used for GPSTrackRef, GPSImgDirectionRef and GPSDestBearingRef 'exif-gpsdirection-t' => 'ܨܘܒܐ ܬܪܝܨܐ', 'exif-gpsdirection-m' => 'ܨܘܒܐ ܡܓܢܛܝܣܝܐ', 'exif-dc-contributor' => 'ܫܘܬܦܢ̈ܐ', # 'all' in various places, this might be different for inflected languages 'watchlistall2' => 'ܟܠ', 'namespacesall' => 'ܟܠ', 'monthsall' => 'ܟܠ', 'limitall' => 'ܟܠ', # Email address confirmation 'confirmemail' => 'ܫܪܪ ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ', 'confirmemail_subject' => 'ܫܘܪܪܐ ܕܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ ܡܢ {{SITENAME}}', 'confirmemail_invalidated' => 'ܫܘܪܪܐ ܕܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ ܐܬܒܛܠ', 'invalidateemail' => 'ܒܛܘܠ ܫܘܪܪܐ ܕܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ', # Delete conflict 'recreate' => 'ܒܪܝ ܙܒܢܬܐ ܐܚܪܬܐ', # action=purge 'confirm_purge_button' => 'ܛܒ', # Multipage image navigation 'imgmultipageprev' => '← ܫܘܚܠܦܐ ܕܩܕܡ', 'imgmultipagenext' => '← ܫܘܚܠܦܐ ܕܒܬܪ', 'imgmultigo' => 'ܙܠ!', 'imgmultigoto' => 'ܙܠ ܠܦܐܬܐ $1', # Table pager 'ascending_abbrev' => 'ܡܣܩܐܝܬ', 'descending_abbrev' => 'ܡܚܬܐܝܬ', 'table_pager_next' => 'ܦܐܬܐ ܕܒܬܪ', 'table_pager_prev' => 'ܦܐܬܐ ܕܩܕܡ', 'table_pager_first' => 'ܦܐܬܐ ܩܕܡܝܬܐ', 'table_pager_last' => 'ܦܐܬܐ ܐܚܪܝܬܐ', 'table_pager_limit_label' => 'ܡܕ̈ܡܐ ܠܟܠ ܦܐܬܐ:', 'table_pager_limit_submit' => 'ܙܠ', 'table_pager_empty' => 'ܠܝܬ ܦܠܛ̈ܐ', # Auto-summaries 'autosumm-blank' => 'ܐܣܦܩ ܦܐܬܐ', 'autoredircomment' => 'ܦܐܬܐ ܨܝܒܬ ܠ [[$1]]', 'autosumm-new' => "ܒܪܐ ܦܐܬܐ ܥܡ '$1'", # Watchlist editor 'watchlistedit-normal-title' => 'ܫܚܠܦ ܪ̈ܗܝܬܐ', 'watchlistedit-normal-legend' => 'ܠܚܝ ܟܘܢܝ̈ܐ ܡܢ ܪ̈ܗܝܬܟ', 'watchlistedit-normal-explain' => 'ܟܘܢܝ̈ܐ ܒܪ̈ܗܝܬܟ ܡܬܚܘܝܢ ܠܬܚܬ. ܠܠܚܝܐ ܕܟܘܢܝܐ, ܫܘܕܥ ܥܠ ܣܢܕܘܩܐ ܕܕܦܢܗ, ܘܕܘܫ "{{int:Watchlistedit-normal-submit}}". ܡܨܬ ܕ[[Special:EditWatchlist/raw|ܬܫܚܠܦܬ ܪ̈ܗܝܬܐ ܦܛܝܪ̈ܬܐ]].', 'watchlistedit-normal-submit' => 'ܠܚܝ ܟܘܢܝܐ', 'watchlistedit-normal-done' => '{{PLURAL:$1|ܚܕ ܟܘܢܝܐ ܐܬܠܚܝ|$1 ܟܘܢܝ̈ܐ ܐܬܠܚܘܢ}} ܡܢ ܪ̈ܗܝܬܟ:', 'watchlistedit-raw-title' => 'ܫܚܠܦ ܪ̈ܗܝܬܐ ܦܛܝܪ̈ܬܐ', 'watchlistedit-raw-legend' => 'ܫܚܠܦ ܪ̈ܗܝܬܐ ܦܛܝܪ̈ܬܐ', 'watchlistedit-raw-titles' => 'ܟܘܢܝ̈ܐ:', 'watchlistedit-raw-submit' => 'ܚܕܬ ܪ̈ܗܝܬܐ', # Watchlist editing tools 'watchlisttools-view' => 'ܚܘܝ ܫܘܚܠܦ̈ܐ ܕ̈ܡܝܐ', 'watchlisttools-edit' => 'ܚܙܝ ܘܫܚܠܦ ܪ̈ܗܝܬܐ', 'watchlisttools-raw' => 'ܫܚܠܦ ܪ̈ܗܝܬܐ ܦܛܝܪ̈ܬܐ', # Special:Version 'version' => 'ܨܚܚܐ', 'version-specialpages' => 'ܦܐܬܬ̈ܐ ܕ̈ܝܠܢܝܬܐ', 'version-other' => 'ܐܚܪܢܐ', 'version-version' => '(ܨܚܚܐ $1)', 'version-poweredby-others' => 'ܐܚܪ̈ܢܐ', 'version-software-version' => 'ܨܚܚܐ', # Special:FilePath 'filepath' => 'ܫܒܝܠܐ ܕܠܦܦܐ', 'filepath-page' => 'ܠܦܦܐ', 'filepath-submit' => 'ܙܠ', # Special:FileDuplicateSearch 'fileduplicatesearch' => 'ܒܨܝ ܥܠ ܠܦܦ̈ܐ ܥܦܝܦ̈ܐ', 'fileduplicatesearch-legend' => 'ܒܨܝܐ ܥܠ ܥܘܦܦܐ', 'fileduplicatesearch-filename' => 'ܫܡܐ ܕܠܦܦܐ:', 'fileduplicatesearch-submit' => 'ܒܨܝ', 'fileduplicatesearch-info' => '$1 × $2 ܦܩܣܠ<br /> ܥܓܪܐ ܕܠܦܦܐ: $3<br /> ܐܕܫܐ ܕ MIME: $4', # Special:SpecialPages 'specialpages' => 'ܦܐܬܬ̈ܐ ܕ̈ܝܠܢܝܬܐ', 'specialpages-note' => '---- * ܦܐܬܬ̈ܐ ܕ̈ܝܠܢܝܬܐ ܥܝܕ̈ܝܬܐ. * <span class="mw-specialpagerestricted">ܦܐܬܬ̈ܐ ܕ̈ܝܠܢܝܬܐ ܕܩܝܘܡ̈ܐ ܒܠܚܘܕ.</span>', 'specialpages-group-maintenance' => 'ܬܫܪܪ̈ܐ ܕܚܕܬܘܬܐ', 'specialpages-group-other' => 'ܦܐܬܬ̈ܐ ܕ̈ܝܠܢܝܬܐ ܐܚܪ̈ܢܝܬܐ', 'specialpages-group-login' => 'ܥܘܠ / ܒܪܝ ܚܘܫܒܢܐ', 'specialpages-group-changes' => 'ܫܘܚܠܦ̈ܐ ܚܕ̈ܬܐ ܘܣܓܠ̈ܐ', 'specialpages-group-media' => 'ܬܫܪܪ̈ܐ ܕܡܝܕܝܐ ܘܐܣܩܬ̈ܐ', 'specialpages-group-users' => 'ܡܦܠܚܢ̈ܐ ܘܙܕ̈ܩܐ', 'specialpages-group-highuse' => 'ܦܐܬܬ̈ܐ ܕܡܬܚܫܚܢܘܬܐ ܥܠܝܬܐ', 'specialpages-group-pages' => 'ܡܟܬܒܘܬ̈ܐ ܕܦܐܬܬ̈ܐ', 'specialpages-group-pagetools' => 'ܡܐܢ̈ܐ ܕܦܐܬܐ', 'specialpages-group-wiki' => 'ܓܠܝܬ̈ܐ ܘܡܐܢ̈ܐ', 'specialpages-group-redirects' => 'ܨܘܝܒܐ ܕܦܐܬܐ ܕܝܠܢܝܬܐ', # Special:BlankPage 'blankpage' => 'ܦܐܬܐ ܣܦܝܩܬܐ', # Special:Tags 'tags' => 'ܚܬ̈ܡܐ ܕܫܘܚܠܦܐ ܬܪܝܨܐ', 'tag-filter' => 'ܡܨܦܝܢܝܬܐ ܕ[[Special:Tags|ܪܘܫܡܐ]]:', 'tag-filter-submit' => 'ܡܨܦܝܢܝܬܐ', 'tags-title' => 'ܪ̈ܘܫܡܐ', 'tags-intro' => 'ܦܐܬܐ ܗܕܐ ܬܓܠܚ ܪ̈ܘܫܡܐ ܕܬܚܪܙܬܐ ܪܒܬ ܫܘܕܥ ܫܘܚܠܦܐ ܒܗ، ܘܣܘܟܠܝܗܝܢ.', 'tags-tag' => 'ܫܡܐ ܕܪܘܫܡܐ', 'tags-display-header' => 'ܡܬܓܠܝܢܘܬܐ ܒܡܟܬܒܘܬ̈ܐ ܕܫܘܚܠܦܐ', 'tags-description-header' => 'ܫܘܡܗܐ ܓܡܝܪܐ ܕܣܘܟܠܐ', 'tags-hitcount-header' => 'ܫܘܚܠܦ̈ܐ ܪ̈ܫܝܡܐ', 'tags-edit' => 'ܫܚܠܦ', 'tags-hitcount' => '$1 {{PLURAL:$1|ܫܘܚܠܦܐ|ܫܘܚܠܦ̈ܐ}}', # Special:ComparePages 'comparepages' => 'ܦܚܘܡ ܒܝܢܝ ܦܐܬܬ̈ܐ', 'compare-selector' => 'ܦܚܘܡ ܒܝܢܝ ܬܢܝܬ̈ܐ ܕܦܐܬܬ̈ܐ', 'compare-page1' => 'ܦܐܬܐ 1', 'compare-page2' => 'ܦܐܬܐ 2', 'compare-rev1' => 'ܬܢܝܬܐ 1', 'compare-rev2' => 'ܬܢܝܬܐ 2', 'compare-submit' => 'ܦܚܘܡ', # HTML forms 'htmlform-submit' => 'ܫܕܪ', 'htmlform-reset' => 'ܠܐ ܬܥܒܕ ܫܘܚܠܦ̈ܐ', 'htmlform-selectorother-other' => 'ܐܚܪܢܐ', # New logging system 'logentry-delete-delete' => '$1 ܫܦ ܦܐܬܐ ܕ $3', 'logentry-move-move' => '$1 ܫܢܐ ܦܐܬܐ ܕ $3 ܠ $4', 'logentry-move-move-noredirect' => '$1 ܫܢܐ ܦܐܬܐ ܕ $3 ܠ $4 ܕܠܐ ܫܒܩܐ ܦܐܬܐ ܕܨܘܝܒܐ', 'logentry-move-move_redir' => '$1 ܫܢܐ ܦܐܬܐ ܕ $3 ܠ $4 ܕܐܝܬܘܗܝ ܦܐܬܐ ܕܨܘܝܒܐ', 'logentry-move-move_redir-noredirect' => '$1 ܫܢܐ ܦܐܬܐ ܕ $3 ܠ $4 ܕܐܝܬܘܗܝ ܦܐܬܐ ܕܨܘܝܒܐ ܘܕܠܐ ܫܒܩܐ ܦܐܬܐ ܕܨܘܝܒܐ', 'logentry-newusers-newusers' => 'ܚܘܫܒܢܐ ܕܡܦܠܚܢܐ $1 ܐܬܒܪܐ', 'logentry-newusers-create' => 'ܚܘܫܒܢܐ ܕܡܦܠܚܢܐ $1 ܐܬܒܪܐ', 'logentry-newusers-create2' => 'ܚܘܫܒܢܐ ܕܡܦܠܚܢܐ $3 ܐܬܒܪܐ ܒܝܕ $1', 'logentry-newusers-autocreate' => 'ܚܘܫܒܢܐ $1 ܐܬܒܪܝ ܝܬܐܝܬ', 'newuserlog-byemail' => 'ܡܠܬܐ ܕܥܠܠܐ ܐܫܬܕܪܬ ܒܝܕ ܒܝܠܕܪܐ ܐܠܩܛܪܘܢܝܐ', # Feedback 'feedback-subject' => 'ܡܠܘܐܐ:', 'feedback-message' => 'ܐܓܪܬܐ:', 'feedback-cancel' => 'ܒܛܘܠ', );
kimberli/5327A-notebook
languages/messages/MessagesArc.php
PHP
gpl-2.0
97,389
/* * This file is part of the CMaNGOS Project. See AUTHORS file for Copyright information * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #include "Common.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Opcodes.h" #include "Log.h" #include "ObjectMgr.h" #include "Player.h" #include "Item.h" #include "UpdateData.h" #include "Chat.h" void WorldSession::HandleSplitItemOpcode(WorldPacket& recv_data) { // DEBUG_LOG("WORLD: CMSG_SPLIT_ITEM"); uint8 srcbag, srcslot, dstbag, dstslot; uint32 count; recv_data >> srcbag >> srcslot >> dstbag >> dstslot >> count; // DEBUG_LOG("STORAGE: receive srcbag = %u, srcslot = %u, dstbag = %u, dstslot = %u, count = %u", srcbag, srcslot, dstbag, dstslot, count); uint16 src = ((srcbag << 8) | srcslot); uint16 dst = ((dstbag << 8) | dstslot); if (src == dst) return; if (count == 0) return; // check count - if zero it's fake packet if (!_player->IsValidPos(srcbag, srcslot, true)) { _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (!_player->IsValidPos(dstbag, dstslot, false)) // can be autostore pos { _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr); return; } _player->SplitItem(src, dst, count); } void WorldSession::HandleSwapInvItemOpcode(WorldPacket& recv_data) { // DEBUG_LOG("WORLD: CMSG_SWAP_INV_ITEM"); uint8 srcslot, dstslot; recv_data >> dstslot >> srcslot; // DEBUG_LOG("STORAGE: receive srcslot = %u, dstslot = %u", srcslot, dstslot); // prevent attempt swap same item to current position generated by client at special cheating sequence if (srcslot == dstslot) return; if (!_player->IsValidPos(INVENTORY_SLOT_BAG_0, srcslot, true)) { _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (!_player->IsValidPos(INVENTORY_SLOT_BAG_0, dstslot, true)) { _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr); return; } uint16 src = ((INVENTORY_SLOT_BAG_0 << 8) | srcslot); uint16 dst = ((INVENTORY_SLOT_BAG_0 << 8) | dstslot); _player->SwapItem(src, dst); } void WorldSession::HandleAutoEquipItemSlotOpcode(WorldPacket& recv_data) { ObjectGuid itemGuid; uint8 dstslot; recv_data >> itemGuid >> dstslot; // cheating attempt, client should never send opcode in that case if (!Player::IsEquipmentPos(INVENTORY_SLOT_BAG_0, dstslot)) return; Item* item = _player->GetItemByGuid(itemGuid); uint16 dstpos = dstslot | (INVENTORY_SLOT_BAG_0 << 8); if (!item || item->GetPos() == dstpos) return; _player->SwapItem(item->GetPos(), dstpos); } void WorldSession::HandleSwapItem(WorldPacket& recv_data) { // DEBUG_LOG("WORLD: CMSG_SWAP_ITEM"); uint8 dstbag, dstslot, srcbag, srcslot; recv_data >> dstbag >> dstslot >> srcbag >> srcslot ; // DEBUG_LOG("STORAGE: receive srcbag = %u, srcslot = %u, dstbag = %u, dstslot = %u", srcbag, srcslot, dstbag, dstslot); uint16 src = ((srcbag << 8) | srcslot); uint16 dst = ((dstbag << 8) | dstslot); // prevent attempt swap same item to current position generated by client at special cheating sequence if (src == dst) return; if (!_player->IsValidPos(srcbag, srcslot, true)) { _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } if (!_player->IsValidPos(dstbag, dstslot, true)) { _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr); return; } _player->SwapItem(src, dst); } void WorldSession::HandleAutoEquipItemOpcode(WorldPacket& recv_data) { // DEBUG_LOG("WORLD: CMSG_AUTOEQUIP_ITEM"); uint8 srcbag, srcslot; recv_data >> srcbag >> srcslot; // DEBUG_LOG("STORAGE: receive srcbag = %u, srcslot = %u", srcbag, srcslot); Item* pSrcItem = _player->GetItemByPos(srcbag, srcslot); if (!pSrcItem) return; // only at cheat uint16 dest; InventoryResult msg = _player->CanEquipItem(NULL_SLOT, dest, pSrcItem, !pSrcItem->IsBag()); if (msg != EQUIP_ERR_OK) { _player->SendEquipError(msg, pSrcItem, nullptr); return; } uint16 src = pSrcItem->GetPos(); if (dest == src) // prevent equip in same slot, only at cheat return; Item* pDstItem = _player->GetItemByPos(dest); if (!pDstItem) // empty slot, simple case { _player->RemoveItem(srcbag, srcslot, true); _player->EquipItem(dest, pSrcItem, true); _player->AutoUnequipOffhandIfNeed(); } else // have currently equipped item, not simple case { uint8 dstbag = pDstItem->GetBagSlot(); uint8 dstslot = pDstItem->GetSlot(); msg = _player->CanUnequipItem(dest, !pSrcItem->IsBag()); if (msg != EQUIP_ERR_OK) { _player->SendEquipError(msg, pDstItem, nullptr); return; } // check dest->src move possibility ItemPosCountVec sSrc; uint16 eSrc = 0; if (_player->IsInventoryPos(src)) { msg = _player->CanStoreItem(srcbag, srcslot, sSrc, pDstItem, true); if (msg != EQUIP_ERR_OK) msg = _player->CanStoreItem(srcbag, NULL_SLOT, sSrc, pDstItem, true); if (msg != EQUIP_ERR_OK) msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, sSrc, pDstItem, true); } else if (_player->IsBankPos(src)) { msg = _player->CanBankItem(srcbag, srcslot, sSrc, pDstItem, true); if (msg != EQUIP_ERR_OK) msg = _player->CanBankItem(srcbag, NULL_SLOT, sSrc, pDstItem, true); if (msg != EQUIP_ERR_OK) msg = _player->CanBankItem(NULL_BAG, NULL_SLOT, sSrc, pDstItem, true); } else if (_player->IsEquipmentPos(src)) { msg = _player->CanEquipItem(srcslot, eSrc, pDstItem, true); if (msg == EQUIP_ERR_OK) msg = _player->CanUnequipItem(eSrc, true); } if (msg != EQUIP_ERR_OK) { _player->SendEquipError(msg, pDstItem, pSrcItem); return; } // now do moves, remove... _player->RemoveItem(dstbag, dstslot, false); _player->RemoveItem(srcbag, srcslot, false); // add to dest _player->EquipItem(dest, pSrcItem, true); // add to src if (_player->IsInventoryPos(src)) _player->StoreItem(sSrc, pDstItem, true); else if (_player->IsBankPos(src)) _player->BankItem(sSrc, pDstItem, true); else if (_player->IsEquipmentPos(src)) _player->EquipItem(eSrc, pDstItem, true); _player->AutoUnequipOffhandIfNeed(); } } void WorldSession::HandleDestroyItemOpcode(WorldPacket& recv_data) { // DEBUG_LOG("WORLD: CMSG_DESTROYITEM"); uint8 bag, slot, count, data1, data2, data3; recv_data >> bag >> slot >> count >> data1 >> data2 >> data3; // DEBUG_LOG("STORAGE: receive bag = %u, slot = %u, count = %u", bag, slot, count); uint16 pos = (bag << 8) | slot; // prevent drop unequipable items (in combat, for example) and non-empty bags if (_player->IsEquipmentPos(pos) || _player->IsBagPos(pos)) { InventoryResult msg = _player->CanUnequipItem(pos, false); if (msg != EQUIP_ERR_OK) { _player->SendEquipError(msg, _player->GetItemByPos(pos), nullptr); return; } } Item* pItem = _player->GetItemByPos(bag, slot); if (!pItem) { _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); return; } // checked at client side and not have server side appropriate error output if (pItem->GetProto()->Flags & ITEM_FLAG_INDESTRUCTIBLE) { _player->SendEquipError(EQUIP_ERR_CANT_DROP_SOULBOUND, nullptr, nullptr); return; } if (count) { uint32 i_count = count; _player->DestroyItemCount(pItem, i_count, true); } else _player->DestroyItem(bag, slot, true); } void WorldSession::HandleReadItemOpcode(WorldPacket& recv_data) { // DEBUG_LOG("WORLD: Received opcode CMSG_READ_ITEM"); uint8 bag, slot; recv_data >> bag >> slot; // sLog.outDetail("STORAGE: Read bag = %u, slot = %u", bag, slot); Item* pItem = _player->GetItemByPos(bag, slot); if (pItem && pItem->GetProto()->PageText) { WorldPacket data; InventoryResult msg = _player->CanUseItem(pItem); if (msg == EQUIP_ERR_OK) { data.Initialize(SMSG_READ_ITEM_OK, 8); DETAIL_LOG("STORAGE: Item page sent"); } else { data.Initialize(SMSG_READ_ITEM_FAILED, 8); DETAIL_LOG("STORAGE: Unable to read item"); _player->SendEquipError(msg, pItem, nullptr); } data << pItem->GetObjectGuid(); SendPacket(&data); } else _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, nullptr, nullptr); } void WorldSession::HandlePageQuerySkippedOpcode(WorldPacket& recv_data) { DEBUG_LOG("WORLD: Received opcode CMSG_PAGE_TEXT_QUERY"); uint32 itemid; ObjectGuid guid; recv_data >> itemid >> guid; DETAIL_LOG("Packet Info: itemid: %u guid: %s", itemid, guid.GetString().c_str()); } void WorldSession::HandleSellItemOpcode(WorldPacket& recv_data) { DEBUG_LOG("WORLD: Received opcode CMSG_SELL_ITEM"); ObjectGuid vendorGuid; ObjectGuid itemGuid; uint32 count; recv_data >> vendorGuid; recv_data >> itemGuid; recv_data >> count; if (!itemGuid) return; Creature* pCreature = GetPlayer()->GetNPCIfCanInteractWith(vendorGuid, UNIT_NPC_FLAG_VENDOR); if (!pCreature) { DEBUG_LOG("WORLD: HandleSellItemOpcode - %s not found or you can't interact with him.", vendorGuid.GetString().c_str()); _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, itemGuid, 0); return; } Item* pItem = _player->GetItemByGuid(itemGuid); if (pItem) { // prevent sell not owner item if (_player->GetObjectGuid() != pItem->GetOwnerGuid()) { _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, pCreature, itemGuid, 0); return; } // prevent sell non empty bag by drag-and-drop at vendor's item list if (pItem->IsBag() && !((Bag*)pItem)->IsEmpty()) { _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, pCreature, itemGuid, 0); return; } // prevent sell currently looted item if (_player->GetLootGuid() == pItem->GetObjectGuid()) { _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, pCreature, itemGuid, 0); return; } // special case at auto sell (sell all) if (count == 0) { count = pItem->GetCount(); } else { // prevent sell more items that exist in stack (possible only not from client) if (count > pItem->GetCount()) { _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, pCreature, itemGuid, 0); return; } } ItemPrototype const* pProto = pItem->GetProto(); if (pProto) { if (pProto->SellPrice > 0) { if (count < pItem->GetCount()) // need split items { Item* pNewItem = pItem->CloneItem(count, _player); if (!pNewItem) { sLog.outError("WORLD: HandleSellItemOpcode - could not create clone of item %u; count = %u", pItem->GetEntry(), count); _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, pCreature, itemGuid, 0); return; } pItem->SetCount(pItem->GetCount() - count); _player->ItemRemovedQuestCheck(pItem->GetEntry(), count); if (_player->IsInWorld()) pItem->SendCreateUpdateToPlayer(_player); pItem->SetState(ITEM_CHANGED, _player); _player->AddItemToBuyBackSlot(pNewItem); if (_player->IsInWorld()) pNewItem->SendCreateUpdateToPlayer(_player); } else { _player->ItemRemovedQuestCheck(pItem->GetEntry(), pItem->GetCount()); _player->RemoveItem(pItem->GetBagSlot(), pItem->GetSlot(), true); pItem->RemoveFromUpdateQueueOf(_player); _player->AddItemToBuyBackSlot(pItem); } uint64 money = pProto->SellPrice * count; _player->ModifyMoney(money); _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_MONEY_FROM_VENDORS, money); } else _player->SendSellError(SELL_ERR_CANT_SELL_ITEM, pCreature, itemGuid, 0); return; } } _player->SendSellError(SELL_ERR_CANT_FIND_ITEM, pCreature, itemGuid, 0); return; } void WorldSession::HandleBuybackItem(WorldPacket& recv_data) { DEBUG_LOG("WORLD: Received opcode CMSG_BUYBACK_ITEM"); ObjectGuid vendorGuid; uint32 slot; recv_data >> vendorGuid >> slot; Creature* pCreature = GetPlayer()->GetNPCIfCanInteractWith(vendorGuid, UNIT_NPC_FLAG_VENDOR); if (!pCreature) { DEBUG_LOG("WORLD: HandleBuybackItem - %s not found or you can't interact with him.", vendorGuid.GetString().c_str()); _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, ObjectGuid(), 0); return; } Item* pItem = _player->GetItemFromBuyBackSlot(slot); if (pItem) { uint64 price = _player->GetUInt32Value(PLAYER_FIELD_BUYBACK_PRICE_1 + slot - BUYBACK_SLOT_START); if (_player->GetMoney() < price) { _player->SendBuyError(BUY_ERR_NOT_ENOUGHT_MONEY, pCreature, pItem->GetEntry(), 0); return; } ItemPosCountVec dest; InventoryResult msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, dest, pItem, false); if (msg == EQUIP_ERR_OK) { _player->ModifyMoney(-(int64)price); _player->RemoveItemFromBuyBackSlot(slot, false); _player->ItemAddedQuestCheck(pItem->GetEntry(), pItem->GetCount()); _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_RECEIVE_EPIC_ITEM, pItem->GetEntry(), pItem->GetCount()); _player->StoreItem(dest, pItem, true); } else _player->SendEquipError(msg, pItem, nullptr); return; } else _player->SendBuyError(BUY_ERR_CANT_FIND_ITEM, pCreature, 0, 0); } void WorldSession::HandleBuyItemOpcode(WorldPacket& recv_data) { ObjectGuid vendorGuid, bagGuid; uint32 item, slot, count; uint8 type, bagSlot; recv_data >> vendorGuid >> type >> item >> slot >> count >> bagGuid >> bagSlot; DEBUG_LOG("WORLD: Received opcode CMSG_BUY_ITEM, vendorguid: %s, type: %u, item: %u, slot: %u, count: %u, bagGuid: %s, bagSlog: %u", vendorGuid.GetString().c_str(), type, item, slot, count, bagGuid.GetString().c_str(), bagSlot); // client side expected counting from 1, and we send to client vendorslot+1 already if (slot > 0) --slot; else return; // cheating switch (type) { case VENDOR_ITEM_TYPE_NONE: break; case VENDOR_ITEM_TYPE_ITEM: { uint8 bag = NULL_BAG; // init for case invalid bagGUID // find bag slot by bag guid if (bagGuid == _player->GetObjectGuid()) bag = INVENTORY_SLOT_BAG_0; else { for (int i = INVENTORY_SLOT_BAG_START; i < INVENTORY_SLOT_BAG_END; ++i) { if (Bag* pBag = (Bag*)_player->GetItemByPos(INVENTORY_SLOT_BAG_0, i)) { if (bagGuid == pBag->GetObjectGuid()) { bag = i; break; } } } } GetPlayer()->BuyItemFromVendorSlot(vendorGuid, slot, item, count, bag, bagSlot); break; } case VENDOR_ITEM_TYPE_CURRENCY: { GetPlayer()->BuyCurrencyFromVendorSlot(vendorGuid, slot, item, count); break; } } } void WorldSession::HandleListInventoryOpcode(WorldPacket& recv_data) { ObjectGuid guid; recv_data >> guid; if (!GetPlayer()->isAlive()) return; DEBUG_LOG("WORLD: Received opcode CMSG_LIST_INVENTORY"); SendListInventory(guid); } void WorldSession::SendListInventory(ObjectGuid vendorguid) { DEBUG_LOG("WORLD: Sent SMSG_LIST_INVENTORY"); Creature* pCreature = GetPlayer()->GetNPCIfCanInteractWith(vendorguid, UNIT_NPC_FLAG_VENDOR); if (!pCreature) { DEBUG_LOG("WORLD: SendListInventory - %s not found or you can't interact with him.", vendorguid.GetString().c_str()); _player->SendSellError(SELL_ERR_CANT_FIND_VENDOR, nullptr, ObjectGuid(), 0); return; } // Stop the npc if moving pCreature->StopMoving(); VendorItemData const* vItems = pCreature->GetVendorItems(); VendorItemData const* tItems = pCreature->GetVendorTemplateItems(); uint8 customitems = vItems ? vItems->GetItemCount() : 0; uint8 numitems = customitems + (tItems ? tItems->GetItemCount() : 0); std::vector<bool> bitFlags; float discountMod = _player->GetReputationPriceDiscount(pCreature); uint8 count = 0; ByteBuffer buffer; for (uint8 vendorslot = 0; vendorslot < numitems; ++vendorslot) { VendorItem const* crItem = vendorslot < customitems ? vItems->GetItem(vendorslot) : tItems->GetItem(vendorslot - customitems); if (crItem) { uint32 price, displayId, buyCount, maxDurability; int32 maxCount; if (crItem->type == VENDOR_ITEM_TYPE_ITEM) { ItemPrototype const * pProto = ObjectMgr::GetItemPrototype(crItem->item); if (!pProto) continue; if (!_player->isGameMaster()) { // class wrong item skip only for bindable case if ((pProto->AllowableClass & _player->getClassMask()) == 0 && pProto->Bonding == BIND_WHEN_PICKED_UP) continue; // race wrong item skip always if ((pProto->Flags2 & ITEM_FLAG2_HORDE_ONLY) && _player->GetTeam() != HORDE) continue; if ((pProto->Flags2 & ITEM_FLAG2_ALLIANCE_ONLY) && _player->GetTeam() != ALLIANCE) continue; if ((pProto->AllowableRace & _player->getRaceMask()) == 0) continue; if (crItem->conditionId && !sObjectMgr.IsPlayerMeetToCondition(crItem->conditionId, _player, pCreature->GetMap(), pCreature, CONDITION_FROM_VENDOR)) continue; } // possible item coverting for BoA case if (pProto->Flags & ITEM_FLAG_BOA) { // convert if can use and then buy if (pProto->RequiredReputationFaction && uint32(_player->GetReputationRank(pProto->RequiredReputationFaction)) >= pProto->RequiredReputationRank) { // checked at convert data loading as existed if (uint32 newItemId = sObjectMgr.GetItemConvert(crItem->item, _player->getRaceMask())) pProto = ObjectMgr::GetItemPrototype(newItemId); } } ++count; if (count >= MAX_VENDOR_ITEMS) break; // reputation discount maxDurability = pProto->MaxDurability; price = (crItem->ExtendedCost == 0 || pProto->Flags2 & ITEM_FLAG2_EXT_COST_REQUIRES_GOLD) ? uint32(floor(pProto->BuyPrice * discountMod)) : 0; displayId = pProto->DisplayInfoID; maxCount = crItem->maxcount <= 0 ? -1 : int32(pCreature->GetVendorItemCurrentCount(crItem)); buyCount = pProto->BuyCount; } else if (crItem->type == VENDOR_ITEM_TYPE_CURRENCY) { CurrencyTypesEntry const * pCurrency = sCurrencyTypesStore.LookupEntry(crItem->item); if (!pCurrency) continue; if (pCurrency->Category == CURRENCY_CATEGORY_META) continue; ++count; if (count >= MAX_VENDOR_ITEMS) break; maxDurability = 0; price = 0; displayId = 0; maxCount = -1; buyCount = crItem->maxcount; } else continue; bitFlags.push_back(crItem->ExtendedCost == 0); bitFlags.push_back(true); // unk buffer << uint32(vendorslot + 1); // client size expected counting from 1 buffer << uint32(maxDurability); if (crItem->ExtendedCost) buffer << uint32(crItem->ExtendedCost); buffer << uint32(crItem->item); buffer << uint32(crItem->type); buffer << uint32(price); buffer << uint32(displayId); buffer << int32(maxCount); buffer << uint32(buyCount); } } WorldPacket data(SMSG_LIST_INVENTORY, (8 + 3 + 1 + 1 + numitems * 8 * 4)); data.WriteGuidMask<1, 0>(vendorguid); data.WriteBits(count, 21); data.WriteGuidMask<3, 6, 5, 2, 7>(vendorguid); for (uint32 i = 0; i < bitFlags.size(); ++i) data.WriteBit(bitFlags[i]); data.WriteGuidMask<4>(vendorguid); data.FlushBits(); data.append(buffer); data.WriteGuidBytes<5, 4, 1, 0, 6>(vendorguid); data << uint8(count == 0); data.WriteGuidBytes<2, 3, 7>(vendorguid); SendPacket(&data); } void WorldSession::HandleAutoStoreBagItemOpcode(WorldPacket& recv_data) { // DEBUG_LOG("WORLD: CMSG_AUTOSTORE_BAG_ITEM"); uint8 srcbag, srcslot, dstbag; recv_data >> srcbag >> srcslot >> dstbag; // DEBUG_LOG("STORAGE: receive srcbag = %u, srcslot = %u, dstbag = %u", srcbag, srcslot, dstbag); Item* pItem = _player->GetItemByPos(srcbag, srcslot); if (!pItem) return; if (!_player->IsValidPos(dstbag, NULL_SLOT, false)) // can be autostore pos { _player->SendEquipError(EQUIP_ERR_ITEM_DOESNT_GO_TO_SLOT, nullptr, nullptr); return; } uint16 src = pItem->GetPos(); // check unequip potability for equipped items and bank bags if (_player->IsEquipmentPos(src) || _player->IsBagPos(src)) { InventoryResult msg = _player->CanUnequipItem(src, !_player->IsBagPos(src)); if (msg != EQUIP_ERR_OK) { _player->SendEquipError(msg, pItem, nullptr); return; } } ItemPosCountVec dest; InventoryResult msg = _player->CanStoreItem(dstbag, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { _player->SendEquipError(msg, pItem, nullptr); return; } // no-op: placed in same slot if (dest.size() == 1 && dest[0].pos == src) { // just remove gray item state _player->SendEquipError(EQUIP_ERR_NONE, pItem, nullptr); return; } _player->RemoveItem(srcbag, srcslot, true); _player->StoreItem(dest, pItem, true); } bool WorldSession::CheckBanker(ObjectGuid guid) { // GM case if (guid == GetPlayer()->GetObjectGuid()) { // command case will return only if player have real access to command if (!ChatHandler(GetPlayer()).FindCommand("bank")) { DEBUG_LOG("%s attempt open bank in cheating way.", guid.GetString().c_str()); return false; } } // banker case else { if (!GetPlayer()->GetNPCIfCanInteractWith(guid, UNIT_NPC_FLAG_BANKER)) { DEBUG_LOG("Banker %s not found or you can't interact with him.", guid.GetString().c_str()); return false; } } return true; } void WorldSession::HandleBuyBankSlotOpcode(WorldPacket& recvPacket) { DEBUG_LOG("WORLD: CMSG_BUY_BANK_SLOT"); ObjectGuid guid; recvPacket >> guid; if (!CheckBanker(guid)) return; uint32 slot = _player->GetBankBagSlotCount(); // next slot ++slot; DETAIL_LOG("PLAYER: Buy bank bag slot, slot number = %u", slot); BankBagSlotPricesEntry const* slotEntry = sBankBagSlotPricesStore.LookupEntry(slot); if (!slotEntry) return; uint64 price = slotEntry->price; if (_player->GetMoney() < price) return; _player->SetBankBagSlotCount(slot); _player->ModifyMoney(-int64(price)); _player->GetAchievementMgr().UpdateAchievementCriteria(ACHIEVEMENT_CRITERIA_TYPE_BUY_BANK_SLOT); } void WorldSession::HandleAutoBankItemOpcode(WorldPacket& recvPacket) { DEBUG_LOG("WORLD: CMSG_AUTOBANK_ITEM"); uint8 srcbag, srcslot; recvPacket >> srcbag >> srcslot; DEBUG_LOG("STORAGE: receive srcbag = %u, srcslot = %u", srcbag, srcslot); Item* pItem = _player->GetItemByPos(srcbag, srcslot); if (!pItem) return; ItemPosCountVec dest; InventoryResult msg = _player->CanBankItem(NULL_BAG, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { _player->SendEquipError(msg, pItem, nullptr); return; } // no-op: placed in same slot if (dest.size() == 1 && dest[0].pos == pItem->GetPos()) { // just remove gray item state _player->SendEquipError(EQUIP_ERR_NONE, pItem, nullptr); return; } _player->RemoveItem(srcbag, srcslot, true); _player->BankItem(dest, pItem, true); } void WorldSession::HandleAutoStoreBankItemOpcode(WorldPacket& recvPacket) { DEBUG_LOG("WORLD: CMSG_AUTOSTORE_BANK_ITEM"); uint8 srcbag, srcslot; recvPacket >> srcbag >> srcslot; DEBUG_LOG("STORAGE: receive srcbag = %u, srcslot = %u", srcbag, srcslot); Item* pItem = _player->GetItemByPos(srcbag, srcslot); if (!pItem) return; if (_player->IsBankPos(srcbag, srcslot)) // moving from bank to inventory { ItemPosCountVec dest; InventoryResult msg = _player->CanStoreItem(NULL_BAG, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { _player->SendEquipError(msg, pItem, nullptr); return; } _player->RemoveItem(srcbag, srcslot, true); _player->StoreItem(dest, pItem, true); } else // moving from inventory to bank { ItemPosCountVec dest; InventoryResult msg = _player->CanBankItem(NULL_BAG, NULL_SLOT, dest, pItem, false); if (msg != EQUIP_ERR_OK) { _player->SendEquipError(msg, pItem, nullptr); return; } _player->RemoveItem(srcbag, srcslot, true); _player->BankItem(dest, pItem, true); } } void WorldSession::HandleSetAmmoOpcode(WorldPacket& recv_data) { if (!GetPlayer()->isAlive()) { GetPlayer()->SendEquipError(EQUIP_ERR_YOU_ARE_DEAD, nullptr, nullptr); return; } DEBUG_LOG("WORLD: CMSG_SET_AMMO"); uint32 item; recv_data >> item; if (!item) GetPlayer()->RemoveAmmo(); else GetPlayer()->SetAmmo(item); } void WorldSession::SendEnchantmentLog(ObjectGuid targetGuid, ObjectGuid casterGuid, uint32 itemId, uint32 enchantId) { WorldPacket data(SMSG_ENCHANTMENTLOG, (8 + 8 + 4 + 4 + 1)); // last check 2.0.10 data << targetGuid.WriteAsPacked(); data << casterGuid.WriteAsPacked(); data << uint32(itemId); data << uint32(enchantId); SendPacket(&data); } void WorldSession::SendItemEnchantTimeUpdate(ObjectGuid playerGuid, ObjectGuid itemGuid, uint32 slot, uint32 duration) { // last check 2.0.10 WorldPacket data(SMSG_ITEM_ENCHANT_TIME_UPDATE, (8 + 4 + 4 + 8)); data << ObjectGuid(itemGuid); data << uint32(slot); data << uint32(duration); data << ObjectGuid(playerGuid); SendPacket(&data); } void WorldSession::HandleWrapItemOpcode(WorldPacket& recv_data) { DEBUG_LOG("Received opcode CMSG_WRAP_ITEM"); uint8 gift_bag, gift_slot, item_bag, item_slot; // recv_data.hexlike(); recv_data >> gift_bag >> gift_slot; // paper recv_data >> item_bag >> item_slot; // item DEBUG_LOG("WRAP: receive gift_bag = %u, gift_slot = %u, item_bag = %u, item_slot = %u", gift_bag, gift_slot, item_bag, item_slot); Item* gift = _player->GetItemByPos(gift_bag, gift_slot); if (!gift) { _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, nullptr); return; } // cheating: non-wrapper wrapper (all empty wrappers are stackable) if (!(gift->GetProto()->Flags & ITEM_FLAG_WRAPPER) || gift->GetMaxStackCount() == 1) { _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, gift, nullptr); return; } Item* item = _player->GetItemByPos(item_bag, item_slot); if (!item) { _player->SendEquipError(EQUIP_ERR_ITEM_NOT_FOUND, item, nullptr); return; } if (item == gift) // not possible with packet from real client { _player->SendEquipError(EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED, item, nullptr); return; } if (item->IsEquipped()) { _player->SendEquipError(EQUIP_ERR_EQUIPPED_CANT_BE_WRAPPED, item, nullptr); return; } if (item->GetGuidValue(ITEM_FIELD_GIFTCREATOR)) // HasFlag(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED); { _player->SendEquipError(EQUIP_ERR_WRAPPED_CANT_BE_WRAPPED, item, nullptr); return; } if (item->IsBag()) { _player->SendEquipError(EQUIP_ERR_BAGS_CANT_BE_WRAPPED, item, nullptr); return; } if (item->IsSoulBound()) { _player->SendEquipError(EQUIP_ERR_BOUND_CANT_BE_WRAPPED, item, nullptr); return; } if (item->GetMaxStackCount() != 1) { _player->SendEquipError(EQUIP_ERR_STACKABLE_CANT_BE_WRAPPED, item, nullptr); return; } // maybe not correct check (it is better than nothing) if (item->GetProto()->MaxCount > 0) { _player->SendEquipError(EQUIP_ERR_UNIQUE_CANT_BE_WRAPPED, item, nullptr); return; } CharacterDatabase.BeginTransaction(); CharacterDatabase.PExecute("INSERT INTO character_gifts VALUES ('%u', '%u', '%u', '%u')", item->GetOwnerGuid().GetCounter(), item->GetGUIDLow(), item->GetEntry(), item->GetUInt32Value(ITEM_FIELD_FLAGS)); item->SetEntry(gift->GetEntry()); switch (item->GetEntry()) { case 5042: item->SetEntry(5043); break; case 5048: item->SetEntry(5044); break; case 17303: item->SetEntry(17302); break; case 17304: item->SetEntry(17305); break; case 17307: item->SetEntry(17308); break; case 21830: item->SetEntry(21831); break; } item->SetGuidValue(ITEM_FIELD_GIFTCREATOR, _player->GetObjectGuid()); item->SetUInt32Value(ITEM_FIELD_FLAGS, ITEM_DYNFLAG_WRAPPED); item->SetState(ITEM_CHANGED, _player); if (item->GetState() == ITEM_NEW) // save new item, to have alway for `character_gifts` record in `item_instance` { // after save it will be impossible to remove the item from the queue item->RemoveFromUpdateQueueOf(_player); item->SaveToDB(); // item gave inventory record unchanged and can be save standalone } CharacterDatabase.CommitTransaction(); uint32 count = 1; _player->DestroyItemCount(gift, count, true); } void WorldSession::HandleSocketOpcode(WorldPacket& recv_data) { DEBUG_LOG("WORLD: CMSG_SOCKET_GEMS"); ObjectGuid itemGuid; ObjectGuid gemGuids[MAX_GEM_SOCKETS]; recv_data >> itemGuid; if (!itemGuid.IsItem()) return; for (int i = 0; i < MAX_GEM_SOCKETS; ++i) recv_data >> gemGuids[i]; // cheat -> tried to socket same gem multiple times for (int i = 0; i < MAX_GEM_SOCKETS; ++i) { ObjectGuid gemGuid = gemGuids[i]; if (!gemGuid) continue; if (!gemGuid.IsItem()) return; for (int j = i + 1; j < MAX_GEM_SOCKETS; ++j) if (gemGuids[j] == gemGuid) return; } Item* itemTarget = _player->GetItemByGuid(itemGuid); if (!itemTarget) // missing item to socket return; ItemPrototype const* itemProto = itemTarget->GetProto(); if (!itemProto) return; // this slot is excepted when applying / removing meta gem bonus uint8 slot = itemTarget->IsEquipped() ? itemTarget->GetSlot() : uint8(NULL_SLOT); Item* Gems[MAX_GEM_SOCKETS]; for (int i = 0; i < MAX_GEM_SOCKETS; ++i) Gems[i] = gemGuids[i] ? _player->GetItemByGuid(gemGuids[i]) : nullptr; GemPropertiesEntry const* GemProps[MAX_GEM_SOCKETS]; for (int i = 0; i < MAX_GEM_SOCKETS; ++i) // get geminfo from dbc storage GemProps[i] = (Gems[i]) ? sGemPropertiesStore.LookupEntry(Gems[i]->GetProto()->GemProperties) : nullptr; for (int i = 0; i < MAX_GEM_SOCKETS; ++i) // check for hack maybe { if (!GemProps[i]) continue; // tried to put gem in socket where no socket exists (take care about prismatic sockets) if (!itemProto->Socket[i].Color) { // no prismatic socket if (!itemTarget->GetEnchantmentId(PRISMATIC_ENCHANTMENT_SLOT)) return; // not first not-colored (not normally used) socket if (i != 0 && !itemProto->Socket[i - 1].Color && (i + 1 >= MAX_GEM_SOCKETS || itemProto->Socket[i + 1].Color)) return; // ok, this is first not colored socket for item with prismatic socket } // tried to put normal gem in meta socket if (itemProto->Socket[i].Color == SOCKET_COLOR_META && GemProps[i]->color != SOCKET_COLOR_META) return; // tried to put meta gem in normal socket if (itemProto->Socket[i].Color != SOCKET_COLOR_META && GemProps[i]->color == SOCKET_COLOR_META) return; } uint32 GemEnchants[MAX_GEM_SOCKETS]; uint32 OldEnchants[MAX_GEM_SOCKETS]; for (int i = 0; i < MAX_GEM_SOCKETS; ++i) // get new and old enchantments { GemEnchants[i] = (GemProps[i]) ? GemProps[i]->spellitemenchantement : 0; OldEnchants[i] = itemTarget->GetEnchantmentId(EnchantmentSlot(SOCK_ENCHANTMENT_SLOT + i)); } // check unique-equipped conditions for (int i = 0; i < MAX_GEM_SOCKETS; ++i) { if (!Gems[i]) continue; // continue check for case when attempt add 2 similar unique equipped gems in one item. ItemPrototype const* iGemProto = Gems[i]->GetProto(); // unique item (for new and already placed bit removed enchantments if (iGemProto->Flags & ITEM_FLAG_UNIQUE_EQUIPPED) { for (int j = 0; j < MAX_GEM_SOCKETS; ++j) { if (i == j) // skip self continue; if (Gems[j]) { if (iGemProto->ItemId == Gems[j]->GetEntry()) { _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr); return; } } else if (OldEnchants[j]) { if (SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(OldEnchants[j])) { if (iGemProto->ItemId == enchantEntry->GemID) { _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr); return; } } } } } // unique limit type item int32 limit_newcount = 0; if (iGemProto->ItemLimitCategory) { if (ItemLimitCategoryEntry const* limitEntry = sItemLimitCategoryStore.LookupEntry(iGemProto->ItemLimitCategory)) { // NOTE: limitEntry->mode not checked because if item have have-limit then it applied and to equip case for (int j = 0; j < MAX_GEM_SOCKETS; ++j) { if (Gems[j]) { // destroyed gem if (OldEnchants[j]) { if (SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(OldEnchants[j])) if (ItemPrototype const* jProto = ObjectMgr::GetItemPrototype(enchantEntry->GemID)) if (iGemProto->ItemLimitCategory == jProto->ItemLimitCategory) --limit_newcount; } // new gem if (iGemProto->ItemLimitCategory == Gems[j]->GetProto()->ItemLimitCategory) ++limit_newcount; } // existing gem else if (OldEnchants[j]) { if (SpellItemEnchantmentEntry const* enchantEntry = sSpellItemEnchantmentStore.LookupEntry(OldEnchants[j])) if (ItemPrototype const* jProto = ObjectMgr::GetItemPrototype(enchantEntry->GemID)) if (iGemProto->ItemLimitCategory == jProto->ItemLimitCategory) ++limit_newcount; } } if (limit_newcount > 0 && uint32(limit_newcount) > limitEntry->maxCount) { _player->SendEquipError(EQUIP_ERR_ITEM_UNIQUE_EQUIPPABLE_SOCKETED, itemTarget, nullptr); return; } } } // for equipped item check all equipment for duplicate equipped gems if (itemTarget->IsEquipped()) { if (InventoryResult res = _player->CanEquipUniqueItem(Gems[i], slot, limit_newcount >= 0 ? limit_newcount : 0)) { _player->SendEquipError(res, itemTarget, nullptr); return; } } } bool SocketBonusActivated = itemTarget->GemsFitSockets(); // save state of socketbonus _player->ToggleMetaGemsActive(slot, false); // turn off all metagems (except for the target item) // if a meta gem is being equipped, all information has to be written to the item before testing if the conditions for the gem are met // remove ALL enchants for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + MAX_GEM_SOCKETS; ++enchant_slot) _player->ApplyEnchantment(itemTarget, EnchantmentSlot(enchant_slot), false); for (int i = 0; i < MAX_GEM_SOCKETS; ++i) { if (GemEnchants[i]) { uint32 count = 1; itemTarget->SetEnchantment(EnchantmentSlot(SOCK_ENCHANTMENT_SLOT + i), GemEnchants[i], 0, 0, _player->GetObjectGuid()); if (Item* guidItem = gemGuids[i] ? _player->GetItemByGuid(gemGuids[i]) : nullptr) _player->DestroyItemCount(guidItem, count, true); } } for (uint32 enchant_slot = SOCK_ENCHANTMENT_SLOT; enchant_slot < SOCK_ENCHANTMENT_SLOT + MAX_GEM_SOCKETS; ++enchant_slot) _player->ApplyEnchantment(itemTarget, EnchantmentSlot(enchant_slot), true); bool SocketBonusToBeActivated = itemTarget->GemsFitSockets();// current socketbonus state if (SocketBonusActivated != SocketBonusToBeActivated) // if there was a change... { _player->ApplyEnchantment(itemTarget, BONUS_ENCHANTMENT_SLOT, false); itemTarget->SetEnchantment(BONUS_ENCHANTMENT_SLOT, (SocketBonusToBeActivated ? itemTarget->GetProto()->socketBonus : 0), 0, 0, _player->GetObjectGuid()); _player->ApplyEnchantment(itemTarget, BONUS_ENCHANTMENT_SLOT, true); // it is not displayed, client has an inbuilt system to determine if the bonus is activated } _player->ToggleMetaGemsActive(slot, true); // turn on all metagems (except for target item) itemTarget->SendUpdateSockets(); } void WorldSession::HandleCancelTempEnchantmentOpcode(WorldPacket& recv_data) { DEBUG_LOG("WORLD: CMSG_CANCEL_TEMP_ENCHANTMENT"); uint32 eslot; recv_data >> eslot; // apply only to equipped item if (!Player::IsEquipmentPos(INVENTORY_SLOT_BAG_0, eslot)) return; Item* item = GetPlayer()->GetItemByPos(INVENTORY_SLOT_BAG_0, eslot); if (!item) return; if (!item->GetEnchantmentId(TEMP_ENCHANTMENT_SLOT)) return; GetPlayer()->ApplyEnchantment(item, TEMP_ENCHANTMENT_SLOT, false); item->ClearEnchantment(TEMP_ENCHANTMENT_SLOT); } void WorldSession::HandleItemRefundInfoRequest(WorldPacket& recv_data) { DEBUG_LOG("WORLD: CMSG_ITEM_REFUND_INFO_REQUEST"); ObjectGuid itemGuid; recv_data >> itemGuid; Item* item = _player->GetItemByGuid(itemGuid); if (!item) { DEBUG_LOG("Item refund: item not found!"); return; } if (!(item->GetProto()->Flags & ITEM_FLAG_REFUNDABLE)) { DEBUG_LOG("Item refund: item not refundable!"); return; } // item refund system not implemented yet } /** * Handles the packet sent by the client when requesting information about item text. * * This function is called when player clicks on item which has some flag set */ void WorldSession::HandleItemTextQuery(WorldPacket& recv_data) { ObjectGuid itemGuid; recv_data >> itemGuid; DEBUG_LOG("CMSG_ITEM_TEXT_QUERY item guid: %u", itemGuid.GetCounter()); WorldPacket data(SMSG_ITEM_TEXT_QUERY_RESPONSE, (4 + 10)); // guess size if (Item* item = _player->GetItemByGuid(itemGuid)) { data << uint8(0); // has text data << ObjectGuid(itemGuid); // item guid data << item->GetText(); } else { data << uint8(1); // no text } SendPacket(&data); } void WorldSession::SendItemDb2Reply(uint32 entry) { WorldPacket data(SMSG_DB_REPLY, 44); ItemPrototype const* proto = sObjectMgr.GetItemPrototype(entry); if (!proto) { data << uint32(-1); // entry data << uint32(DB2_REPLY_ITEM); data << uint32(time(NULL)); // hotfix date data << uint32(0); // size of next block SendPacket(&data); return; } data << uint32(entry); data << uint32(DB2_REPLY_ITEM); data << uint32(sObjectMgr.GetHotfixDate(entry, DB2_REPLY_ITEM)); ByteBuffer buff; buff << uint32(entry); buff << uint32(proto->Class); buff << uint32(proto->SubClass); buff << int32(proto->Unk0); buff << uint32(proto->Material); buff << uint32(proto->DisplayInfoID); buff << uint32(proto->InventoryType); buff << uint32(proto->Sheath); data << uint32(buff.size()); data.append(buff); SendPacket(&data); } void WorldSession::SendItemSparseDb2Reply(uint32 entry) { WorldPacket data(SMSG_DB_REPLY, 526); ItemPrototype const* proto = sObjectMgr.GetItemPrototype(entry); if (!proto) { data << uint32(-1); // entry data << uint32(DB2_REPLY_SPARSE); data << uint32(time(NULL)); // hotfix date data << uint32(0); // size of next block SendPacket(&data); return; } data << uint32(entry); data << uint32(DB2_REPLY_SPARSE); data << uint32(sObjectMgr.GetHotfixDate(entry, DB2_REPLY_SPARSE)); ByteBuffer buff; buff << uint32(entry); buff << uint32(proto->Quality); buff << uint32(proto->Flags); buff << uint32(proto->Flags2); buff << float(proto->Unknown); buff << float(proto->Unknown1); buff << uint32(proto->BuyCount); buff << int32(proto->BuyPrice); buff << uint32(proto->SellPrice); buff << uint32(proto->InventoryType); buff << int32(proto->AllowableClass); buff << int32(proto->AllowableRace); buff << uint32(proto->ItemLevel); buff << uint32(proto->RequiredLevel); buff << uint32(proto->RequiredSkill); buff << uint32(proto->RequiredSkillRank); buff << uint32(proto->RequiredSpell); buff << uint32(proto->RequiredHonorRank); buff << uint32(proto->RequiredCityRank); buff << uint32(proto->RequiredReputationFaction); buff << uint32(proto->RequiredReputationRank); buff << int32(proto->MaxCount); buff << int32(proto->Stackable); buff << uint32(proto->ContainerSlots); for (uint32 x = 0; x < MAX_ITEM_PROTO_STATS; ++x) buff << uint32(proto->ItemStat[x].ItemStatType); for (uint32 x = 0; x < MAX_ITEM_PROTO_STATS; ++x) buff << int32(proto->ItemStat[x].ItemStatValue); for (uint32 x = 0; x < MAX_ITEM_PROTO_STATS; ++x) buff << int32(proto->ItemStat[x].ItemStatType2); for (uint32 x = 0; x < MAX_ITEM_PROTO_STATS; ++x) buff << int32(proto->ItemStat[x].ItemStatValue2); buff << uint32(proto->ScalingStatDistribution); buff << uint32(proto->DamageType); buff << uint32(proto->Delay); buff << float(proto->RangedModRange); for (uint32 x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) buff << int32(proto->Spells[x].SpellId); for (uint32 x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) buff << uint32(proto->Spells[x].SpellTrigger); for (uint32 x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) buff << int32(proto->Spells[x].SpellCharges); for (uint32 x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) buff << int32(proto->Spells[x].SpellCooldown); for (uint32 x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) buff << uint32(proto->Spells[x].SpellCategory); for (uint32 x = 0; x < MAX_ITEM_PROTO_SPELLS; ++x) buff << int32(proto->Spells[x].SpellCategoryCooldown); buff << uint32(proto->Bonding); // item name std::string name = proto->Name1; buff << uint16(name.length()); if (name.length()) buff << name; for (uint32 i = 0; i < 3; ++i) // other 3 names buff << uint16(0); std::string desc = proto->Description; buff << uint16(desc.length()); if (desc.length()) buff << desc; buff << uint32(proto->PageText); buff << uint32(proto->LanguageID); buff << uint32(proto->PageMaterial); buff << uint32(proto->StartQuest); buff << uint32(proto->LockID); buff << int32(proto->Material); buff << uint32(proto->Sheath); buff << int32(proto->RandomProperty); buff << int32(proto->RandomSuffix); buff << uint32(proto->ItemSet); buff << uint32(proto->Area); buff << uint32(proto->Map); buff << uint32(proto->BagFamily); buff << uint32(proto->TotemCategory); for (uint32 x = 0; x < MAX_ITEM_PROTO_SOCKETS; ++x) buff << uint32(proto->Socket[x].Color); for (uint32 x = 0; x < MAX_ITEM_PROTO_SOCKETS; ++x) buff << uint32(proto->Socket[x].Content); buff << uint32(proto->socketBonus); buff << uint32(proto->GemProperties); buff << float(proto->ArmorDamageModifier); buff << int32(proto->Duration); buff << uint32(proto->ItemLimitCategory); buff << uint32(proto->HolidayId); buff << float(proto->StatScalingFactor); buff << uint32(proto->Unknown400_1); buff << uint32(proto->Unknown400_2); data << uint32(buff.size()); data.append(buff); SendPacket(&data); }
Ulduar/mangos-cata
src/game/ItemHandler.cpp
C++
gpl-2.0
49,724
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Serialization; using System.Text; using Gwupe.Cloud.Messaging.Elements; namespace Gwupe.Cloud.Messaging.Response { [DataContract] public class VCardRs : API.Response { public override String type { get { return "VCard-RS"; } set { } } [DataMember] public UserElement userElement; [DataMember] public TeamElement teamElement; [DataMember] public RelationshipElement relationshipElement; public PartyElement PartyElement { get { return IsTeam() ? (PartyElement)teamElement : userElement; } } public Boolean IsTeam() { return teamElement != null; } } }
gwupe/Gwupe
BlitsMeCloudClient/Messaging/Response/VCardRs.cs
C#
gpl-2.0
881
<?php /** * Register all actions and filters for the plugin * * @link http://boozang.com * @since 1.0.0 * * @package Boozang * @subpackage Boozang/includes */ /** * Register all actions and filters for the plugin. * * Maintain a list of all hooks that are registered throughout * the plugin, and register them with the WordPress API. Call the * run function to execute the list of actions and filters. * * @package Boozang * @subpackage Boozang/includes * @author Mats <mats.ljunggren@boozang.com> */ class Boozang_Loader { /** * The array of actions registered with WordPress. * * @since 1.0.0 * @access protected * @var array $actions The actions registered with WordPress to fire when the plugin loads. */ protected $actions; /** * The array of filters registered with WordPress. * * @since 1.0.0 * @access protected * @var array $filters The filters registered with WordPress to fire when the plugin loads. */ protected $filters; /** * Initialize the collections used to maintain the actions and filters. * * @since 1.0.0 */ public function __construct() { $this->actions = array(); $this->filters = array(); } /** * Add a new action to the collection to be registered with WordPress. * * @since 1.0.0 * @param string $hook The name of the WordPress action that is being registered. * @param object $component A reference to the instance of the object on which the action is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority Optional. he priority at which the function should be fired. Default is 10. * @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1. */ public function add_action( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this->actions = $this->add( $this->actions, $hook, $component, $callback, $priority, $accepted_args ); } /** * Add a new filter to the collection to be registered with WordPress. * * @since 1.0.0 * @param string $hook The name of the WordPress filter that is being registered. * @param object $component A reference to the instance of the object on which the filter is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority Optional. he priority at which the function should be fired. Default is 10. * @param int $accepted_args Optional. The number of arguments that should be passed to the $callback. Default is 1 */ public function add_filter( $hook, $component, $callback, $priority = 10, $accepted_args = 1 ) { $this->filters = $this->add( $this->filters, $hook, $component, $callback, $priority, $accepted_args ); } /** * A utility function that is used to register the actions and hooks into a single * collection. * * @since 1.0.0 * @access private * @param array $hooks The collection of hooks that is being registered (that is, actions or filters). * @param string $hook The name of the WordPress filter that is being registered. * @param object $component A reference to the instance of the object on which the filter is defined. * @param string $callback The name of the function definition on the $component. * @param int $priority The priority at which the function should be fired. * @param int $accepted_args The number of arguments that should be passed to the $callback. * @return array The collection of actions and filters registered with WordPress. */ private function add( $hooks, $hook, $component, $callback, $priority, $accepted_args ) { $hooks[] = array( 'hook' => $hook, 'component' => $component, 'callback' => $callback, 'priority' => $priority, 'accepted_args' => $accepted_args ); return $hooks; } /** * Register the filters and actions with WordPress. * * @since 1.0.0 */ public function run() { foreach ( $this->filters as $hook ) { add_filter( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } foreach ( $this->actions as $hook ) { add_action( $hook['hook'], array( $hook['component'], $hook['callback'] ), $hook['priority'], $hook['accepted_args'] ); } } }
ljunggren/boozang-wp
includes/class-boozang-loader.php
PHP
gpl-2.0
4,838
using System; namespace DLib.Model.Interfaces { public interface ICreated { DateTime created_on { get; set; } string created_by { get; set; } } }
daredev/DLib
DLib/DLib/Model/Interfaces/ICreated.cs
C#
gpl-3.0
178
using CP77.CR2W.Reflection; namespace CP77.CR2W.Types { [REDMeta] public class DropPointController : ScriptableDC { public DropPointController(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name) { } } }
Traderain/Wolven-kit
CP77.CR2W/Types/cp77/DropPointController.cs
C#
gpl-3.0
231
package com.example.sample.unit.test.SampleUnitTestsSB_154.dao.mockito; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.MatcherAssert.assertThat; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import javax.sql.DataSource; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.springframework.boot.test.mock.mockito.MockBean; import org.springframework.boot.test.mock.mockito.SpyBean; import org.springframework.test.context.junit4.SpringRunner; import com.example.sample.unit.test.SampleUnitTestsSB_154.dao.ExampleDAOImpl; @RunWith(SpringRunner.class) // since 1.4.X version we can use this annotation to run the test using SB features public class ExampleDAOImplTest { // include the query because if you change the query accidentally the test case will fail (it's a good checkpoint) final static String QUERY_FIND_ALL = " SELECT * FROM TEST "; // SpyBean instantiates the subject of test, injects the mocked dependencies and invokes the real object methods @SpyBean ExampleDAOImpl exampleDAOImpl; // mock the autowired dependency of the test subject @MockBean DataSource dataSourceMock; // mocks the connection used by the DataSource mock @MockBean Connection connectionMock; // mocks the prepared statment used by the DataSource mock @MockBean PreparedStatement preparedStatementMock = null; // mocks the result set used by the DataSource mock @MockBean ResultSet resultSetMock = null; // used to assert and catch the expected exceptions thrown by the test subject @Rule public ExpectedException thrown = ExpectedException.none(); // expect values to be returned by the dao private Map<String,String> expectedNames; // executed before each test case method -> initializes the expected values @Before public void setUp() { expectedNames = new HashMap<>(); for (int i = 1; i < 6; i++) { expectedNames.put(String.valueOf(i), "Name "+ i); } // we don't need initializes the mocked objects and their dependencies -> Spring Boot doing that :) // MockitoAnnotations.initMocks(this); } @Test public void findAllWithValidArgumentsShouldReturnAMapWithAllNames() throws Exception { // you can use in static way or do a static import // mocks the expected behavior for the DAO in this test case // important: you will test only the logic and the coverage of the test subject so mock the dependencies for that Mockito.doReturn(connectionMock).when(dataSourceMock).getConnection(); Mockito.doReturn(preparedStatementMock).when(connectionMock).prepareStatement(QUERY_FIND_ALL); Mockito.doReturn(resultSetMock).when(preparedStatementMock).executeQuery(); // mocks the ResultSet iteration and sets the expect results // you can chain the expected behavior of the iteration Mockito.doReturn(true).doReturn(true).doReturn(true).doReturn(true).doReturn(true).doReturn(false).when(resultSetMock).next(); Mockito.doReturn("1").doReturn("2").doReturn("3").doReturn("4").doReturn("5").when(resultSetMock).getString(1); Mockito.doReturn(expectedNames.get("1")) .doReturn(expectedNames.get("2")) .doReturn(expectedNames.get("3")) .doReturn(expectedNames.get("4")) .doReturn(expectedNames.get("5")) .when(resultSetMock).getString(2); // mocks the finally block Mockito.doNothing().when(resultSetMock).close(); // the close method is a void method so you don't expect any result Mockito.doNothing().when(preparedStatementMock).close(); Mockito.doNothing().when(connectionMock).close(); // invokes the test subject that uses the mocked behaviors Map<String,String> result = exampleDAOImpl.findAll(); // assert the expected results of the test case assertThat(result, notNullValue()); assertThat(result.size(), equalTo(expectedNames.size())); assertThat(result.get("1"), equalTo(expectedNames.get("1"))); // should be "Name 1" assertThat(result.get("1"), equalTo("Name 1")); // another way for the previous assertion assertThat(result.get("2"), equalTo(expectedNames.get("2"))); assertThat(result.get("3"), equalTo(expectedNames.get("3"))); assertThat(result.get("4"), equalTo(expectedNames.get("4"))); assertThat(result.get("5"), equalTo(expectedNames.get("5"))); // indicates to Mockito that verifies if the mocked objects were called Mockito.verify(dataSourceMock).getConnection(); // you should include Mockito.verify for each mocked method and object } @Test public void findAllWithValidArgumentsShouldThrowASQLExceptionWhenGetConnectionThrowsAnException() throws Exception { SQLException expectedException = new SQLException("Get Connection Exception"); // should be before the test subject method invocation // indicates that the test case expects an exception of SQLException class with this message thrown.expect(SQLException.class); thrown.expectMessage(expectedException.getMessage()); // forces to throw an exception from the service to test the controller's catch code Mockito.doThrow(expectedException).when(dataSourceMock).getConnection(); // mocks the finally block Mockito.doNothing().when(resultSetMock).close(); // the close method is a void method so you don't expect any result Mockito.doNothing().when(preparedStatementMock).close(); Mockito.doNothing().when(connectionMock).close(); // invokes the test subject that uses the mocked behaviors // don't expect any assert because the DAO method should thrown an Exception exampleDAOImpl.findAll(); Mockito.verify(dataSourceMock).getConnection(); // you should include Mockito.verify for each mocked method and object } }
Gabotto/SampleUnitTests
SampleUnitTests-SB_1.5.4/src/test/java/com/example/sample/unit/test/SampleUnitTestsSB_154/dao/mockito/ExampleDAOImplTest.java
Java
gpl-3.0
5,914
from preprocessing.tests import TestMetabolicStandardScaler from preprocessing.tests import TestMetabolicChangeScaler from preprocessing.tests import TestMetabolicSolutionScaler from preprocessing.tests import TestMostActivePathwayScaler from classifiers.tests import TestMetaboliteLevelDiseaseClassifier from classifiers.tests import TestSolutionLevelDiseaseClassifier from classifiers.tests import TestFromSolutionSolutionLevelDiseaseClassifier from classifiers.tests import TestDummyClassifier from clustering.tests import TestMetaboliteLevelDiseaseClustering from metrics.test import TestExtendedJaccard from services.tests import TestSolutionService from services.tests import TestNamingService from services.tests import TestDataReader import unittest if __name__ == "__main__": unittest.main()
MuhammedHasan/disease-diagnosis
src/tests.py
Python
gpl-3.0
812
import { resolve } from 'path'; import { loadData } from '@common/load'; import { cl /*, select*/ } from '@common/debug-select'; import { IRNGNormalTypeEnum } from '@rng/normal/in01-type'; import { globalUni, RNGKind } from '@rng/global-rng'; import { IRNGTypeEnum } from '@rng/irng-type'; //const rbinomDomainWarns = select('rbinom')("argument out of domain in '%s'"); //rbinomDomainWarns; import { rbinom } from '..'; describe('rbinom', function () { beforeAll(() => { RNGKind(IRNGTypeEnum.MERSENNE_TWISTER, IRNGNormalTypeEnum.INVERSION); cl.clear('_rbinom'); }); it('n=10, unifrom=Mersenne T, norm=Inversion, size=100, n=10, prob=0.2', () => { const uni = globalUni(); uni.init(1234); const actual = rbinom(10, 100, 0.5); expect(actual).toEqualFloatingPointBinary([47, 40, 48, 47, 48, 53, 52, 53, 53, 47]); }); it('n=10, size=Inf, prob=0.4', () => { const uni = globalUni(); uni.init(12345); const nans = rbinom(10, Infinity, 0.4); expect(nans).toEqualFloatingPointBinary(Array.from({ length: 10 }, () => NaN)); }); it('n=10, size=10.2 prob=0.4', () => { const nans = rbinom(10, 10.2, 0.4); expect(nans).toEqualFloatingPointBinary(Array.from({ length: 10 }, () => NaN)); }); it('n=10, size=10 prob=1.4', () => { const nans = rbinom(10, 10, 1.4); expect(nans).toEqualFloatingPointBinary(Array.from({ length: 10 }, () => NaN)); }); it('n=10, size=0 prob=0.4', () => { const zeros = rbinom(10, 0, 0.4); expect(zeros).toEqualFloatingPointBinary(Array.from({ length: 10 }, () => 0)); }); it('n=10, size=4 prob=1', () => { const fours = rbinom(10, 4, 1); expect(fours).toEqualFloatingPointBinary( Array.from({ length: 10 }, () => 4)); }); it('n=10, size=Number.MAX_SAFE_INTEGER * 2, prob=0.5', () => { globalUni().init(12345); const z = rbinom(10, 2147483647, 0.5); expect(z).toEqualFloatingPointBinary([ 1073728257, 1073715082, 1073725385, 1073713876, 1073744356, 1073764266, 1073752331, 1073741288, 1073727785, 1073688147 ]); }); it('n=100, size=500, prob=0.9', async () => { const uni = globalUni(); uni.init(12345); const [y] = await loadData(resolve(__dirname, 'fixture-generation', 'rbinom1.R'), /\s+/, 1); const actual = rbinom(100, 500, 0.9); expect(actual).toEqualFloatingPointBinary(y); }); it('n=100, size=500, prob=0.001', async () => { const uni = globalUni(); uni.init(12345); const [y] = await loadData(resolve(__dirname, 'fixture-generation', 'rbinom2.R'), /\s+/, 1); const actual = rbinom(100, 500, 0.001); expect(actual).toEqualFloatingPointBinary(y); }); });
jacobbogers/libRmath.js
src/lib/distributions/binomial/__test__/rbinom.test.ts
TypeScript
gpl-3.0
2,954
# coding: utf-8 from __future__ import unicode_literals import uuid from django.db import models from django.conf import settings class PricePercentageChange(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) done = models.BooleanField('已经提醒过', default=False) threshold = models.FloatField(null=True, db_index=True) increase = models.BooleanField('上涨还是下跌') owner = models.ForeignKey(settings.AUTH_USER_MODEL, verbose_name='创建者', related_name='percent_change', on_delete=models.CASCADE) period = models.IntegerField('分钟', default=60, db_index=True) class Meta: ordering = ["-threshold"] db_table = 'eosram_price_percent_change'
polyrabbit/WeCron
WeCron/eosram/models/percent.py
Python
gpl-3.0
763