code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
3
942
language
stringclasses
30 values
license
stringclasses
15 values
size
int32
3
1.05M
<?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
/*= Global -------------------------------------------------------------- */ /* sellMediaCart */ .sellMediaCart_items img { max-width: 50px; max-height: 50px; } .sellMediaCart_items th { font-weight: bold; } .sellMediaCart_items td { vertical-align: middle; } .sellMediaCart_items td.item-decrement { text-align: right; padding: 6px 0 6px 10px; } .sellMediaCart_items td.item-increment { text-align: left; margin-left: 0; } .sellMediaCart_items td.item-quantity { text-align: center; padding: 6px 0; width: 20px; } .sellMediaCart_items td.item-decrement a, .sellMediaCart_items td.item-increment a { background: #eee; border: 1px solid #ddd; padding: 0 1px; font-size: 10px; text-decoration: none; width: 14px; display: inline-block; text-align: center; } .sellMediaCart_items td.item-decrement a:hover, .sellMediaCart_items td.item-increment a:hover { background: #ddd; border-color: #ccc; } .sell-media-totals { margin: 10px 0; float: right; clear: both; width: 200px; } .sell-media-totals-table { border-top: 5px solid #eee; border-bottom: 5px solid #eee; padding: 20px 0; } .sell-media-value, .sellMediaCart_items th.item-total, .sellMediaCart_items td.item-total { text-align: right; } .sell-media-bold { font-weight: bold; } .sell-media-green { color: green; } .item-remove, .remove-all { padding-right: 10px; text-align: right; font-size: 10px; } .hide { display: none; } #sell_media_payment_gateway input { margin-right: 10px; } .sell-media-checkout-button .stripe-button-el { margin-bottom: 10px; width: 100%; text-align: center; text-decoration: none; text-transform: none; } input[type="submit"].sell-media-button, .sell-media-button, a.sell-media-button:link, #sell-media-submit { border: none; background: #555; padding: 7px 5%; display: block; width: 90%; color: #FFF; text-align: center; text-transform: none; text-decoration: none !important; text-shadow: none; font-size: 14px; border-radius: 3px; } input[type="submit"].sell-media-button:hover, .sell-media-button:hover, #sell-media-submit:hover { background: #000; color: #FFF; text-decoration: none; } .sell-media-button:disabled { background: #ccc; } /* Product Purchases */ table.sell-media-products { width: 100%; } .sell-media-products th { font-weight: bold; } .sell-media-products th, .sell-media-products td { padding: 5px; } .sell-media-products td.sell-media-product-total, .sell-media-products th.sell-media-product-subtotal, .sell-media-products td.sell-media-products-grandtotal { text-align: right; } .sell-media-products .text-center { text-align: center; } .sell-media { width: 100%; margin: 0 auto; } .has-sidebar .sell-media #content, .sell-media #content { margin: 10px 0; padding: 0; max-width: 100%; width: 100%; } .group:after { content: ""; display: table; clear: both; } .sell-media-alignleft { float: left; text-align: left; margin: 0 20px 20px 0; text-align: center; } .sell-media-alignright { float: right; text-align: right; margin: 0 0 20px 20px; text-align: center; } .sell-media-aligncenter { display: block; margin-left: auto; margin-right: auto; margin-bottom: 20px; text-align: center; } .sell-media h3 a, .sell-media-text { text-decoration: none; } .sell-media-credit { font-size: 11px; } .sell-media-dialog-box .sell-media-credit { position: absolute; bottom: 25px; left: 25px; } /*= Single -------------------------------------------------------------- */ .sell-media .sell-media-content { float: left; margin-right: 5%; width: 65%; position: relative; } .sell-media img { display: block; max-width: 100%; height: auto; } .sell-media .sell-media-content-text { margin: 10px 0; } .sell-media .sell-media-meta { clear: none; float: right; line-height: 1.5; width: 30%; } .sell-media .sell-media-postmeta { clear: both; } .sell-media ul { margin: 0 0 20px; padding: 0; list-style: none; } .sell-media li { margin: 6px 0; } .sell-media li .title { font-weight: 700; border: 0; } #sell-media-single .gallery .gallery-item a img { max-width: 95%; } .sell-media .sell-media-prev-next { text-align: center; padding: 10px 0; clear: both; } .sell-media .sell-media-prev-next .next { margin: 0 0 0 10px; } .sell-media .sell-media-prev-next .prev { margin: 0 10px 0; } .sell-media-single-button { margin-bottom: 20px; } /*= Archives -------------------------------------------------------------- */ .sell-media .sell-media-grid { position: relative; float: left; margin: 0 2% 2% 0; width: 32%; } .sell-media .sell-media-grid-container { margin: 10px 0; } .sell-media .sell-media-grid:nth-child(3n), .sell-media .end { margin-right: 0; } .sell-media .sell-media-grid:nth-child(3n+1) { clear: left; } .sell-media .sell-media-grid .item-inner { background: #000; } .sell-media .sell-media-grid .item-inner img { opacity: 1; transition: opacity .2s ease-in-out; -moz-transition: opacity .2s ease-in-out; -webkit-transition: opacity .2s ease-in-out; -webkit-backface-visibility: hidden; /* fixes chrome jump */ } .sell-media .sell-media-grid .item-overlay { display: none; } .sell-media .sell-media-grid:hover .item-overlay { display: inline; } .sell-media .sell-media-grid:hover .item-inner img { opacity: .3; } .sell-media .sell-media-grid .item-overlay a { color: #ccc; color: rgba(255,255,255,.7); -webkit-transition:color .2s ease-in; -moz-transition:color .2s ease-in; -o-transition:color .2s ease-in; transition:color .2s ease-in; text-decoration: none; } .sell-media .sell-media-grid .item-overlay a:hover { color: #fff; } .sell-media .sell-media-grid h3 { margin: 0; position: absolute; top: 82%; text-align: center; width: 100%; } .sell-media .sell-media-grid .add-to-lightbox, .sell-media .sell-media-grid .remove-lightbox, .sell-media .sell-media-grid .sell-media-text { position: absolute; top: 10px; text-transform: uppercase; font-size: 11px; font-size: .8rem; letter-spacing: 1px; } .sell-media .sell-media-grid .add-to-lightbox, .sell-media .sell-media-grid .remove-lightbox { left: 10px; padding: 10px; background-color: #469696; top: 10px; } .sell-media .sell-media-grid .sell-media-text { right: 12px; padding: 10px; background-color: #469696; top: 10px; } #sell-media-lightbox-content .sell-media-grid .sell-media-text { top: 0px !important; right: 0px !important; } #sell-media-lightbox-content .sell-media-grid .remove-lightbox { top: 0px !important; left: 0px !important; } .sell-media-pagination-container { clear: both; text-align: center } .sell-media-pagination-container .page-numbers { padding: 0 3px; } .sell-media-breadcrumbs li { display: inline; font-size: 11px; list-style-type: none; } .sell-media-breadcrumbs .raquo { margin: 0 6px; vertical-align: middle; } /*= Cart -------------------------------------------------------------- */ .sell-media-dialog-overlay { width: 100%; height: 100%; filter:alpha(opacity=50); -moz-opacity: 0.5; -khtml-opacity: 0.5; opacity: 0.5; background: #000; position: absolute; top:0; left:0; z-index: 3000; display: none; } .sell-media-dialog-box { position: absolute; top: 50px; min-height: 250px; background: #f5f5f7; box-shadow: 0 12px 30px rgba(0,0,0,0.6); border: 1px solid rgba(0,0,0,0.9); -webkit-border-radius: 6px; -moz-border-radius: 6px; -ms-border-radius: 6px; -o-border-radius: 6px; border-radius: 6px; width: 302px; box-sizing: border-box; z-index: 5000; display: none; } .sell-media-dialog-box .content { color: #666; font-family: arial; font-size: 11px; padding: 25px; } .sell-media-dialog-box figure { margin: 0; padding: 0; text-align: center; width: 100%; background: transparent; } .sell-media-dialog-box figcaption, .sell-media-dialog-box footer { font-size: 10px; margin: 5px 0; text-align: center; } .sell-media-dialog-box img { display: block; margin-left: auto; margin-right: auto; max-width: 100%; width: auto; height: auto; max-height: 167px; } .sell-media-dialog-box img.wp-post-image { float: none; } .sell-media-dialog-box section { margin: 20px 0 0; } .sell-media-dialog-box select { width: 100%; } .sell-media-dialog-box .license_desc { color: #999; } .sell-media-dialog-box .license_desc:after { clear: both; } .total-container, .button-container { clear: both; margin: 20px 0; } .price-container { color: green; } .sell-media-dialog-box .subtotal { font-weight: bold; margin-bottom: 20px; } .sell-media-dialog-box .cart { padding-left: 16px; background: url(../images/cart.png) no-repeat 0 50%; } .sell-media-dialog-box fieldset { margin: 20px 0; border: 0; } .sell-media-dialog-box legend { margin: 0 0 5px; font-size: 12px; } .sell-media-dialog-box .total-container { margin: 20px 0; } .sell-media-dialog-box .close { right: 5px; top: 5px; position: absolute; cursor: pointer; font-size: 20px; line-height: 1; text-align: center; width: 20px; } .sell-media-dialog-box .sell-media-button { display: block; width: 100%; } .sell-media-dialog-box, .sell-media-dialog-box p, .sell-media-dialog-box a, .sell-media-dialog-box a:visited { color: #333; } .sell-media-dialog-box a:hover, .sell-media-dialog-box a:focus { color: #000; } .sell-media-dialog-box p { margin-bottom: 10px; } .sell-media-dialog-box .sell-media-added { margin: 15px 0; text-align: center; padding: 10px; background: #fcf9d0; } /*= Checkout -------------------------------------------------------------- */ .sell-media-req { color: #FF0000; font-size: 12px; position: relative; top: 0; margin-left: 3px; float: left; } .sell-media-subtotal { margin: 0 0 1em; padding: 0 0 1em; } .sell_media_fieldset { margin: 10px 0; } .sell_media_form_control { width: 185px; } .sellMediaCart_items .size-license { display: block; font-size: 10px; color: #aaa; font-style: italic; } .text-center { text-align: center; } .quiet { color: #999; } .small { font-size: 10px; } .sell-media-load-checkout { background: url( ../images/ajax-loader.gif) no-repeat center top; position: absolute; height: 32px; width: 100%; text-align: center; padding-top: 20px; color: #BBB; font-size: 12px; } /*= Search -------------------------------------------------------------- */ .sell-media-search { clear: both; height: 125px; margin: 20px 0; position: relative; } .wp-advanced-search { border: 1px solid #ccc; background-color: #ededed; color: #333; margin: 0 0 40px; padding: 3%; position: absolute; z-index: 100; width: 100%; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .wp-advanced-search.active { box-shadow: 0 0 10px rgba(0,0,0,.2); } .wpas-search-field { float: left; width: 70%; } .wpas-submit { float: right; width: 30%; } .wpas-search_query input[type=text], .wpas-submit input[type=submit] { height: 50px; padding: 10px; -webkit-box-sizing: border-box; -moz-box-sizing: border-box; box-sizing: border-box; } .wpas-search_query input[type=text] { border: 1px solid #ccc; border-right: 0; } .wpas-search_query input[type=text], .wpas-submit input[type=submit] { border-radius: 0; width: 100%; } #search_query { font-size: 20px; } .chosen-choices { margin-bottom: 0 !important; } .wpas-submit input[type=submit] { background: #555; border: 0; border-radius: 0; box-shadow: none; color: #eee; font-family: "HelveticaNeue-Light", "Helvetica Neue Light", "Helvetica Neue", Helvetica, Arial, "Lucida Grande", sans-serif; letter-spacing: 2px; font-size: 12px; text-shadow: none; text-transform: uppercase; } .wpas-submit input[type=submit]:hover { background: #000; } .wpas-field { border-radius: 0; margin-bottom: 10px; } input.wpas-text[type=text] { border-radius: 0; font-size: 13px; color: #aaa; } #wpas-tax_collection, #wpas-tax_keywords, #wpas-meta_sell_media_price, #wpas-1 { clear: both; display: none; } #wpas-tax_collection input, #wpas-tax_keywords input, #wpas-meta_sell_media_price input { padding: 6px; height: 15px; } #wpas-1 { float: right; } #sell-media-toggle-search-options { width: 12px; height: 12px; display: block; background: url('../images/chosen-sprite.png') -42px 1px no-repeat; text-indent: -999em; } #sell-media-toggle-search-options:hover { cursor: pointer; } /*= Shortcode sell_media_shortcode_all -------------------------------------------------------------- */ .sell-media-shortcode-all h3 { float: left; font-size: 1.2em; margin: 0; padding: 0; width: 70%; line-height: 1em; } .sell-media .sell-media-shortcode-all .sell-media-grid .sell-media-text { font-size: 1em; } /*= Shortcode sell_media_item ------------------------------------------------------------------- */ .sell-media-item-container { display: inline-block; } .sell-media-item-container a.sell-media-cart-trigger { display: block; } /*= Shortcode sell_media_download_list ------------------------------------------------------------------- */ .downloads { margin: 1em 0; clear:both; } .downloads .download { display: block; clear: both; } .downloads img { float:left; margin:0 20px 20px 0; } .sell-media-ajax-loader { background: url( ../images/ajax-loader.gif) no-repeat center 70px; height: 58px; width: 100%; text-align: center; padding-top: 100px; color: #BBB; font-size: 12px; } #purchase-history td { vertical-align: top; border-bottom: 1px solid #DFDFDF; padding: 10px 0 5px 0; } #purchase-history th { border: solid #DFDFDF; border-width: 1px 0 1px 0; padding: 10px 0; } #purchase-history table { font-size: 13px; margin-bottom: 50px; } #purchase-history ul.payment-meta { margin: 10px 0; padding: 0; font-size: 12px; } /*= Form styling ------------------------------------------------------------------- */ .sell-media-form input[type="number"].small-text { width: 40px; } .sell-media-tooltip { cursor: help; font-size: 10px; padding: 3px 0 0 5px; } .sell-media-tooltip { display: inline; position: relative; } .sell-media-tooltip:hover:after { background: #333; background: rgba(0,0,0,.8); border-radius: 2px; bottom: 26px; color: #fff; content: attr(data-tooltip); left: 0; padding: 8px 12px; position: absolute; z-index: 98; width: 180px; font-size: 12px; line-height: 1.5; } .sell-media-tooltip:hover:before { border: solid; border-color: #333 transparent; border-width: 6px 6px 0 6px; bottom: 20px; content: ""; left: 50%; position: absolute; z-index: 99; } /*= Terms and Conditions -----------------------------------------------------------------------*/ #terms-and-conditions-dialog { z-index: 10000; position: absolute; width: 400px; background: #fff; color: #555; box-shadow: 0 0 40px #000; padding: 25px; line-height: 1.5em; } #terms-and-conditions-dialog .close { cursor: pointer; font-size: 20px; position: absolute; right: 5px; text-align: center; top: 5px; width: 20px; } #sell_media_termsdiv { clear: both; } #sell_media_terms_cb { margin: 5px 5px 0 0; } /*= Error styling -------------------------------------------------------------- */ .sell-media-error { font-size: 13px; margin: 0 0 0 7px; color:#ff0000; } /*= Clearing Floats -------------------------------------------------------------- */ .cf:before, .cf:after, .sell-media-grid-container:before, .sell-media-grid-container:after, .wp-advanced-search:before, .wp-advanced-search:after { content: " "; display: table; } .cf:after, .sell-media-grid-container:after, .wp-advanced-search:after { clear: both; } /*= Lightbox -------------------------------------------------------------- */ .lightbox-counter { margin-left: 4px; } .sell-media-label, .lightbox-counter { display: inline; padding: .2em .6em .3em; font-size: 75%; line-height: 1; color: #fff; background: #d9534f; text-align: center; white-space: nowrap; vertical-align: baseline; border-radius: .25em; } /*= Media queries -------------------------------------------------------------- */ @media only screen and (max-width : 768px) { .sell-media-totals, .sell-media-checkout-button, .sell-media .sell-media-content, .sell-media .sell-media-meta { float: none; width: 100%; } .sell-media .sell-media-grid { float: none; margin: 25px auto; width: 100%; } .sell-media .sell-media-grid img { display: block; margin: 0 auto; } .sell-media .sell-media-grid h3, .sell-media .sell-media-grid .sell-media-text { float: none; display: block; margin: 10px 0; text-align: center; } }
Webfactoo-repo/Pixpantry
wp-content/plugins/sell-media/css/sell_media.css
CSS
gpl-2.0
16,874
package DDB::FILESYSTEM; $VERSION = 1.00; use strict; use vars qw( $AUTOLOAD $obj_table ); use DDB::UTIL; use Carp; my $count = 0; { $obj_table = 'bddb.filesystem'; my %_attr_data = ( _id => ['','read/write'], _param_type => ['','read/write'], _host => ['','read/write'], _nodie => [0,'read/write'], _name => ['','read/write'], _param => ['','read/write'], _description => ['','read/write'], _insert_date => ['','read/write'], _timestamp => ['','read/write'], ); sub _accessible { my ($self,$attr,$mode) = @_; $_attr_data{$attr}[1] =~ /read/; } sub _default_for { my ($self,$attr) = @_; $_attr_data{$attr}[0]; } sub _standard_keys { keys %_attr_data; } } sub new { my ($caller,%param) = @_; my $caller_is_obj = ref($caller); my $class = $caller_is_obj || $caller; my $self = bless{},$class; foreach my $attrname ( $self->_standard_keys() ) { my ($argname) = ($attrname =~ /^_(.*)/); if (exists $param{$argname}) { $self->{$attrname} = $param{$argname}; } elsif ($caller_is_obj) { $self->{$attrname} = $caller->{$attrname}; } else { $self->{$attrname} = $self->_default_for($attrname); } } return $self; } sub DESTROY { } sub AUTOLOAD { no strict "refs"; my ($self,$newval) = @_; if ($AUTOLOAD =~ /.*::get(_\w+)/ && $self->_accessible($1,'read')) { my $attrname = $1; *{$AUTOLOAD} = sub { return $_[0]->{$attrname}; }; return $self->{$attrname}; } if ($AUTOLOAD =~ /.*::set(_\w+)/ && $self->_accessible($1,'write')) { my $attrname = $1; *{$AUTOLOAD} = sub { $_[0]->{$attrname} = $_[1]; return; }; $self->{$1} = $newval; return; } croak "No such method: $AUTOLOAD"; } sub load { my($self,%param)=@_; confess "No id\n" unless $self->{_id}; ($self->{_param_type},$self->{_host},$self->{_name},$self->{_param},$self->{_description},$self->{_insert_date},$self->{_timestamp}) = $ddb_global{dbh}->selectrow_array("SELECT param_type,host,name,param,description,insert_date,timestamp FROM $obj_table WHERE id = $self->{_id}"); if ($self->{_param_type} eq 'executable' && !$self->{_nodie}) { confess "Cannot find ('$self->{_param}'; $self->{_id}, $self->{_nodie})\n" unless -f $self->{_param}; } } sub add { my($self,%param)=@_; confess "No param_type\n" unless $self->{_param_type}; confess "No host\n" unless $self->{_host}; confess "No name\n" unless $self->{_name}; confess "No param\n" unless $self->{_param}; confess "No description\n" unless $self->{_description}; confess "DO HAVE id\n" if $self->{_id}; my $sth = $ddb_global{dbh}->prepare("INSERT $obj_table (param_type,host,name,param,description,insert_date) VALUES (?,?,?,?,?,NOW())"); $sth->execute( $self->{_param_type},$self->{_host},$self->{_name},$self->{_param},$self->{_description}); $self->{_id} = $sth->{mysql_insertid}; } sub save { my($self,%param)=@_; confess "No id\n" unless $self->{_id}; confess "No param_type\n" unless $self->{_param_type}; confess "No host\n" unless $self->{_host}; confess "No name\n" unless $self->{_name}; confess "No param\n" unless $self->{_param}; confess "No description\n" unless $self->{_description}; my $sth = $ddb_global{dbh}->prepare("UPDATE $obj_table SET param_type = ?,host = ?,name = ?, param = ?, description = ? WHERE id = ?"); $sth->execute( $self->{_param_type},$self->{_host},$self->{_name},$self->{_param},$self->{_description}, $self->{_id} ); } sub get_param { my($self,%param)=@_; if ($param{directory}) { confess "Cannot find directory: $self->{_param}\n" unless -d $self->{_param}; } return $self->{_param}; } sub get_ids { my($self,%param)=@_; my @where; for (keys %param) { next if $_ eq 'dbh'; if ($_ eq 'param_type') { push @where, sprintf "%s = '%s'", $_, $param{$_}; } elsif ($_ eq 'search') { push @where, &_search( $param{$_}, ['param_type','host','param','description','name']); } else { confess "Unknown: $_\n"; } } return $ddb_global{dbh}->selectcol_arrayref("SELECT id FROM $obj_table") if $#where < 0; my $statement = sprintf "SELECT id FROM $obj_table WHERE %s", ( join " AND ", @where ); return $ddb_global{dbh}->selectcol_arrayref($statement); } sub exists { my($self,%param)=@_; confess "No name\n" unless $self->{_name}; $self->{_id} = $ddb_global{dbh}->selectrow_array("SELECT id FROM $obj_table WHERE name = $self->{_name} AND host = '$ddb_global{hosttype}'"); return $self->{_id} if $self->{_id}; $self->{_id} = $ddb_global{dbh}->selectrow_array("SELECT id FROM $obj_table WHERE name = $self->{_name} AND '$ddb_global{hosttype}' REGEXP host"); return $self->{_id} if $self->{_id}; $self->{_id} = $ddb_global{dbh}->selectrow_array("SELECT id FROM $obj_table WHERE name = $self->{_name} AND host = '%'"); return ($self->{_id}) ? $self->{_id} : 0; } sub get_object { my($self,%param)=@_; # if ($param{name} && !$param{id}) { # $param{id} = $ddb_global{dbh}->selectrow_array("SELECT id FROM $obj_table WHERE name = \"$param{name}\"" ); # } # if (!$param{id}) { # #Overwrote to force using "which" if(1==1){ # auto-create # Calls 'which' on given parameter 'name.' 2> /dev/null pipes STDERR to null, so it does not enter @ret. my @ret = `which $param{name} 2> /dev/null`; if ($#ret == 0) { chomp $ret[0]; } else { #DEBUG print "'which' failed to return executable path for '$param{name}'\n"; print "Attempting to access '$param{name}' in ddb_global dict.\n"; $ret[0] = $ddb_global{$param{name}}; #DEBUG if ($ddb_global{$param{name}}) { printf "%s : %s\n",$param{name},$ret[0]; } else { warn "'$param{name}' not found in ddb_global dict. Continuing to run..."; } } my $OBJ = $self->new( %param ); $OBJ->set_param_type( 'executable' ); $OBJ->set_host( '%' ); $OBJ->set_param( $ret[0] ); $OBJ->set_description( $ret[0] ); return $OBJ; } confess "No id ($param{name})\n" unless $param{id}; my $OBJ = $self->new( %param ); $OBJ->load(); return $OBJ; } sub check_DDB { my($self,%param)=@_; confess "No param-prefix\n" unless $param{prefix}; if (1==1) { # check syntax my @ary = `find $ddb_global{lib}/DDB -name "*.pm"`; my $count = 0; for my $file (@ary) { chomp $file; my $ret = `perl -c $file 2>&1`; if ($ret =~ /syntax OK$/) { $count++; } else { printf "%s\n", $ret; } } printf "Syntax OK for %s of %s files\n",$count,$#ary+1; } if (1==0) { # list deps my @deps = `grep -R -P "^\\s*use\\b|^\\s*require\\b" * | perl -ane 'chomp; \$_ =~ s/^[\\w\\.\\/#]+:\\s*//; printf "%s\n", \$_' | grep -v "^use DDB" | grep -v "^use vars" | grep -v "require DDB" | sort | uniq -c | more`; printf "%s\n", join "", @deps; } if (1==1) { # check tables my $dir = get_tmpdir(); `mysql -s -e "SHOW TABLES" $param{prefix} > $dir/$param{prefix}.tabs`; `mysql -s -e "SHOW TABLES" $param{prefix}Mzxml >> $dir/$param{prefix}.tabs`; `mysql -s -e "SHOW TABLES" $param{prefix}Decoy >> $dir/$param{prefix}.tabs`; `mysql -s -e "SHOW TABLES" $ddb_global{commondb} >> $dir/$param{prefix}.tabs`; my $shell = 'grep -R -P "\t\\\\\$obj_table[_\w]* = " '.$ddb_global{lib}.'/DDB/ | grep -v grep | grep -v Binary > '.$dir.'/obj_table'; #printf "$shell\n"; `$shell`; my @tabs = `cat $dir/$param{prefix}.tabs`; my %tables; for my $tab (@tabs) { chomp $tab; $tables{$tab}->{tab} = 0 unless defined $tables{$tab}->{tab}; $tables{$tab}->{tab}++; } my @obj_table = `cat $dir/obj_table`; for my $obj (@obj_table) { chomp $obj; my $tab = ''; $obj =~ s/\$ENV\{decoydb\}/DECOY/; $obj =~ s/\$ENV\{mzxmldb\}/MZXML/; $obj =~ s/\$ddb_global\{decoydb\}/DECOY/; $obj =~ s/\$ddb_global\{mzxmldb\}/MZXML/; $obj =~ s/\$ddb_global\{commondb\}/COMMON/; if ($obj =~ /\$obj_table\w* = ['"](\w+)['"]/) { $tab = $1; } elsif ($obj =~ /\$obj_table\w* = ['"]\w+\.(\w+)['"]/) { $tab = $1; } else { confess "Unknown row: $obj\n"; } confess "No tab\n" unless $tab; $tables{$tab}->{obj} = 0 unless defined $tables{$tab}->{obj}; $tables{$tab}->{obj}++; } for my $key (keys %tables) { $tables{$key}->{obj} = 0 unless defined $tables{$key}->{obj}; $tables{$key}->{tab} = 0 unless defined $tables{$key}->{tab}; if ($tables{$key}->{tab} == 1 && $tables{$key}->{obj} == 1) { #printf "BOTH!!! $key\n"; } elsif ($tables{$key}->{tab} == 1 && $tables{$key}->{obj} == 0) { printf "NO OBJECT: %s %s %s\n", $key,$tables{$key}->{tab},$tables{$key}->{obj}; } elsif ($tables{$key}->{tab} == 0 && $tables{$key}->{obj} == 1) { printf "NO TABLE: %s %s %s\n", $key,$tables{$key}->{tab},$tables{$key}->{obj}; } else { #printf "NONE: %s %s %s\n", $key,$tables{$key}->{tab},$tables{$key}->{obj}; } } } if (1==1) { # check for objects that are no longer In use my @ary = `find $ddb_global{lib}/DDB -name "*.pm"`; for my $file (@ary) { chomp $file; my $tfile = $file; $tfile =~ s/$ddb_global{lib}\/// || warn "Cannot nule $tfile\n"; $tfile =~ s/.pm// || warn "Cannot nuke the end from $tfile\n"; $tfile =~ s/\//::/g; my @ret = grep{ $_ =~ /require/ }`grep -R 'require $tfile;' $ddb_global{lib}/DDB/*`; chomp @ret; my %have; for my $t (@ret) { my $tmfile = (split /\s+/, $t)[0]; $tmfile =~ s/:.*// || warn "Cannot nuke the end from $tmfile ($t)\n"; next if $tmfile eq $file; my $tmmfile = $tmfile; next unless $tmfile =~ /\.pm$/; $tmmfile =~ s/\.pm// || warn "Cannot nuke the end from $tmmfile\n"; $tmmfile =~ s/$ddb_global{lib}// || warn "Cannot nule $tmmfile\n"; $have{$tmmfile} = 1; } my @refs = keys %have; printf "%s\t%s\t(%s)\n", $tfile,$#refs+1,join ", ", @refs if $#refs < 0; } } if (1==1) { printf "Check beginning and end o\n"; my @ary = `find $ddb_global{lib}/DDB -name "*.pm"`; for my $file (@ary) { chomp $file; my @lines = `cat $file`; chomp @lines; my $edata; my $bdata; for my $line (@lines) { next if $line =~ /^#/; next if $line =~ /\s#/; $edata->{ substr($line,-1) }++; $line =~ s/^\t+//; $bdata->{space}++ if $line =~ /^ /; } for my $key (keys %$edata) { next if $key eq '{'; next if $key eq '}'; next if $key eq '('; next if $key eq ','; next if $key eq ';'; printf "$file: END: $key $edata->{$key}\n"; } for my $key (keys %$bdata) { printf "$file: BEG: $key $bdata->{$key}\n"; } #last; } } # perl -pi.bakk -e s/self-\>{_dbh}/ddb_global{dbh}/g PAGE.pm # perl -pi.bak -e s/param{dbh}/ddb_global{dbh}/g PAGE.pm # perl -pi.bakk -e s/self-\>{_dbh}/ddb_global{dbh}/g ./GROUP.pm # perl -pi.bak -e s/param{dbh}/ddb_global{dbh}/g ./GROUP.pm # perl -pi.bakkk -e s/dbh.....ddb_global.dbh.,.// PAGE.pm # perl -pi.bakkk -e s/dbh.....ddb_global.dbh.,.//g ./PAGE.pm # find . -name "*.pm" | perl -ane 'printf "perl -pi.bakkk -e s/dbh.....ddb_global.dbh.,.//g %s\n", $F[0] ' >> script2 # find . -name "*.pm" | perl -ane 'printf "perl -pi.bakkkk -e s/_dbh.......,..read.write...,//g %s\n", $F[0] ' >> script3 # find . -name "*.pm" | perl -ane 'printf "perl -pi.bakkkkk -e s/new. dbh.....ddb_global.dbh...;/new();/g %s\n", $F[0] ' >> script4 return ''; } sub get_status { my($self,%param)=@_; my $status = 'Cannot find executable'; $status = 'OK' if -x $self->{_param}; return $status; } 1;
dpenfoldbrown/DDB_ginzu
FILESYSTEM.pm
Perl
gpl-2.0
11,310
/************************************************** file: demo_tx.c purpose: simple demo that transmits characters to the serial port and print them on the screen, exit the program by pressing Ctrl-C compile with the command: gcc demo_tx.c rs232.c -Wall -Wextra -o2 -o test_tx **************************************************/ #include <stdlib.h> #include <stdio.h> #ifdef _WIN32 #include <Windows.h> #else #include <unistd.h> #endif #include "rs232.h" int main() { int i=0, cport_nr=16, /* /dev/ttyUSB0 (see doc.txt) */ bdrate=115200, /* 115200 baud */ j = 0; char mode[]={'8','N','1',0}, str[2][512]; strcpy(str[0], "The quick brown fox jumped over the lazy grey dog.\n"); strcpy(str[1], "Happy serial programming!\n"); if(RS232_OpenComport(cport_nr, bdrate, mode)) { printf("Can not open comport\n"); return(0); } while(j<10) { RS232_cputs(cport_nr, str[i]); printf("sent: %s\n", str[i]); #ifdef _WIN32 Sleep(1000); #else usleep(1000000); /* sleep for 1 Second */ #endif i++; j++; i %= 2; } RS232_CloseComport(cport_nr); return(0); }
jcmcclurg/serverpower
unused/xbeecom/RS-232-Lib/demo_tx.c
C
gpl-2.0
1,158
OBJS=btt.o __TARGET=btt TARGET=$(__TARGET) LIBS_DEPEND=-lubacktrace -lautelan-appkey .PHONY:all all:$(TARGET) .PHONY: clean clean: rm -f $(OBJS) $(TARGET) $(TARGET):$(OBJS) ${CC} ${CFLAGS} ${LDFLAGS} $(LIBS_DEPEND) -o $(TARGET) $(OBJS) echo $(OBJS) > $(FILENO_PATH)/$(__TARGET).fileno %.o:%.c ${CC} -c ${CFLAGS} -D__THIS_FILE=$(shell $(FILENO_BIN) $@ $(OBJS)) $< -o $@
tcdog001/ap_project
package/autelan-app/src/btt/Makefile
Makefile
gpl-2.0
376
/********************************************************************* * * msnd.h * * Turtle Beach MultiSound Sound Card Driver for Linux * * Some parts of this header file were derived from the Turtle Beach * MultiSound Driver Development Kit. * * Copyright (C) 1998 Andrew Veliath * Copyright (C) 1993 Turtle Beach Systems, Inc. * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. * * $Id: msnd.h,v 1.1.1.1 2010/04/09 09:38:36 feiyan Exp $ * ********************************************************************/ #ifndef __MSND_H #define __MSND_H #define VERSION "0.8.3.1" #define DEFSAMPLERATE DSP_DEFAULT_SPEED #define DEFSAMPLESIZE AFMT_U8 #define DEFCHANNELS 1 #define DEFFIFOSIZE 128 #define SNDCARD_MSND 38 #define SRAM_BANK_SIZE 0x8000 #define SRAM_CNTL_START 0x7F00 #define DSP_BASE_ADDR 0x4000 #define DSP_BANK_BASE 0x4000 #define HP_ICR 0x00 #define HP_CVR 0x01 #define HP_ISR 0x02 #define HP_IVR 0x03 #define HP_NU 0x04 #define HP_INFO 0x04 #define HP_TXH 0x05 #define HP_RXH 0x05 #define HP_TXM 0x06 #define HP_RXM 0x06 #define HP_TXL 0x07 #define HP_RXL 0x07 #define HP_ICR_DEF 0x00 #define HP_CVR_DEF 0x12 #define HP_ISR_DEF 0x06 #define HP_IVR_DEF 0x0f #define HP_NU_DEF 0x00 #define HP_IRQM 0x09 #define HPR_BLRC 0x08 #define HPR_SPR1 0x09 #define HPR_SPR2 0x0A #define HPR_TCL0 0x0B #define HPR_TCL1 0x0C #define HPR_TCL2 0x0D #define HPR_TCL3 0x0E #define HPR_TCL4 0x0F #define HPICR_INIT 0x80 #define HPICR_HM1 0x40 #define HPICR_HM0 0x20 #define HPICR_HF1 0x10 #define HPICR_HF0 0x08 #define HPICR_TREQ 0x02 #define HPICR_RREQ 0x01 #define HPCVR_HC 0x80 #define HPISR_HREQ 0x80 #define HPISR_DMA 0x40 #define HPISR_HF3 0x10 #define HPISR_HF2 0x08 #define HPISR_TRDY 0x04 #define HPISR_TXDE 0x02 #define HPISR_RXDF 0x01 #define HPIO_290 0 #define HPIO_260 1 #define HPIO_250 2 #define HPIO_240 3 #define HPIO_230 4 #define HPIO_220 5 #define HPIO_210 6 #define HPIO_3E0 7 #define HPMEM_NONE 0 #define HPMEM_B000 1 #define HPMEM_C800 2 #define HPMEM_D000 3 #define HPMEM_D400 4 #define HPMEM_D800 5 #define HPMEM_E000 6 #define HPMEM_E800 7 #define HPIRQ_NONE 0 #define HPIRQ_5 1 #define HPIRQ_7 2 #define HPIRQ_9 3 #define HPIRQ_10 4 #define HPIRQ_11 5 #define HPIRQ_12 6 #define HPIRQ_15 7 #define HIMT_PLAY_DONE 0x00 #define HIMT_RECORD_DONE 0x01 #define HIMT_MIDI_EOS 0x02 #define HIMT_MIDI_OUT 0x03 #define HIMT_MIDI_IN_UCHAR 0x0E #define HIMT_DSP 0x0F #define HDEX_BASE 0x92 #define HDEX_PLAY_START (0 + HDEX_BASE) #define HDEX_PLAY_STOP (1 + HDEX_BASE) #define HDEX_PLAY_PAUSE (2 + HDEX_BASE) #define HDEX_PLAY_RESUME (3 + HDEX_BASE) #define HDEX_RECORD_START (4 + HDEX_BASE) #define HDEX_RECORD_STOP (5 + HDEX_BASE) #define HDEX_MIDI_IN_START (6 + HDEX_BASE) #define HDEX_MIDI_IN_STOP (7 + HDEX_BASE) #define HDEX_MIDI_OUT_START (8 + HDEX_BASE) #define HDEX_MIDI_OUT_STOP (9 + HDEX_BASE) #define HDEX_AUX_REQ (10 + HDEX_BASE) #define HIWORD(l) ((WORD)((((DWORD)(l)) >> 16) & 0xFFFF)) #define LOWORD(l) ((WORD)(DWORD)(l)) #define HIBYTE(w) ((BYTE)(((WORD)(w) >> 8) & 0xFF)) #define LOBYTE(w) ((BYTE)(w)) #define MAKELONG(low,hi) ((long)(((WORD)(low))|(((DWORD)((WORD)(hi)))<<16))) #define MAKEWORD(low,hi) ((WORD)(((BYTE)(low))|(((WORD)((BYTE)(hi)))<<8))) #define PCTODSP_OFFSET(w) (USHORT)((w)/2) #define PCTODSP_BASED(w) (USHORT)(((w)/2) + DSP_BASE_ADDR) #define DSPTOPC_BASED(w) (((w) - DSP_BASE_ADDR) * 2) #ifdef SLOWIO #define msnd_outb outb_p #define msnd_inb inb_p #else #define msnd_outb outb #define msnd_inb inb #endif /* JobQueueStruct */ #define JQS_wStart 0x00 #define JQS_wSize 0x02 #define JQS_wHead 0x04 #define JQS_wTail 0x06 #define JQS__size 0x08 /* DAQueueDataStruct */ #define DAQDS_wStart 0x00 #define DAQDS_wSize 0x02 #define DAQDS_wFormat 0x04 #define DAQDS_wSampleSize 0x06 #define DAQDS_wChannels 0x08 #define DAQDS_wSampleRate 0x0A #define DAQDS_wIntMsg 0x0C #define DAQDS_wFlags 0x0E #define DAQDS__size 0x10 typedef u8 BYTE; typedef u16 USHORT; typedef u16 WORD; typedef u32 DWORD; typedef void __iomem * LPDAQD; /* Generic FIFO */ typedef struct { size_t n, len; char *data; int head, tail; } msnd_fifo; typedef struct multisound_dev { /* Linux device info */ char *name; int dsp_minor, mixer_minor; int ext_midi_dev, hdr_midi_dev; /* Hardware resources */ int io, numio; int memid, irqid; int irq, irq_ref; unsigned char info; void __iomem *base; /* Motorola 56k DSP SMA */ void __iomem *SMA; void __iomem *DAPQ, *DARQ, *MODQ, *MIDQ, *DSPQ; void __iomem *pwDSPQData, *pwMIDQData, *pwMODQData; int dspq_data_buff, dspq_buff_size; /* State variables */ enum { msndClassic, msndPinnacle } type; mode_t mode; unsigned long flags; #define F_RESETTING 0 #define F_HAVEDIGITAL 1 #define F_AUDIO_WRITE_INUSE 2 #define F_WRITING 3 #define F_WRITEBLOCK 4 #define F_WRITEFLUSH 5 #define F_AUDIO_READ_INUSE 6 #define F_READING 7 #define F_READBLOCK 8 #define F_EXT_MIDI_INUSE 9 #define F_HDR_MIDI_INUSE 10 #define F_DISABLE_WRITE_NDELAY 11 wait_queue_head_t writeblock; wait_queue_head_t readblock; wait_queue_head_t writeflush; spinlock_t lock; int nresets; unsigned long recsrc; int left_levels[16]; int right_levels[16]; int mixer_mod_count; int calibrate_signal; int play_sample_size, play_sample_rate, play_channels; int play_ndelay; int rec_sample_size, rec_sample_rate, rec_channels; int rec_ndelay; BYTE bCurrentMidiPatch; /* Digital audio FIFOs */ msnd_fifo DAPF, DARF; int fifosize; int last_playbank, last_recbank; /* MIDI in callback */ void (*midi_in_interrupt)(struct multisound_dev *); } multisound_dev_t; #ifndef mdelay # define mdelay(a) udelay((a) * 1000) #endif int msnd_register(multisound_dev_t *dev); void msnd_unregister(multisound_dev_t *dev); void msnd_init_queue(void __iomem *, int start, int size); void msnd_fifo_init(msnd_fifo *f); void msnd_fifo_free(msnd_fifo *f); int msnd_fifo_alloc(msnd_fifo *f, size_t n); void msnd_fifo_make_empty(msnd_fifo *f); int msnd_fifo_write_io(msnd_fifo *f, char __iomem *buf, size_t len); int msnd_fifo_read_io(msnd_fifo *f, char __iomem *buf, size_t len); int msnd_fifo_write(msnd_fifo *f, const char *buf, size_t len); int msnd_fifo_read(msnd_fifo *f, char *buf, size_t len); int msnd_send_dsp_cmd(multisound_dev_t *dev, BYTE cmd); int msnd_send_word(multisound_dev_t *dev, unsigned char high, unsigned char mid, unsigned char low); int msnd_upload_host(multisound_dev_t *dev, char *bin, int len); int msnd_enable_irq(multisound_dev_t *dev); int msnd_disable_irq(multisound_dev_t *dev); #endif /* __MSND_H */
ndmsystems/linux-2.6.22-tc
sound/oss/msnd.h
C
gpl-2.0
7,385
if [ -d tmp ]; then echo -n "Restarting Nginx ... " rm -f tmp/restart.txt touch tmp/restart.txt fi
taq/traquitana
config/nginx.sh
Shell
gpl-2.0
111
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
/* * Copyright (c) International Business Machines Corp., 2001 * Ported by Wayne Boyer * * 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 */ /* * DESCRIPTION * Testcase to check creat(2) sets the following errnos correctly: * 1. EISDIR * 2. ENAMETOOLONG * 3. ENOENT * 4. ENOTDIR * 5. EFAULT * 6. EACCES * 7. ELOOP * 8. EROFS * * * ALGORITHM * 1. Attempt to creat(2) an existing directory, and test for * EISDIR * 2. Attempt to creat(2) a file whose name is more than * VFS_MAXNAMLEN and test for ENAMETOOLONG. * 3. Attempt to creat(2) a file inside a directory which doesn't * exist, and test for ENOENT * 4. Attempt to creat(2) a file, the pathname of which comprises * a component which is a file, test for ENOTDIR. * 5. Attempt to creat(2) a file with a bad address * and test for EFAULT * 6. Attempt to creat(2) a file in a directory with no * execute permission and test for EACCES * 7. Attempt to creat(2) a file which links the other file that * links the former and test for ELOOP * 8. Attempt to creat(2) a file in a Read-only file system * and test for EROFS */ #include <errno.h> #include <string.h> #include <pwd.h> #include <sys/mman.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/mount.h> #include "tst_test.h" #define TEST_FILE "test_dir" #define NO_DIR "testfile/testdir" #define NOT_DIR "file1/testdir" #define TEST6_FILE "dir6/file6" #define TEST7_FILE "file7" #define TEST8_FILE "mntpoint/tmp" #define MODE1 0444 #define MODE2 0666 static void setup(void); static void cleanup(void); static void test6_setup(void); static void test6_cleanup(void); #if !defined(UCLINUX) static void bad_addr_setup(int); #endif static struct passwd *ltpuser; static char long_name[PATH_MAX+2]; static const char *device; static int mount_flag; static struct test_case_t { char *fname; int mode; int error; void (*setup)(); void (*cleanup)(void); } tcases[] = { {TEST_FILE, MODE1, EISDIR, NULL, NULL}, {long_name, MODE1, ENAMETOOLONG, NULL, NULL}, {NO_DIR, MODE1, ENOENT, NULL, NULL}, {NOT_DIR, MODE1, ENOTDIR, NULL, NULL}, #if !defined(UCLINUX) {NULL, MODE1, EFAULT, bad_addr_setup, NULL}, #endif {TEST6_FILE, MODE1, EACCES, test6_setup, test6_cleanup}, {TEST7_FILE, MODE1, ELOOP, NULL, NULL}, {TEST8_FILE, MODE1, EROFS, NULL, NULL}, }; static void verify_creat(unsigned int i) { if (tcases[i].setup != NULL) tcases[i].setup(i); TEST(creat(tcases[i].fname, tcases[i].mode)); if (tcases[i].cleanup != NULL) tcases[i].cleanup(); if (TEST_RETURN != -1) { tst_res(TFAIL, "call succeeded unexpectedly"); return; } if (TEST_ERRNO == tcases[i].error) { tst_res(TPASS | TTERRNO, "got expected failure"); return; } tst_res(TFAIL | TTERRNO, "expected %s", tst_strerrno(tcases[i].error)); } static void setup(void) { ltpuser = SAFE_GETPWNAM("nobody"); SAFE_MKDIR(TEST_FILE, MODE2); memset(long_name, 'a', PATH_MAX+1); SAFE_TOUCH("file1", MODE1, NULL); SAFE_MKDIR("dir6", MODE2); SAFE_SYMLINK(TEST7_FILE, "test_file_eloop2"); SAFE_SYMLINK("test_file_eloop2", TEST7_FILE); SAFE_MKFS(tst_device->dev, tst_device->fs_type, NULL, NULL); SAFE_MKDIR("mntpoint", 0777); SAFE_MOUNT(tst_device->dev, "mntpoint", tst_device->fs_type, MS_RDONLY, NULL); mount_flag = 1; } #if !defined(UCLINUX) static void bad_addr_setup(int i) { if (tcases[i].fname) return; tcases[i].fname = SAFE_MMAP(0, 1, PROT_NONE, MAP_PRIVATE | MAP_ANONYMOUS, 0, 0); } #endif static void test6_setup(void) { SAFE_SETEUID(ltpuser->pw_uid); } static void test6_cleanup(void) { SAFE_SETEUID(0); } static void cleanup(void) { if (mount_flag && tst_umount("mntpoint") < 0) tst_brk(TBROK | TERRNO, "umount device:%s failed", device); } static struct tst_test test = { .tid = "creat06", .tcnt = ARRAY_SIZE(tcases), .test = verify_creat, .needs_root = 1, .needs_tmpdir = 1, .needs_device = 1, .cleanup = cleanup, .setup = setup, };
Havner/ltp
testcases/kernel/syscalls/creat/creat06.c
C
gpl-2.0
4,650
/* Copyright (c) 2015-2016 The Linux Foundation. All rights reserved. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License version 2 and * only 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. */ #define pr_fmt(fmt) "SMB1351 %s: " fmt, __func__ #ifdef CONFIG_LGE_PM_PARALLEL_CHARGING #define DEFINE #endif #include <linux/i2c.h> #include <linux/debugfs.h> #include <linux/errno.h> #include <linux/module.h> #include <linux/interrupt.h> #include <linux/slab.h> #include <linux/power_supply.h> #include <linux/regulator/driver.h> #include <linux/regulator/of_regulator.h> #include <linux/regulator/machine.h> #include <linux/of.h> #include <linux/mutex.h> #include <linux/delay.h> #include <linux/qpnp/qpnp-adc.h> #include <linux/pinctrl/consumer.h> #include <linux/bitops.h> /* Mask/Bit helpers */ #define _SMB1351_MASK(BITS, POS) \ ((unsigned char)(((1 << (BITS)) - 1) << (POS))) #define SMB1351_MASK(LEFT_BIT_POS, RIGHT_BIT_POS) \ _SMB1351_MASK((LEFT_BIT_POS) - (RIGHT_BIT_POS) + 1, \ (RIGHT_BIT_POS)) /* Configuration registers */ #define CHG_CURRENT_CTRL_REG 0x0 #define FAST_CHG_CURRENT_MASK SMB1351_MASK(7, 4) #define AC_INPUT_CURRENT_LIMIT_MASK SMB1351_MASK(3, 0) #define CHG_OTH_CURRENT_CTRL_REG 0x1 #define PRECHG_CURRENT_MASK SMB1351_MASK(7, 5) #define ITERM_MASK SMB1351_MASK(4, 2) #define USB_2_3_MODE_SEL_BIT BIT(1) #define USB_2_3_MODE_SEL_BY_I2C 0 #define USB_2_3_MODE_SEL_BY_PIN 0x2 #define USB_5_1_CMD_POLARITY_BIT BIT(0) #define USB_CMD_POLARITY_500_1_100_0 0 #define USB_CMD_POLARITY_500_0_100_1 0x1 #define VARIOUS_FUNC_REG 0x2 #define SUSPEND_MODE_CTRL_BIT BIT(7) #define SUSPEND_MODE_CTRL_BY_PIN 0 #define SUSPEND_MODE_CTRL_BY_I2C 0x80 #define BATT_TO_SYS_POWER_CTRL_BIT BIT(6) #define MAX_SYS_VOLTAGE BIT(5) #define AICL_EN_BIT BIT(4) #define AICL_DET_TH_BIT BIT(3) #define APSD_EN_BIT BIT(2) #define BATT_OV_BIT BIT(1) #define VCHG_FUNC_BIT BIT(0) #define VFLOAT_REG 0x3 #define PRECHG_TO_FAST_VOLTAGE_CFG_MASK SMB1351_MASK(7, 6) #define VFLOAT_MASK SMB1351_MASK(5, 0) #define CHG_CTRL_REG 0x4 #define AUTO_RECHG_BIT BIT(7) #define AUTO_RECHG_ENABLE 0 #define AUTO_RECHG_DISABLE 0x80 #define ITERM_EN_BIT BIT(6) #define ITERM_ENABLE 0 #define ITERM_DISABLE 0x40 #define MAPPED_AC_INPUT_CURRENT_LIMIT_MASK SMB1351_MASK(5, 4) #define AUTO_RECHG_TH_BIT BIT(3) #define AUTO_RECHG_TH_50MV 0 #define AUTO_RECHG_TH_100MV 0x8 #define AFCV_MASK SMB1351_MASK(2, 0) #define CHG_STAT_TIMERS_CTRL_REG 0x5 #define STAT_OUTPUT_POLARITY_BIT BIT(7) #define STAT_OUTPUT_ACTIVE_HIGH BIT(7) #define STAT_OUTPUT_ACTIVE_LOW 0 #define STAT_OUTPUT_MODE_BIT BIT(6) #define STAT_OUTPUT_CTRL_BIT BIT(5) #define OTH_CHG_IL_BIT BIT(4) #define COMPLETE_CHG_TIMEOUT_MASK SMB1351_MASK(3, 2) #define PRECHG_TIMEOUT_MASK SMB1351_MASK(1, 0) #define CHG_PIN_EN_CTRL_REG 0x6 #define LED_BLINK_FUNC_BIT BIT(7) #define EN_PIN_CTRL_MASK SMB1351_MASK(6, 5) #define EN_BY_I2C_0_DISABLE 0 #define EN_BY_I2C_0_ENABLE 0x20 #define EN_BY_PIN_HIGH_ENABLE 0x40 #define EN_BY_PIN_LOW_ENABLE 0x60 #define USBCS_CTRL_BIT BIT(4) #define USBCS_CTRL_BY_I2C 0 #define USBCS_CTRL_BY_PIN 0x10 #define USBCS_INPUT_STATE_BIT BIT(3) #define CHG_ERR_BIT BIT(2) #define APSD_DONE_BIT BIT(1) #define USB_FAIL_BIT BIT(0) #define THERM_A_CTRL_REG 0x7 #define MIN_SYS_VOLTAGE_MASK SMB1351_MASK(7, 6) #define LOAD_BATT_10MA_FVC_BIT BIT(5) #define THERM_MONITOR_BIT BIT(4) #define THERM_MONITOR_EN 0 #define SOFT_COLD_TEMP_LIMIT_MASK SMB1351_MASK(3, 2) #define SOFT_HOT_TEMP_LIMIT_MASK SMB1351_MASK(1, 0) #define WDOG_SAFETY_TIMER_CTRL_REG 0x8 #define AICL_FAIL_OPTION_BIT BIT(7) #define AICL_FAIL_TO_SUSPEND 0 #define AICL_FAIL_TO_150_MA 0x80 #define WDOG_TIMEOUT_MASK SMB1351_MASK(6, 5) #define WDOG_IRQ_SAFETY_TIMER_MASK SMB1351_MASK(4, 3) #define WDOG_IRQ_SAFETY_TIMER_EN_BIT BIT(2) #define WDOG_OPTION_BIT BIT(1) #define WDOG_TIMER_EN_BIT BIT(0) #define OTG_USBIN_AICL_CTRL_REG 0x9 #define OTG_ID_PIN_CTRL_MASK SMB1351_MASK(7, 6) #define OTG_PIN_POLARITY_BIT BIT(5) #define DCIN_IC_GLITCH_FILTER_HV_ADAPTER_MASK SMB1351_MASK(4, 3) #define DCIN_IC_GLITCH_FILTER_LV_ADAPTER_BIT BIT(2) #define USBIN_AICL_CFG1_BIT BIT(1) #define USBIN_AICL_CFG0_BIT BIT(0) #define OTG_TLIM_CTRL_REG 0xA #define SWITCH_FREQ_MASK SMB1351_MASK(7, 6) #define SWITCH_FREQ_SHIFT 6 #define THERM_LOOP_TEMP_SEL_MASK SMB1351_MASK(5, 4) #define OTG_OC_LIMIT_MASK SMB1351_MASK(3, 2) #define OTG_BATT_UVLO_TH_MASK SMB1351_MASK(1, 0) #define HARD_SOFT_LIMIT_CELL_TEMP_REG 0xB #define HARD_LIMIT_COLD_TEMP_ALARM_TRIP_MASK SMB1351_MASK(7, 6) #define HARD_LIMIT_HOT_TEMP_ALARM_TRIP_MASK SMB1351_MASK(5, 4) #define SOFT_LIMIT_COLD_TEMP_ALARM_TRIP_MASK SMB1351_MASK(3, 2) #define SOFT_LIMIT_HOT_TEMP_ALARM_TRIP_MASK SMB1351_MASK(1, 0) #define FAULT_INT_CFG_REG 0xC #define HOT_COLD_HARD_LIMIT_BIT BIT(7) #define HOT_COLD_SOFT_LIMIT_BIT BIT(6) #define BATT_UVLO_IN_OTG_BIT BIT(5) #define OTG_OC_BIT BIT(4) #define INPUT_OVLO_BIT BIT(3) #define INPUT_UVLO_BIT BIT(2) #define AICL_DONE_FAIL_BIT BIT(1) #define INTERNAL_OVER_TEMP_BIT BIT(0) #define STATUS_INT_CFG_REG 0xD #define CHG_OR_PRECHG_TIMEOUT_BIT BIT(7) #define RID_CHANGE_BIT BIT(6) #define BATT_OVP_BIT BIT(5) #define FAST_TERM_TAPER_RECHG_INHIBIT_BIT BIT(4) #define WDOG_TIMER_BIT BIT(3) #define POK_BIT BIT(2) #define BATT_MISSING_BIT BIT(1) #define BATT_LOW_BIT BIT(0) #define VARIOUS_FUNC_2_REG 0xE #define CHG_HOLD_OFF_TIMER_AFTER_PLUGIN_BIT BIT(7) #define CHG_INHIBIT_BIT BIT(6) #define FAST_CHG_CC_IN_BATT_SOFT_LIMIT_MODE_BIT BIT(5) #define FVCL_IN_BATT_SOFT_LIMIT_MODE_MASK SMB1351_MASK(4, 3) #define HARD_TEMP_LIMIT_BEHAVIOR_BIT BIT(2) #define PRECHG_TO_FASTCHG_BIT BIT(1) #define STAT_PIN_CONFIG_BIT BIT(0) #define FLEXCHARGER_REG 0x10 #define AFVC_IRQ_BIT BIT(7) #define CHG_CONFIG_MASK SMB1351_MASK(6, 4) #define LOW_BATT_VOLTAGE_DET_TH_MASK SMB1351_MASK(3, 0) #define VARIOUS_FUNC_3_REG 0x11 #define SAFETY_TIMER_EN_MASK SMB1351_MASK(7, 6) #define BLOCK_SUSPEND_DURING_VBATT_LOW_BIT BIT(5) #define TIMEOUT_SEL_FOR_APSD_BIT BIT(4) #define SDP_SUSPEND_BIT BIT(3) #define QC_2P1_AUTO_INCREMENT_MODE_BIT BIT(2) #define QC_2P1_AUTH_ALGO_BIT BIT(1) #define DCD_EN_BIT BIT(0) #define HVDCP_BATT_MISSING_CTRL_REG 0x12 #define HVDCP_ADAPTER_SEL_MASK SMB1351_MASK(7, 6) #define HVDCP_EN_BIT BIT(5) #define HVDCP_AUTO_INCREMENT_LIMIT_BIT BIT(4) #define BATT_MISSING_ON_INPUT_PLUGIN_BIT BIT(3) #define BATT_MISSING_2P6S_POLLER_BIT BIT(2) #define BATT_MISSING_ALGO_BIT BIT(1) #define BATT_MISSING_THERM_PIN_SOURCE_BIT BIT(0) #define PON_OPTIONS_REG 0x13 #define SYSOK_INOK_POLARITY_BIT BIT(7) #define SYSOK_INOK_POLARITY_INVERT BIT(7) #define SYSOK_OPTIONS_MASK SMB1351_MASK(6, 4) #define SYSOK_INOK_OPTION1 0x00 #define INPUT_MISSING_POLLER_CONFIG_BIT BIT(3) #define VBATT_LOW_DISABLED_OR_RESET_STATE_BIT BIT(2) #define QC_2P1_AUTH_ALGO_IRQ_EN_BIT BIT(0) #define OTG_MODE_POWER_OPTIONS_REG 0x14 #define ADAPTER_CONFIG_MASK SMB1351_MASK(7, 6) #define MAP_HVDCP_BIT BIT(5) #define SDP_LOW_BATT_FORCE_USB5_OVER_USB1_BIT BIT(4) #define OTG_HICCUP_MODE_BIT BIT(2) #define INPUT_CURRENT_LIMIT_MASK SMB1351_MASK(1, 0) #define CHARGER_I2C_CTRL_REG 0x15 #define FULLON_MODE_EN_BIT BIT(7) #define I2C_HS_MODE_EN_BIT BIT(6) #define SYSON_LDO_OUTPUT_SEL_BIT BIT(5) #define VBATT_TRACKING_VOLTAGE_DIFF_BIT BIT(4) #define DISABLE_AFVC_WHEN_ENTER_TAPER_BIT BIT(3) #define VCHG_IINV_BIT BIT(2) #define AFVC_OVERRIDE_BIT BIT(1) #define SYSOK_PIN_CONFIG_BIT BIT(0) #define VERSION_REG 0x2E #define VERSION_MASK BIT(1) /* Command registers */ #define CMD_I2C_REG 0x30 #define CMD_RELOAD_BIT BIT(7) #define CMD_BQ_CFG_ACCESS_BIT BIT(6) #define CMD_INPUT_LIMIT_REG 0x31 #define CMD_OVERRIDE_BIT BIT(7) #define CMD_SUSPEND_MODE_BIT BIT(6) #define CMD_INPUT_CURRENT_MODE_BIT BIT(3) #define CMD_INPUT_CURRENT_MODE_APSD 0 #define CMD_INPUT_CURRENT_MODE_CMD 0x08 #define CMD_USB_2_3_SEL_BIT BIT(2) #define CMD_USB_2_MODE 0 #define CMD_USB_3_MODE 0x4 #define CMD_USB_1_5_AC_CTRL_MASK SMB1351_MASK(1, 0) #define CMD_USB_100_MODE 0 #define CMD_USB_500_MODE 0x2 #define CMD_USB_HC_MODE 0x1 #define CMD_CHG_REG 0x32 #define CMD_DISABLE_THERM_MONITOR_BIT BIT(4) #define CMD_TURN_OFF_STAT_PIN_BIT BIT(3) #define CMD_PRE_TO_FAST_EN_BIT BIT(2) #define CMD_CHG_EN_BIT BIT(1) #define CMD_CHG_DISABLE 0 #define CMD_CHG_ENABLE 0x2 #define CMD_OTG_EN_BIT BIT(0) #define CMD_DEAD_BATT_REG 0x33 #define CMD_STOP_DEAD_BATT_TIMER_MASK SMB1351_MASK(7, 0) #define CMD_HVDCP_REG 0x34 #define CMD_APSD_RE_RUN_BIT BIT(7) #define CMD_FORCE_HVDCP_2P0_BIT BIT(5) #define CMD_HVDCP_MODE_MASK SMB1351_MASK(5, 0) /* Status registers */ #define STATUS_0_REG 0x36 #define STATUS_AICL_DONE_BIT BIT(7) #define STATUS_INPUT_MODE_MASK SMB1351_MASK(6, 5) #define STATUS_INPUT_SUSPEND BIT(4) #define STATUS_INPUT_CURRENT_LIMIT_MASK SMB1351_MASK(3, 0) #define STATUS_1_REG 0x37 #define STATUS_INPUT_RANGE_MASK SMB1351_MASK(7, 4) #define STATUS_INPUT_RANGE_12V BIT(7) #define STATUS_INPUT_RANGE_5V_9V BIT(6) #define STATUS_INPUT_RANGE_9V BIT(5) #define STATUS_INPUT_RANGE_5V BIT(4) #define STATUS_INPUT_USB_BIT BIT(0) #define STATUS_2_REG 0x38 #define STATUS_FAST_CHG_BIT BIT(7) #define STATUS_HARD_LIMIT_BIT BIT(6) #define STATUS_FLOAT_VOLTAGE_MASK SMB1351_MASK(5, 0) #define STATUS_3_REG 0x39 #define STATUS_CHG_BIT BIT(7) #define STATUS_PRECHG_CURRENT_MASK SMB1351_MASK(6, 4) #define STATUS_FAST_CHG_CURRENT_MASK SMB1351_MASK(3, 0) #define STATUS_4_REG 0x3A #define STATUS_OTG_BIT BIT(7) #define STATUS_AFVC_BIT BIT(6) #define STATUS_DONE_BIT BIT(5) #define STATUS_BATT_LESS_THAN_2V_BIT BIT(4) #define STATUS_HOLD_OFF_BIT BIT(3) #define STATUS_CHG_MASK SMB1351_MASK(2, 1) #define STATUS_NO_CHARGING 0 #define STATUS_FAST_CHARGING 0x4 #define STATUS_PRE_CHARGING 0x2 #define STATUS_TAPER_CHARGING 0x6 #define STATUS_CHG_EN_STATUS_BIT BIT(0) #define STATUS_5_REG 0x3B #define STATUS_SOURCE_DETECTED_MASK SMB1351_MASK(7, 0) #define STATUS_PORT_CDP 0x80 #define STATUS_PORT_DCP 0x40 #define STATUS_PORT_OTHER 0x20 #define STATUS_PORT_SDP 0x10 #define STATUS_PORT_ACA_A 0x8 #define STATUS_PORT_ACA_B 0x4 #define STATUS_PORT_ACA_C 0x2 #define STATUS_PORT_ACA_DOCK 0x1 #define STATUS_6_REG 0x3C #define STATUS_DCD_TIMEOUT_BIT BIT(7) #define STATUS_DCD_GOOD_DG_BIT BIT(6) #define STATUS_OCD_GOOD_DG_BIT BIT(5) #define STATUS_RID_ABD_DG_BIT BIT(4) #define STATUS_RID_FLOAT_STATE_MACHINE_BIT BIT(3) #define STATUS_RID_A_STATE_MACHINE_BIT BIT(2) #define STATUS_RID_B_STATE_MACHINE_BIT BIT(1) #define STATUS_RID_C_STATE_MACHINE_BIT BIT(0) #define STATUS_7_REG 0x3D #define STATUS_HVDCP_MASK SMB1351_MASK(7, 0) #define HVDCP_SEL_5V BIT(1) #define HVDCP_SEL_9V BIT(2) #define HVDCP_SEL_12V BIT(3) #define STATUS_8_REG 0x3E #define STATUS_USNIN_HV_INPUT_SEL_BIT BIT(5) #define STATUS_USBIN_LV_UNDER_INPUT_SEL_BIT BIT(4) #define STATUS_USBIN_LV_INPUT_SEL_BIT BIT(3) /* Revision register */ #define CHG_REVISION_REG 0x3F #define GUI_REVISION_MASK SMB1351_MASK(7, 4) #define DEVICE_REVISION_MASK SMB1351_MASK(3, 0) /* IRQ status registers */ #define IRQ_A_REG 0x40 #define IRQ_HOT_HARD_BIT BIT(6) #define IRQ_COLD_HARD_BIT BIT(4) #define IRQ_HOT_SOFT_BIT BIT(2) #define IRQ_COLD_SOFT_BIT BIT(0) #define IRQ_B_REG 0x41 #define IRQ_BATT_TERMINAL_REMOVED_BIT BIT(6) #define IRQ_BATT_MISSING_BIT BIT(4) #define IRQ_LOW_BATT_VOLTAGE_BIT BIT(2) #define IRQ_INTERNAL_TEMP_LIMIT_BIT BIT(0) #define IRQ_C_REG 0x42 #define IRQ_PRE_TO_FAST_VOLTAGE_BIT BIT(6) #define IRQ_RECHG_BIT BIT(4) #define IRQ_TAPER_BIT BIT(2) #define IRQ_TERM_BIT BIT(0) #define IRQ_D_REG 0x43 #define IRQ_BATT_OV_BIT BIT(6) #define IRQ_CHG_ERROR_BIT BIT(4) #define IRQ_CHG_TIMEOUT_BIT BIT(2) #define IRQ_PRECHG_TIMEOUT_BIT BIT(0) #define IRQ_E_REG 0x44 #define IRQ_USBIN_OV_BIT BIT(6) #define IRQ_USBIN_UV_BIT BIT(4) #define IRQ_AFVC_BIT BIT(2) #define IRQ_POWER_OK_BIT BIT(0) #define IRQ_F_REG 0x45 #define IRQ_OTG_OVER_CURRENT_BIT BIT(6) #define IRQ_OTG_FAIL_BIT BIT(4) #define IRQ_RID_BIT BIT(2) #define IRQ_OTG_OC_RETRY_BIT BIT(0) #define IRQ_G_REG 0x46 #define IRQ_SOURCE_DET_BIT BIT(6) #define IRQ_AICL_DONE_BIT BIT(4) #define IRQ_AICL_FAIL_BIT BIT(2) #define IRQ_CHG_INHIBIT_BIT BIT(0) #define IRQ_H_REG 0x47 #define IRQ_IC_LIMIT_STATUS_BIT BIT(5) #define IRQ_HVDCP_2P1_STATUS_BIT BIT(4) #define IRQ_HVDCP_AUTH_DONE_BIT BIT(2) #define IRQ_WDOG_TIMEOUT_BIT BIT(0) /* constants */ #define USB2_MIN_CURRENT_MA 100 #define USB2_MAX_CURRENT_MA 500 #define USB3_MIN_CURRENT_MA 150 #define USB3_MAX_CURRENT_MA 900 #define SMB1351_IRQ_REG_COUNT 8 #define SMB1351_CHG_PRE_MIN_MA 100 #define SMB1351_CHG_FAST_MIN_MA 1000 #define SMB1351_CHG_FAST_MAX_MA 4500 #define SMB1351_CHG_PRE_SHIFT 5 #define SMB1351_CHG_FAST_SHIFT 4 #define DEFAULT_BATT_CAPACITY 50 #define DEFAULT_BATT_TEMP 250 #define SUSPEND_CURRENT_MA 2 #define CHG_ITERM_200MA 0x0 #define CHG_ITERM_300MA 0x04 #define CHG_ITERM_400MA 0x08 #define CHG_ITERM_500MA 0x0C #define CHG_ITERM_600MA 0x10 #define CHG_ITERM_700MA 0x14 #define ADC_TM_WARM_COOL_THR_ENABLE ADC_TM_HIGH_LOW_THR_ENABLE enum reason { USER = BIT(0), THERMAL = BIT(1), CURRENT = BIT(2), SOC = BIT(3), PARALLEL = BIT(4), ITERM = BIT(5), }; static char *pm_batt_supplied_to[] = { "bms", }; struct smb1351_regulator { struct regulator_desc rdesc; struct regulator_dev *rdev; }; enum chip_version { SMB_UNKNOWN = 0, SMB1350, SMB1351, SMB_MAX_TYPE, }; static const char *smb1351_version_str[SMB_MAX_TYPE] = { [SMB_UNKNOWN] = "Unknown", [SMB1350] = "SMB1350", [SMB1351] = "SMB1351", }; enum workaround_flags { CHG_FORCE_ESR_WA = BIT(0), CHG_FG_NOTIFY_JEITA = BIT(1), CHG_ITERM_CHECK_SOC = BIT(2), CHG_SOC_BASED_RESUME = BIT(3), }; enum wakeup_src { I2C_ACCESS, HVDCP_DETECT, REMOVAL_DETECT, RERUN_APSD, PARALLEL_CHARGE, PARALLEL_TAPER, FORCE_ESR_PULSE, ITERM_CHECK_SOC, WAKEUP_SRC_MAX, }; #define WAKEUP_SRC_MASK GENMASK(WAKEUP_SRC_MAX, 0) struct smb1351_wakeup_source { struct wakeup_source source; unsigned long enabled_bitmap; spinlock_t ws_lock; }; /* parallel primary charger */ struct parallel_main_cfg { struct power_supply *psy; struct mutex lock; bool avail; bool slave_detected; int min_current_thr_ma; int min_9v_current_thr_ma; int min_12v_current_thr_ma; int allowed_lowering_ma; int main_chg_fcc_percent; int main_chg_icl_percent; int total_icl_ma; int slave_icl_ma; struct delayed_work parallel_work; }; struct smb1351_charger { struct i2c_client *client; struct device *dev; bool recharge_disabled; int recharge_mv; bool iterm_disabled; int iterm_ma; int vfloat_mv; int switch_freq; int chg_present; int fake_battery_soc; int resume_soc; bool chg_autonomous_mode; bool disable_apsd; bool using_pmic_therm; bool jeita_supported; bool fg_notify_jeita; bool battery_missing; const char *bms_psy_name; bool resume_completed; bool irq_waiting; struct delayed_work chg_remove_work; struct delayed_work hvdcp_det_work; struct delayed_work rerun_apsd_work; struct delayed_work init_fg_work; struct delayed_work iterm_check_soc_work; struct smb1351_wakeup_source smb1351_ws; /* status tracking */ bool batt_full; bool batt_hot; bool batt_cold; bool batt_warm; bool batt_cool; int battchg_disabled_status; int usb_suspended_status; int target_fastchg_current_max_ma; int fastchg_current_max_ma; int main_fcc_ma_before_esr; int slave_fcc_ma_before_esr; int workaround_flags; int parallel_pin_polarity_setting; bool is_slave; bool use_external_fg; bool parallel_charger_present; bool bms_controlled_charging; bool apsd_rerun; bool usbin_ov; bool chg_remove_work_scheduled; bool force_hvdcp_2p0; bool check_parallel; bool in_esr_pulse; enum chip_version version; u32 wa_flags; int pre_soc; /* psy */ struct power_supply *usb_psy; int usb_psy_ma; enum power_supply_type usb_psy_type; struct power_supply *bms_psy; struct power_supply batt_psy; struct power_supply parallel_psy; struct smb1351_regulator otg_vreg; struct mutex irq_complete; struct mutex fcc_lock; struct dentry *debug_root; u32 peek_poke_address; /* adc_tm parameters */ struct qpnp_vadc_chip *vadc_dev; struct qpnp_adc_tm_chip *adc_tm_dev; struct qpnp_adc_tm_btm_param adc_param; /* jeita parameters */ int batt_hot_decidegc; int batt_cold_decidegc; int batt_warm_decidegc; int batt_cool_decidegc; int batt_missing_decidegc; unsigned int batt_warm_ma; unsigned int batt_warm_mv; unsigned int batt_cool_ma; unsigned int batt_cool_mv; /* pinctrl parameters */ const char *pinctrl_state_name; struct pinctrl *smb_pinctrl; /* parallel primary */ struct parallel_main_cfg parallel; }; struct smb_irq_info { const char *name; int (*smb_irq)(struct smb1351_charger *chip, u8 rt_stat); int high; int low; }; struct irq_handler_info { u8 stat_reg; u8 val; u8 prev_val; struct smb_irq_info irq_info[4]; }; /* USB input charge current */ static int usb_chg_current[] = { 500, 685, 1000, 1100, 1200, 1300, 1500, 1600, 1700, 1800, 2000, 2200, 2500, 3000, }; static int fast_chg_current[] = { 1000, 1200, 1400, 1600, 1800, 2000, 2200, 2400, 2600, 2800, 3000, 3400, 3600, 3800, 4000, 4640, }; static int pre_chg_current[] = { 200, 300, 400, 500, 600, 700, }; struct battery_status { bool batt_hot; bool batt_warm; bool batt_cool; bool batt_cold; bool batt_present; }; enum { BATT_HOT = 0, BATT_WARM, BATT_NORMAL, BATT_COOL, BATT_COLD, BATT_MISSING, BATT_STATUS_MAX, }; static struct battery_status batt_s[] = { [BATT_HOT] = {1, 0, 0, 0, 1}, [BATT_WARM] = {0, 1, 0, 0, 1}, [BATT_NORMAL] = {0, 0, 0, 0, 1}, [BATT_COOL] = {0, 0, 1, 0, 1}, [BATT_COLD] = {0, 0, 0, 1, 1}, [BATT_MISSING] = {0, 0, 0, 1, 0}, }; static void smb1351_stay_awake(struct smb1351_wakeup_source *source, enum wakeup_src wk_src) { unsigned long flags; spin_lock_irqsave(&source->ws_lock, flags); if (!__test_and_set_bit(wk_src, &source->enabled_bitmap)) __pm_stay_awake(&source->source); spin_unlock_irqrestore(&source->ws_lock, flags); } static void smb1351_relax(struct smb1351_wakeup_source *source, enum wakeup_src wk_src) { unsigned long flags; spin_lock_irqsave(&source->ws_lock, flags); if (__test_and_clear_bit(wk_src, &source->enabled_bitmap) && !(source->enabled_bitmap & WAKEUP_SRC_MASK)) { __pm_relax(&source->source); } spin_unlock_irqrestore(&source->ws_lock, flags); } static void smb1351_wakeup_src_init(struct smb1351_charger *chip) { spin_lock_init(&chip->smb1351_ws.ws_lock); wakeup_source_init(&chip->smb1351_ws.source, "smb1351"); } static int smb1351_read_reg(struct smb1351_charger *chip, int reg, u8 *val) { s32 ret; smb1351_stay_awake(&chip->smb1351_ws, I2C_ACCESS); ret = i2c_smbus_read_byte_data(chip->client, reg); if (ret < 0) { pr_err("i2c read fail: can't read from %02x: %d\n", reg, ret); smb1351_relax(&chip->smb1351_ws, I2C_ACCESS); return ret; } else { *val = ret; } smb1351_relax(&chip->smb1351_ws, I2C_ACCESS); pr_debug("Reading 0x%02x=0x%02x\n", reg, *val); return 0; } static int smb1351_write_reg(struct smb1351_charger *chip, int reg, u8 val) { s32 ret; smb1351_stay_awake(&chip->smb1351_ws, I2C_ACCESS); ret = i2c_smbus_write_byte_data(chip->client, reg, val); if (ret < 0) { pr_err("i2c write fail: can't write %02x to %02x: %d\n", val, reg, ret); smb1351_relax(&chip->smb1351_ws, I2C_ACCESS); return ret; } smb1351_relax(&chip->smb1351_ws, I2C_ACCESS); pr_debug("Writing 0x%02x=0x%02x\n", reg, val); return 0; } static int smb1351_masked_write(struct smb1351_charger *chip, int reg, u8 mask, u8 val) { s32 rc; u8 temp; rc = smb1351_read_reg(chip, reg, &temp); if (rc) { pr_err("read failed: reg=%03X, rc=%d\n", reg, rc); return rc; } temp &= ~mask; temp |= val & mask; rc = smb1351_write_reg(chip, reg, temp); if (rc) { pr_err("write failed: reg=%03X, rc=%d\n", reg, rc); return rc; } return 0; } static int smb1351_enable_volatile_writes(struct smb1351_charger *chip) { int rc; rc = smb1351_masked_write(chip, CMD_I2C_REG, CMD_BQ_CFG_ACCESS_BIT, CMD_BQ_CFG_ACCESS_BIT); if (rc) pr_err("Couldn't write CMD_BQ_CFG_ACCESS_BIT rc=%d\n", rc); return rc; } static int smb1351_usb_suspend(struct smb1351_charger *chip, int reason, bool suspend) { int rc = 0; int suspended; suspended = chip->usb_suspended_status; #ifdef CONFIG_LGE_PM_PARALLEL_CHARGING pr_err("reason = %d requested_suspend = %d suspended_status = %d\n", reason, suspend, suspended); #else pr_debug("reason = %d requested_suspend = %d suspended_status = %d\n", reason, suspend, suspended); #endif if (suspend == false) suspended &= ~reason; else suspended |= reason; pr_debug("new suspended_status = %d\n", suspended); rc = smb1351_masked_write(chip, CMD_INPUT_LIMIT_REG, CMD_SUSPEND_MODE_BIT, suspended ? CMD_SUSPEND_MODE_BIT : 0); if (rc) pr_err("Couldn't suspend rc = %d\n", rc); else chip->usb_suspended_status = suspended; return rc; } static int smb1351_battchg_disable(struct smb1351_charger *chip, int reason, int disable) { int rc = 0; int disabled; if (chip->chg_autonomous_mode) { pr_debug("Charger in autonomous mode\n"); return 0; } disabled = chip->battchg_disabled_status; pr_debug("reason = %d requested_disable = %d disabled_status = %d\n", reason, disable, disabled); if (disable == true) disabled |= reason; else disabled &= ~reason; pr_debug("new disabled_status = %d\n", disabled); rc = smb1351_masked_write(chip, CMD_CHG_REG, CMD_CHG_EN_BIT, disabled ? 0 : CMD_CHG_ENABLE); if (rc) pr_err("Couldn't %s battery-charging rc=%d\n", disable ? "disable" : "enable", rc); else chip->battchg_disabled_status = disabled; return rc; } #define INPUT_MODE_HC 0x00 #define INPUT_MODE_USB100 (0x01 << 5) #define INPUT_MODE_USB500 (0x02 << 5) static int smb1351_get_usb_chg_current(struct smb1351_charger *chip, int *icl_ma) { int rc, i; bool is_usb3; u8 icl_status, usb_mode; rc = smb1351_read_reg(chip, STATUS_0_REG, &icl_status); if (rc) { pr_err("read STATUS_0 failed, rc=%d\n", rc); return rc; } if (icl_status & STATUS_INPUT_SUSPEND) { pr_debug("USB suspended!\n"); *icl_ma = 0; return rc; } rc = smb1351_read_reg(chip, CMD_INPUT_LIMIT_REG, &usb_mode); if (rc) { pr_err("read CMD_IL failed, rc=%d\n", rc); return rc; } is_usb3 = !!(usb_mode & CMD_USB_2_3_SEL_BIT); switch (icl_status & STATUS_INPUT_MODE_MASK) { case INPUT_MODE_USB100: if (is_usb3) *icl_ma = USB3_MIN_CURRENT_MA; else *icl_ma = USB2_MIN_CURRENT_MA; break; case INPUT_MODE_USB500: if (is_usb3) *icl_ma = USB3_MAX_CURRENT_MA; else *icl_ma = USB2_MAX_CURRENT_MA; break; case INPUT_MODE_HC: i = icl_status & STATUS_INPUT_CURRENT_LIMIT_MASK; if (i >= ARRAY_SIZE(usb_chg_current)) i = ARRAY_SIZE(usb_chg_current) - 1; *icl_ma = usb_chg_current[i]; break; default: break; } pr_debug("USB ICL status: %d\n", *icl_ma); return rc; } static int smb1351_set_usb_chg_current(struct smb1351_charger *chip, int current_ma) { int i, rc = 0, icl_result_ma = 0; u8 reg = 0, mask = 0; pr_debug("USB current_ma = %d\n", current_ma); if (chip->chg_autonomous_mode) { pr_debug("Charger in autonomous mode\n"); return 0; } /* set suspend bit when urrent_ma <= 2 */ if (current_ma <= SUSPEND_CURRENT_MA) { smb1351_usb_suspend(chip, CURRENT, true); pr_debug("USB suspend\n"); return 0; } if (current_ma > SUSPEND_CURRENT_MA && current_ma < USB2_MIN_CURRENT_MA) current_ma = USB2_MIN_CURRENT_MA; if (current_ma == USB2_MIN_CURRENT_MA) { /* USB 2.0 - 100mA */ reg = CMD_USB_2_MODE | CMD_USB_100_MODE; } else if (current_ma == USB3_MIN_CURRENT_MA) { /* USB 3.0 - 150mA */ reg = CMD_USB_3_MODE | CMD_USB_100_MODE; } else if (current_ma == USB2_MAX_CURRENT_MA) { /* USB 2.0 - 500mA */ reg = CMD_USB_2_MODE | CMD_USB_500_MODE; } else if (current_ma == USB3_MAX_CURRENT_MA) { /* USB 3.0 - 900mA */ reg = CMD_USB_3_MODE | CMD_USB_500_MODE; } else if (current_ma > USB2_MAX_CURRENT_MA) { /* HC mode - if none of the above */ reg = CMD_USB_HC_MODE; rc = smb1351_get_usb_chg_current(chip, &icl_result_ma); if (rc) { pr_err("Get ICL result failed, rc=%d\n", rc); return rc; } for (i = ARRAY_SIZE(usb_chg_current) - 1; i >= 0; i--) { if (usb_chg_current[i] <= current_ma) break; } if (i < 0) i = 0; rc = smb1351_masked_write(chip, CHG_CURRENT_CTRL_REG, AC_INPUT_CURRENT_LIMIT_MASK, i); if (rc) { pr_err("Couldn't set input mA rc=%d\n", rc); return rc; } current_ma = usb_chg_current[i]; } /* control input current mode by command */ reg |= CMD_INPUT_CURRENT_MODE_CMD; mask = CMD_INPUT_CURRENT_MODE_BIT | CMD_USB_2_3_SEL_BIT | CMD_USB_1_5_AC_CTRL_MASK; rc = smb1351_masked_write(chip, CMD_INPUT_LIMIT_REG, mask, reg); if (rc) { pr_err("Couldn't set charging mode rc = %d\n", rc); return rc; } /* unset the suspend bit here */ smb1351_usb_suspend(chip, CURRENT, false); /* * AICL couldn't be rerun if the current being set is larger * than the ICL result. Configure it to USB500 mode first * and then to USB_HC mode to force AICL rerun. */ if ((icl_result_ma < current_ma) && (reg & CMD_USB_HC_MODE)) { rc = smb1351_masked_write(chip, CMD_INPUT_LIMIT_REG, mask, CMD_USB_2_MODE | CMD_USB_500_MODE | CMD_INPUT_CURRENT_MODE_CMD); if (rc) { pr_err("Set USB500 for AICL rerun failed, rc=%d\n", rc); return rc; } rc = smb1351_masked_write(chip, CMD_INPUT_LIMIT_REG, mask, reg); if (rc) { pr_err("Set USBAC for AICL rerun failed, rc=%d\n", rc); return rc; } } return rc; } static int smb1351_fastchg_current_set(struct smb1351_charger *chip, unsigned int fastchg_current) { int i, rc; bool is_pre_chg = false; #ifdef CONFIG_LGE_PM_PARALLEL_CHARGING pr_err("%s - fastchg_current[%d]\n", __func__, fastchg_current); #endif mutex_lock(&chip->fcc_lock); if (fastchg_current < SMB1351_CHG_PRE_MIN_MA) fastchg_current = SMB1351_CHG_PRE_MIN_MA; if (fastchg_current > SMB1351_CHG_FAST_MAX_MA) fastchg_current = SMB1351_CHG_FAST_MAX_MA; pr_debug("set fastchg current mA=%d\n", fastchg_current); /* * fast chg current could not support less than 1000mA * use pre chg to instead for the parallel charging */ if (fastchg_current < SMB1351_CHG_FAST_MIN_MA) { is_pre_chg = true; pr_debug("is_pre_chg true, current is %d\n", fastchg_current); } if (is_pre_chg) { /* set prechg current */ for (i = ARRAY_SIZE(pre_chg_current) - 1; i >= 0; i--) { if (pre_chg_current[i] <= fastchg_current) break; } if (i < 0) i = 0; chip->fastchg_current_max_ma = pre_chg_current[i]; pr_debug("prechg setting %02x\n", i); i = i << SMB1351_CHG_PRE_SHIFT; rc = smb1351_masked_write(chip, CHG_OTH_CURRENT_CTRL_REG, PRECHG_CURRENT_MASK, i); if (rc) pr_err("Couldn't write CHG_OTH_CURRENT_CTRL_REG rc=%d\n", rc); rc = smb1351_masked_write(chip, VARIOUS_FUNC_2_REG, PRECHG_TO_FASTCHG_BIT, PRECHG_TO_FASTCHG_BIT); if (rc) pr_err("Write VARIOUS_FUNC_2_REG failed, rc=%d\n", rc); } else { if (chip->version == SMB_UNKNOWN) { rc = -EINVAL; goto done; } /* SMB1350 supports FCC upto 2600 mA */ if (chip->version == SMB1350 && fastchg_current > 2600) fastchg_current = 2600; /* set fastchg current */ for (i = ARRAY_SIZE(fast_chg_current) - 1; i >= 0; i--) { if (fast_chg_current[i] <= fastchg_current) break; } if (i < 0) i = 0; chip->fastchg_current_max_ma = fast_chg_current[i]; i = i << SMB1351_CHG_FAST_SHIFT; pr_debug("fastchg limit=%d setting %02x\n", chip->fastchg_current_max_ma, i); /* make sure pre chg mode is disabled */ rc = smb1351_masked_write(chip, VARIOUS_FUNC_2_REG, PRECHG_TO_FASTCHG_BIT, 0); if (rc) pr_err("Couldn't write VARIOUS_FUNC_2_REG rc=%d\n", rc); rc = smb1351_masked_write(chip, CHG_CURRENT_CTRL_REG, FAST_CHG_CURRENT_MASK, i); if (rc) pr_err("Write CURRENT_CTRL_REG failed, rc=%d\n", rc); } done: mutex_unlock(&chip->fcc_lock); return rc; } #define MIN_FLOAT_MV 3500 #define MAX_FLOAT_MV 4500 #define VFLOAT_STEP_MV 20 static int smb1351_float_voltage_set(struct smb1351_charger *chip, int vfloat_mv) { u8 temp; if ((vfloat_mv < MIN_FLOAT_MV) || (vfloat_mv > MAX_FLOAT_MV)) { pr_err("bad float voltage mv =%d asked to set\n", vfloat_mv); return -EINVAL; } temp = (vfloat_mv - MIN_FLOAT_MV) / VFLOAT_STEP_MV; return smb1351_masked_write(chip, VFLOAT_REG, VFLOAT_MASK, temp); } static int smb1351_chg_set_appropriate_battery_current( struct smb1351_charger *chip) { int rc; unsigned int current_max = chip->target_fastchg_current_max_ma; if (chip->batt_cool) current_max = min(current_max, chip->batt_cool_ma); if (chip->batt_warm) current_max = min(current_max, chip->batt_warm_ma); pr_debug("setting FCC to %dmA", current_max); rc = smb1351_fastchg_current_set(chip, current_max); if (rc) pr_err("Couldn't set charging current rc = %d\n", rc); return rc; } static int smb1351_chg_set_appropriate_vfloat(struct smb1351_charger *chip) { int rc; unsigned int vfloat = chip->vfloat_mv; if (chip->batt_cool) vfloat = min(vfloat, chip->batt_cool_mv); if (chip->batt_warm) vfloat = min(vfloat, chip->batt_warm_mv); pr_debug("setting vfloat to %dmV\n", vfloat); rc = smb1351_float_voltage_set(chip, vfloat); if (rc) pr_err("Couldn't set float voltage rc = %d\n", rc); return rc; } static int smb1351_iterm_set(struct smb1351_charger *chip, int iterm_ma) { int rc; u8 reg; if (iterm_ma <= 200) reg = CHG_ITERM_200MA; else if (iterm_ma <= 300) reg = CHG_ITERM_300MA; else if (iterm_ma <= 400) reg = CHG_ITERM_400MA; else if (iterm_ma <= 500) reg = CHG_ITERM_500MA; else if (iterm_ma <= 600) reg = CHG_ITERM_600MA; else reg = CHG_ITERM_700MA; rc = smb1351_masked_write(chip, CHG_OTH_CURRENT_CTRL_REG, ITERM_MASK, reg); if (rc) { pr_err("Couldn't set iterm rc = %d\n", rc); return rc; } /* enable the iterm */ rc = smb1351_masked_write(chip, CHG_CTRL_REG, ITERM_EN_BIT, ITERM_ENABLE); if (rc) { pr_err("Couldn't enable iterm rc = %d\n", rc); return rc; } return 0; } #define N_TYPE_BIT 8 static int smb1351_get_usb_supply_type(struct smb1351_charger *chip, enum power_supply_type *type) { int rc, index; u8 reg; static const char * const usb_ps_type_str[] = { "ACA_DOCK", "ACA_C", "ACA_B", "ACA_A", "SDP", "OTHER", "DCP", "CDP", }; rc = smb1351_read_reg(chip, STATUS_5_REG, &reg); if (rc) { pr_err("Couldn't read STATUS_5 rc = %d\n", rc); return rc; } switch (reg) { case STATUS_PORT_ACA_DOCK: case STATUS_PORT_ACA_C: case STATUS_PORT_ACA_B: case STATUS_PORT_ACA_A: *type = POWER_SUPPLY_TYPE_USB_ACA; break; case STATUS_PORT_CDP: *type = POWER_SUPPLY_TYPE_USB_CDP; break; case STATUS_PORT_DCP: *type = POWER_SUPPLY_TYPE_USB_DCP; break; case STATUS_PORT_SDP: *type = POWER_SUPPLY_TYPE_USB; break; case STATUS_PORT_OTHER: *type = POWER_SUPPLY_TYPE_USB_DCP; break; default: *type = POWER_SUPPLY_TYPE_UNKNOWN; break; } if (*type == POWER_SUPPLY_TYPE_UNKNOWN) { pr_debug("Can't get correct power supply type!"); } else { index = find_first_bit((unsigned long *)&reg, N_TYPE_BIT); pr_debug("STATUS_5_REG(0x3B)=%x, USB type = %s\n", reg, usb_ps_type_str[index]); } return rc; } static int smb1351_set_bms_property(struct smb1351_charger *chip, enum power_supply_property prop, int value) { int rc; union power_supply_propval propval = {0, }; if (chip->bms_psy_name && !chip->bms_psy) chip->bms_psy = power_supply_get_by_name((char *)chip->bms_psy_name); if (IS_ERR_OR_NULL(chip->bms_psy)) { pr_debug("BMS(fg) power supply not present\n"); return -ENODEV; } propval.intval = value; rc = chip->bms_psy->set_property(chip->bms_psy, prop, &propval); if (rc) { pr_err("Set BMS property %d failed, rc=%d\n", prop, rc); return rc; } return rc; } static int smb1351_get_bms_property(struct smb1351_charger *chip, enum power_supply_property prop, int *val) { int rc; union power_supply_propval propval = {0, }; if (chip->bms_psy_name && !chip->bms_psy) chip->bms_psy = power_supply_get_by_name((char *)chip->bms_psy_name); if (IS_ERR_OR_NULL(chip->bms_psy)) { pr_debug("BMS(fg) power supply not present\n"); return -ENODEV; } rc = chip->bms_psy->get_property(chip->bms_psy, prop, &propval); if (rc) { pr_err("Set BMS property %d failed, rc=%d\n", prop, rc); return rc; } *val = propval.intval; return rc; } static int smb1351_chg_otg_regulator_enable(struct regulator_dev *rdev) { int rc = 0; struct smb1351_charger *chip = rdev_get_drvdata(rdev); rc = smb1351_masked_write(chip, CMD_CHG_REG, CMD_OTG_EN_BIT, CMD_OTG_EN_BIT); if (rc) pr_err("Couldn't enable OTG mode rc=%d\n", rc); return rc; } static int smb1351_chg_otg_regulator_disable(struct regulator_dev *rdev) { int rc = 0; struct smb1351_charger *chip = rdev_get_drvdata(rdev); rc = smb1351_masked_write(chip, CMD_CHG_REG, CMD_OTG_EN_BIT, 0); if (rc) pr_err("Couldn't disable OTG mode rc=%d\n", rc); return rc; } static int smb1351_chg_otg_regulator_is_enable(struct regulator_dev *rdev) { int rc = 0; u8 reg = 0; struct smb1351_charger *chip = rdev_get_drvdata(rdev); rc = smb1351_read_reg(chip, CMD_CHG_REG, &reg); if (rc) { pr_err("Couldn't read OTG enable bit rc=%d\n", rc); return rc; } return (reg & CMD_OTG_EN_BIT) ? 1 : 0; } struct regulator_ops smb1351_chg_otg_reg_ops = { .enable = smb1351_chg_otg_regulator_enable, .disable = smb1351_chg_otg_regulator_disable, .is_enabled = smb1351_chg_otg_regulator_is_enable, }; static int smb1351_regulator_init(struct smb1351_charger *chip) { int rc = 0; struct regulator_init_data *init_data; struct regulator_config cfg = {}; init_data = of_get_regulator_init_data(chip->dev, chip->dev->of_node); if (!init_data) { pr_err("Unable to allocate memory\n"); return -ENOMEM; } if (init_data->constraints.name) { chip->otg_vreg.rdesc.owner = THIS_MODULE; chip->otg_vreg.rdesc.type = REGULATOR_VOLTAGE; chip->otg_vreg.rdesc.ops = &smb1351_chg_otg_reg_ops; chip->otg_vreg.rdesc.name = init_data->constraints.name; cfg.dev = chip->dev; cfg.init_data = init_data; cfg.driver_data = chip; cfg.of_node = chip->dev->of_node; init_data->constraints.valid_ops_mask |= REGULATOR_CHANGE_STATUS; chip->otg_vreg.rdev = regulator_register( &chip->otg_vreg.rdesc, &cfg); if (IS_ERR(chip->otg_vreg.rdev)) { rc = PTR_ERR(chip->otg_vreg.rdev); chip->otg_vreg.rdev = NULL; if (rc != -EPROBE_DEFER) pr_err("OTG reg failed, rc=%d\n", rc); } } return rc; } static int smb_chip_get_version(struct smb1351_charger *chip) { u8 ver; int rc = 0; if (chip->version == SMB_UNKNOWN) { rc = smb1351_read_reg(chip, VERSION_REG, &ver); if (rc) { pr_err("Couldn't read version rc=%d\n", rc); return rc; } /* If bit 1 is set, it is SMB1350 */ if (ver & VERSION_MASK) chip->version = SMB1350; else chip->version = SMB1351; } return rc; } #define INIT_FG_RETRY_MS 1000 static int smb1351_hw_init(struct smb1351_charger *chip) { int rc; u8 reg = 0, mask = 0; /* configure smb_pinctrl to enable irqs */ if (chip->pinctrl_state_name) { chip->smb_pinctrl = pinctrl_get_select(chip->dev, chip->pinctrl_state_name); if (IS_ERR(chip->smb_pinctrl)) { pr_err("Could not get/set %s pinctrl state rc = %ld\n", chip->pinctrl_state_name, PTR_ERR(chip->smb_pinctrl)); return PTR_ERR(chip->smb_pinctrl); } } /* * If the charger is pre-configured for autonomous operation, * do not apply additional settings */ if (chip->chg_autonomous_mode) { pr_debug("Charger configured for autonomous mode\n"); return 0; } rc = smb_chip_get_version(chip); if (rc) { pr_err("Couldn't get version rc = %d\n", rc); return rc; } rc = smb1351_enable_volatile_writes(chip); if (rc) { pr_err("Couldn't configure volatile writes rc=%d\n", rc); return rc; } /* Enable charging before we move into register based CHG_EN control */ rc = smb1351_battchg_disable(chip, USER, chip->usb_suspended_status); if (rc) return rc; /* setup battery missing source */ reg = BATT_MISSING_THERM_PIN_SOURCE_BIT; mask = BATT_MISSING_THERM_PIN_SOURCE_BIT; rc = smb1351_masked_write(chip, HVDCP_BATT_MISSING_CTRL_REG, mask, reg); if (rc) { pr_err("Couldn't set HVDCP_BATT_MISSING_CTRL_REG rc=%d\n", rc); return rc; } /* setup defaults for CHG_PIN_EN_CTRL_REG */ reg = EN_BY_I2C_0_DISABLE | USBCS_CTRL_BY_I2C | CHG_ERR_BIT | APSD_DONE_BIT | LED_BLINK_FUNC_BIT; mask = EN_PIN_CTRL_MASK | USBCS_CTRL_BIT | CHG_ERR_BIT | APSD_DONE_BIT | LED_BLINK_FUNC_BIT; rc = smb1351_masked_write(chip, CHG_PIN_EN_CTRL_REG, mask, reg); if (rc) { pr_err("Couldn't set CHG_PIN_EN_CTRL_REG rc=%d\n", rc); return rc; } /* setup USB 2.0/3.0 detection and USB 500/100 command polarity */ reg = USB_2_3_MODE_SEL_BY_I2C | USB_CMD_POLARITY_500_1_100_0; mask = USB_2_3_MODE_SEL_BIT | USB_5_1_CMD_POLARITY_BIT; rc = smb1351_masked_write(chip, CHG_OTH_CURRENT_CTRL_REG, mask, reg); if (rc) { pr_err("Couldn't set CHG_OTH_CURRENT_CTRL_REG rc=%d\n", rc); return rc; } /* setup USB suspend, AICL and APSD */ reg = SUSPEND_MODE_CTRL_BY_I2C | AICL_EN_BIT; if (!chip->disable_apsd) reg |= APSD_EN_BIT; mask = SUSPEND_MODE_CTRL_BIT | AICL_EN_BIT | APSD_EN_BIT; rc = smb1351_masked_write(chip, VARIOUS_FUNC_REG, mask, reg); if (rc) { pr_err("Couldn't set VARIOUS_FUNC_REG rc=%d\n", rc); return rc; } /* Fault and Status IRQ configuration */ reg = HOT_COLD_HARD_LIMIT_BIT | HOT_COLD_SOFT_LIMIT_BIT | OTG_OC_BIT | INPUT_OVLO_BIT | INPUT_UVLO_BIT | AICL_DONE_FAIL_BIT; rc = smb1351_write_reg(chip, FAULT_INT_CFG_REG, reg); if (rc) { pr_err("Couldn't set FAULT_INT_CFG_REG rc=%d\n", rc); return rc; } reg = CHG_OR_PRECHG_TIMEOUT_BIT | RID_CHANGE_BIT | BATT_OVP_BIT | FAST_TERM_TAPER_RECHG_INHIBIT_BIT | BATT_MISSING_BIT | BATT_LOW_BIT; rc = smb1351_write_reg(chip, STATUS_INT_CFG_REG, reg); if (rc) { pr_err("Couldn't set STATUS_INT_CFG_REG rc=%d\n", rc); return rc; } /* setup THERM Monitor */ if (!chip->using_pmic_therm) { rc = smb1351_masked_write(chip, THERM_A_CTRL_REG, THERM_MONITOR_BIT, THERM_MONITOR_EN); if (rc) { pr_err("Couldn't set THERM_A_CTRL_REG rc=%d\n", rc); return rc; } } /* set the fast charge current limit */ rc = smb1351_fastchg_current_set(chip, chip->target_fastchg_current_max_ma); if (rc) { pr_err("Couldn't set fastchg current rc=%d\n", rc); return rc; } /* set the float voltage */ if (chip->vfloat_mv != -EINVAL) { rc = smb1351_float_voltage_set(chip, chip->vfloat_mv); if (rc) { pr_err("Couldn't set float voltage rc = %d\n", rc); return rc; } } /* set iterm */ if (chip->iterm_ma != -EINVAL) { if (chip->iterm_disabled) { pr_err("Error: Both iterm_disabled and iterm_ma set\n"); return -EINVAL; } else { rc = smb1351_iterm_set(chip, chip->iterm_ma); if (rc) { pr_err("Couldn't set iterm rc = %d\n", rc); return rc; } } } else if (chip->iterm_disabled) { rc = smb1351_masked_write(chip, CHG_CTRL_REG, ITERM_EN_BIT, ITERM_DISABLE); if (rc) { pr_err("Couldn't set iterm rc = %d\n", rc); return rc; } } /* set recharge-threshold */ if (chip->recharge_mv != -EINVAL) { if (chip->recharge_disabled) { pr_err("Error: Both recharge_disabled and recharge_mv set\n"); return -EINVAL; } else { reg = AUTO_RECHG_ENABLE; if (chip->recharge_mv > 50) reg |= AUTO_RECHG_TH_100MV; else reg |= AUTO_RECHG_TH_50MV; rc = smb1351_masked_write(chip, CHG_CTRL_REG, AUTO_RECHG_BIT | AUTO_RECHG_TH_BIT, reg); if (rc) { pr_err("Couldn't set rechg-cfg rc = %d\n", rc); return rc; } } } else if (chip->recharge_disabled || (chip->wa_flags & CHG_SOC_BASED_RESUME)) { rc = smb1351_masked_write(chip, CHG_CTRL_REG, AUTO_RECHG_BIT, AUTO_RECHG_DISABLE); if (rc) { pr_err("Couldn't disable auto-rechg rc = %d\n", rc); return rc; } } /* Update switching frequency based on device tree entry */ if (chip->switch_freq != -EINVAL) { rc = smb1351_masked_write(chip, OTG_TLIM_CTRL_REG, SWITCH_FREQ_MASK, (chip->switch_freq << SWITCH_FREQ_SHIFT)); if (rc) { pr_err("Set switching frequency failed, r=%d\n", rc); return rc; } } /* set STAT pin behavior: active low, indicate charging status */ rc = smb1351_masked_write(chip, CHG_STAT_TIMERS_CTRL_REG, STAT_OUTPUT_POLARITY_BIT | STAT_OUTPUT_MODE_BIT | STAT_OUTPUT_CTRL_BIT, 0); if (rc) { pr_err("Set STAT pin polarity failed, r=%d\n", rc); return rc; } if (chip->parallel.avail) { rc = smb1351_masked_write(chip, PON_OPTIONS_REG, SYSOK_INOK_POLARITY_BIT | SYSOK_OPTIONS_MASK, SYSOK_INOK_POLARITY_INVERT | SYSOK_INOK_OPTION1); if (rc) { pr_err("Program PON option failed, rc=%d\n", rc); return rc; } } if (chip->use_external_fg) { rc = smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_IGNORE_FALSE_NEGATIVE_ISENSE, 0); if (rc) { pr_debug("set IGNORE_FALSE_NEGATIVE_ISENSE failed, rc=%d\n", rc); /* start a delay worker to do it again if failed */ schedule_delayed_work(&chip->init_fg_work, msecs_to_jiffies(INIT_FG_RETRY_MS)); } else if (chip->fg_notify_jeita) { rc = smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_ENABLE_JEITA_DETECTION, 1); if (rc) { pr_err("Set ENABLE_JEITA_DETECTION failed, rc=%d\n", rc); return rc; } } } /* Enable HVDCP */ rc = smb1351_masked_write(chip, HVDCP_BATT_MISSING_CTRL_REG, HVDCP_EN_BIT, HVDCP_EN_BIT); if (rc) { pr_err("Failed to enable HVDCP, rc=%d\n", rc); return rc; } /* enable/disable charging by suspending usb */ rc = smb1351_usb_suspend(chip, USER, chip->usb_suspended_status); if (rc) { pr_err("Unable to %s USB input. rc=%d\n", chip->usb_suspended_status ? "suspend" : "enable", rc); return rc; } rc = smb1351_battchg_disable(chip, USER, chip->usb_suspended_status); if (rc) pr_err("Couldn't %s charging rc = %d\n", chip->usb_suspended_status ? "disable" : "enable", rc); return rc; } static enum power_supply_property smb1351_battery_properties[] = { POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_CHARGING_ENABLED, POWER_SUPPLY_PROP_BATTERY_CHARGING_ENABLED, POWER_SUPPLY_PROP_CHARGE_TYPE, POWER_SUPPLY_PROP_CAPACITY, POWER_SUPPLY_PROP_HEALTH, POWER_SUPPLY_PROP_TEMP, POWER_SUPPLY_PROP_TECHNOLOGY, POWER_SUPPLY_PROP_MODEL_NAME, }; static int smb1351_get_prop_batt_status(struct smb1351_charger *chip) { int rc; u8 reg = 0; if (chip->batt_full) return POWER_SUPPLY_STATUS_FULL; rc = smb1351_read_reg(chip, STATUS_4_REG, &reg); if (rc) { pr_err("Couldn't read STATUS_4 rc = %d\n", rc); return POWER_SUPPLY_STATUS_UNKNOWN; } pr_debug("STATUS_4_REG(0x3A)=%x\n", reg); if (reg & STATUS_HOLD_OFF_BIT) return POWER_SUPPLY_STATUS_NOT_CHARGING; if (reg & STATUS_CHG_MASK) return POWER_SUPPLY_STATUS_CHARGING; return POWER_SUPPLY_STATUS_DISCHARGING; } static int smb1351_get_prop_batt_present(struct smb1351_charger *chip) { return !chip->battery_missing; } static int smb1351_get_prop_batt_capacity(struct smb1351_charger *chip) { int rc = 0, soc = 0; if (chip->fake_battery_soc >= 0) return chip->fake_battery_soc; rc = smb1351_get_bms_property(chip, POWER_SUPPLY_PROP_CAPACITY, &soc); if (rc) { pr_debug("Get capacity from BMS failed, rc=%d\n", rc); return DEFAULT_BATT_CAPACITY; } pr_debug("SoC = %d\n", soc); return soc; } static int smb1351_get_prop_batt_temp(struct smb1351_charger *chip) { int rc = 0, temp = 0; struct qpnp_vadc_result results; rc = smb1351_get_bms_property(chip, POWER_SUPPLY_PROP_TEMP, &temp); if (rc) { temp = DEFAULT_BATT_TEMP; pr_debug("Get tempertory from BMS failed, rc=%d\n", rc); } if (chip->vadc_dev) { rc = qpnp_vadc_read(chip->vadc_dev, LR_MUX1_BATT_THERM, &results); if (rc) pr_debug("Unable to read adc batt temp rc=%d\n", rc); else temp = (int)results.physical; } pr_debug("temperature: %d\n", temp); return temp; } static int smb1351_get_prop_charge_type(struct smb1351_charger *chip) { int rc; u8 reg = 0; rc = smb1351_read_reg(chip, STATUS_4_REG, &reg); if (rc) { pr_err("Couldn't read STATUS_4 rc = %d\n", rc); return POWER_SUPPLY_CHARGE_TYPE_UNKNOWN; } pr_debug("STATUS_4_REG(0x3A)=%x\n", reg); reg &= STATUS_CHG_MASK; if (reg == STATUS_FAST_CHARGING) return POWER_SUPPLY_CHARGE_TYPE_FAST; else if (reg == STATUS_TAPER_CHARGING) return POWER_SUPPLY_CHARGE_TYPE_TAPER; else if (reg == STATUS_PRE_CHARGING) return POWER_SUPPLY_CHARGE_TYPE_TRICKLE; else return POWER_SUPPLY_CHARGE_TYPE_NONE; } static int smb1351_get_prop_batt_health(struct smb1351_charger *chip) { union power_supply_propval ret = {0, }; if (chip->batt_hot) ret.intval = POWER_SUPPLY_HEALTH_OVERHEAT; else if (chip->batt_cold) ret.intval = POWER_SUPPLY_HEALTH_COLD; else if (chip->batt_warm) ret.intval = POWER_SUPPLY_HEALTH_WARM; else if (chip->batt_cool) ret.intval = POWER_SUPPLY_HEALTH_COOL; else ret.intval = POWER_SUPPLY_HEALTH_GOOD; return ret.intval; } static int smb1351_get_usbid_status(struct smb1351_charger *chip, bool *gnd) { int rc; u8 regval; rc = smb1351_read_reg(chip, STATUS_6_REG, &regval); if (rc) { pr_err("Read STATUS_6 failed, rc=%d\n", rc); return rc; } *gnd = !regval; return rc; } static struct power_supply *smb1351_get_parallel_slave( struct smb1351_charger *chip) { if (!chip->parallel.avail) return NULL; if (chip->parallel.psy) return chip->parallel.psy; chip->parallel.psy = power_supply_get_by_name("usb-parallel"); if (!chip->parallel.psy) pr_debug("parallel slave not found\n"); return chip->parallel.psy; } /* * Get the mininum parallel charging current threshold according to * the voltage provided on the charger adapter */ static int smb1351_get_min_parallel_current_ma(struct smb1351_charger *chip) { int rc; u8 value; rc = smb1351_read_reg(chip, STATUS_1_REG, &value); if (rc) { pr_err("read STATUS_7_REG failed, rc = %d\n", rc); return rc; } switch (value & STATUS_INPUT_RANGE_MASK) { case STATUS_INPUT_RANGE_5V: case STATUS_INPUT_RANGE_5V_9V: rc = chip->parallel.min_current_thr_ma; break; case STATUS_INPUT_RANGE_9V: rc = chip->parallel.min_9v_current_thr_ma; break; case STATUS_INPUT_RANGE_12V: rc = chip->parallel.min_12v_current_thr_ma; break; default: rc = -EINVAL; break; } return rc; } static int smb1351_parallel_charger_disable_slave( struct smb1351_charger *chip) { int rc; struct power_supply *parallel_psy = smb1351_get_parallel_slave(chip); if (!parallel_psy || !chip->parallel.slave_detected) return 0; pr_debug("Disable parallel slave!\n"); chip->parallel.total_icl_ma = 0; chip->parallel.slave_icl_ma = 0; /* Suspend USB and clear PRESENT to slave charger */ power_supply_set_current_limit(parallel_psy, SUSPEND_CURRENT_MA * 1000); power_supply_set_present(parallel_psy, false); /* Restore main charger FCC && ICL as the standalone */ rc = smb1351_chg_set_appropriate_battery_current(chip); if (rc) { pr_err("restore FCC to %d failed\n", chip->target_fastchg_current_max_ma); return rc; } rc = smb1351_set_usb_chg_current(chip, chip->usb_psy_ma); if (rc) { pr_err("restore ICL to %d failed\n", chip->usb_psy_ma); return rc; } pr_debug("Restore ICL %dmA to the main charger\n", chip->usb_psy_ma); return rc; } /* * Enable slave, and split the total input current to main charger * and the slave according to the percent. */ static int smb1351_parallel_charger_enable_slave( struct smb1351_charger *chip, int total_icl_ma) { struct power_supply *parallel_psy = smb1351_get_parallel_slave(chip); union power_supply_propval pval = {0, }; int rc, slave_icl_ma, actual_slave_icl_ma, main_icl_ma; int slave_fcc_ma, actual_slave_fcc_ma, main_fcc_ma; if (!parallel_psy || !chip->parallel.slave_detected) return 0; pr_debug("Enable parallel slave!\n"); /* * Set slave's float voltage a little high main charger * to avoid slave trigger taper before the main charger */ rc = power_supply_set_voltage_limit(parallel_psy, chip->vfloat_mv + 50); if (rc) { pr_err("Set slave VFLT failed, rc=%d\n", rc); return rc; } /* split the ICL for main and slave charger */ slave_icl_ma = total_icl_ma * (100 - chip->parallel.main_chg_icl_percent) / 100; /* set the allotted ICL for slave */ rc = power_supply_set_present(parallel_psy, true); if (rc) { pr_err("Set slave present failed, rc=%d\n", rc); return rc; } rc = power_supply_set_current_limit(parallel_psy, slave_icl_ma * 1000); if (rc) { pr_err("Set slave ICL to %dmA failed, rc=%d\n", slave_icl_ma, rc); return rc; } chip->parallel.slave_icl_ma = slave_icl_ma; /* get the ICL real set in HW */ parallel_psy->get_property(parallel_psy, POWER_SUPPLY_PROP_CURRENT_MAX, &pval); actual_slave_icl_ma = pval.intval / 1000; pr_debug("parallel slave ICL, program %d, set %d\n", slave_icl_ma, actual_slave_icl_ma); /* set the allotted ICL for main charger */ main_icl_ma = max(total_icl_ma - actual_slave_icl_ma, 0); rc = smb1351_set_usb_chg_current(chip, main_icl_ma); if (rc) { pr_err("set main charger ICL %d failed, rc=%d\n", main_icl_ma, rc); return rc; } pr_debug("ICL split, total %d: main %d, slave %d\n", total_icl_ma, main_icl_ma, actual_slave_icl_ma); /* split the FCC for main and slave charger */ slave_fcc_ma = chip->target_fastchg_current_max_ma * (100 - chip->parallel.main_chg_fcc_percent) / 100; /* set the allotted FCC to slave charger */ pval.intval = slave_fcc_ma * 1000; parallel_psy->set_property(parallel_psy, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, &pval); parallel_psy->get_property(parallel_psy, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, &pval); actual_slave_fcc_ma = pval.intval / 1000; /* set the allotted FCC to main charger */ main_fcc_ma = chip->target_fastchg_current_max_ma - actual_slave_fcc_ma; rc = smb1351_fastchg_current_set(chip, main_fcc_ma); if (rc) { pr_err("Set main charger FCC %d failed, rc=%d\n", main_fcc_ma, rc); return rc; } pr_debug("FCC split, total %d: main %d, slave %d\n", chip->target_fastchg_current_max_ma, main_fcc_ma, actual_slave_fcc_ma); return rc; } /* * Check conditions if it's able to enable the slave for parallel * charging, and also calculate the max current could be drawn from * the charger adapter. */ static bool smb1351_attempt_enable_parallel_slave( struct smb1351_charger *chip, int *ret_total_icl_ma) { struct power_supply *parallel_psy = smb1351_get_parallel_slave(chip); union power_supply_propval pval = {0, }; enum power_supply_type type; int min_icl_thr_ma, main_current_icl_ma; int slave_current_icl_ma, total_icl_ma; int rc; pr_debug("Check if it is OK to enable slave!\n"); if (!parallel_psy || !chip->parallel.slave_detected) return false; /* * Report false to disable parallel charging if NOT in fastchg mode, * only when battery is connected or parallel slave hasn't been * enabled. */ if (smb1351_get_prop_charge_type(chip) != POWER_SUPPLY_CHARGE_TYPE_FAST && (smb1351_get_prop_batt_present(chip) || chip->parallel.slave_icl_ma == 0)) { pr_debug("Not in fastchg mode, disable parallel!\n"); return false; } /* If battery health NOT good */ if (smb1351_get_prop_batt_health(chip) != POWER_SUPPLY_HEALTH_GOOD) { pr_debug("JEITA active, disable parallel!\n"); return false; } /* Only start parallel charger in DCP/HVDCP */ rc = smb1351_get_usb_supply_type(chip, &type); if (rc) { pr_err("Get USB power supply type failed, rc=%d\n", rc); return false; } else if (type == POWER_SUPPLY_TYPE_USB_CDP || type == POWER_SUPPLY_TYPE_USB) { pr_debug("USB type %d, disable parallel!\n", type); return false; } min_icl_thr_ma = smb1351_get_min_parallel_current_ma(chip); if (min_icl_thr_ma <= 0) { pr_debug("Get min ICL threshold failed, disable parallel!\n"); return false; } rc = smb1351_get_usb_chg_current(chip, &main_current_icl_ma); if (rc) { pr_debug("Get main charger ICL failed, skipping!\n"); return false; } pr_debug("main charger ICL = %d\n", main_current_icl_ma); /* * If parallel is not enabled, and main charger ICL is less than min * parallel ICL threshold, disable parallel. * Record the total ICL at 1st place. */ if (chip->parallel.total_icl_ma == 0) { if (main_current_icl_ma < min_icl_thr_ma) { pr_debug("Current ICL %d lower than threshold %d, skipping!\n", main_current_icl_ma, min_icl_thr_ma); return false; } chip->parallel.total_icl_ma = main_current_icl_ma; pr_debug("Not in parallel charging previously, total_icl = %d\n", main_current_icl_ma); } /* Check if parallel slave already draw some current */ parallel_psy->get_property(parallel_psy, POWER_SUPPLY_PROP_CURRENT_MAX, &pval); slave_current_icl_ma = pval.intval / 1000; if (slave_current_icl_ma == SUSPEND_CURRENT_MA) slave_current_icl_ma = 0; pr_debug("slave charger ICL = %d\n", slave_current_icl_ma); total_icl_ma = min(main_current_icl_ma + slave_current_icl_ma, chip->usb_psy_ma); pr_debug("calculated total ICL = %d\n", total_icl_ma); /* * If calculated total ICL is below than allowed_lowering, * disable parallel */ if (total_icl_ma < chip->parallel.total_icl_ma - chip->parallel.allowed_lowering_ma) { pr_debug("total ICL reduced to below the threshold: %d < (%d-%d)\n", total_icl_ma, chip->parallel.total_icl_ma, chip->parallel.allowed_lowering_ma); return false; } *ret_total_icl_ma = total_icl_ma; pr_debug("Final total ICL for parallel charging = %d\n", total_icl_ma); return true; } #define MIN_SLAVER_FCC_MA 500 #define SLAVE_CHG_FCC_REDUCTION_PERCENTAGE 75 #define SLAVER_FCC_REDUCTION_MAX_TRIES 3 static int smb1351_parallel_charger_taper_attempt( struct smb1351_charger *chip) { struct power_supply *parallel_psy = smb1351_get_parallel_slave(chip); union power_supply_propval pval = {0, }; int rc, slave_fcc_ma, tries = 0; u8 value; if (!parallel_psy || !chip->parallel.slave_detected) return 0; smb1351_stay_awake(&chip->smb1351_ws, PARALLEL_TAPER); try_again: mutex_lock(&chip->parallel.lock); if (chip->parallel.slave_icl_ma == 0) { pr_debug("Parallel slave not enabled, skipping\n"); rc = 0; goto done; } rc = parallel_psy->get_property(parallel_psy, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, &pval); if (rc) { pr_err("Get slave FCC failed, rc=%d\n", rc); goto done; } tries += 1; slave_fcc_ma = pval.intval / 1000; if (slave_fcc_ma < MIN_SLAVER_FCC_MA || tries > SLAVER_FCC_REDUCTION_MAX_TRIES) { pr_debug("reduce slave FCC can't exist taper, disable slave\n"); smb1351_parallel_charger_disable_slave(chip); goto done; } pval.intval = slave_fcc_ma * SLAVE_CHG_FCC_REDUCTION_PERCENTAGE / 100; pval.intval *= 1000; rc = parallel_psy->set_property(parallel_psy, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, &pval); if (rc) { pr_err("Set slave FCC %duA failed, rc=%d\n", pval.intval, rc); goto done; } mutex_unlock(&chip->parallel.lock); /* * Sleep 100ms to make sure the charger has a chance to * go back to fast charging state. */ msleep(100); mutex_lock(&chip->parallel.lock); rc = smb1351_read_reg(chip, IRQ_C_REG, &value); if (rc) { pr_err("Read IRQ_C failed, rc=%d\n", rc); goto done; } if (value & IRQ_TAPER_BIT) { mutex_unlock(&chip->parallel.lock); pr_debug("recheck: %d\n", tries); goto try_again; } done: mutex_unlock(&chip->parallel.lock); smb1351_relax(&chip->smb1351_ws, PARALLEL_TAPER); return rc; } static void smb1351_parallel_work(struct work_struct *work) { struct smb1351_charger *chip = container_of(work, struct smb1351_charger, parallel.parallel_work.work); int rc, pre_icl_ma, icl_ma, total_icl_ma = 0; /* Get ICL twice with 500ms delays to check if ICl settled */ rc = smb1351_get_usb_chg_current(chip, &pre_icl_ma); if (rc) { pr_err("Get ICL result failed, rc = %d\n", rc); return; } msleep(500); rc = smb1351_get_usb_chg_current(chip, &icl_ma); if (rc) { pr_err("Get ICL result failed, rc = %d\n", rc); return; } if ((pre_icl_ma > 0) && (pre_icl_ma == icl_ma)) { pr_debug("AICL stable at %d\n", icl_ma); } else { pr_debug("AICL changed %d -> %d, double check\n", pre_icl_ma, icl_ma); goto recheck; } mutex_lock(&chip->parallel.lock); if (smb1351_attempt_enable_parallel_slave(chip, &total_icl_ma)) { pr_debug("Enable parallel slave, total_icl = %d!\n", total_icl_ma); smb1351_parallel_charger_enable_slave(chip, total_icl_ma); } else { if (chip->parallel.slave_icl_ma != 0) { pr_debug("Disable parallel slave!\n"); smb1351_parallel_charger_disable_slave(chip); } } mutex_unlock(&chip->parallel.lock); smb1351_relax(&chip->smb1351_ws, PARALLEL_CHARGE); return; recheck: pr_debug("reschedule!\n"); schedule_delayed_work(&chip->parallel.parallel_work, 0); } static void smb1351_parallel_check_start(struct smb1351_charger *chip) { struct power_supply *parallel_psy = smb1351_get_parallel_slave(chip); if (!parallel_psy || !chip->parallel.slave_detected) return; cancel_delayed_work_sync(&chip->parallel.parallel_work); smb1351_stay_awake(&chip->smb1351_ws, PARALLEL_CHARGE); schedule_delayed_work(&chip->parallel.parallel_work, 0); pr_debug("parallel work scheduled\n"); } static void smb1351_init_fg_work(struct work_struct *work) { int rc; struct smb1351_charger *chip = container_of(work, struct smb1351_charger, init_fg_work.work); rc = smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_IGNORE_FALSE_NEGATIVE_ISENSE, 0); if (rc) { pr_debug("Disable isense patch failed, rc=%d\n", rc); goto recheck; } if (chip->fg_notify_jeita) { rc = smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_ENABLE_JEITA_DETECTION, 1); if (rc) { pr_debug("Enable FG JEITA IRQ failed, rc=%d\n", rc); goto recheck; } } return; recheck: /* start a delay worker to do it again if failed */ schedule_delayed_work(&chip->init_fg_work, msecs_to_jiffies(INIT_FG_RETRY_MS)); } static void smb1351_handle_jeita_from_fg(struct smb1351_charger *chip, int health) { int rc; bool disable; if (health <= POWER_SUPPLY_HEALTH_UNKNOWN || health > POWER_SUPPLY_HEALTH_COOL) { pr_err("health state not valid: %d\n", health); return; } switch (health) { case POWER_SUPPLY_HEALTH_GOOD: chip->batt_hot = false; chip->batt_cold = false; chip->batt_warm = false; chip->batt_cool = false; break; case POWER_SUPPLY_HEALTH_OVERHEAT: chip->batt_hot = true; chip->batt_cold = false; chip->batt_warm = false; chip->batt_cool = false; break; case POWER_SUPPLY_HEALTH_COLD: chip->batt_hot = false; chip->batt_cold = true; chip->batt_cool = false; chip->batt_warm = false; break; case POWER_SUPPLY_HEALTH_WARM: chip->batt_hot = false; chip->batt_cold = false; chip->batt_warm = true; chip->batt_cool = false; break; case POWER_SUPPLY_HEALTH_COOL: chip->batt_hot = false; chip->batt_cold = false; chip->batt_warm = false; chip->batt_cool = true; break; default: pr_debug("health: %d, not a JEITA state\n", health); break; } pr_debug("hot: %d, cold: %d, warm = %d, cool = %d\n", chip->batt_hot, chip->batt_cold, chip->batt_warm, chip->batt_cool); disable = (chip->batt_hot || chip->batt_cold) ? true : false; rc = smb1351_battchg_disable(chip, THERMAL, disable); if (rc) { pr_err("%s charging for THERMAL failed, rc=%d\n", disable ? "Disable" : "Enable", rc); return; } rc = smb1351_chg_set_appropriate_battery_current(chip); if (rc) { pr_err("Set battery current failed\n"); return; } rc = smb1351_chg_set_appropriate_vfloat(chip); if (rc) { pr_err("Set float voltage failed\n"); return; } smb1351_parallel_check_start(chip); if (chip->use_external_fg) { smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_STATUS, smb1351_get_prop_batt_status(chip)); smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_HEALTH, smb1351_get_prop_batt_health(chip)); } pr_debug("end!\n"); } static int smb1351_batt_property_is_writeable(struct power_supply *psy, enum power_supply_property psp) { switch (psp) { case POWER_SUPPLY_PROP_CHARGING_ENABLED: case POWER_SUPPLY_PROP_BATTERY_CHARGING_ENABLED: case POWER_SUPPLY_PROP_CAPACITY: return 1; default: break; } return 0; } static int smb1351_battery_set_property(struct power_supply *psy, enum power_supply_property prop, const union power_supply_propval *val) { int rc; struct smb1351_charger *chip = container_of(psy, struct smb1351_charger, batt_psy); switch (prop) { case POWER_SUPPLY_PROP_STATUS: if (!chip->bms_controlled_charging) return -EINVAL; switch (val->intval) { case POWER_SUPPLY_STATUS_FULL: rc = smb1351_battchg_disable(chip, SOC, true); if (rc) { pr_err("Couldn't disable charging rc = %d\n", rc); } else { chip->batt_full = true; pr_debug("status = FULL, batt_full = %d\n", chip->batt_full); } break; case POWER_SUPPLY_STATUS_DISCHARGING: chip->batt_full = false; power_supply_changed(&chip->batt_psy); pr_debug("status = DISCHARGING, batt_full = %d\n", chip->batt_full); break; case POWER_SUPPLY_STATUS_CHARGING: rc = smb1351_battchg_disable(chip, SOC, false); if (rc) { pr_err("Couldn't enable charging rc = %d\n", rc); } else { chip->batt_full = false; pr_debug("status = CHARGING, batt_full = %d\n", chip->batt_full); } break; default: return -EINVAL; } break; case POWER_SUPPLY_PROP_CHARGING_ENABLED: smb1351_usb_suspend(chip, USER, !val->intval); break; case POWER_SUPPLY_PROP_BATTERY_CHARGING_ENABLED: smb1351_battchg_disable(chip, USER, !val->intval); break; case POWER_SUPPLY_PROP_CAPACITY: chip->fake_battery_soc = val->intval; power_supply_changed(&chip->batt_psy); break; case POWER_SUPPLY_PROP_HEALTH: if (chip->fg_notify_jeita) smb1351_handle_jeita_from_fg(chip, val->intval); break; default: return -EINVAL; } return 0; } static int smb1351_battery_get_property(struct power_supply *psy, enum power_supply_property prop, union power_supply_propval *val) { struct smb1351_charger *chip = container_of(psy, struct smb1351_charger, batt_psy); switch (prop) { case POWER_SUPPLY_PROP_STATUS: val->intval = smb1351_get_prop_batt_status(chip); break; case POWER_SUPPLY_PROP_PRESENT: val->intval = smb1351_get_prop_batt_present(chip); break; case POWER_SUPPLY_PROP_CAPACITY: val->intval = smb1351_get_prop_batt_capacity(chip); break; case POWER_SUPPLY_PROP_CHARGING_ENABLED: val->intval = !chip->usb_suspended_status; break; case POWER_SUPPLY_PROP_BATTERY_CHARGING_ENABLED: val->intval = !chip->battchg_disabled_status; break; case POWER_SUPPLY_PROP_CHARGE_TYPE: val->intval = smb1351_get_prop_charge_type(chip); break; case POWER_SUPPLY_PROP_HEALTH: val->intval = smb1351_get_prop_batt_health(chip); break; case POWER_SUPPLY_PROP_TEMP: val->intval = smb1351_get_prop_batt_temp(chip); break; case POWER_SUPPLY_PROP_TECHNOLOGY: val->intval = POWER_SUPPLY_TECHNOLOGY_LION; break; case POWER_SUPPLY_PROP_MODEL_NAME: val->strval = "smb1351"; break; default: return -EINVAL; } return 0; } static enum power_supply_property smb1351_parallel_properties[] = { POWER_SUPPLY_PROP_CHARGING_ENABLED, POWER_SUPPLY_PROP_STATUS, POWER_SUPPLY_PROP_PRESENT, POWER_SUPPLY_PROP_CURRENT_MAX, POWER_SUPPLY_PROP_VOLTAGE_MAX, POWER_SUPPLY_PROP_INPUT_CURRENT_LIMITED, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, }; static int smb1351_parallel_set_chg_present(struct smb1351_charger *chip, int present) { int rc; u8 reg, mask = 0; pr_debug("set slave present = %d\n", present); if (present == chip->parallel_charger_present) { pr_debug("present %d -> %d, skipping\n", chip->parallel_charger_present, present); return 0; } chip->parallel_charger_present = present; if (present) { /* Check if SMB1351 is present */ rc = smb1351_read_reg(chip, CHG_REVISION_REG, &reg); if (rc) { pr_debug("Failed to detect smb1351-parallel-charger, may be absent\n"); return -ENODEV; } rc = smb_chip_get_version(chip); if (rc) { pr_err("Couldn't get version rc = %d\n", rc); return rc; } rc = smb1351_enable_volatile_writes(chip); if (rc) { pr_err("Couldn't configure for volatile rc = %d\n", rc); return rc; } /* set the float voltage */ if (chip->vfloat_mv != -EINVAL) { rc = smb1351_float_voltage_set(chip, chip->vfloat_mv); if (rc) { pr_err("Couldn't set float voltage rc = %d\n", rc); return rc; } } /* set recharge-threshold and enable auto recharge */ if (chip->recharge_mv != -EINVAL) { reg = AUTO_RECHG_ENABLE; if (chip->recharge_mv > 50) reg |= AUTO_RECHG_TH_100MV; else reg |= AUTO_RECHG_TH_50MV; rc = smb1351_masked_write(chip, CHG_CTRL_REG, AUTO_RECHG_BIT | AUTO_RECHG_TH_BIT, reg); if (rc) { pr_err("Couldn't set rechg-cfg rc = %d\n", rc); return rc; } } #ifdef CONFIG_LGE_PM_PARALLEL_CHARGING /* set charging enable by I2C */ reg = EN_BY_I2C_0_ENABLE | USBCS_CTRL_BY_I2C; #else /* set chg en by pin active low */ reg = chip->parallel_pin_polarity_setting | USBCS_CTRL_BY_I2C; #endif rc = smb1351_masked_write(chip, CHG_PIN_EN_CTRL_REG, EN_PIN_CTRL_MASK | USBCS_CTRL_BIT, reg); if (rc) { pr_err("Couldn't set en pin rc=%d\n", rc); return rc; } /* control USB suspend via command bits */ rc = smb1351_masked_write(chip, VARIOUS_FUNC_REG, SUSPEND_MODE_CTRL_BIT, SUSPEND_MODE_CTRL_BY_I2C); if (rc) { pr_err("Couldn't set USB suspend rc=%d\n", rc); return rc; } /* * setup USB 2.0/3.0 detection and USB 500/100 * command polarity */ reg = USB_2_3_MODE_SEL_BY_I2C | USB_CMD_POLARITY_500_1_100_0; mask = USB_2_3_MODE_SEL_BIT | USB_5_1_CMD_POLARITY_BIT; rc = smb1351_masked_write(chip, CHG_OTH_CURRENT_CTRL_REG, mask, reg); if (rc) { pr_err("Couldn't set CHG_OTH_CURRENT_CTRL_REG rc=%d\n", rc); return rc; } /* set fast charging current limit */ chip->target_fastchg_current_max_ma = SMB1351_CHG_FAST_MIN_MA; rc = smb1351_fastchg_current_set(chip, chip->target_fastchg_current_max_ma); if (rc) { pr_err("Couldn't set fastchg current rc=%d\n", rc); return rc; } #ifdef CONFIG_LGE_PM_PARALLEL_CHARGING /* adapter allowance to 5~9V */ rc = smb1351_masked_write(chip, FLEXCHARGER_REG, CHG_CONFIG_MASK, 0); if (rc) { pr_err("Couldn't set charger config adapter rc = %d\n", rc); return rc; } /* jeita disable */ rc = smb1351_masked_write(chip, THERM_A_CTRL_REG, SOFT_COLD_TEMP_LIMIT_MASK, 0); if (rc) { pr_err("Couldn't set soft cold limit rc = %d\n", rc); return rc; } rc = smb1351_masked_write(chip, THERM_A_CTRL_REG, SOFT_HOT_TEMP_LIMIT_MASK, 0); if (rc) { pr_err("Couldn't set soft hot limit rc = %d\n", rc); return rc; } #endif /* * Suspend USB input (CURRENT reason) to avoid slave start * charging before any SW logic been run. USB input will be * un-suspended (CURRENT reason) after allotted ICL being set. */ chip->usb_psy_ma = SUSPEND_CURRENT_MA; rc = smb1351_usb_suspend(chip, CURRENT, true); if (rc) { pr_err("Suspend USB (CURRENT) failed, rc=%d\n", rc); return rc; } rc = smb1351_usb_suspend(chip, PARALLEL, false); if (rc) { pr_err("Suspend USB (PARALLEL) failed, rc=%d\n", rc); return rc; } } else { rc = smb1351_usb_suspend(chip, PARALLEL, true); if (rc) { pr_debug("Suspend USB (PARALLEL) failed, rc=%d\n", rc); return rc; } } return 0; } static bool smb1351_is_input_current_limited(struct smb1351_charger *chip) { int rc; u8 reg; rc = smb1351_read_reg(chip, IRQ_H_REG, &reg); if (rc) { pr_err("Failed to read IRQ_H_REG for ICL status: %d\n", rc); return false; } return !!(reg & IRQ_IC_LIMIT_STATUS_BIT); } static int smb1351_parallel_set_property(struct power_supply *psy, enum power_supply_property prop, const union power_supply_propval *val) { int rc = 0; struct smb1351_charger *chip = container_of(psy, struct smb1351_charger, parallel_psy); switch (prop) { case POWER_SUPPLY_PROP_CHARGING_ENABLED: /* *CHG EN is controlled by pin in the parallel charging. *Use suspend if disable charging by command. */ if (chip->parallel_charger_present) { rc = smb1351_usb_suspend(chip, USER, !val->intval); if (rc) pr_err("%suspend charger failed\n", val->intval ? "Un-s" : "S"); } break; case POWER_SUPPLY_PROP_PRESENT: rc = smb1351_parallel_set_chg_present(chip, val->intval); if (rc) pr_err("Set charger %spresent failed\n", val->intval ? "" : "un-"); break; case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX: if (chip->parallel_charger_present) { chip->target_fastchg_current_max_ma = val->intval / 1000; rc = smb1351_fastchg_current_set(chip, chip->target_fastchg_current_max_ma); } break; case POWER_SUPPLY_PROP_CURRENT_MAX: if (chip->parallel_charger_present) { rc = smb1351_set_usb_chg_current(chip, val->intval / 1000); } break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: if (chip->parallel_charger_present && (chip->vfloat_mv != val->intval)) { rc = smb1351_float_voltage_set(chip, val->intval); if (!rc) chip->vfloat_mv = val->intval; } else { chip->vfloat_mv = val->intval; } break; default: return -EINVAL; } return rc; } static int smb1351_parallel_is_writeable(struct power_supply *psy, enum power_supply_property prop) { switch (prop) { case POWER_SUPPLY_PROP_CHARGING_ENABLED: return 1; default: return 0; } } static int smb1351_parallel_get_property(struct power_supply *psy, enum power_supply_property prop, union power_supply_propval *val) { struct smb1351_charger *chip = container_of(psy, struct smb1351_charger, parallel_psy); int rc, icl; switch (prop) { case POWER_SUPPLY_PROP_CHARGING_ENABLED: val->intval = !chip->usb_suspended_status; break; case POWER_SUPPLY_PROP_CURRENT_MAX: if (chip->parallel_charger_present) { rc = smb1351_get_usb_chg_current(chip, &icl); if (rc) { pr_err("Get ICL result failed, rc=%d\n", rc); return rc; } if (icl > 0) val->intval = icl * 1000; else val->intval = 0; } else { val->intval = 0; } break; case POWER_SUPPLY_PROP_VOLTAGE_MAX: val->intval = chip->vfloat_mv; break; case POWER_SUPPLY_PROP_PRESENT: val->intval = chip->parallel_charger_present; break; case POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX: if (chip->parallel_charger_present) val->intval = chip->fastchg_current_max_ma * 1000; else val->intval = 0; break; case POWER_SUPPLY_PROP_STATUS: if (chip->parallel_charger_present) val->intval = smb1351_get_prop_batt_status(chip); else val->intval = POWER_SUPPLY_STATUS_DISCHARGING; break; case POWER_SUPPLY_PROP_INPUT_CURRENT_LIMITED: if (chip->parallel_charger_present) val->intval = smb1351_is_input_current_limited(chip) ? 1 : 0; else val->intval = 0; break; default: return -EINVAL; } return 0; } static void smb1351_chg_ctrl_in_jeita(struct smb1351_charger *chip) { union power_supply_propval ret = {0, }; int rc; /* enable the iterm to prevent the reverse boost */ if (chip->iterm_disabled) { if (chip->batt_cool || chip->batt_warm) { rc = smb1351_iterm_set(chip, 100); pr_debug("set the iterm due to JEITA\n"); } else { rc = smb1351_masked_write(chip, CHG_CTRL_REG, ITERM_EN_BIT, ITERM_DISABLE); pr_debug("disable the iterm when exits warm/cool\n"); } if (rc) { pr_err("Couldn't set iterm rc = %d\n", rc); return; } } /* * When JEITA back to normal, the charging maybe disabled due to * the current termination. So re-enable the charging if the soc * is less than 100 in the normal mode. A 200ms delay is requred * before the disabe and enable operation. */ if (chip->bms_psy) { rc = chip->bms_psy->get_property(chip->bms_psy, POWER_SUPPLY_PROP_CAPACITY, &ret); if (rc) { pr_err("Couldn't read the bms capacity rc = %d\n", rc); return; } if (!chip->batt_cool && !chip->batt_warm && !chip->batt_cold && !chip->batt_hot && ret.intval < 100) { rc = smb1351_battchg_disable(chip, THERMAL, true); if (rc) { pr_err("Couldn't disable charging rc = %d\n", rc); return; } /* delay for resetting the charging */ msleep(200); rc = smb1351_battchg_disable(chip, THERMAL, false); if (rc) { pr_err("Couldn't enable charging rc = %d\n", rc); return; } else { chip->batt_full = false; pr_debug("re-enable charging, batt_full = %d\n", chip->batt_full); } pr_debug("batt psy changed\n"); power_supply_changed(&chip->batt_psy); } } } #define HYSTERESIS_DECIDEGC 20 static void smb1351_chg_adc_notification(enum qpnp_tm_state state, void *ctx) { struct smb1351_charger *chip = ctx; struct battery_status *cur; int temp; if (state >= ADC_TM_STATE_NUM) { pr_err("invalid state parameter %d\n", state); return; } temp = smb1351_get_prop_batt_temp(chip); pr_debug("temp = %d state = %s\n", temp, state == ADC_TM_WARM_STATE ? "hot" : "cold"); /* reset the adc status request */ chip->adc_param.state_request = ADC_TM_WARM_COOL_THR_ENABLE; /* temp from low to high */ if (state == ADC_TM_WARM_STATE) { /* WARM -> HOT */ if (temp >= chip->batt_hot_decidegc) { cur = &batt_s[BATT_HOT]; chip->adc_param.low_temp = chip->batt_hot_decidegc - HYSTERESIS_DECIDEGC; chip->adc_param.state_request = ADC_TM_COOL_THR_ENABLE; /* NORMAL -> WARM */ } else if (temp >= chip->batt_warm_decidegc && chip->jeita_supported) { cur = &batt_s[BATT_WARM]; chip->adc_param.low_temp = chip->batt_warm_decidegc - HYSTERESIS_DECIDEGC; chip->adc_param.high_temp = chip->batt_hot_decidegc; /* COOL -> NORMAL */ } else if (temp >= chip->batt_cool_decidegc && chip->jeita_supported) { cur = &batt_s[BATT_NORMAL]; chip->adc_param.low_temp = chip->batt_cool_decidegc - HYSTERESIS_DECIDEGC; chip->adc_param.high_temp = chip->batt_warm_decidegc; /* COLD -> COOL */ } else if (temp >= chip->batt_cold_decidegc) { cur = &batt_s[BATT_COOL]; chip->adc_param.low_temp = chip->batt_cold_decidegc - HYSTERESIS_DECIDEGC; if (chip->jeita_supported) chip->adc_param.high_temp = chip->batt_cool_decidegc; else chip->adc_param.high_temp = chip->batt_hot_decidegc; /* MISSING -> COLD */ } else if (temp >= chip->batt_missing_decidegc) { cur = &batt_s[BATT_COLD]; chip->adc_param.high_temp = chip->batt_cold_decidegc; chip->adc_param.low_temp = chip->batt_missing_decidegc - HYSTERESIS_DECIDEGC; } /* temp from high to low */ } else { /* COLD -> MISSING */ if (temp <= chip->batt_missing_decidegc) { cur = &batt_s[BATT_MISSING]; chip->adc_param.high_temp = chip->batt_missing_decidegc + HYSTERESIS_DECIDEGC; chip->adc_param.state_request = ADC_TM_WARM_THR_ENABLE; /* COOL -> COLD */ } else if (temp <= chip->batt_cold_decidegc) { cur = &batt_s[BATT_COLD]; chip->adc_param.high_temp = chip->batt_cold_decidegc + HYSTERESIS_DECIDEGC; /* add low_temp to enable batt present check */ chip->adc_param.low_temp = chip->batt_missing_decidegc; /* NORMAL -> COOL */ } else if (temp <= chip->batt_cool_decidegc && chip->jeita_supported) { cur = &batt_s[BATT_COOL]; chip->adc_param.high_temp = chip->batt_cool_decidegc + HYSTERESIS_DECIDEGC; chip->adc_param.low_temp = chip->batt_cold_decidegc; /* WARM -> NORMAL */ } else if (temp <= chip->batt_warm_decidegc && chip->jeita_supported) { cur = &batt_s[BATT_NORMAL]; chip->adc_param.high_temp = chip->batt_warm_decidegc + HYSTERESIS_DECIDEGC; chip->adc_param.low_temp = chip->batt_cool_decidegc; /* HOT -> WARM */ } else if (temp <= chip->batt_hot_decidegc) { cur = &batt_s[BATT_WARM]; if (chip->jeita_supported) chip->adc_param.low_temp = chip->batt_warm_decidegc; else chip->adc_param.low_temp = chip->batt_cold_decidegc; chip->adc_param.high_temp = chip->batt_hot_decidegc + HYSTERESIS_DECIDEGC; } } if (cur->batt_present) chip->battery_missing = false; else chip->battery_missing = true; if (cur->batt_hot ^ chip->batt_hot || cur->batt_cold ^ chip->batt_cold) { chip->batt_hot = cur->batt_hot; chip->batt_cold = cur->batt_cold; /* stop charging explicitly since we use PMIC thermal pin*/ if (cur->batt_hot || cur->batt_cold || chip->battery_missing) smb1351_battchg_disable(chip, THERMAL, 1); else smb1351_battchg_disable(chip, THERMAL, 0); } if ((chip->batt_warm ^ cur->batt_warm || chip->batt_cool ^ cur->batt_cool) && chip->jeita_supported) { chip->batt_warm = cur->batt_warm; chip->batt_cool = cur->batt_cool; smb1351_chg_set_appropriate_battery_current(chip); smb1351_chg_set_appropriate_vfloat(chip); smb1351_chg_ctrl_in_jeita(chip); } pr_debug("hot %d, cold %d, warm %d, cool %d, soft jeita supported %d, missing %d, low = %d deciDegC, high = %d deciDegC\n", chip->batt_hot, chip->batt_cold, chip->batt_warm, chip->batt_cool, chip->jeita_supported, chip->battery_missing, chip->adc_param.low_temp, chip->adc_param.high_temp); if (qpnp_adc_tm_channel_measure(chip->adc_tm_dev, &chip->adc_param)) pr_err("request ADC error\n"); } static void smb1351_rerun_apsd_work(struct work_struct *work) { int rc; struct smb1351_charger *chip = container_of(work, struct smb1351_charger, rerun_apsd_work.work); pr_debug("Rerunning APSD\n"); chip->apsd_rerun = true; rc = smb1351_masked_write(chip, CMD_HVDCP_REG, CMD_APSD_RE_RUN_BIT, CMD_APSD_RE_RUN_BIT); if (rc) pr_err("Couldn't re-run APSD algo, rc = %d\n", rc); smb1351_relax(&chip->smb1351_ws, RERUN_APSD); } static void smb1351_hvdcp_det_work(struct work_struct *work) { int rc; u8 reg; bool is_hvdcp; struct smb1351_charger *chip = container_of(work, struct smb1351_charger, hvdcp_det_work.work); rc = smb1351_read_reg(chip, STATUS_7_REG, &reg); if (rc) { pr_err("Couldn't read STATUS_7_REG rc = %d\n", rc); goto end; } pr_debug("STATUS_7_REG = 0x%02X\n", reg); is_hvdcp = !!(reg & (HVDCP_SEL_5V | HVDCP_SEL_9V | HVDCP_SEL_12V)); if (is_hvdcp) { pr_debug("HVDCP detected; notifying USB PSY\n"); power_supply_set_supply_type(chip->usb_psy, POWER_SUPPLY_TYPE_USB_HVDCP); } end: smb1351_relax(&chip->smb1351_ws, HVDCP_DETECT); } #define HVDCP_NOTIFY_MS 2500 static int smb1351_apsd_complete_handler(struct smb1351_charger *chip, u8 status) { int rc = 0; enum power_supply_type type = POWER_SUPPLY_TYPE_UNKNOWN; struct power_supply *parallel_psy = smb1351_get_parallel_slave(chip); /* * If apsd is disabled, charger detection is done by * USB phy driver. */ if (chip->disable_apsd || chip->usbin_ov) { pr_debug("APSD %s, status = %d\n", chip->disable_apsd ? "disabled" : "enabled", !!status); pr_debug("USBIN ov, status = %d\n", chip->usbin_ov); return 0; } if (status) { chip->chg_present = true; rc = smb1351_get_usb_supply_type(chip, &type); if (rc) { pr_err("Get USB power supply type failed, rc=%d\n", rc); return rc; } pr_debug("APSD complete. USB type detected=%d chg_present=%d\n", type, chip->chg_present); /* * If defined force hvdcp 2p0 property, * we force to hvdcp 2p0 in the APSD handler. */ if (chip->force_hvdcp_2p0) { pr_debug("Force set to HVDCP 2.0 mode\n"); smb1351_masked_write(chip, VARIOUS_FUNC_3_REG, QC_2P1_AUTH_ALGO_BIT, 0); smb1351_masked_write(chip, CMD_HVDCP_REG, CMD_FORCE_HVDCP_2P0_BIT, CMD_FORCE_HVDCP_2P0_BIT); type = POWER_SUPPLY_TYPE_USB_HVDCP; } else if (type == POWER_SUPPLY_TYPE_USB_DCP) { pr_debug("schedule hvdcp detection worker\n"); smb1351_stay_awake(&chip->smb1351_ws, HVDCP_DETECT); schedule_delayed_work(&chip->hvdcp_det_work, msecs_to_jiffies(HVDCP_NOTIFY_MS)); } power_supply_set_supply_type(chip->usb_psy, type); /* * SMB is now done sampling the D+/D- lines, * indicate USB driver */ pr_debug("updating usb_psy present=%d\n", chip->chg_present); power_supply_set_present(chip->usb_psy, chip->chg_present); chip->apsd_rerun = false; /* set parallel slave PRESENT */ if (parallel_psy) { pr_debug("set parallel charger present!\n"); rc = power_supply_set_present(parallel_psy, true); if (rc) pr_debug("parallel slave absent!\n"); else chip->parallel.slave_detected = true; } } return rc; } /* * As source detect interrupt is not triggered on the falling edge, * we need to schedule a work for checking source detect status after * charger UV interrupt fired. */ #define FIRST_CHECK_DELAY_MS 100 #define SECOND_CHECK_DELAY_MS 1000 #define RERUN_CHG_REMOVE_DELAY_MS 1500 static void smb1351_chg_remove_work(struct work_struct *work) { int rc; u8 reg; struct smb1351_charger *chip = container_of(work, struct smb1351_charger, chg_remove_work.work); struct power_supply *parallel_psy = smb1351_get_parallel_slave(chip); rc = smb1351_read_reg(chip, IRQ_G_REG, &reg); if (rc) { pr_err("Couldn't read IRQ_G_REG rc = %d\n", rc); goto end; } if (!(reg & IRQ_SOURCE_DET_BIT)) { pr_debug("chg removed\n"); chip->chg_present = false; /* clear parallel slave PRESENT */ if (parallel_psy && chip->parallel.slave_detected) { pr_debug("set parallel charger un-present!\n"); power_supply_set_present(parallel_psy, false); } power_supply_set_supply_type(chip->usb_psy, POWER_SUPPLY_TYPE_UNKNOWN); power_supply_set_present(chip->usb_psy, chip->chg_present); pr_debug("Set usb psy dp=r dm=r\n"); power_supply_set_dp_dm(chip->usb_psy, POWER_SUPPLY_DP_DM_DPR_DMR); chip->apsd_rerun = false; } else if (!chip->chg_remove_work_scheduled) { chip->chg_remove_work_scheduled = true; goto reschedule; } else { pr_debug("charger is present\n"); } end: chip->chg_remove_work_scheduled = false; smb1351_relax(&chip->smb1351_ws, REMOVAL_DETECT); return; reschedule: pr_debug("reschedule after 1s\n"); schedule_delayed_work(&chip->chg_remove_work, msecs_to_jiffies(SECOND_CHECK_DELAY_MS)); } static int smb1351_usbin_uv_handler(struct smb1351_charger *chip, u8 status) { int chg_remove_delay = FIRST_CHECK_DELAY_MS; struct power_supply *parallel_psy = smb1351_get_parallel_slave(chip); int rc; pr_debug("enter, status = %d\n", !!status); /* use this to detect USB insertion only if !apsd */ if (chip->disable_apsd) { /* * If APSD is disabled, src det interrupt won't trigger. * Hence use usbin_uv for removal and insertion notification */ if (status == 0) { chip->chg_present = true; pr_debug("updating usb_psy present=%d\n", chip->chg_present); power_supply_set_supply_type(chip->usb_psy, POWER_SUPPLY_TYPE_USB); power_supply_set_present(chip->usb_psy, chip->chg_present); /* set parallel slave PRESENT */ if (parallel_psy) { rc = power_supply_set_present( parallel_psy, true); if (rc) pr_debug("parallel slave absent!\n"); else chip->parallel.slave_detected = true; } } else { chip->chg_present = false; /* clear parallel slave PRESENT */ if (parallel_psy && chip->parallel.slave_detected) power_supply_set_present(parallel_psy, false); power_supply_set_supply_type(chip->usb_psy, POWER_SUPPLY_TYPE_UNKNOWN); power_supply_set_present(chip->usb_psy, chip->chg_present); pr_debug("updating usb_psy present=%d\n", chip->chg_present); } return 0; } if (status) { cancel_delayed_work_sync(&chip->hvdcp_det_work); if (chip->wa_flags & CHG_ITERM_CHECK_SOC) cancel_delayed_work_sync(&chip->iterm_check_soc_work); smb1351_relax(&chip->smb1351_ws, REMOVAL_DETECT); pr_debug("schedule charger remove worker\n"); if (chip->apsd_rerun) chg_remove_delay = RERUN_CHG_REMOVE_DELAY_MS; smb1351_stay_awake(&chip->smb1351_ws, REMOVAL_DETECT); schedule_delayed_work(&chip->chg_remove_work, msecs_to_jiffies(chg_remove_delay)); } else { cancel_delayed_work_sync(&chip->chg_remove_work); smb1351_relax(&chip->smb1351_ws, REMOVAL_DETECT); pr_debug("Set usb psy dp=f dm=f\n"); power_supply_set_dp_dm(chip->usb_psy, POWER_SUPPLY_DP_DM_DPF_DMF); } pr_debug("chip->chg_present = %d\n", chip->chg_present); return 0; } static int smb1351_usbin_ov_handler(struct smb1351_charger *chip, u8 status) { struct power_supply *parallel_psy = smb1351_get_parallel_slave(chip); int health; int rc; u8 reg; pr_debug("enter, status = %d\n", !!status); rc = smb1351_read_reg(chip, IRQ_E_REG, &reg); if (rc) pr_err("Couldn't read IRQ_E rc = %d\n", rc); if (status != 0) { chip->chg_present = false; chip->usbin_ov = true; /* clear parallel slave PRESENT */ if (parallel_psy && chip->parallel.slave_detected) power_supply_set_present(parallel_psy, false); power_supply_set_supply_type(chip->usb_psy, POWER_SUPPLY_TYPE_UNKNOWN); power_supply_set_present(chip->usb_psy, chip->chg_present); } else { chip->usbin_ov = false; if (reg & IRQ_USBIN_UV_BIT) pr_debug("Charger unplugged from OV\n"); else smb1351_apsd_complete_handler(chip, 1); } if (chip->usb_psy) { health = status ? POWER_SUPPLY_HEALTH_OVERVOLTAGE : POWER_SUPPLY_HEALTH_GOOD; power_supply_set_health_state(chip->usb_psy, health); pr_debug("chip ov status is %d\n", health); } pr_debug("chip->chg_present = %d\n", chip->chg_present); return 0; } static int smb1351_usbid_handler(struct smb1351_charger *chip, u8 status) { bool usbid_gnd; int rc; if (!!status) { rc = smb1351_get_usbid_status(chip, &usbid_gnd); if (rc) { pr_err("Get usbid failed!"); return 0; } pr_debug("usbid grounded: %d\n", usbid_gnd); if (chip->usb_psy) power_supply_set_usb_otg(chip->usb_psy, usbid_gnd); } if (chip->use_external_fg) smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_STATUS, smb1351_get_prop_batt_status(chip)); return 0; } static int smb1351_fast_chg_handler(struct smb1351_charger *chip, u8 status) { pr_debug("enter, status = 0x%02x\n", status); chip->check_parallel = true; if (chip->use_external_fg) smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_STATUS, smb1351_get_prop_batt_status(chip)); return 0; } static int smb1351_taper_handler(struct smb1351_charger *chip, u8 status) { pr_debug("enter, status = 0x%02x\n", status); if (!!status) smb1351_parallel_charger_taper_attempt(chip); if (chip->use_external_fg) smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_STATUS, smb1351_get_prop_batt_status(chip)); return 0; } static int smb1351_recharge_handler(struct smb1351_charger *chip, u8 status) { pr_debug("enter, status = 0x%02x\n", status); if (!chip->bms_controlled_charging) chip->batt_full = !status; chip->check_parallel = true; if (chip->use_external_fg) smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_STATUS, smb1351_get_prop_batt_status(chip)); return 0; } #define FULL_SOC 100 #define ITERM_CHECK_MS 10000 #define ITERM_RECHECK_COUNT 3 static void smb1351_iterm_check_soc_work(struct work_struct *work) { int rc, current_ua, soc; struct smb1351_charger *chip = container_of(work, struct smb1351_charger, iterm_check_soc_work.work); static int retry; if (!chip->chg_present) { pr_debug("Plugged out, ignore!\n"); goto done; } rc = smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_UPDATE_NOW, 1); if (rc) { pr_err("Update bms status failed, rc=%d\n", rc); goto recheck; } rc = smb1351_get_bms_property(chip, POWER_SUPPLY_PROP_CURRENT_NOW, &current_ua); if (rc) { pr_err("Get bms current now failed, rc=%d\n", rc); goto recheck; } pr_debug("current: %d ua!", current_ua); if (current_ua >= 0) { pr_debug("Terminated? large current consumption?"); retry++; goto recheck; } if (retry > ITERM_RECHECK_COUNT) { pr_debug("retry timed out!\n"); goto done; } if (-1 * current_ua / 1000 < chip->iterm_ma) { pr_debug("Charging current is less than iterm, terminate!"); chip->batt_full = true; goto done; } rc = smb1351_get_bms_property(chip, POWER_SUPPLY_PROP_CAPACITY, &soc); if (rc) { pr_err("Get bms capacity failed, rc=%d\n", rc); goto recheck; } if (soc == FULL_SOC) { pr_debug("FG has terminated, terminate charger!\n"); chip->batt_full = true; goto done; } done: if (chip->batt_full) { smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_STATUS, smb1351_get_prop_batt_status(chip)); if (chip->wa_flags & CHG_SOC_BASED_RESUME) { rc = smb1351_battchg_disable(chip, SOC, true); if (rc) { pr_err("Disable charger for SOC failed, rc=%d\n", rc); goto recheck; } } } rc = smb1351_masked_write(chip, CHG_CTRL_REG, ITERM_EN_BIT, ITERM_ENABLE); if (rc) { pr_err("Re-enable iterm failed, rc=%d\n", rc); goto recheck; } chip->iterm_disabled = false; smb1351_relax(&chip->smb1351_ws, ITERM_CHECK_SOC); return; recheck: schedule_delayed_work(&chip->iterm_check_soc_work, msecs_to_jiffies(ITERM_CHECK_MS)); } static int smb1351_chg_term_handler(struct smb1351_charger *chip, u8 status) { int rc, soc; pr_debug("enter, status = 0x%02x\n", status); if (!chip->bms_controlled_charging && !(chip->wa_flags & CHG_ITERM_CHECK_SOC)) chip->batt_full = !!status; /* Only check parallel when falling */ if (!status) chip->check_parallel = true; if (!(chip->wa_flags & CHG_ITERM_CHECK_SOC)) return 0; if (!!status && !chip->batt_full) { rc = smb1351_get_bms_property(chip, POWER_SUPPLY_PROP_CAPACITY, &soc); if (rc) { pr_err("Get capacity failed, rc=%d\n", rc); return rc; } if (soc != FULL_SOC) { pr_debug("FG haven't reported FULL, soc=%d\n", soc); /* * disable termination, restart charging, * hold a wakelock and start a timer for * checking SOC until the SOC reach to * FULL_SOC. */ rc = smb1351_masked_write(chip, CHG_CTRL_REG, ITERM_EN_BIT, ITERM_DISABLE); if (rc) { pr_err("disable iterm failed, rc=%d", rc); return rc; } chip->iterm_disabled = true; /* toggle charging disble bit for re-charge */ rc = smb1351_battchg_disable(chip, ITERM, true); if (rc) { pr_err("Disable charger for ITERM failed, rc=%d\n", rc); return rc; } rc = smb1351_battchg_disable(chip, ITERM, false); if (rc) { pr_err("Enable charger for ITERM failed, rc=%d\n", rc); return rc; } smb1351_stay_awake(&chip->smb1351_ws, ITERM_CHECK_SOC); schedule_delayed_work(&chip->iterm_check_soc_work, 0); } else { pr_debug("Terminated, FG report full\n"); chip->batt_full = true; } } return 0; } static int smb1351_safety_timeout_handler(struct smb1351_charger *chip, u8 status) { pr_debug("enter, status = 0x%02x\n", status); chip->check_parallel = true; if (chip->use_external_fg) smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_STATUS, smb1351_get_prop_batt_status(chip)); return 0; } static int smb1351_chg_error_handler(struct smb1351_charger *chip, u8 status) { pr_debug("enter, status = 0x%02x\n", status); chip->check_parallel = true; if (chip->use_external_fg) smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_STATUS, smb1351_get_prop_batt_status(chip)); return 0; } static int smb1351_aicl_done_handler(struct smb1351_charger *chip, u8 status) { pr_debug("enter, status = 0x%02x\n", status); chip->check_parallel = true; return 0; } static int smb1351_hot_hard_handler(struct smb1351_charger *chip, u8 status) { pr_debug("enter, status = 0x%02x\n", status); chip->batt_hot = !!status; chip->check_parallel = true; return 0; } static int smb1351_cold_hard_handler(struct smb1351_charger *chip, u8 status) { pr_debug("enter, status = 0x%02x\n", status); chip->batt_cold = !!status; chip->check_parallel = true; return 0; } static int smb1351_hot_soft_handler(struct smb1351_charger *chip, u8 status) { pr_debug("enter, status = 0x%02x\n", status); chip->batt_warm = !!status; chip->check_parallel = true; return 0; } static int smb1351_cold_soft_handler(struct smb1351_charger *chip, u8 status) { pr_debug("enter, status = 0x%02x\n", status); chip->batt_cool = !!status; chip->check_parallel = true; return 0; } static int smb1351_battery_missing_handler(struct smb1351_charger *chip, u8 status) { pr_debug("enter, status = 0x%02x\n", status); if (status) chip->battery_missing = true; else chip->battery_missing = false; if (chip->use_external_fg) smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_STATUS, smb1351_get_prop_batt_status(chip)); return 0; } static struct irq_handler_info handlers[] = { [0] = { .stat_reg = IRQ_A_REG, .val = 0, .prev_val = 0, .irq_info = { { .name = "cold_soft", .smb_irq = smb1351_cold_soft_handler, }, { .name = "hot_soft", .smb_irq = smb1351_hot_soft_handler, }, { .name = "cold_hard", .smb_irq = smb1351_cold_hard_handler, }, { .name = "hot_hard", .smb_irq = smb1351_hot_hard_handler, }, }, }, [1] = { .stat_reg = IRQ_B_REG, .val = 0, .prev_val = 0, .irq_info = { { .name = "internal_temp_limit", }, { .name = "vbatt_low", }, { .name = "battery_missing", .smb_irq = smb1351_battery_missing_handler, }, { .name = "batt_therm_removed", }, }, }, [2] = { .stat_reg = IRQ_C_REG, .val = 0, .prev_val = 0, .irq_info = { { .name = "chg_term", .smb_irq = smb1351_chg_term_handler, }, { .name = "taper", .smb_irq = smb1351_taper_handler, }, { .name = "recharge", .smb_irq = smb1351_recharge_handler, }, { .name = "fast_chg", .smb_irq = smb1351_fast_chg_handler, }, }, }, [3] = { .stat_reg = IRQ_D_REG, .val = 0, .prev_val = 0, .irq_info = { { .name = "prechg_timeout", }, { .name = "safety_timeout", .smb_irq = smb1351_safety_timeout_handler, }, { .name = "chg_error", .smb_irq = smb1351_chg_error_handler, }, { .name = "batt_ov", }, }, }, [4] = { .stat_reg = IRQ_E_REG, .val = 0, .prev_val = 0, .irq_info = { { .name = "power_ok", }, { .name = "afvc", }, { .name = "usbin_uv", .smb_irq = smb1351_usbin_uv_handler, }, { .name = "usbin_ov", .smb_irq = smb1351_usbin_ov_handler, }, }, }, [5] = { .stat_reg = IRQ_F_REG, .val = 0, .prev_val = 0, .irq_info = { { .name = "otg_oc_retry", }, { .name = "rid", .smb_irq = smb1351_usbid_handler, }, { .name = "otg_fail", }, { .name = "otg_oc", }, }, }, [6] = { .stat_reg = IRQ_G_REG, .val = 0, .prev_val = 0, .irq_info = { { .name = "chg_inhibit", }, { .name = "aicl_fail", }, { .name = "aicl_done", .smb_irq = smb1351_aicl_done_handler, }, { .name = "apsd_complete", .smb_irq = smb1351_apsd_complete_handler, }, }, }, [7] = { .stat_reg = IRQ_H_REG, .val = 0, .prev_val = 0, .irq_info = { { .name = "wdog_timeout", }, { .name = "hvdcp_auth_done", }, }, }, }; #define IRQ_LATCHED_MASK 0x02 #define IRQ_STATUS_MASK 0x01 #define BITS_PER_IRQ 2 static irqreturn_t smb1351_chg_stat_handler(int irq, void *dev_id) { struct smb1351_charger *chip = dev_id; int i, j; u8 triggered; u8 changed; u8 rt_stat, prev_rt_stat; int rc; int handler_count = 0; mutex_lock(&chip->irq_complete); chip->irq_waiting = true; if (!chip->resume_completed) { pr_debug("IRQ triggered before device-resume\n"); disable_irq_nosync(irq); mutex_unlock(&chip->irq_complete); return IRQ_HANDLED; } chip->irq_waiting = false; for (i = 0; i < ARRAY_SIZE(handlers); i++) { rc = smb1351_read_reg(chip, handlers[i].stat_reg, &handlers[i].val); if (rc) { pr_err("Couldn't read %d rc = %d\n", handlers[i].stat_reg, rc); continue; } for (j = 0; j < ARRAY_SIZE(handlers[i].irq_info); j++) { triggered = handlers[i].val & (IRQ_LATCHED_MASK << (j * BITS_PER_IRQ)); rt_stat = handlers[i].val & (IRQ_STATUS_MASK << (j * BITS_PER_IRQ)); prev_rt_stat = handlers[i].prev_val & (IRQ_STATUS_MASK << (j * BITS_PER_IRQ)); changed = prev_rt_stat ^ rt_stat; if (triggered || changed) rt_stat ? handlers[i].irq_info[j].high++ : handlers[i].irq_info[j].low++; if ((triggered || changed) && handlers[i].irq_info[j].smb_irq != NULL) { handler_count++; rc = handlers[i].irq_info[j].smb_irq(chip, rt_stat); if (rc) pr_err("Couldn't handle %d irq for reg 0x%02x rc = %d\n", j, handlers[i].stat_reg, rc); } } handlers[i].prev_val = handlers[i].val; } if (chip->check_parallel) { smb1351_parallel_check_start(chip); chip->check_parallel = false; } pr_debug("handler count = %d\n", handler_count); if (handler_count) { pr_debug("batt psy changed\n"); power_supply_changed(&chip->batt_psy); } mutex_unlock(&chip->irq_complete); return IRQ_HANDLED; } #define DEFAULT_SDP_MA 500 #define DEFAULT_CDP_MA 1500 #define DEFAULT_DCP_MA 1800 #define DEFAULT_HVDCP_MA 1800 #define DEFAULT_HVDCP3_MA 3000 static int smb1351_update_usb_supply_icl(struct smb1351_charger *chip) { int rc, type, icl; union power_supply_propval pval = {0, }; rc = chip->usb_psy->get_property(chip->usb_psy, POWER_SUPPLY_PROP_TYPE, &pval); if (rc) { pr_err("Get USB supply type failed, rc=%d\n", rc); return rc; } type = pval.intval; chip->usb_psy_type = type; rc = chip->usb_psy->get_property(chip->usb_psy, POWER_SUPPLY_PROP_CURRENT_MAX, &pval); if (!rc) icl = pval.intval / 1000; else return rc; /* * Only update ICL when DCP/HVDCP/HVDCP3 being detected * For other types such as SDP/CDP, keep the ICL set in * USB PHY to avoid violating USB spec. */ switch (type) { case POWER_SUPPLY_TYPE_USB_DCP: icl = DEFAULT_DCP_MA; break; case POWER_SUPPLY_TYPE_USB_HVDCP: icl = DEFAULT_HVDCP_MA; break; case POWER_SUPPLY_TYPE_USB_HVDCP_3: icl = DEFAULT_HVDCP3_MA; break; default: break; } chip->usb_psy_ma = icl; pr_debug("type = %d, icl = %d\n", type, icl); return rc; } #define ESR_PULSE_DELTA_MA 200 static int smb1351_force_esr_pulse_en(struct smb1351_charger *chip, bool en) { int rc = 0, current_in_esr = 0, fg_current_now = 0; int main_fcc_in_esr = 0, slave_fcc_in_esr = 0; int actual_slave_fcc_in_esr = 0; union power_supply_propval pval = {0,}; struct power_supply *parallel_psy = smb1351_get_parallel_slave(chip); if (chip->in_esr_pulse == en) { pr_err("ESR pulse is already %s\n", en ? "enabled" : "disabled"); return 0; } if (en) { rc = smb1351_get_bms_property(chip, POWER_SUPPLY_PROP_CURRENT_NOW, &fg_current_now); if (rc) { pr_debug("Get battery current from BMS(fg) failed, rc=%d\n", rc); return rc; } pr_debug("ibatt from FG reading: %duA\n", fg_current_now); fg_current_now = abs(fg_current_now); fg_current_now /= 1000; chip->main_fcc_ma_before_esr = chip->fastchg_current_max_ma; current_in_esr = max(chip->iterm_ma + ESR_PULSE_DELTA_MA, fg_current_now - ESR_PULSE_DELTA_MA); pr_debug("Force battery current to %d in ESR pulse\n", current_in_esr); } mutex_lock(&chip->parallel.lock); /* * If parallel charging is not enabled, set the current_in_esr * to main charger to achieve the ESR pulse */ if (!parallel_psy || !chip->parallel.slave_detected || chip->parallel.slave_icl_ma == 0) { rc = smb1351_fastchg_current_set(chip, en ? current_in_esr : chip->main_fcc_ma_before_esr); if (!rc) chip->in_esr_pulse = en; else pr_err("set FCC for ESR failed, rc=%d\n", rc); goto unlock; } /* * If parallel charging is enabled, split current_in_esr and * set it to main and slave charger accordingly */ if (en) { rc = parallel_psy->get_property(parallel_psy, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, &pval); if (rc) { pr_err("get slave fcc failed, rc=%d\n", rc); goto unlock; } chip->slave_fcc_ma_before_esr = pval.intval / 1000; slave_fcc_in_esr = current_in_esr * (100 - chip->parallel.main_chg_fcc_percent) / 100; pval.intval = slave_fcc_in_esr * 1000; rc = parallel_psy->set_property(parallel_psy, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, &pval); if (rc) { pr_err("set slave fcc for ESR failed, rc=%d\n", rc); goto unlock; } rc = parallel_psy->get_property(parallel_psy, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, &pval); if (rc) { pr_err("get slave fcc for ESR failed, rc=%d\n", rc); goto unlock; } actual_slave_fcc_in_esr = pval.intval / 1000; pr_debug("slave_fcc_in_esr = %dmA, actual_slave_fcc_in_esr = %dmA\n", slave_fcc_in_esr, actual_slave_fcc_in_esr); main_fcc_in_esr = current_in_esr - actual_slave_fcc_in_esr; rc = smb1351_fastchg_current_set(chip, main_fcc_in_esr); if (rc) { pr_err("Set main fcc for ESR failed, rc=%d\n", rc); goto unlock; } pr_debug("main_fcc_in_esr = %dmA\n", main_fcc_in_esr); } else { pval.intval = chip->slave_fcc_ma_before_esr * 1000; rc = parallel_psy->set_property(parallel_psy, POWER_SUPPLY_PROP_CONSTANT_CHARGE_CURRENT_MAX, &pval); if (rc) { pr_err("restore fcc for slave failed, rc=%d\n", rc); goto unlock; } rc = smb1351_fastchg_current_set(chip, chip->main_fcc_ma_before_esr); if (rc) { pr_err("restore fcc for main failed, rc=%d\n", rc); goto unlock; } pr_debug("restore, main_fcc = %dmA, slave_fcc = %dmA\n", chip->main_fcc_ma_before_esr, chip->slave_fcc_ma_before_esr); } chip->in_esr_pulse = en; unlock: mutex_unlock(&chip->parallel.lock); return rc; } #define ESR_PULSE_TIME_MS 1500 static void smb1351_force_esr_for_fg(struct smb1351_charger *chip) { int rc = 0, esr_count = 0; if (!chip->chg_present) { pr_debug("No force ESR pulse when no charging\n"); return; } rc = smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_UPDATE_NOW, 1); if (rc) { pr_debug("Update BMS(fg) status failed, rc=%d\n", rc); return; } rc = smb1351_get_bms_property(chip, POWER_SUPPLY_PROP_ESR_COUNT, &esr_count); if (rc) { pr_debug("Get ESR count from BMS(fg) failed, rc=%d\n", rc); return; } if (esr_count != 0) { pr_debug("ESR count is not zero: %d, skipping\n", esr_count); return; } smb1351_stay_awake(&chip->smb1351_ws, FORCE_ESR_PULSE); rc = smb1351_force_esr_pulse_en(chip, true); if (rc) { pr_err("Force ESR pulse enable failed, rc=%d\n", rc); smb1351_relax(&chip->smb1351_ws, FORCE_ESR_PULSE); return; } msleep(ESR_PULSE_TIME_MS); rc = smb1351_force_esr_pulse_en(chip, false); if (rc) pr_err("Force ESR pulse disable failed, rc=%d\n", rc); smb1351_relax(&chip->smb1351_ws, FORCE_ESR_PULSE); } static void battery_soc_changed(struct smb1351_charger *chip) { int rc, soc; soc = smb1351_get_prop_batt_capacity(chip); if (chip->pre_soc == soc) return; if (chip->wa_flags & CHG_FORCE_ESR_WA) smb1351_force_esr_for_fg(chip); if ((chip->wa_flags & CHG_SOC_BASED_RESUME) && chip->batt_full && (soc <= chip->resume_soc)) { rc = smb1351_battchg_disable(chip, SOC, false); if (rc) { pr_err("Enable charge for SOC failed, rc=%d\n", rc); return; } chip->batt_full = false; smb1351_set_bms_property(chip, POWER_SUPPLY_PROP_STATUS, smb1351_get_prop_batt_status(chip)); } chip->pre_soc = soc; } static void smb1351_external_power_changed(struct power_supply *psy) { struct smb1351_charger *chip = container_of(psy, struct smb1351_charger, batt_psy); struct power_supply *parallel_psy = smb1351_get_parallel_slave(chip); union power_supply_propval prop = {0,}; int rc, online = 0, slave_present = 0; battery_soc_changed(chip); if (parallel_psy) { parallel_psy->get_property(parallel_psy, POWER_SUPPLY_PROP_PRESENT, &prop); slave_present = prop.intval; /* Don't update main charger ICL if slave is enabled */ if (chip->parallel.slave_detected && slave_present && chip->parallel.slave_icl_ma != 0) { pr_debug("Ignore ICL setting as parallel-slave is enabled\n"); return; } } rc = chip->usb_psy->get_property(chip->usb_psy, POWER_SUPPLY_PROP_ONLINE, &prop); if (rc) { pr_err("Couldn't read USB online property, rc=%d\n", rc); return; } online = prop.intval; rc = smb1351_update_usb_supply_icl(chip); if (rc) { pr_err("Update USB supply ICL failed!\n"); return; } pr_debug("online = %d, current_limit = %d\n", online, chip->usb_psy_ma); smb1351_enable_volatile_writes(chip); smb1351_set_usb_chg_current(chip, chip->usb_psy_ma); pr_debug("updating batt psy\n"); } #define LAST_CNFG_REG 0x16 static int show_cnfg_regs(struct seq_file *m, void *data) { struct smb1351_charger *chip = m->private; int rc; u8 reg; u8 addr; for (addr = 0; addr <= LAST_CNFG_REG; addr++) { rc = smb1351_read_reg(chip, addr, &reg); if (!rc) seq_printf(m, "0x%02x = 0x%02x\n", addr, reg); } return 0; } static int cnfg_debugfs_open(struct inode *inode, struct file *file) { struct smb1351_charger *chip = inode->i_private; return single_open(file, show_cnfg_regs, chip); } static const struct file_operations cnfg_debugfs_ops = { .owner = THIS_MODULE, .open = cnfg_debugfs_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #define FIRST_CMD_REG 0x30 #define LAST_CMD_REG 0x34 static int show_cmd_regs(struct seq_file *m, void *data) { struct smb1351_charger *chip = m->private; int rc; u8 reg; u8 addr; for (addr = FIRST_CMD_REG; addr <= LAST_CMD_REG; addr++) { rc = smb1351_read_reg(chip, addr, &reg); if (!rc) seq_printf(m, "0x%02x = 0x%02x\n", addr, reg); } return 0; } static int cmd_debugfs_open(struct inode *inode, struct file *file) { struct smb1351_charger *chip = inode->i_private; return single_open(file, show_cmd_regs, chip); } static const struct file_operations cmd_debugfs_ops = { .owner = THIS_MODULE, .open = cmd_debugfs_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; #define FIRST_STATUS_REG 0x36 #define LAST_STATUS_REG 0x3F static int show_status_regs(struct seq_file *m, void *data) { struct smb1351_charger *chip = m->private; int rc; u8 reg; u8 addr; for (addr = FIRST_STATUS_REG; addr <= LAST_STATUS_REG; addr++) { rc = smb1351_read_reg(chip, addr, &reg); if (!rc) seq_printf(m, "0x%02x = 0x%02x\n", addr, reg); } return 0; } static int status_debugfs_open(struct inode *inode, struct file *file) { struct smb1351_charger *chip = inode->i_private; return single_open(file, show_status_regs, chip); } static const struct file_operations status_debugfs_ops = { .owner = THIS_MODULE, .open = status_debugfs_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int show_irq_count(struct seq_file *m, void *data) { int i, j, total = 0; for (i = 0; i < ARRAY_SIZE(handlers); i++) for (j = 0; j < 4; j++) { seq_printf(m, "%s=%d\t(high=%d low=%d)\n", handlers[i].irq_info[j].name, handlers[i].irq_info[j].high + handlers[i].irq_info[j].low, handlers[i].irq_info[j].high, handlers[i].irq_info[j].low); total += (handlers[i].irq_info[j].high + handlers[i].irq_info[j].low); } seq_printf(m, "\n\tTotal = %d\n", total); return 0; } static int irq_count_debugfs_open(struct inode *inode, struct file *file) { struct smb1351_charger *chip = inode->i_private; return single_open(file, show_irq_count, chip); } static const struct file_operations irq_count_debugfs_ops = { .owner = THIS_MODULE, .open = irq_count_debugfs_open, .read = seq_read, .llseek = seq_lseek, .release = single_release, }; static int get_reg(void *data, u64 *val) { struct smb1351_charger *chip = data; int rc; u8 temp; rc = smb1351_read_reg(chip, chip->peek_poke_address, &temp); if (rc) { pr_err("Couldn't read reg %x rc = %d\n", chip->peek_poke_address, rc); return -EAGAIN; } *val = temp; return 0; } static int set_reg(void *data, u64 val) { struct smb1351_charger *chip = data; int rc; u8 temp; temp = (u8) val; rc = smb1351_write_reg(chip, chip->peek_poke_address, temp); if (rc) { pr_err("Couldn't write 0x%02x to 0x%02x rc= %d\n", temp, chip->peek_poke_address, rc); return -EAGAIN; } return 0; } DEFINE_SIMPLE_ATTRIBUTE(poke_poke_debug_ops, get_reg, set_reg, "0x%02llx\n"); static int force_irq_set(void *data, u64 val) { struct smb1351_charger *chip = data; smb1351_chg_stat_handler(chip->client->irq, data); return 0; } DEFINE_SIMPLE_ATTRIBUTE(force_irq_ops, NULL, force_irq_set, "0x%02llx\n"); #ifdef DEBUG static void dump_regs(struct smb1351_charger *chip) { int rc; u8 reg; u8 addr; for (addr = 0; addr <= LAST_CNFG_REG; addr++) { rc = smb1351_read_reg(chip, addr, &reg); if (rc) pr_err("Couldn't read 0x%02x rc = %d\n", addr, rc); else pr_debug("0x%02x = 0x%02x\n", addr, reg); } for (addr = FIRST_STATUS_REG; addr <= LAST_STATUS_REG; addr++) { rc = smb1351_read_reg(chip, addr, &reg); if (rc) pr_err("Couldn't read 0x%02x rc = %d\n", addr, rc); else pr_debug("0x%02x = 0x%02x\n", addr, reg); } for (addr = FIRST_CMD_REG; addr <= LAST_CMD_REG; addr++) { rc = smb1351_read_reg(chip, addr, &reg); if (rc) pr_err("Couldn't read 0x%02x rc = %d\n", addr, rc); else pr_debug("0x%02x = 0x%02x\n", addr, reg); } } #else static void dump_regs(struct smb1351_charger *chip) { } #endif #define MAIN_CHG_DEFAULT_FCC_PERCENT 50 #define MAIN_CHG_DEFAULT_ICL_PERCENT 50 static int smb1351_parse_parallel_charger_dt(struct smb1351_charger *chip) { int rc; struct device_node *node = chip->dev->of_node; rc = of_property_read_u32(node, "qcom,parallel-usb-min-current-ma", &chip->parallel.min_current_thr_ma); if (rc && rc != -EINVAL) goto bail_out; rc = of_property_read_u32(node, "qcom,parallel-usb-9v-min-current-ma", &chip->parallel.min_9v_current_thr_ma); if (rc && rc != -EINVAL) goto bail_out; rc = of_property_read_u32(node, "qcom,parallel-usb-12v-min-current-ma", &chip->parallel.min_12v_current_thr_ma); if (rc && rc != -EINVAL) goto bail_out; rc = of_property_read_u32(node, "qcom,parallel-allowed-lowering-ma", &chip->parallel.allowed_lowering_ma); if (rc && rc != -EINVAL) goto bail_out; rc = of_property_read_u32(node, "qcom,parallel-main-chg-fcc-percent", &chip->parallel.main_chg_fcc_percent); if (rc < 0) chip->parallel.main_chg_fcc_percent = MAIN_CHG_DEFAULT_FCC_PERCENT; rc = of_property_read_u32(node, "qcom,parallel-main-chg-icl-percent", &chip->parallel.main_chg_icl_percent); if (rc < 0) chip->parallel.main_chg_icl_percent = MAIN_CHG_DEFAULT_ICL_PERCENT; chip->parallel.avail = true; pr_debug("parallel main charger settings: min_curr = %d, min_9v_curr = %d, min_12v_curr = %d, allowed_lowering = %d, fcc_percent = %d, icl_percent = %d\n", chip->parallel.min_current_thr_ma, chip->parallel.min_9v_current_thr_ma, chip->parallel.min_12v_current_thr_ma, chip->parallel.allowed_lowering_ma, chip->parallel.main_chg_fcc_percent, chip->parallel.main_chg_icl_percent); return 0; bail_out: chip->parallel.min_current_thr_ma = -EINVAL; chip->parallel.min_9v_current_thr_ma = -EINVAL; chip->parallel.min_12v_current_thr_ma = -EINVAL; chip->parallel.allowed_lowering_ma = -EINVAL; pr_debug("parallel charger not support!\n"); return 0; } static int smb1351_parse_dt(struct smb1351_charger *chip) { int rc; struct device_node *node = chip->dev->of_node; if (!node) { pr_err("device tree info. missing\n"); return -EINVAL; } chip->usb_suspended_status = of_property_read_bool(node, "qcom,charging-disabled"); chip->chg_autonomous_mode = of_property_read_bool(node, "qcom,chg-autonomous-mode"); chip->disable_apsd = of_property_read_bool(node, "qcom,disable-apsd"); chip->using_pmic_therm = of_property_read_bool(node, "qcom,using-pmic-therm"); chip->bms_controlled_charging = of_property_read_bool(node, "qcom,bms-controlled-charging"); chip->force_hvdcp_2p0 = of_property_read_bool(node, "qcom,force-hvdcp-2p0"); rc = of_property_read_string(node, "qcom,bms-psy-name", &chip->bms_psy_name); if (rc) chip->bms_psy_name = NULL; chip->resume_soc = -EINVAL; if (of_property_read_bool(node, "qcom,use-external-fg")) { chip->use_external_fg = true; chip->wa_flags |= CHG_FORCE_ESR_WA | CHG_FG_NOTIFY_JEITA | CHG_ITERM_CHECK_SOC; rc = of_property_read_u32(node, "qcom,resume-soc", &chip->resume_soc); if (!rc && chip->resume_soc > 0) chip->wa_flags |= CHG_SOC_BASED_RESUME; } rc = of_property_read_u32(node, "qcom,fastchg-current-max-ma", &chip->target_fastchg_current_max_ma); if (rc) chip->target_fastchg_current_max_ma = SMB1351_CHG_FAST_MAX_MA; chip->iterm_disabled = of_property_read_bool(node, "qcom,iterm-disabled"); rc = of_property_read_u32(node, "qcom,iterm-ma", &chip->iterm_ma); if (rc) chip->iterm_ma = -EINVAL; rc = of_property_read_u32(node, "qcom,float-voltage-mv", &chip->vfloat_mv); if (rc) chip->vfloat_mv = -EINVAL; rc = of_property_read_u32(node, "qcom,recharge-mv", &chip->recharge_mv); if (rc) chip->recharge_mv = -EINVAL; chip->recharge_disabled = of_property_read_bool(node, "qcom,recharge-disabled"); rc = of_property_read_u32(node, "qcom,switch-freq", &chip->switch_freq); if (rc < 0) chip->switch_freq = -EINVAL; /* thermal and jeita support */ rc = of_property_read_u32(node, "qcom,batt-cold-decidegc", &chip->batt_cold_decidegc); if (rc < 0) chip->batt_cold_decidegc = -EINVAL; rc = of_property_read_u32(node, "qcom,batt-hot-decidegc", &chip->batt_hot_decidegc); if (rc < 0) chip->batt_hot_decidegc = -EINVAL; rc = of_property_read_u32(node, "qcom,batt-warm-decidegc", &chip->batt_warm_decidegc); if (rc < 0) chip->batt_warm_decidegc = -EINVAL; rc = of_property_read_u32(node, "qcom,batt-cool-decidegc", &chip->batt_cool_decidegc); if (rc < 0) chip->batt_cool_decidegc = -EINVAL; if ((chip->batt_warm_decidegc != -EINVAL && chip->batt_cool_decidegc != -EINVAL) || (chip->wa_flags & CHG_FG_NOTIFY_JEITA)) { rc = of_property_read_u32(node, "qcom,batt-cool-mv", &chip->batt_cool_mv); rc |= of_property_read_u32(node, "qcom,batt-warm-mv", &chip->batt_warm_mv); rc |= of_property_read_u32(node, "qcom,batt-cool-ma", &chip->batt_cool_ma); rc |= of_property_read_u32(node, "qcom,batt-warm-ma", &chip->batt_warm_ma); if (rc) chip->jeita_supported = false; else if (chip->wa_flags & CHG_FG_NOTIFY_JEITA) chip->fg_notify_jeita = true; else chip->jeita_supported = true; } pr_debug("fg_notify_jeita = %d, jeita_supported = %d\n", chip->fg_notify_jeita, chip->jeita_supported); rc = of_property_read_u32(node, "qcom,batt-missing-decidegc", &chip->batt_missing_decidegc); chip->pinctrl_state_name = of_get_property(node, "pinctrl-names", NULL); smb1351_parse_parallel_charger_dt(chip); return 0; } #define RERUN_APSD_DELAY_MS 1000 static int smb1351_determine_initial_state(struct smb1351_charger *chip) { int rc; u8 reg = 0; /* * It is okay to read the interrupt status here since * interrupts aren't requested. Reading interrupt status * clears the interrupt so be careful to read interrupt * status only in interrupt handling code */ rc = smb1351_read_reg(chip, IRQ_B_REG, &reg); if (rc) { pr_err("Couldn't read IRQ_B rc = %d\n", rc); goto fail_init_status; } chip->battery_missing = (reg & IRQ_BATT_MISSING_BIT) ? true : false; rc = smb1351_read_reg(chip, IRQ_C_REG, &reg); if (rc) { pr_err("Couldn't read IRQ_C rc = %d\n", rc); goto fail_init_status; } chip->batt_full = (reg & IRQ_TERM_BIT) ? true : false; rc = smb1351_read_reg(chip, IRQ_A_REG, &reg); if (rc) { pr_err("Couldn't read irq A rc = %d\n", rc); return rc; } if (reg & IRQ_HOT_HARD_BIT) chip->batt_hot = true; if (reg & IRQ_COLD_HARD_BIT) chip->batt_cold = true; if (reg & IRQ_HOT_SOFT_BIT) chip->batt_warm = true; if (reg & IRQ_COLD_SOFT_BIT) chip->batt_cool = true; rc = smb1351_read_reg(chip, IRQ_E_REG, &reg); if (rc) { pr_err("Couldn't read IRQ_E rc = %d\n", rc); goto fail_init_status; } if (reg & IRQ_USBIN_UV_BIT) { smb1351_usbin_uv_handler(chip, 1); } else { smb1351_stay_awake(&chip->smb1351_ws, RERUN_APSD); schedule_delayed_work(&chip->rerun_apsd_work, msecs_to_jiffies(RERUN_APSD_DELAY_MS)); } rc = smb1351_read_reg(chip, IRQ_G_REG, &reg); if (rc) { pr_err("Couldn't read IRQ_G rc = %d\n", rc); goto fail_init_status; } if (reg & IRQ_SOURCE_DET_BIT) smb1351_apsd_complete_handler(chip, 1); return 0; fail_init_status: pr_err("Couldn't determine initial status\n"); return rc; } static int is_parallel_slave(struct i2c_client *client) { struct device_node *node = client->dev.of_node; return of_property_read_bool(node, "qcom,parallel-charger"); } static int create_debugfs_entries(struct smb1351_charger *chip) { struct dentry *ent; char str[16]; snprintf(str, ARRAY_SIZE(str), "smb1351_%s", chip->is_slave ? "slave" : "main"); chip->debug_root = debugfs_create_dir(str, NULL); if (!chip->debug_root) { pr_err("Couldn't create debug dir\n"); } else { ent = debugfs_create_file("config_registers", S_IFREG | S_IRUGO, chip->debug_root, chip, &cnfg_debugfs_ops); if (!ent) pr_err("Couldn't create cnfg debug file\n"); ent = debugfs_create_file("status_registers", S_IFREG | S_IRUGO, chip->debug_root, chip, &status_debugfs_ops); if (!ent) pr_err("Couldn't create status debug file\n"); ent = debugfs_create_file("cmd_registers", S_IFREG | S_IRUGO, chip->debug_root, chip, &cmd_debugfs_ops); if (!ent) pr_err("Couldn't create cmd debug file\n"); ent = debugfs_create_x32("address", S_IFREG | S_IWUSR | S_IRUGO, chip->debug_root, &(chip->peek_poke_address)); if (!ent) pr_err("Couldn't create address debug file\n"); ent = debugfs_create_file("data", S_IFREG | S_IWUSR | S_IRUGO, chip->debug_root, chip, &poke_poke_debug_ops); if (!ent) pr_err("Couldn't create data debug file\n"); if (!chip->is_slave) { ent = debugfs_create_file("force_irq", S_IFREG | S_IWUSR | S_IRUGO, chip->debug_root, chip, &force_irq_ops); if (!ent) pr_err("Couldn't create data debug file\n"); ent = debugfs_create_file("irq_count", S_IFREG | S_IRUGO, chip->debug_root, chip, &irq_count_debugfs_ops); if (!ent) pr_err("Couldn't create count debug file\n"); } } return 0; } static int smb1351_main_charger_probe(struct i2c_client *client, const struct i2c_device_id *id) { int rc; struct smb1351_charger *chip; struct power_supply *usb_psy; u8 reg = 0; usb_psy = power_supply_get_by_name("usb"); if (!usb_psy) { pr_debug("USB psy not found; deferring probe\n"); return -EPROBE_DEFER; } chip = devm_kzalloc(&client->dev, sizeof(*chip), GFP_KERNEL); if (!chip) { pr_err("Couldn't allocate memory\n"); return -ENOMEM; } chip->client = client; chip->dev = &client->dev; chip->usb_psy = usb_psy; chip->fake_battery_soc = -EINVAL; INIT_DELAYED_WORK(&chip->chg_remove_work, smb1351_chg_remove_work); INIT_DELAYED_WORK(&chip->hvdcp_det_work, smb1351_hvdcp_det_work); INIT_DELAYED_WORK(&chip->rerun_apsd_work, smb1351_rerun_apsd_work); smb1351_wakeup_src_init(chip); /* probe the device to check if its actually connected */ rc = smb1351_read_reg(chip, CHG_REVISION_REG, &reg); if (rc) { pr_err("Failed to detect smb1351, device may be absent\n"); rc = -ENODEV; goto trash_ws; } pr_debug("smb1351 chip revision is %d\n", reg); rc = smb1351_parse_dt(chip); if (rc) { pr_err("Couldn't parse DT nodes rc=%d\n", rc); goto trash_ws; } /* using vadc and adc_tm for implementing pmic therm */ if (chip->using_pmic_therm) { chip->vadc_dev = qpnp_get_vadc(chip->dev, "chg"); if (IS_ERR(chip->vadc_dev)) { rc = PTR_ERR(chip->vadc_dev); if (rc != -EPROBE_DEFER) pr_err("vadc property missing\n"); goto trash_ws; } chip->adc_tm_dev = qpnp_get_adc_tm(chip->dev, "chg"); if (IS_ERR(chip->adc_tm_dev)) { rc = PTR_ERR(chip->adc_tm_dev); if (rc != -EPROBE_DEFER) pr_err("adc_tm property missing\n"); goto trash_ws; } } i2c_set_clientdata(client, chip); chip->batt_psy.name = "battery"; chip->batt_psy.type = POWER_SUPPLY_TYPE_BATTERY; chip->batt_psy.get_property = smb1351_battery_get_property; chip->batt_psy.set_property = smb1351_battery_set_property; chip->batt_psy.property_is_writeable = smb1351_batt_property_is_writeable; chip->batt_psy.properties = smb1351_battery_properties; chip->batt_psy.num_properties = ARRAY_SIZE(smb1351_battery_properties); chip->batt_psy.external_power_changed = smb1351_external_power_changed; chip->batt_psy.supplied_to = pm_batt_supplied_to; chip->batt_psy.num_supplicants = ARRAY_SIZE(pm_batt_supplied_to); chip->resume_completed = true; mutex_init(&chip->irq_complete); mutex_init(&chip->fcc_lock); mutex_init(&chip->parallel.lock); rc = power_supply_register(chip->dev, &chip->batt_psy); if (rc) { pr_err("Couldn't register batt psy rc=%d\n", rc); goto destroy_mutex; } INIT_DELAYED_WORK(&chip->parallel.parallel_work, smb1351_parallel_work); INIT_DELAYED_WORK(&chip->init_fg_work, smb1351_init_fg_work); INIT_DELAYED_WORK(&chip->iterm_check_soc_work, smb1351_iterm_check_soc_work); dump_regs(chip); rc = smb1351_regulator_init(chip); if (rc) { pr_err("Couldn't initialize smb1351 ragulator rc=%d\n", rc); goto fail_smb1351_regulator_init; } rc = smb1351_hw_init(chip); if (rc) { pr_err("Couldn't intialize hardware rc=%d\n", rc); goto fail_smb1351_hw_init; } rc = smb1351_determine_initial_state(chip); if (rc) { pr_err("Couldn't determine initial state rc=%d\n", rc); goto fail_smb1351_hw_init; } /* STAT irq configuration */ if (client->irq) { rc = devm_request_threaded_irq(&client->dev, client->irq, NULL, smb1351_chg_stat_handler, IRQF_ONESHOT, "smb1351_chg_stat_irq", chip); if (rc) { pr_err("Failed STAT irq=%d request rc = %d\n", client->irq, rc); goto fail_smb1351_hw_init; } enable_irq_wake(client->irq); } if (chip->using_pmic_therm) { if (!chip->jeita_supported) { /* add hot/cold temperature monitor */ chip->adc_param.low_temp = chip->batt_cold_decidegc; chip->adc_param.high_temp = chip->batt_hot_decidegc; } else { chip->adc_param.low_temp = chip->batt_cool_decidegc; chip->adc_param.high_temp = chip->batt_warm_decidegc; } chip->adc_param.timer_interval = ADC_MEAS2_INTERVAL_1S; chip->adc_param.state_request = ADC_TM_WARM_COOL_THR_ENABLE; chip->adc_param.btm_ctx = chip; chip->adc_param.threshold_notification = smb1351_chg_adc_notification; chip->adc_param.channel = LR_MUX1_BATT_THERM; rc = qpnp_adc_tm_channel_measure(chip->adc_tm_dev, &chip->adc_param); if (rc) { pr_err("requesting ADC error %d\n", rc); goto fail_smb1351_hw_init; } } create_debugfs_entries(chip); dump_regs(chip); pr_info("smb1351 successfully probed. charger=%d, batt=%d version=%s\n", chip->chg_present, smb1351_get_prop_batt_present(chip), smb1351_version_str[chip->version]); return 0; fail_smb1351_hw_init: regulator_unregister(chip->otg_vreg.rdev); fail_smb1351_regulator_init: power_supply_unregister(&chip->batt_psy); destroy_mutex: mutex_destroy(&chip->irq_complete); mutex_destroy(&chip->fcc_lock); mutex_destroy(&chip->parallel.lock); trash_ws: wakeup_source_trash(&chip->smb1351_ws.source); return rc; } static int smb1351_parallel_slave_probe(struct i2c_client *client, const struct i2c_device_id *id) { int rc; struct smb1351_charger *chip; struct device_node *node = client->dev.of_node; chip = devm_kzalloc(&client->dev, sizeof(*chip), GFP_KERNEL); if (!chip) { pr_err("Couldn't allocate memory\n"); return -ENOMEM; } chip->client = client; chip->dev = &client->dev; chip->is_slave = true; chip->usb_suspended_status = of_property_read_bool(node, "qcom,charging-disabled"); rc = of_property_read_u32(node, "qcom,float-voltage-mv", &chip->vfloat_mv); if (rc) chip->vfloat_mv = -EINVAL; rc = of_property_read_u32(node, "qcom,recharge-mv", &chip->recharge_mv); if (rc) chip->recharge_mv = -EINVAL; rc = of_property_read_u32(node, "qcom,parallel-en-pin-polarity", &chip->parallel_pin_polarity_setting); if (rc) chip->parallel_pin_polarity_setting = EN_BY_PIN_LOW_ENABLE; else chip->parallel_pin_polarity_setting = chip->parallel_pin_polarity_setting ? EN_BY_PIN_HIGH_ENABLE : EN_BY_PIN_LOW_ENABLE; i2c_set_clientdata(client, chip); chip->parallel_psy.name = "usb-parallel"; chip->parallel_psy.type = POWER_SUPPLY_TYPE_USB_PARALLEL; chip->parallel_psy.get_property = smb1351_parallel_get_property; chip->parallel_psy.set_property = smb1351_parallel_set_property; chip->parallel_psy.properties = smb1351_parallel_properties; chip->parallel_psy.property_is_writeable = smb1351_parallel_is_writeable; chip->parallel_psy.num_properties = ARRAY_SIZE(smb1351_parallel_properties); mutex_init(&chip->fcc_lock); mutex_init(&chip->irq_complete); smb1351_wakeup_src_init(chip); rc = power_supply_register(chip->dev, &chip->parallel_psy); if (rc) { pr_err("Couldn't register parallel psy rc=%d\n", rc); goto fail_register_psy; } chip->resume_completed = true; create_debugfs_entries(chip); pr_info("smb1351 parallel successfully probed.\n"); return 0; fail_register_psy: wakeup_source_trash(&chip->smb1351_ws.source); mutex_destroy(&chip->irq_complete); mutex_destroy(&chip->fcc_lock); return rc; } static int smb1351_charger_probe(struct i2c_client *client, const struct i2c_device_id *id) { if (is_parallel_slave(client)) return smb1351_parallel_slave_probe(client, id); else return smb1351_main_charger_probe(client, id); } static int smb1351_charger_remove(struct i2c_client *client) { struct smb1351_charger *chip = i2c_get_clientdata(client); cancel_delayed_work_sync(&chip->chg_remove_work); power_supply_unregister(&chip->batt_psy); wakeup_source_trash(&chip->smb1351_ws.source); mutex_destroy(&chip->irq_complete); mutex_destroy(&chip->fcc_lock); if (is_parallel_slave(client)) mutex_destroy(&chip->parallel.lock); debugfs_remove_recursive(chip->debug_root); return 0; } static int smb1351_suspend(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct smb1351_charger *chip = i2c_get_clientdata(client); /* no suspend resume activities for parallel charger */ if (chip->is_slave) return 0; mutex_lock(&chip->irq_complete); chip->resume_completed = false; mutex_unlock(&chip->irq_complete); return 0; } static int smb1351_suspend_noirq(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct smb1351_charger *chip = i2c_get_clientdata(client); /* no suspend resume activities for parallel charger */ if (chip->is_slave) return 0; if (chip->irq_waiting) { pr_err_ratelimited("Aborting suspend, an interrupt was detected while suspending\n"); return -EBUSY; } return 0; } static int smb1351_resume(struct device *dev) { struct i2c_client *client = to_i2c_client(dev); struct smb1351_charger *chip = i2c_get_clientdata(client); /* no suspend resume activities for parallel charger */ if (chip->is_slave) return 0; mutex_lock(&chip->irq_complete); chip->resume_completed = true; if (chip->irq_waiting) { mutex_unlock(&chip->irq_complete); smb1351_chg_stat_handler(client->irq, chip); enable_irq(client->irq); } else { mutex_unlock(&chip->irq_complete); } return 0; } static const struct dev_pm_ops smb1351_pm_ops = { .suspend = smb1351_suspend, .suspend_noirq = smb1351_suspend_noirq, .resume = smb1351_resume, }; static struct of_device_id smb1351_match_table[] = { { .compatible = "qcom,smb1351-charger",}, { }, }; static const struct i2c_device_id smb1351_charger_id[] = { {"smb1351-charger", 0}, {}, }; MODULE_DEVICE_TABLE(i2c, smb1351_charger_id); static struct i2c_driver smb1351_charger_driver = { .driver = { .name = "smb1351-charger", .owner = THIS_MODULE, .of_match_table = smb1351_match_table, .pm = &smb1351_pm_ops, }, .probe = smb1351_charger_probe, .remove = smb1351_charger_remove, .id_table = smb1351_charger_id, }; module_i2c_driver(smb1351_charger_driver); MODULE_DESCRIPTION("smb1351 Charger"); MODULE_LICENSE("GPL v2"); MODULE_ALIAS("i2c:smb1351-charger");
Alucard24/Alucard-Kernel-LG-G5
drivers/power/smb1351-charger.c
C
gpl-2.0
129,937
<?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
; ( -- ) ; R( -- ) VE_RBRACKET: .db $01, "]" .dw VE_HEAD .set VE_HEAD = VE_RBRACKET XT_RBRACKET: .dw DO_COLON PFA_RBRACKET: .dw XT_DOLITERAL .dw 1 .dw XT_STATE .dw XT_STORE .dw XT_EXIT
ytmytm/avr-amforth-90S8515
words/rightbracket.asm
Assembly
gpl-2.0
222
<?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
#include <linux/module.h> #include <linux/vermagic.h> #include <linux/compiler.h> MODULE_INFO(vermagic, VERMAGIC_STRING); __visible struct module __this_module __attribute__((section(".gnu.linkonce.this_module"))) = { .name = KBUILD_MODNAME, .init = init_module, #ifdef CONFIG_MODULE_UNLOAD .exit = cleanup_module, #endif .arch = MODULE_ARCH_INIT, }; MODULE_INFO(intree, "Y"); static const struct modversion_info ____versions[] __used __attribute__((section("__versions"))) = { { 0xb95b937f, __VMLINUX_SYMBOL_STR(module_layout) }, { 0x2e5810c6, __VMLINUX_SYMBOL_STR(__aeabi_unwind_cpp_pr1) }, { 0xe225af02, __VMLINUX_SYMBOL_STR(led_trigger_event) }, { 0xb1ad28e0, __VMLINUX_SYMBOL_STR(__gnu_mcount_nc) }, { 0x5eaab8a3, __VMLINUX_SYMBOL_STR(led_trigger_unregister_simple) }, { 0x9b7c1e68, __VMLINUX_SYMBOL_STR(led_trigger_register_simple) }, }; static const char __module_depends[] __used __attribute__((section(".modinfo"))) = "depends="; MODULE_INFO(srcversion, "232663F6477C9D5D6F7F695");
avareldalton85/rpi2-linux-rt
drivers/leds/trigger/ledtrig-camera.mod.c
C
gpl-2.0
1,008
/* Unix SMB/Netbios implementation. Version 1.9. NBT netbios library routines Copyright (C) Andrew Tridgell 1994-1998 Copyright (C) Luke Kenneth Casson Leighton 1994-1998 Copyright (C) Jeremy Allison 1994-1998 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ #include "includes.h" extern int ClientNMB; int num_response_packets = 0; /*************************************************************************** Add an expected response record into the list **************************************************************************/ static void add_response_record(struct subnet_record *subrec, struct response_record *rrec) { struct response_record *rrec2; num_response_packets++; /* count of total number of packets still around */ DEBUG(4,("add_response_record: adding response record id:%hu to subnet %s. num_records:%d\n", rrec->response_id, subrec->subnet_name, num_response_packets)); if (!subrec->responselist) { subrec->responselist = rrec; rrec->prev = NULL; rrec->next = NULL; return; } for (rrec2 = subrec->responselist; rrec2->next; rrec2 = rrec2->next) ; rrec2->next = rrec; rrec->next = NULL; rrec->prev = rrec2; } /*************************************************************************** Remove an expected response record from the list **************************************************************************/ void remove_response_record(struct subnet_record *subrec, struct response_record *rrec) { if (rrec->prev) rrec->prev->next = rrec->next; if (rrec->next) rrec->next->prev = rrec->prev; if (subrec->responselist == rrec) subrec->responselist = rrec->next; if(rrec->userdata) { if(rrec->userdata->free_fn) { (*rrec->userdata->free_fn)(rrec->userdata); } else { ZERO_STRUCTP(rrec->userdata); SAFE_FREE(rrec->userdata); } } /* Ensure we can delete. */ rrec->packet->locked = False; free_packet(rrec->packet); ZERO_STRUCTP(rrec); SAFE_FREE(rrec); num_response_packets--; /* count of total number of packets still around */ } /**************************************************************************** Create a response record for an outgoing packet. **************************************************************************/ struct response_record *make_response_record( struct subnet_record *subrec, struct packet_struct *p, response_function resp_fn, timeout_response_function timeout_fn, success_function success_fn, fail_function fail_fn, struct userdata_struct *userdata) { struct response_record *rrec; struct nmb_packet *nmb = &p->packet.nmb; if (!(rrec = (struct response_record *)malloc(sizeof(*rrec)))) { DEBUG(0,("make_response_queue_record: malloc fail for response_record.\n")); return NULL; } memset((char *)rrec, '\0', sizeof(*rrec)); rrec->response_id = nmb->header.name_trn_id; rrec->resp_fn = resp_fn; rrec->timeout_fn = timeout_fn; rrec->success_fn = success_fn; rrec->fail_fn = fail_fn; rrec->packet = p; if(userdata) { /* Intelligent userdata. */ if(userdata->copy_fn) { if((rrec->userdata = (*userdata->copy_fn)(userdata)) == NULL) { DEBUG(0,("make_response_queue_record: copy fail for userdata.\n")); ZERO_STRUCTP(rrec); SAFE_FREE(rrec); return NULL; } } else { /* Primitive userdata, do a memcpy. */ if((rrec->userdata = (struct userdata_struct *) malloc(sizeof(struct userdata_struct)+userdata->userdata_len)) == NULL) { DEBUG(0,("make_response_queue_record: malloc fail for userdata.\n")); ZERO_STRUCTP(rrec); SAFE_FREE(rrec); return NULL; } rrec->userdata->copy_fn = userdata->copy_fn; rrec->userdata->free_fn = userdata->free_fn; rrec->userdata->userdata_len = userdata->userdata_len; memcpy(rrec->userdata->data, userdata->data, userdata->userdata_len); } } else rrec->userdata = NULL; rrec->num_msgs = 0; if(!nmb->header.nm_flags.bcast) rrec->repeat_interval = 5; /* 5 seconds for unicast packets. */ else rrec->repeat_interval = 1; /* XXXX should be in ms */ rrec->repeat_count = 3; /* 3 retries */ rrec->repeat_time = time(NULL) + rrec->repeat_interval; /* initial retry time */ /* This packet is not being processed. */ rrec->in_expiration_processing = False; /* Lock the packet so we won't lose it while it's on the list. */ p->locked = True; add_response_record(subrec, rrec); return rrec; } /**************************************************************************** Find a response in a subnet's name query response list. **************************************************************************/ static struct response_record *find_response_record_on_subnet( struct subnet_record *subrec, uint16 id) { struct response_record *rrec = NULL; for (rrec = subrec->responselist; rrec; rrec = rrec->next) { if (rrec->response_id == id) { DEBUG(4, ("find_response_record: found response record id = %hu on subnet %s\n", id, subrec->subnet_name)); break; } } return rrec; } /**************************************************************************** Find a response in any subnet's name query response list. **************************************************************************/ struct response_record *find_response_record(struct subnet_record **ppsubrec, uint16 id) { struct response_record *rrec = NULL; for ((*ppsubrec) = FIRST_SUBNET; (*ppsubrec); (*ppsubrec) = NEXT_SUBNET_INCLUDING_UNICAST(*ppsubrec)) { if((rrec = find_response_record_on_subnet(*ppsubrec, id)) != NULL) return rrec; } /* There should never be response records on the remote_broadcast subnet. Sanity check to ensure this is so. */ if(remote_broadcast_subnet->responselist != NULL) { DEBUG(0,("find_response_record: response record found on subnet %s. This should \ never happen !\n", remote_broadcast_subnet->subnet_name)); } /* Now check the WINS server subnet if it exists. */ if(wins_server_subnet != NULL) { *ppsubrec = wins_server_subnet; if((rrec = find_response_record_on_subnet(*ppsubrec, id))!= NULL) return rrec; } DEBUG(0,("find_response_record: response packet id %hu received with no \ matching record.\n", id)); *ppsubrec = NULL; return NULL; } /**************************************************************************** Check if a refresh is queued for a particular name on a particular subnet. **************************************************************************/ BOOL is_refresh_already_queued(struct subnet_record *subrec, struct name_record *namerec) { struct response_record *rrec = NULL; for (rrec = subrec->responselist; rrec; rrec = rrec->next) { struct packet_struct *p = rrec->packet; struct nmb_packet *nmb = &p->packet.nmb; if((nmb->header.opcode == NMB_NAME_REFRESH_OPCODE_8) || (nmb->header.opcode == NMB_NAME_REFRESH_OPCODE_9)) { /* Yes it's a queued refresh - check if the name is correct. */ if(nmb_name_equal(&nmb->question.question_name, &namerec->name)) return True; } } return False; }
jophxy/samba
source/nambd/nmbd_responserecordsdb.c
C
gpl-2.0
8,136
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!--NewPage--> <HTML> <HEAD> <!-- Generated by javadoc (build 1.6.0_26) on Sun Aug 07 21:00:26 CEST 2011 --> <TITLE> de.hsa.jam.ui Class Hierarchy </TITLE> <META NAME="date" CONTENT="2011-08-07"> <LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../stylesheet.css" TITLE="Style"> <SCRIPT type="text/javascript"> function windowTitle() { if (location.href.indexOf('is-external=true') == -1) { parent.document.title="de.hsa.jam.ui Class Hierarchy"; } } </SCRIPT> <NOSCRIPT> </NOSCRIPT> </HEAD> <BODY BGCOLOR="white" onload="windowTitle();"> <HR> <!-- ========= START OF TOP NAVBAR ======= --> <A NAME="navbar_top"><!-- --></A> <A HREF="#skip-navbar_top" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_top_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../de/hsa/jam/evaluation/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../de/hsa/jam/util/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?de/hsa/jam/ui/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_top"></A> <!-- ========= END OF TOP NAVBAR ========= --> <HR> <CENTER> <H2> Hierarchy For Package de.hsa.jam.ui </H2> </CENTER> <DL> <DT><B>Package Hierarchies:</B><DD><A HREF="../../../../overview-tree.html">All Packages</A></DL> <HR> <H2> Class Hierarchy </H2> <UL> <LI TYPE="circle">java.lang.Object<UL> <LI TYPE="circle">de.hsa.jam.ui.<A HREF="../../../../de/hsa/jam/ui/AbstractView.html" title="class in de.hsa.jam.ui"><B>AbstractView</B></A><UL> <LI TYPE="circle">de.hsa.jam.ui.<A HREF="../../../../de/hsa/jam/ui/ChromaticTunerFrame.html" title="class in de.hsa.jam.ui"><B>ChromaticTunerFrame</B></A><LI TYPE="circle">de.hsa.jam.ui.<A HREF="../../../../de/hsa/jam/ui/MainWindow.html" title="class in de.hsa.jam.ui"><B>MainWindow</B></A><LI TYPE="circle">de.hsa.jam.ui.<A HREF="../../../../de/hsa/jam/ui/MetronomeFrame.html" title="class in de.hsa.jam.ui"><B>MetronomeFrame</B></A></UL> <LI TYPE="circle">java.awt.Component (implements java.awt.image.ImageObserver, java.awt.MenuContainer, java.io.Serializable) <UL> <LI TYPE="circle">java.awt.Container<UL> <LI TYPE="circle">javax.swing.JComponent (implements java.io.Serializable) <UL> <LI TYPE="circle">javax.swing.JPanel (implements javax.accessibility.Accessible) <UL> <LI TYPE="circle">de.hsa.jam.ui.<A HREF="../../../../de/hsa/jam/ui/SimplePlotterFrame.html" title="class in de.hsa.jam.ui"><B>SimplePlotterFrame</B></A> (implements java.lang.Runnable) </UL> <LI TYPE="circle">abc.ui.swing.JScoreComponent (implements abc.ui.swing.ScoreTemplateChangeListener) <UL> <LI TYPE="circle">de.hsa.jam.ui.<A HREF="../../../../de/hsa/jam/ui/ScorePanel.html" title="class in de.hsa.jam.ui"><B>ScorePanel</B></A></UL> </UL> </UL> </UL> <LI TYPE="circle">javax.swing.filechooser.FileFilter<UL> <LI TYPE="circle">de.hsa.jam.ui.<A HREF="../../../../de/hsa/jam/ui/CustomFileFilter.html" title="class in de.hsa.jam.ui"><B>CustomFileFilter</B></A></UL> </UL> </UL> <HR> <!-- ======= START OF BOTTOM NAVBAR ====== --> <A NAME="navbar_bottom"><!-- --></A> <A HREF="#skip-navbar_bottom" title="Skip navigation links"></A> <TABLE BORDER="0" WIDTH="100%" CELLPADDING="1" CELLSPACING="0" SUMMARY=""> <TR> <TD COLSPAN=2 BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A NAME="navbar_bottom_firstrow"><!-- --></A> <TABLE BORDER="0" CELLPADDING="0" CELLSPACING="3" SUMMARY=""> <TR ALIGN="center" VALIGN="top"> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../overview-summary.html"><FONT CLASS="NavBarFont1"><B>Overview</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="package-summary.html"><FONT CLASS="NavBarFont1"><B>Package</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Class</FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <FONT CLASS="NavBarFont1">Use</FONT>&nbsp;</TD> <TD BGCOLOR="#FFFFFF" CLASS="NavBarCell1Rev"> &nbsp;<FONT CLASS="NavBarFont1Rev"><B>Tree</B></FONT>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../deprecated-list.html"><FONT CLASS="NavBarFont1"><B>Deprecated</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../index-files/index-1.html"><FONT CLASS="NavBarFont1"><B>Index</B></FONT></A>&nbsp;</TD> <TD BGCOLOR="#EEEEFF" CLASS="NavBarCell1"> <A HREF="../../../../help-doc.html"><FONT CLASS="NavBarFont1"><B>Help</B></FONT></A>&nbsp;</TD> </TR> </TABLE> </TD> <TD ALIGN="right" VALIGN="top" ROWSPAN=3><EM> </EM> </TD> </TR> <TR> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> &nbsp;<A HREF="../../../../de/hsa/jam/evaluation/package-tree.html"><B>PREV</B></A>&nbsp; &nbsp;<A HREF="../../../../de/hsa/jam/util/package-tree.html"><B>NEXT</B></A></FONT></TD> <TD BGCOLOR="white" CLASS="NavBarCell2"><FONT SIZE="-2"> <A HREF="../../../../index.html?de/hsa/jam/ui/package-tree.html" target="_top"><B>FRAMES</B></A> &nbsp; &nbsp;<A HREF="package-tree.html" target="_top"><B>NO FRAMES</B></A> &nbsp; &nbsp;<SCRIPT type="text/javascript"> <!-- if(window==top) { document.writeln('<A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A>'); } //--> </SCRIPT> <NOSCRIPT> <A HREF="../../../../allclasses-noframe.html"><B>All Classes</B></A> </NOSCRIPT> </FONT></TD> </TR> </TABLE> <A NAME="skip-navbar_bottom"></A> <!-- ======== END OF BOTTOM NAVBAR ======= --> <HR> </BODY> </HTML>
mwager/jAM
docs/javadoc/de/hsa/jam/ui/package-tree.html
HTML
gpl-2.0
7,434
<?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
#include <stdio.h> int main() { int a, b; float c, d; a = 13; b = 5; c = a / b; // divide using integers d = (float) a / (float) b; // divide integers typecast as floats printf("[integers]\t a = %d\t b = %d\n", a, b); printf("[floats]\t c = %f\t d = %f\n", c, d); } =========================================================OUTPUT=========================================== #cd Desktop #gcc -o typecasting typecasting.c #./typecasting [integers] a = 13 b = 5 [floats] c = 2.000000 d = 2.600000
sachinnuwarad/-The-Art-of-Exploitation
type_casting.c
C
gpl-2.0
564
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>Todo</title> <meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width"> <link href="lib/ionic/css/ionic.css" rel="stylesheet"> <script src="lib/ionic/js/ionic.bundle.js"></script> <script src="js/app.js"></script> <!-- Needed for Cordova/PhoneGap (will be a 404 during development) --> <script src="cordova.js"></script> </head> <body ng-app="todo" ng-controller="TodoCtrl"> <ion-side-menus> <!-- Center content --> <ion-side-menu-content> <ion-header-bar class="bar-dark"> <button class="button button-icon" ng-click="toggleProjects()"> <i class="icon ion-navicon"></i> </button> <h1 class="title">{{activeProject.title}}</h1> <!-- New Task button--> <button class="button button-icon" ng-click="newTask()"> <i class="icon ion-compose"></i> </button> </ion-header-bar> <ion-content scroll="false"> <ion-list> <ion-item ng-repeat="task in activeProject.tasks"> {{task.title}} </ion-item> </ion-list> </ion-content> </ion-side-menu-content> <!-- Left menu --> <ion-side-menu side="left"> <ion-header-bar class="bar-dark"> <h1 class="title">Projects</h1> <button class="button button-icon ion-plus" ng-click="newProject()"> </button> </ion-header-bar> <ion-content scroll="false"> <ion-list> <ion-item ng-repeat="project in projects" ng-click="selectProject(project, $index)" ng-class="{active: activeProject == project}"> {{project.title}} </ion-item> </ion-list> </ion-content> </ion-side-menu> <script id="new-task.html" type="text/ng-template"> <div class="modal"> <!-- Modal header bar --> <ion-header-bar class="bar-secondary"> <h1 class="title">New Task</h1> <button class="button button-clear button-positive" ng-click="closeNewTask()">Cancel</button> </ion-header-bar> <!-- Modal content area --> <ion-content> <form ng-submit="createTask(task)"> <div class="list"> <label class="item item-input"> <input type="text" placeholder="What do you need to do?" ng-model="task.title"> </label> </div> <div class="padding"> <button type="submit" class="button button-block button-positive">Create Task</button> </div> </form> </ion-content> </div> </script> </ion-side-menus> </body> </html>
bonobo-coop/ionic-demo
src/www/index.html
HTML
gpl-2.0
2,846
--require "VolatilitySpec" local QuantCORE = QuantCORE(); local ParameterManager = QuantCORE:ParameterManager(); function OnParameterNotify( key, paramType, fromSnapshot ) if fromSnapshot == true then print("----------fromSnapshot = true--------") else print("----------fromSnapshot = false-------") end print("OnParameterNotify()"); print("Key="..key); print("Parameter type="..ParameterTypeToString(paramType)); -- Get table of VolatilitySpecification for key local specs = ParameterManager:GetVolatilitySpec(key); if specs == nil then print("No VolatilitySpecification found in parameter manager for key="..key); else print("The VolatilitySpecification number ="..#specs); -- Print details in each VolatilitySpecification local specIndex = 1; while (specIndex <= #specs) do local volSpec = specs[specIndex]; print("Key of spec"..specIndex.."="..volSpec:GetKey()); local volSeriesTable = volSpec:GetVolSeries(); if volSeriesTable == nil then print("No volatility series get from VolatilitySpecification"); return; end print("volatility series number in spec"..specIndex.." = "..#volSeriesTable); -- Print all volatility series in each VolatilitySpecification local seriesIndex = 1; while (seriesIndex <= #volSeriesTable) do local volSeries = volSeriesTable[seriesIndex]; if volSeries == nil then print("No volatility series!"); return; end print("Expire date="..volSeries:GetExpireDate():AsString()); print("Expire label="..volSeries:GetExpireLabel()); local volTable = volSeries:GetVolatilities(); if volTable == nil then print("No volatilities get from VolatilitySeries"); return; end print("Volatilities numer = "..#volTable); local index = 1; while (index <= #volTable) do local vol = volTable[index]; print("Strike: "..tostring(vol:GetStrike())); print("Volatility: "..tostring(vol:GetVolatility())); index = index+1 end seriesIndex = seriesIndex + 1; end specIndex = specIndex+1 end end end
MarcusChang/Repo-QUANTengine
QUANTengine/QuantENGINE_API/QuantMGR/ParameterManager/VolatilitySpec/stateless.lua
Lua
gpl-2.0
2,582
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
/* * Copyright (c) 2010 Mark Liversedge (liversedge@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 */ #include <QMacCocoaViewContainer> //---------------------------------------------------------------------- // Cocoa / OBJC helpers etc // // this is a utility -- since this source file // is included in C++ and Objective-C code the // declaration of native components is referenced // directly or just as a void * //---------------------------------------------------------------------- class CocoaInitializer { public: CocoaInitializer(); ~CocoaInitializer(); private: class Private; Private* d; }; #ifdef __OBJC__ # define ADD_COCOA_NATIVE_REF(CocoaClass) \ @class CocoaClass; \ typedef CocoaClass *Native##CocoaClass##Ref #else /* __OBJC__ */ # define ADD_COCOA_NATIVE_REF(CocoaClass) typedef void *Native##CocoaClass##Ref #endif /* __OBJC__ */ // The above is merely to do the following, but // we may add more native widgets in the future ADD_COCOA_NATIVE_REF (NSSegmentedControl); // The native Cocoa segmented button is held within // a QMacCocoaView container. class QtMacSegmentedButton : public QMacCocoaViewContainer { Q_OBJECT; public: QtMacSegmentedButton (int aCount, QWidget *aParent = 0); QSize sizeHint() const; void setTitle (int aSegment, const QString &aTitle); void setToolTip (int aSegment, const QString &aTip); void setEnabled (int aSegment, bool fEnabled); void setSelected(int index) const; void animateClick (int aSegment); void onClicked (int aSegment); signals: void clicked (int aSegment, bool aChecked = false); private: /* Private member vars */ NativeNSSegmentedControlRef mNativeRef; };
g3rg/GoldenCheetah
src/QtMacSegmentedButton.h
C
gpl-2.0
2,417
<?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
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no" name="viewport"> <title>FlexMonitor | Log in</title> <link rel="stylesheet" href="bower_components/AdminLTE/bootstrap/css/bootstrap.min.css"> <link rel="stylesheet" href="bower_components/AdminLTE/dist/css/AdminLTE.min.css"> </head> <body class="hold-transition login-page" ng-app="flexAppLogin"> <div class="login-box" ng-controller="flexLoginCtrl"> <div class="login-logo"> <a href="#/"><i><b>Flex</b>Monitor</i></a> </div> <div class="login-box-body"> <p class="login-box-msg">Informe suas credenciais para iniciar a sessão</p> <form> <div class="form-group has-feedback"> <input type="text" class="form-control" placeholder="Usuário" ng-model="user.username"> <span class="glyphicon glyphicon-user form-control-feedback"></span> </div> <div class="form-group has-feedback"> <input type="password" class="form-control" placeholder="Senha" ng-model="user.password"> <span class="glyphicon glyphicon-lock form-control-feedback"></span> </div> <div ng-show="errorMessage"> <p class="text-red"><i class="glyphicon glyphicon-remove"></i> {{errorMessage}}</p> </div> <div> <button type="submit" ng-click="login(user)" class="btn btn-primary btn-block">Entrar</button> </div> </form> <hr> <div> <div class="pull-right"> <b>Versão</b> 1.0.0 </div> <strong><a href="http://www.celtab.org.br/" target="_blank"><i>Celtab</i></a></strong> </div> </div> </div> <script type="text/javascript" src="bower_components/angular/angular.min.js"></script> <script> angular.module('flexAppLogin', []).controller('flexLoginCtrl', function($scope, $http){ $scope.login = function(user){ $http.post(window.location.origin + '/login', user).success(function(data){ localStorage.setItem('flexUser', angular.toJson(data)); window.location = window.location.origin; }).error(function(data){ $scope.errorMessage = data.message; $scope.user = null; }); } }); </script> </body> </html>
CELTAB/rfidmonitor-platform
web-dev/public/login/index.html
HTML
gpl-2.0
2,430
<?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
/** ****************************************************************************** * @file PWR/PWR_CurrentConsumption/stm32f4xx_lp_modes.c * @author MCD Application Team * @version V1.2.3 * @date 09-October-2015 * @brief This file provides firmware functions to manage the following * functionalities of the STM32F4xx Low Power Modes: * - Sleep Mode * - STOP mode with RTC * - STANDBY mode without RTC and BKPSRAM * - STANDBY mode with RTC * - STANDBY mode with RTC and BKPSRAM ****************************************************************************** * @attention * * <h2><center>&copy; COPYRIGHT(c) 2015 STMicroelectronics</center></h2> * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. Neither the name of STMicroelectronics nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER * CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, * OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************** */ /* Includes ------------------------------------------------------------------*/ #include "main.h" /** @addtogroup STM32F4xx_HAL_Examples * @{ */ /** @addtogroup PWR_CurrentConsumption * @{ */ /* Private typedef -----------------------------------------------------------*/ /* Private define ------------------------------------------------------------*/ /* Private macro -------------------------------------------------------------*/ /* Private variables ---------------------------------------------------------*/ /* RTC handler declaration */ RTC_HandleTypeDef RTCHandle; /* Private function prototypes -----------------------------------------------*/ static void SYSCLKConfig_STOP(void); /* Private functions ---------------------------------------------------------*/ /** * @brief This function configures the system to enter Sleep mode for * current consumption measurement purpose. * Sleep Mode * ========== * - System Running at PLL (168MHz) * - Flash 5 wait state * - Instruction and Data caches ON * - Prefetch ON * - Code running from Internal FLASH * - All peripherals disabled. * - Wakeup using EXTI Line (Key Button) * @param None * @retval None */ void SleepMode_Measure(void) { GPIO_InitTypeDef GPIO_InitStruct; /* Configure all GPIO as analog to reduce current consumption on non used IOs */ /* Enable GPIOs clock */ __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOE_CLK_ENABLE(); __HAL_RCC_GPIOH_CLK_ENABLE(); GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Pin = GPIO_PIN_All; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); HAL_GPIO_Init(GPIOE, &GPIO_InitStruct); HAL_GPIO_Init(GPIOH, &GPIO_InitStruct); HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* Disable GPIOs clock */ __HAL_RCC_GPIOA_CLK_DISABLE(); __HAL_RCC_GPIOB_CLK_DISABLE(); __HAL_RCC_GPIOC_CLK_DISABLE(); __HAL_RCC_GPIOD_CLK_DISABLE(); __HAL_RCC_GPIOE_CLK_DISABLE(); __HAL_RCC_GPIOH_CLK_DISABLE(); /* Configure Key Button */ BSP_PB_Init(BUTTON_KEY, BUTTON_MODE_EXTI); /* Suspend Tick increment to prevent wakeup by Systick interrupt. Otherwise the Systick interrupt will wake up the device within 1ms (HAL time base) */ HAL_SuspendTick(); /* Request to enter SLEEP mode */ HAL_PWR_EnterSLEEPMode(PWR_MAINREGULATOR_ON, PWR_SLEEPENTRY_WFI); /* Resume Tick interrupt if disabled prior to sleep mode entry */ HAL_ResumeTick(); /* Initialize LED6 */ BSP_LED_Init(LED6); /* Turn LED6 On */ BSP_LED_On(LED6); /* Inserted Delay */ HAL_Delay(200); } /** * @brief This function configures the system to enter Stop mode with RTC * clocked by LSE or LSI for current consumption measurement purpose. * STOP Mode with RTC clocked by LSE/LSI * ===================================== * - RTC Clocked by LSE or LSI * - Regulator in LP mode * - HSI, HSE OFF and LSI OFF if not used as RTC Clock source * - No IWDG * - FLASH in deep power down mode * - Automatic Wakeup using RTC clocked by LSE/LSI (~20s) * @param None * @retval None */ void StopMode_Measure(void) { GPIO_InitTypeDef GPIO_InitStruct; /* Configure all GPIO as analog to reduce current consumption on non used IOs */ /* Enable GPIOs clock */ __HAL_RCC_GPIOA_CLK_ENABLE(); __HAL_RCC_GPIOB_CLK_ENABLE(); __HAL_RCC_GPIOC_CLK_ENABLE(); __HAL_RCC_GPIOD_CLK_ENABLE(); __HAL_RCC_GPIOE_CLK_ENABLE(); __HAL_RCC_GPIOH_CLK_ENABLE(); GPIO_InitStruct.Mode = GPIO_MODE_ANALOG; GPIO_InitStruct.Speed = GPIO_SPEED_HIGH; GPIO_InitStruct.Pull = GPIO_NOPULL; GPIO_InitStruct.Pin = GPIO_PIN_All; HAL_GPIO_Init(GPIOC, &GPIO_InitStruct); HAL_GPIO_Init(GPIOD, &GPIO_InitStruct); HAL_GPIO_Init(GPIOE, &GPIO_InitStruct); HAL_GPIO_Init(GPIOH, &GPIO_InitStruct); HAL_GPIO_Init(GPIOA, &GPIO_InitStruct); HAL_GPIO_Init(GPIOB, &GPIO_InitStruct); /* Disable GPIOs clock */ __HAL_RCC_GPIOA_CLK_DISABLE(); __HAL_RCC_GPIOB_CLK_DISABLE(); __HAL_RCC_GPIOC_CLK_DISABLE(); __HAL_RCC_GPIOD_CLK_DISABLE(); __HAL_RCC_GPIOE_CLK_DISABLE(); __HAL_RCC_GPIOH_CLK_DISABLE(); RTCHandle.Instance = RTC; /* Configure RTC prescaler and RTC data registers as follow: - Hour Format = Format 24 - Asynch Prediv = Value according to source clock - Synch Prediv = Value according to source clock - OutPut = Output Disable - OutPutPolarity = High Polarity - OutPutType = Open Drain */ RTCHandle.Init.HourFormat = RTC_HOURFORMAT_24; RTCHandle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV; RTCHandle.Init.SynchPrediv = RTC_SYNCH_PREDIV; RTCHandle.Init.OutPut = RTC_OUTPUT_DISABLE; RTCHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; RTCHandle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; if(HAL_RTC_Init(&RTCHandle) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /*## Configure the Wake up timer ###########################################*/ /* RTC Wakeup Interrupt Generation: Wakeup Time Base = (RTC_WAKEUPCLOCK_RTCCLK_DIV /(LSI)) Wakeup Time = Wakeup Time Base * WakeUpCounter = (RTC_WAKEUPCLOCK_RTCCLK_DIV /(LSI)) * WakeUpCounter ==> WakeUpCounter = Wakeup Time / Wakeup Time Base To configure the wake up timer to 20s the WakeUpCounter is set to 0xA017: RTC_WAKEUPCLOCK_RTCCLK_DIV = RTCCLK_Div16 = 16 Wakeup Time Base = 16 /(~32.768KHz) = ~0,488 ms Wakeup Time = ~20s = 0,488ms * WakeUpCounter ==> WakeUpCounter = ~20s/0,488ms = 40983 = 0xA017 */ /* Disable Wake-up timer */ if(HAL_RTCEx_DeactivateWakeUpTimer(&RTCHandle) != HAL_OK) { /* Initialization Error */ Error_Handler(); } HAL_RTCEx_SetWakeUpTimer_IT(&RTCHandle, 0xA017, RTC_WAKEUPCLOCK_RTCCLK_DIV16); /* FLASH Deep Power Down Mode enabled */ HAL_PWREx_EnableFlashPowerDown(); /* Enter Stop Mode */ HAL_PWR_EnterSTOPMode(PWR_LOWPOWERREGULATOR_ON, PWR_STOPENTRY_WFI); /* Configures system clock after wake-up from STOP: enable HSE, PLL and select PLL as system clock source (HSE and PLL are disabled in STOP mode) */ SYSCLKConfig_STOP(); /* Disable Wake-up timer */ if(HAL_RTCEx_DeactivateWakeUpTimer(&RTCHandle) != HAL_OK) { /* Initialization Error */ Error_Handler(); } } /** * @brief This function configures the system to enter Standby mode for * current consumption measurement purpose. * STANDBY Mode * ============ * - Backup SRAM and RTC OFF * - IWDG and LSI OFF * - Wakeup using WakeUp Pin (PA.00) * @param None * @retval None */ void StandbyMode_Measure(void) { /* Enable Power Clock*/ __HAL_RCC_PWR_CLK_ENABLE(); /* Allow access to Backup */ HAL_PWR_EnableBkUpAccess(); /* Reset RTC Domain */ __HAL_RCC_BACKUPRESET_FORCE(); __HAL_RCC_BACKUPRESET_RELEASE(); /* Disable all used wakeup sources: Pin1(PA.0) */ HAL_PWR_DisableWakeUpPin(PWR_WAKEUP_PIN1); /* Clear all related wakeup flags */ __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU); /* Re-enable all used wakeup sources: Pin1(PA.0) */ HAL_PWR_EnableWakeUpPin(PWR_WAKEUP_PIN1); /* Request to enter STANDBY mode */ HAL_PWR_EnterSTANDBYMode(); } /** * @brief This function configures the system to enter Standby mode with RTC * clocked by LSE or LSI for current consumption measurement purpose. * STANDBY Mode with RTC clocked by LSE/LSI * ======================================== * - RTC Clocked by LSE/LSI * - IWDG OFF * - Backup SRAM OFF * - Automatic Wakeup using RTC clocked by LSE/LSI (after ~20s) * @param None * @retval None */ void StandbyRTCMode_Measure(void) { RTCHandle.Instance = RTC; /* Configure RTC prescaler and RTC data registers as follow: - Hour Format = Format 24 - Asynch Prediv = Value according to source clock - Synch Prediv = Value according to source clock - OutPut = Output Disable - OutPutPolarity = High Polarity - OutPutType = Open Drain */ RTCHandle.Init.HourFormat = RTC_HOURFORMAT_24; RTCHandle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV; RTCHandle.Init.SynchPrediv = RTC_SYNCH_PREDIV; RTCHandle.Init.OutPut = RTC_OUTPUT_DISABLE; RTCHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; RTCHandle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; if(HAL_RTC_Init(&RTCHandle) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /*## Configure the Wake up timer ###########################################*/ /* RTC Wakeup Interrupt Generation: Wakeup Time Base = (RTC_WAKEUPCLOCK_RTCCLK_DIV /(LSI)) Wakeup Time = Wakeup Time Base * WakeUpCounter = (RTC_WAKEUPCLOCK_RTCCLK_DIV /(LSI)) * WakeUpCounter ==> WakeUpCounter = Wakeup Time / Wakeup Time Base To configure the wake up timer to 20s the WakeUpCounter is set to 0xA017: RTC_WAKEUPCLOCK_RTCCLK_DIV = RTCCLK_Div16 = 16 Wakeup Time Base = 16 /(~32.768KHz) = ~0,488 ms Wakeup Time = ~20s = 0,488ms * WakeUpCounter ==> WakeUpCounter = ~20s/0,488ms = 40983 = 0xA017 */ /* Disable Wake-up timer */ if(HAL_RTCEx_DeactivateWakeUpTimer(&RTCHandle) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /*## Disable all used wakeup sources: Wake up Timer ########################*/ HAL_RTCEx_DeactivateWakeUpTimer(&RTCHandle); /*## Clear all related wakeup flags ########################################*/ /* Clear PWR wake up Flag */ __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU); /* Clear RTC Wake Up timer Flag */ __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&RTCHandle, RTC_FLAG_WUTF); /*## Setting the Wake up time ##############################################*/ HAL_RTCEx_SetWakeUpTimer_IT(&RTCHandle, 0xA017, RTC_WAKEUPCLOCK_RTCCLK_DIV16); /*## Enter the Standby mode ################################################*/ /* Request to enter STANDBY mode */ HAL_PWR_EnterSTANDBYMode(); } /** * @brief This function configures the system to enter Standby mode with RTC * clocked by LSE or LSI and with Backup SRAM ON for current consumption * measurement purpose. * STANDBY Mode with RTC clocked by LSE/LSI and BKPSRAM * ==================================================== * - RTC Clocked by LSE or LSI * - Backup SRAM ON * - IWDG OFF * - Automatic Wakeup using RTC clocked by LSE/LSI (after ~20s) * @param None * @retval None */ void StandbyRTCBKPSRAMMode_Measure(void) { /* Configure RTC prescaler and RTC data registers as follow: - Hour Format = Format 24 - Asynch Prediv = Value according to source clock - Synch Prediv = Value according to source clock - OutPut = Output Disable - OutPutPolarity = High Polarity - OutPutType = Open Drain */ RTCHandle.Instance = RTC; RTCHandle.Init.HourFormat = RTC_HOURFORMAT_24; RTCHandle.Init.AsynchPrediv = RTC_ASYNCH_PREDIV; RTCHandle.Init.SynchPrediv = RTC_SYNCH_PREDIV; RTCHandle.Init.OutPut = RTC_OUTPUT_DISABLE; RTCHandle.Init.OutPutPolarity = RTC_OUTPUT_POLARITY_HIGH; RTCHandle.Init.OutPutType = RTC_OUTPUT_TYPE_OPENDRAIN; if(HAL_RTC_Init(&RTCHandle) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /*## Configure the Wake up timer ###########################################*/ /* RTC Wakeup Interrupt Generation: Wakeup Time Base = (RTC_WAKEUPCLOCK_RTCCLK_DIV /(LSI)) Wakeup Time = Wakeup Time Base * WakeUpCounter = (RTC_WAKEUPCLOCK_RTCCLK_DIV /(LSI)) * WakeUpCounter ==> WakeUpCounter = Wakeup Time / Wakeup Time Base To configure the wake up timer to 20s the WakeUpCounter is set to 0xA017: RTC_WAKEUPCLOCK_RTCCLK_DIV = RTCCLK_Div16 = 16 Wakeup Time Base = 16 /(~32.768KHz) = ~0,488 ms Wakeup Time = ~20s = 0,488ms * WakeUpCounter ==> WakeUpCounter = ~20s/0,488ms = 40983 = 0xA017 */ /* Disable Wake-up timer */ if(HAL_RTCEx_DeactivateWakeUpTimer(&RTCHandle) != HAL_OK) { /* Initialization Error */ Error_Handler(); } /*## Clear all related wakeup flags ########################################*/ /* Clear PWR wake up Flag */ __HAL_PWR_CLEAR_FLAG(PWR_FLAG_WU); /* Clear RTC Wake Up timer Flag */ __HAL_RTC_WAKEUPTIMER_CLEAR_FLAG(&RTCHandle, RTC_FLAG_WUTF); /*## Setting the Wake up time ##############################################*/ HAL_RTCEx_SetWakeUpTimer_IT(&RTCHandle, 0xA017, RTC_WAKEUPCLOCK_RTCCLK_DIV16); /* Enable BKPRAM Clock */ __HAL_RCC_BKPSRAM_CLK_ENABLE(); /* Enable the Backup SRAM low power Regulator */ HAL_PWREx_EnableBkUpReg(); /*## Enter the Standby mode ################################################*/ /* Request to enter STANDBY mode */ HAL_PWR_EnterSTANDBYMode(); } /** * @brief Configures system clock after wake-up from STOP: enable HSE, PLL * and select PLL as system clock source. * @param None * @retval None */ static void SYSCLKConfig_STOP(void) { RCC_ClkInitTypeDef RCC_ClkInitStruct; RCC_OscInitTypeDef RCC_OscInitStruct; uint32_t pFLatency = 0; /* Get the Oscillators configuration according to the internal RCC registers */ HAL_RCC_GetOscConfig(&RCC_OscInitStruct); /* After wake-up from STOP reconfigure the system clock: Enable HSE and PLL */ RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSE; RCC_OscInitStruct.HSEState = RCC_HSE_ON; RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON; if(HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK) { Error_Handler(); } /* Get the Clocks configuration according to the internal RCC registers */ HAL_RCC_GetClockConfig(&RCC_ClkInitStruct, &pFLatency); /* Select PLL as system clock source and configure the HCLK, PCLK1 and PCLK2 clocks dividers */ RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_SYSCLK; RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK; if(HAL_RCC_ClockConfig(&RCC_ClkInitStruct, pFLatency) != HAL_OK) { Error_Handler(); } } /** * @} */ /** * @} */ /************************ (C) COPYRIGHT STMicroelectronics *****END OF FILE****/
kamfor/STMF4
STM/Projects/STM32F401-Discovery/Examples/PWR/PWR_CurrentConsumption/Src/stm32f4xx_lp_modes.c
C
gpl-2.0
17,504
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>PHPXRef 0.7.1 : Unnamed Project : Variable Reference: $import_type</title> <link rel="stylesheet" href="../sample.css" type="text/css"> <link rel="stylesheet" href="../sample-print.css" type="text/css" media="print"> <style id="hilight" type="text/css"></style> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1"> </head> <body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff"> <table class="pagetitle" width="100%"> <tr> <td valign="top" class="pagetitle"> [ <a href="../index.html">Index</a> ] </td> <td align="right" class="pagetitle"> <h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2> </td> </tr> </table> <!-- Generated by PHPXref 0.7.1 at Sat Nov 21 22:13:19 2015 --> <!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net --> <!-- http://phpxref.sourceforge.net/ --> <script src="../phpxref.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> <!-- ext='.html'; relbase='../'; subdir='_variables'; filename='index.html'; cookiekey='phpxref'; handleNavFrame(relbase, subdir, filename); logVariable('import_type'); // --> </script> <script language="JavaScript" type="text/javascript"> if (gwGetCookie('xrefnav')=='off') document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>'); else document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>'); </script> <noscript> <p class="navlinks"> [ <a href="../nav.html" target="_top">Show Explorer</a> ] [ <a href="index.html" target="_top">Hide Navbar</a> ] </p> </noscript> [<a href="../index.html">Top level directory</a>]<br> <script language="JavaScript" type="text/javascript"> <!-- document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>'); document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">'); document.writeln('<tr><td class="searchbox-title">'); document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>'); document.writeln('<\/td><\/tr>'); document.writeln('<tr><td class="searchbox-body" id="searchbox-body">'); document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>'); document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: '); document.writeln('<input type="text" size=10 value="" name="classname"><br>'); document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: '); document.writeln('<input type="text" size=10 value="" name="funcname"><br>'); document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: '); document.writeln('<input type="text" size=10 value="" name="varname"><br>'); document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: '); document.writeln('<input type="text" size=10 value="" name="constname"><br>'); document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: '); document.writeln('<input type="text" size=10 value="" name="tablename"><br>'); document.writeln('<input type="submit" class="searchbox-button" value="Search">'); document.writeln('<\/form>'); document.writeln('<\/td><\/tr><\/table>'); document.writeln('<\/td><\/tr><\/table>'); // --> </script> <div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div> <h3>Variable Cross Reference</h3> <h2><a href="index.html#import_type">$import_type</a></h2> <b>Defined at:</b><ul> <li><a href="../inc/tools/views/_wpxml_file.form.php.html">/inc/tools/views/_wpxml_file.form.php</A> -> <a href="../inc/tools/views/_wpxml_file.form.php.source.html#l140"> line 140</A></li> <li><a href="../inc/tools/model/_wp.funcs.php.html">/inc/tools/model/_wp.funcs.php</A> -> <a href="../inc/tools/model/_wp.funcs.php.source.html#l36"> line 36</A></li> </ul> <br><b>Referenced 6 times:</b><ul> <li><a href="../inc/tools/views/_wpxml_file.form.php.html">/inc/tools/views/_wpxml_file.form.php</a> -> <a href="../inc/tools/views/_wpxml_file.form.php.source.html#l140"> line 140</a></li> <li><a href="../inc/tools/views/_wpxml_file.form.php.html">/inc/tools/views/_wpxml_file.form.php</a> -> <a href="../inc/tools/views/_wpxml_file.form.php.source.html#l141"> line 141</a></li> <li><a href="../inc/tools/views/_wpxml_file.form.php.html">/inc/tools/views/_wpxml_file.form.php</a> -> <a href="../inc/tools/views/_wpxml_file.form.php.source.html#l149"> line 149</a></li> <li><a href="../inc/tools/views/_wpxml_file.form.php.html">/inc/tools/views/_wpxml_file.form.php</a> -> <a href="../inc/tools/views/_wpxml_file.form.php.source.html#l155"> line 155</a></li> <li><a href="../inc/tools/model/_wp.funcs.php.html">/inc/tools/model/_wp.funcs.php</a> -> <a href="../inc/tools/model/_wp.funcs.php.source.html#l36"> line 36</a></li> <li><a href="../inc/tools/model/_wp.funcs.php.html">/inc/tools/model/_wp.funcs.php</a> -> <a href="../inc/tools/model/_wp.funcs.php.source.html#l105"> line 105</a></li> </ul> <!-- A link to the phpxref site in your customized footer file is appreciated ;-) --> <br><hr> <table width="100%"> <tr><td>Generated: Sat Nov 21 22:13:19 2015</td> <td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td> </tr> </table> </body></html>
mgsolipa/b2evolution_phpxref
_variables/import_type.html
HTML
gpl-2.0
5,862
<!doctype html public "-//W3C//DTD HTML 4.0 Transitional//EN" "http://www.w3.org/TR/REC-html40/loose.dtd"> <html> <head> <title>PHPXRef 0.7.1 : Unnamed Project : Function Reference: set_skin_settings()</title> <link rel="stylesheet" href="../sample.css" type="text/css"> <link rel="stylesheet" href="../sample-print.css" type="text/css" media="print"> <style id="hilight" type="text/css"></style> <meta http-equiv="content-type" content="text/html;charset=iso-8859-1"> </head> <body bgcolor="#ffffff" text="#000000" link="#801800" vlink="#300540" alink="#ffffff"> <table class="pagetitle" width="100%"> <tr> <td valign="top" class="pagetitle"> [ <a href="../index.html">Index</a> ] </td> <td align="right" class="pagetitle"> <h2 style="margin-bottom: 0px">PHP Cross Reference of Unnamed Project</h2> </td> </tr> </table> <!-- Generated by PHPXref 0.7.1 at Sat Nov 21 22:13:19 2015 --> <!-- PHPXref (c) 2000-2010 Gareth Watts - gareth@omnipotent.net --> <!-- http://phpxref.sourceforge.net/ --> <script src="../phpxref.js" type="text/javascript"></script> <script language="JavaScript" type="text/javascript"> <!-- ext='.html'; relbase='../'; subdir='_functions'; filename='index.html'; cookiekey='phpxref'; handleNavFrame(relbase, subdir, filename); logFunction('set_skin_settings'); // --> </script> <script language="JavaScript" type="text/javascript"> if (gwGetCookie('xrefnav')=='off') document.write('<p class="navlinks">[ <a href="javascript:navOn()">Show Explorer<\/a> ]<\/p>'); else document.write('<p class="navlinks">[ <a href="javascript:navOff()">Hide Explorer<\/a> ]<\/p>'); </script> <noscript> <p class="navlinks"> [ <a href="../nav.html" target="_top">Show Explorer</a> ] [ <a href="index.html" target="_top">Hide Navbar</a> ] </p> </noscript> [<a href="../index.html">Top level directory</a>]<br> <script language="JavaScript" type="text/javascript"> <!-- document.writeln('<table align="right" class="searchbox-link"><tr><td><a class="searchbox-link" href="javascript:void(0)" onMouseOver="showSearchBox()">Search</a><br>'); document.writeln('<table border="0" cellspacing="0" cellpadding="0" class="searchbox" id="searchbox">'); document.writeln('<tr><td class="searchbox-title">'); document.writeln('<a class="searchbox-title" href="javascript:showSearchPopup()">Search History +</a>'); document.writeln('<\/td><\/tr>'); document.writeln('<tr><td class="searchbox-body" id="searchbox-body">'); document.writeln('<form name="search" style="margin:0px; padding:0px" onSubmit=\'return jump()\'>'); document.writeln('<a class="searchbox-body" href="../_classes/index.html">Class<\/a>: '); document.writeln('<input type="text" size=10 value="" name="classname"><br>'); document.writeln('<a id="funcsearchlink" class="searchbox-body" href="../_functions/index.html">Function<\/a>: '); document.writeln('<input type="text" size=10 value="" name="funcname"><br>'); document.writeln('<a class="searchbox-body" href="../_variables/index.html">Variable<\/a>: '); document.writeln('<input type="text" size=10 value="" name="varname"><br>'); document.writeln('<a class="searchbox-body" href="../_constants/index.html">Constant<\/a>: '); document.writeln('<input type="text" size=10 value="" name="constname"><br>'); document.writeln('<a class="searchbox-body" href="../_tables/index.html">Table<\/a>: '); document.writeln('<input type="text" size=10 value="" name="tablename"><br>'); document.writeln('<input type="submit" class="searchbox-button" value="Search">'); document.writeln('<\/form>'); document.writeln('<\/td><\/tr><\/table>'); document.writeln('<\/td><\/tr><\/table>'); // --> </script> <div id="search-popup" class="searchpopup"><p id="searchpopup-title" class="searchpopup-title">title</p><div id="searchpopup-body" class="searchpopup-body">Body</div><p class="searchpopup-close"><a href="javascript:gwCloseActive()">[close]</a></p></div> <h3>Function and Method Cross Reference</h3> <h2><a href="index.html#set_skin_settings">set_skin_settings()</a></h2> <b>Defined at:</b><ul> <li><a href="../skins_adm/chicago/_adminUI.class.php.html#set_skin_settings">/skins_adm/chicago/_adminUI.class.php</a> -> <a onClick="logFunction('set_skin_settings', '/skins_adm/chicago/_adminUI.class.php.source.html#l460')" href="../skins_adm/chicago/_adminUI.class.php.source.html#l460"> line 460</a></li> <li><a href="../skins_adm/_adminUI_general.class.php.html#set_skin_settings">/skins_adm/_adminUI_general.class.php</a> -> <a onClick="logFunction('set_skin_settings', '/skins_adm/_adminUI_general.class.php.source.html#l1560')" href="../skins_adm/_adminUI_general.class.php.source.html#l1560"> line 1560</a></li> </ul> <b>Referenced 1 times:</b><ul> <li><a href="../inc/users/user.ctrl.php.html">/inc/users/user.ctrl.php</a> -> <a href="../inc/users/user.ctrl.php.source.html#l364"> line 364</a></li> </ul> <!-- A link to the phpxref site in your customized footer file is appreciated ;-) --> <br><hr> <table width="100%"> <tr><td>Generated: Sat Nov 21 22:13:19 2015</td> <td align="right"><i>Cross-referenced by <a href="http://phpxref.sourceforge.net/">PHPXref 0.7.1</a></i></td> </tr> </table> </body></html>
mgsolipa/b2evolution_phpxref
_functions/set_skin_settings.html
HTML
gpl-2.0
5,209
<?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
/* * IPv6 Syncookies implementation for the Linux kernel * * Authors: * Glenn Griffin <ggriffin.kernel@gmail.com> * * Based on IPv4 implementation by Andi Kleen * linux/net/ipv4/syncookies.c * * 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. * */ #include <linux/tcp.h> #include <linux/random.h> #include <linux/cryptohash.h> #include <linux/kernel.h> #include <net/ipv6.h> #include <net/tcp.h> #define COOKIEBITS 24 /* Upper bits store count */ #define COOKIEMASK (((__u32)1 << COOKIEBITS) - 1) static u32 syncookie6_secret[2][16-4+SHA_DIGEST_WORDS] __read_mostly; /* RFC 2460, Section 8.3: * [ipv6 tcp] MSS must be computed as the maximum packet size minus 60 [..] * * Due to IPV6_MIN_MTU=1280 the lowest possible MSS is 1220, which allows * using higher values than ipv4 tcp syncookies. * The other values are chosen based on ethernet (1500 and 9k MTU), plus * one that accounts for common encap (PPPoe) overhead. Table must be sorted. */ static __u16 const msstab[] = { 1280 - 60, /* IPV6_MIN_MTU - 60 */ 1480 - 60, 1500 - 60, 9000 - 60, }; static inline struct sock *get_cookie_sock(struct sock *sk, struct sk_buff *skb, struct request_sock *req, struct dst_entry *dst) { struct inet_connection_sock *icsk = inet_csk(sk); struct sock *child; child = icsk->icsk_af_ops->syn_recv_sock(sk, skb, req, dst); if (child) inet_csk_reqsk_queue_add(sk, req, child); else reqsk_free(req); return child; } static DEFINE_PER_CPU(__u32 [16 + 5 + SHA_WORKSPACE_WORDS], ipv6_cookie_scratch); static u32 cookie_hash(const struct in6_addr *saddr, const struct in6_addr *daddr, __be16 sport, __be16 dport, u32 count, int c) { __u32 *tmp; net_get_random_once(syncookie6_secret, sizeof(syncookie6_secret)); tmp = __get_cpu_var(ipv6_cookie_scratch); /* * we have 320 bits of information to hash, copy in the remaining * 192 bits required for sha_transform, from the syncookie6_secret * and overwrite the digest with the secret */ memcpy(tmp + 10, syncookie6_secret[c], 44); memcpy(tmp, saddr, 16); memcpy(tmp + 4, daddr, 16); tmp[8] = ((__force u32)sport << 16) + (__force u32)dport; tmp[9] = count; sha_transform(tmp + 16, (__u8 *)tmp, tmp + 16 + 5); return tmp[17]; } static __u32 secure_tcp_syn_cookie(const struct in6_addr *saddr, const struct in6_addr *daddr, __be16 sport, __be16 dport, __u32 sseq, __u32 data) { u32 count = tcp_cookie_time(); return (cookie_hash(saddr, daddr, sport, dport, 0, 0) + sseq + (count << COOKIEBITS) + ((cookie_hash(saddr, daddr, sport, dport, count, 1) + data) & COOKIEMASK)); } static __u32 check_tcp_syn_cookie(__u32 cookie, const struct in6_addr *saddr, const struct in6_addr *daddr, __be16 sport, __be16 dport, __u32 sseq) { __u32 diff, count = tcp_cookie_time(); cookie -= cookie_hash(saddr, daddr, sport, dport, 0, 0) + sseq; diff = (count - (cookie >> COOKIEBITS)) & ((__u32) -1 >> COOKIEBITS); if (diff >= MAX_SYNCOOKIE_AGE) return (__u32)-1; return (cookie - cookie_hash(saddr, daddr, sport, dport, count - diff, 1)) & COOKIEMASK; } u32 __cookie_v6_init_sequence(const struct ipv6hdr *iph, const struct tcphdr *th, __u16 *mssp) { int mssind; const __u16 mss = *mssp; for (mssind = ARRAY_SIZE(msstab) - 1; mssind ; mssind--) if (mss >= msstab[mssind]) break; *mssp = msstab[mssind]; return secure_tcp_syn_cookie(&iph->saddr, &iph->daddr, th->source, th->dest, ntohl(th->seq), mssind); } EXPORT_SYMBOL_GPL(__cookie_v6_init_sequence); __u32 cookie_v6_init_sequence(struct sock *sk, const struct sk_buff *skb, __u16 *mssp) { const struct ipv6hdr *iph = ipv6_hdr(skb); const struct tcphdr *th = tcp_hdr(skb); tcp_synq_overflow(sk); NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESSENT); return __cookie_v6_init_sequence(iph, th, mssp); } int __cookie_v6_check(const struct ipv6hdr *iph, const struct tcphdr *th, __u32 cookie) { __u32 seq = ntohl(th->seq) - 1; __u32 mssind = check_tcp_syn_cookie(cookie, &iph->saddr, &iph->daddr, th->source, th->dest, seq); return mssind < ARRAY_SIZE(msstab) ? msstab[mssind] : 0; } EXPORT_SYMBOL_GPL(__cookie_v6_check); struct sock *cookie_v6_check(struct sock *sk, struct sk_buff *skb) { struct tcp_options_received tcp_opt; struct inet_request_sock *ireq; struct tcp_request_sock *treq; struct ipv6_pinfo *np = inet6_sk(sk); struct tcp_sock *tp = tcp_sk(sk); const struct tcphdr *th = tcp_hdr(skb); __u32 cookie = ntohl(th->ack_seq) - 1; struct sock *ret = sk; struct request_sock *req; int mss; struct dst_entry *dst; __u8 rcv_wscale; bool ecn_ok = false; if (!sysctl_tcp_syncookies || !th->ack || th->rst) goto out; if (tcp_synq_no_recent_overflow(sk) || (mss = __cookie_v6_check(ipv6_hdr(skb), th, cookie)) == 0) { NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESFAILED); goto out; } NET_INC_STATS_BH(sock_net(sk), LINUX_MIB_SYNCOOKIESRECV); /* check for timestamp cookie support */ memset(&tcp_opt, 0, sizeof(tcp_opt)); tcp_parse_options(skb, &tcp_opt, 0, NULL); if (!cookie_check_timestamp(&tcp_opt, sock_net(sk), &ecn_ok)) goto out; ret = NULL; req = inet_reqsk_alloc(&tcp6_request_sock_ops); if (!req) goto out; ireq = inet_rsk(req); treq = tcp_rsk(req); treq->listener = NULL; if (security_inet_conn_request(sk, skb, req)) goto out_free; req->mss = mss; ireq->ir_rmt_port = th->source; ireq->ir_num = ntohs(th->dest); ireq->ir_v6_rmt_addr = ipv6_hdr(skb)->saddr; ireq->ir_v6_loc_addr = ipv6_hdr(skb)->daddr; if (ipv6_opt_accepted(sk, skb) || np->rxopt.bits.rxinfo || np->rxopt.bits.rxoinfo || np->rxopt.bits.rxhlim || np->rxopt.bits.rxohlim) { atomic_inc(&skb->users); ireq->pktopts = skb; } ireq->ir_iif = sk->sk_bound_dev_if; /* So that link locals have meaning */ if (!sk->sk_bound_dev_if && ipv6_addr_type(&ireq->ir_v6_rmt_addr) & IPV6_ADDR_LINKLOCAL) ireq->ir_iif = inet6_iif(skb); ireq->ir_mark = inet_request_mark(sk, skb); req->expires = 0UL; req->num_retrans = 0; ireq->ecn_ok = ecn_ok; ireq->snd_wscale = tcp_opt.snd_wscale; ireq->sack_ok = tcp_opt.sack_ok; ireq->wscale_ok = tcp_opt.wscale_ok; ireq->tstamp_ok = tcp_opt.saw_tstamp; req->ts_recent = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsval : 0; treq->snt_synack = tcp_opt.saw_tstamp ? tcp_opt.rcv_tsecr : 0; treq->rcv_isn = ntohl(th->seq) - 1; treq->snt_isn = cookie; /* * We need to lookup the dst_entry to get the correct window size. * This is taken from tcp_v6_syn_recv_sock. Somebody please enlighten * me if there is a preferred way. */ { struct in6_addr *final_p, final; struct flowi6 fl6; memset(&fl6, 0, sizeof(fl6)); fl6.flowi6_proto = IPPROTO_TCP; fl6.daddr = ireq->ir_v6_rmt_addr; final_p = fl6_update_dst(&fl6, np->opt, &final); fl6.saddr = ireq->ir_v6_loc_addr; fl6.flowi6_oif = sk->sk_bound_dev_if; fl6.flowi6_mark = ireq->ir_mark; fl6.fl6_dport = ireq->ir_rmt_port; fl6.fl6_sport = inet_sk(sk)->inet_sport; security_req_classify_flow(req, flowi6_to_flowi(&fl6)); dst = ip6_dst_lookup_flow(sk, &fl6, final_p); if (IS_ERR(dst)) goto out_free; } req->window_clamp = tp->window_clamp ? :dst_metric(dst, RTAX_WINDOW); tcp_select_initial_window(tcp_full_space(sk), req->mss, &req->rcv_wnd, &req->window_clamp, ireq->wscale_ok, &rcv_wscale, dst_metric(dst, RTAX_INITRWND)); ireq->rcv_wscale = rcv_wscale; ret = get_cookie_sock(sk, skb, req, dst); out: return ret; out_free: reqsk_free(req); return NULL; }
xsilon/linux-xsilon
net/ipv6/syncookies.c
C
gpl-2.0
7,764
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
/* * $Id$ * * Copyright (C) 2007,2008,2009 Colin DIDIER * * 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 Street, Fifth Floor, Boston, MA 02110-1301 USA. */ /* * XEP-0092: Software Version */ #include <sys/utsname.h> #include <string.h> #include "module.h" #include "queries.h" #include "settings.h" #include "signals.h" #include "xmpp-servers.h" #include "xmpp-commands.h" #include "disco.h" #include "tools.h" #define XMLNS_VERSION "jabber:iq:version" static void send_version(XMPP_SERVER_REC *server, const char *dest, const char *id) { LmMessage *lmsg; LmMessageNode *node; struct utsname u; char *recoded; recoded = xmpp_recode_out(dest); lmsg = lm_message_new_with_sub_type(recoded, LM_MESSAGE_TYPE_IQ, LM_MESSAGE_SUB_TYPE_RESULT); g_free(recoded); if (id != NULL) lm_message_node_set_attribute(lmsg->node, "id", id); node = lm_message_node_add_child(lmsg->node, "query", NULL); lm_message_node_set_attribute(node, XMLNS, XMLNS_VERSION); if (settings_get_bool("xmpp_send_version")) { lm_message_node_add_child(node, "name", IRSSI_XMPP_PACKAGE); lm_message_node_add_child(node, "version", IRSSI_XMPP_VERSION); if (uname(&u) == 0) lm_message_node_add_child(node, "os", u.sysname); } signal_emit("xmpp send iq", 2, server, lmsg); lm_message_unref(lmsg); } static void request_version(XMPP_SERVER_REC *server, const char *dest) { LmMessage *lmsg; LmMessageNode *node; char *recoded; recoded = xmpp_recode_out(dest); lmsg = lm_message_new_with_sub_type(recoded, LM_MESSAGE_TYPE_IQ, LM_MESSAGE_SUB_TYPE_GET); g_free(recoded); node = lm_message_node_add_child(lmsg->node, "query", NULL); lm_message_node_set_attribute(node, XMLNS, XMLNS_VERSION); signal_emit("xmpp send iq", 2, server, lmsg); lm_message_unref(lmsg); } /* SYNTAX: VER [[<jid>[/<resource>]]|[<name]] */ static void cmd_ver(const char *data, XMPP_SERVER_REC *server, WI_ITEM_REC *item) { char *cmd_dest, *dest; void *free_arg; CMD_XMPP_SERVER(server); if (!cmd_get_params(data, &free_arg, 1, &cmd_dest)) return; dest = xmpp_get_dest(cmd_dest, server, item); request_version(server, dest); g_free(dest); cmd_params_free(free_arg); } static void sig_recv_iq(XMPP_SERVER_REC *server, LmMessage *lmsg, const int type, const char *id, const char *from, const char *to) { LmMessageNode *node, *child; char *name, *version, *os; if (type == LM_MESSAGE_SUB_TYPE_RESULT && (node = lm_find_node(lmsg->node,"query", XMLNS, XMLNS_VERSION)) != NULL) { name = version = os = NULL; for (child = node->children; child != NULL; child = child->next) { if (child->value == NULL) continue; if (name == NULL && strcmp(child->name, "name") == 0) g_strstrip(name = xmpp_recode_in(child->value)); else if (version == NULL && strcmp(child->name, "version") == 0) g_strstrip(version = xmpp_recode_in(child->value)); else if (os == NULL && strcmp(child->name, "os") == 0) g_strstrip(os = xmpp_recode_in(child->value)); } signal_emit("xmpp version", 5, server, from, name, version, os); g_free(name); g_free(version); g_free(os); } else if (type == LM_MESSAGE_SUB_TYPE_GET && (node = lm_find_node(lmsg->node,"query", XMLNS, XMLNS_VERSION)) != NULL) send_version(server, from, id); } void version_init(void) { disco_add_feature(XMLNS_VERSION); settings_add_bool("xmpp", "xmpp_send_version", TRUE); command_bind_xmpp("ver", NULL, (SIGNAL_FUNC)cmd_ver); signal_add("xmpp recv iq", sig_recv_iq); } void version_deinit(void) { command_unbind("ver", (SIGNAL_FUNC)cmd_ver); signal_remove("xmpp recv iq", sig_recv_iq); }
nullalx/irssi-xmpp
src/core/xep/version.c
C
gpl-2.0
4,184
<?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
<html> <!-- Mirrored from www.w3school.com.cn/tiy/showcode.asp?f=demo_php_func_string_strrchr_2 by HTTrack Website Copier/3.x [XR&CO'2014], Wed, 02 Dec 2015 06:12:59 GMT --> <!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=GB2312" /><!-- /Added by HTTrack --> <head> <link rel="stylesheet" type="text/css" href="showcode.css" /> </head> <body> <pre> &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;body&gt; <code class="phpcode">&lt;?php echo strrchr(&quot;Hello world!&quot;,101); ?&gt;</code> &lt;/body&gt; &lt;/html&gt; </pre> </body>
platinhom/ManualHom
Coding/W3School/W3CN/www.w3school.com.cn/tiy/showcodecdcc.html
HTML
gpl-2.0
575
/* * 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
<html> <head> <title>Complete example</title> <script type="text/javascript"><!-- function doSomething() { alert('hello!'); } //--></script> <style type="text/css"> body { font-size: 12pt; background:#ccc } h1, h2, h3 { font-family: verdana, sans-serif } </style> </head> <body> <h1>HTML::WikiConverter</h1> <p>HTML::WikiConverter is a Perl module for converting HTML to wiki markup for a variety of different wiki engines. Currently, it supports <b>many</b> dialects:</p> <ul> <li>DokuWiki <li>Kwiki <li>MediaWiki <li>MoinMoin <li>Oddmuse <li>PhpWiki <li>PmWiki <li>SnipSnap <li>TikiWiki <li>UseMod <li>WakkaWiki <li>(and others) </ul> <p>I'd <em>really</em> like to add support for TWiki, but the way it handles <em><strong>bold italics</strong></em> (and possibly other nested elements) is very disappointing.</p> <h2>Installation</h2> <p>It's very easy to use HTML::WikiConverter. Grab a copy from your favorite <a href="http://www.cpan.org">CPAN mirror</a> and then run something like this:</p> <pre> #!/usr/bin/perl -w use HTML::WikiConverter; my $wc = new HTML::WikiConverter( dialect =&gt; 'MediaWiki' ); print $wc-&gt;html2wiki($html);</pre> <hr /> <p>Alternatively, you might want to try HTML::WikiConverter's command line interface; it's a program called <code>html2wiki</code> and it's stored in <i>bin/html2wiki</i>.</p> <h2>Dialect features</h2> <p>Unfortunately, I haven't managed to implement every feature of each supported dialect. My initial goal was simply to create a converter for MediaWiki (I am a Wikipediholic, after all :-), but then PhpWiki's Reini Urban suggested that I be more ambitious and provide the dialect interface. And so far I've been really happy with the progress.</p> <h2>Bugs</h2> <p>Of course there are always bugs. Luckily, CPAN comes to the rescue again with its <a href="http://rt.cpan.org">bug tracking service</a> for module authors.</p> <p>But where would we be without bugs? My Pacman frog sure wouldn't be happy without 'em! Do you know what a <a href="http://en.wikipedia.org/wiki/Pacman_frog">Pacman frog</a> is? Or how about an Otago skink? Aplysia californica? Why, these are some of my favorite animals!</p> <table> <caption>My favorite animals</caption> <tr> <th>Animal</th> <th>Region</th> <th>Physical traits</th> <th>Food</th> </tr> <tr> <td>Pacman frog</td> <td>Gran Chaco (Argentina)</td> <td>Half mouth, half stomach (quite literally!)</td> <td>Crickets, fish, etc.</td> </tr> <tr> <td>Otago skink</td> <td>Otago (New Zealand)</td> <td>Black, yellow, and green camouflage</td> <td>Insects, fruits, small lizards</td> </tr> <tr> <td>Aplysia california</td> <td>California</td> <td>Deep red-colored sea hare</td> <td>Red and brown seaweed</td> </tr> </table> <h2>Common features</h2> <h3>Images</h3> <p>Many dialects allow embedded images, either from local or remote stores.</p> <p><img src="http://www.google.com/images/logo.gif" alt="Google logo" /></p> <h3>Lists</h3> <p>Wikis also support lists, even extensively nested ones. Some rely on leading characters to determine nest levels, while others rely on spaces or (egad!) tabs.</p> <ul> <li>1 <ul> <li>1a</li> <li>1b</li> </ul> </li> <li>2 <ul> <li>2a <ol> <li>fee</li> <li>fie</li> <li>foe <ul> <li>fum? </ul> </li> </ol> </li> </ul> </li> </ul> <p>Some wikis support definition lists, though they're often used inappropriately (as in MediaWiki, which uses them for indentation).</p> <dl> <dt>Perl</dt> <dd>Pathologically eclectic rubbish lister</dd> <dt>POE</dt> <dd>Perl on ecstasy</dd> </dl> </body> </html>
jashmenn/HTML-WikiConverter
cgi/templates/sample_html.html
HTML
gpl-2.0
3,833
/* glm.h Nate Robins, 1997 ndr@pobox.com, http://www.pobox.com/~ndr/ Wavefront OBJ model file format reader/writer/manipulator. Includes routines for generating smooth normals with preservation of edges, welding redundant vertices & texture coordinate generation (spheremap and planar projections) + more. */ #ifndef __INCLUDED_GLM_H__ #define __INCLUDED_GLM_H__ #pragma warning( disable: 4996 ) #include <GL/glew.h> #include <GL/glut.h> #ifndef M_PI #define M_PI 3.14159265 #endif #define GLM_NONE (0) /* render with only vertices */ #define GLM_FLAT (1 << 0) /* render with facet normals */ #define GLM_SMOOTH (1 << 1) /* render with vertex normals */ #define GLM_TEXTURE (1 << 2) /* render with texture coords */ #define GLM_COLOR (1 << 3) /* render with colors */ #define GLM_MATERIAL (1 << 4) /* render with materials */ /* GLMmaterial: Structure that defines a material in a model. */ typedef struct _GLMmaterial { char* name; /* name of material */ GLfloat diffuse[4]; /* diffuse component */ GLfloat ambient[4]; /* ambient component */ GLfloat specular[4]; /* specular component */ GLfloat emmissive[4]; /* emmissive component */ GLfloat shininess; /* specular exponent */ } GLMmaterial; /* GLMtriangle: Structure that defines a triangle in a model. */ typedef struct _GLMtriangle { GLuint vindices[3]; /* array of triangle vertex indices */ GLuint nindices[3]; /* array of triangle normal indices */ GLuint tindices[3]; /* array of triangle texcoord indices*/ GLuint findex; /* index of triangle facet normal */ } GLMtriangle; /* GLMgroup: Structure that defines a group in a model. */ typedef struct _GLMgroup { char* name; /* name of this group */ GLuint numtriangles; /* number of triangles in this group */ GLuint* triangles; /* array of triangle indices */ GLuint material; /* index to material for group */ struct _GLMgroup* next; /* pointer to next group in model */ } GLMgroup; /* GLMmodel: Structure that defines a model. */ typedef struct _GLMmodel { char* pathname; /* path to this model */ char* mtllibname; /* name of the material library */ GLuint numvertices; /* number of vertices in model */ GLfloat* vertices; /* array of vertices */ GLuint numnormals; /* number of normals in model */ GLfloat* normals; /* array of normals */ GLfloat* normArray; GLuint numtexcoords; /* number of texcoords in model */ GLfloat* texcoords; /* array of texture coordinates */ GLuint numfacetnorms; /* number of facetnorms in model */ GLfloat* facetnorms; /* array of facetnorms */ GLuint numtriangles; /* number of triangles in model */ GLMtriangle* triangles; /* array of triangles */ GLuint nummaterials; /* number of materials in model */ GLMmaterial* materials; /* array of materials */ GLuint numgroups; /* number of groups in model */ GLMgroup* groups; /* linked list of groups */ GLfloat position[3]; /* position of the model */ } GLMmodel; /* glmUnitize: "unitize" a model by translating it to the origin and * scaling it to fit in a unit cube around the origin. Returns the * scalefactor used. * * model - properly initialized GLMmodel structure */ GLfloat glmUnitize(GLMmodel* model); /* glmDimensions: Calculates the dimensions (width, height, depth) of * a model. * * model - initialized GLMmodel structure * dimensions - array of 3 GLfloats (GLfloat dimensions[3]) */ GLvoid glmDimensions(GLMmodel* model, GLfloat* dimensions); /* glmScale: Scales a model by a given amount. * * model - properly initialized GLMmodel structure * scale - scalefactor (0.5 = half as large, 2.0 = twice as large) */ GLvoid glmScale(GLMmodel* model, GLfloat scale); /* glmReverseWinding: Reverse the polygon winding for all polygons in * this model. Default winding is counter-clockwise. Also changes * the direction of the normals. * * model - properly initialized GLMmodel structure */ GLvoid glmReverseWinding(GLMmodel* model); /* glmFacetNormals: Generates facet normals for a model (by taking the * cross product of the two vectors derived from the sides of each * triangle). Assumes a counter-clockwise winding. * * model - initialized GLMmodel structure */ GLvoid glmFacetNormals(GLMmodel* model); /* glmVertexNormals: Generates smooth vertex normals for a model. * First builds a list of all the triangles each vertex is in. Then * loops through each vertex in the the list averaging all the facet * normals of the triangles each vertex is in. Finally, sets the * normal index in the triangle for the vertex to the generated smooth * normal. If the dot product of a facet normal and the facet normal * associated with the first triangle in the list of triangles the * current vertex is in is greater than the cosine of the angle * parameter to the function, that facet normal is not added into the * average normal calculation and the corresponding vertex is given * the facet normal. This tends to preserve hard edges. The angle to * use depends on the model, but 90 degrees is usually a good start. * * model - initialized GLMmodel structure * angle - maximum angle (in degrees) to smooth across */ GLvoid glmVertexNormals(GLMmodel* model, GLfloat angle); /* glmLinearTexture: Generates texture coordinates according to a * linear projection of the texture map. It generates these by * linearly mapping the vertices onto a square. * * model - pointer to initialized GLMmodel structure */ GLvoid glmLinearTexture(GLMmodel* model); /* glmSpheremapTexture: Generates texture coordinates according to a * spherical projection of the texture map. Sometimes referred to as * spheremap, or reflection map texture coordinates. It generates * these by using the normal to calculate where that vertex would map * onto a sphere. Since it is impossible to map something flat * perfectly onto something spherical, there is distortion at the * poles. This particular implementation causes the poles along the X * axis to be distorted. * * model - pointer to initialized GLMmodel structure */ GLvoid glmSpheremapTexture(GLMmodel* model); /* glmDelete: Deletes a GLMmodel structure. * * model - initialized GLMmodel structure */ GLvoid glmDelete(GLMmodel* model); /* glmReadOBJ: Reads a model description from a Wavefront .OBJ file. * Returns a pointer to the created object which should be free'd with * glmDelete(). * * filename - name of the file containing the Wavefront .OBJ format data. */ GLMmodel* glmReadOBJ(char* filename); /* glmWriteOBJ: Writes a model description in Wavefront .OBJ format to * a file. * * model - initialized GLMmodel structure * filename - name of the file to write the Wavefront .OBJ format data to * mode - a bitwise or of values describing what is written to the file * GLM_NONE - write only vertices * GLM_FLAT - write facet normals * GLM_SMOOTH - write vertex normals * GLM_TEXTURE - write texture coords * GLM_FLAT and GLM_SMOOTH should not both be specified. */ GLvoid glmWriteOBJ(GLMmodel* model, char* filename, GLuint mode); /* glmDraw: Renders the model to the current OpenGL context using the * mode specified. * * model - initialized GLMmodel structure * mode - a bitwise OR of values describing what is to be rendered. * GLM_NONE - render with only vertices * GLM_FLAT - render with facet normals * GLM_SMOOTH - render with vertex normals * GLM_TEXTURE - render with texture coords * GLM_FLAT and GLM_SMOOTH should not both be specified. */ GLvoid glmDraw(GLMmodel* model, GLuint mode); /* glmList: Generates and returns a display list for the model using * the mode specified. * * model - initialized GLMmodel structure * mode - a bitwise OR of values describing what is to be rendered. * GLM_NONE - render with only vertices * GLM_FLAT - render with facet normals * GLM_SMOOTH - render with vertex normals * GLM_TEXTURE - render with texture coords * GLM_FLAT and GLM_SMOOTH should not both be specified. */ GLuint glmList(GLMmodel* model, GLuint mode); /* glmWeld: eliminate (weld) vectors that are within an epsilon of * each other. * * model - initialized GLMmodel structure * epsilon - maximum difference between vertices * ( 0.00001 is a good start for a unitized model) * */ GLvoid glmWeld(GLMmodel* model, GLfloat epsilon); #endif
ssmall41/graphics-project
Utils/ModelIO/glm.h
C
gpl-2.0
9,024
/* * drivers/amlogic/iomap/iomap.c * * Copyright (C) 2015 Amlogic, Inc. All rights reserved. * * 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. * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/init.h> #include <linux/printk.h> #include <linux/string.h> #include <linux/of_address.h> #include <linux/io.h> #include <linux/regmap.h> #include <linux/device.h> #include <linux/of_platform.h> #include <linux/platform_device.h> #include <linux/amlogic/iomap.h> #include <asm/compiler.h> #ifndef CONFIG_ARM64 #include <asm/opcodes-sec.h> #endif #if 0 void meson_regmap_lock(void *p) { return; } void meson_regmap_unlock(void *p) { return; } static struct regmap_config meson_regmap_config = { .reg_bits = 32, .val_bits = 32, .reg_stride = 4, .lock = meson_regmap_lock, .unlock = meson_regmap_unlock, }; #endif static const struct of_device_id iomap_dt_match[] = { { .compatible = "amlogic,iomap" }, { /* sentinel */ }, }; void __iomem *meson_reg_map[IO_BUS_MAX]; int aml_reg_read(u32 bus_type, unsigned int reg, unsigned int *val) { #if 0 if ((bus_type >= IO_CBUS_BASE) && (bus_type < IO_BUS_MAX)) return regmap_read(meson_reg_map[bus_type], reg, val); else return -1; #endif if ((bus_type >= IO_CBUS_BASE) && (bus_type < IO_BUS_MAX)) { *val = readl((meson_reg_map[bus_type]+reg)); return 0; } else return -1; } EXPORT_SYMBOL(aml_reg_read); int aml_reg_write(u32 bus_type, unsigned int reg, unsigned int val) { #if 0 if ((bus_type >= IO_CBUS_BASE) && (bus_type < IO_BUS_MAX)) return regmap_write(meson_reg_map[bus_type], reg, val); else return -1; #endif if ((bus_type >= IO_CBUS_BASE) && (bus_type < IO_BUS_MAX)) { writel(val, (meson_reg_map[bus_type]+reg)); return 0; } else return -1; } EXPORT_SYMBOL(aml_reg_write); int aml_regmap_update_bits(u32 bus_type, unsigned int reg, unsigned int mask, unsigned int val) { #if 0 if ((bus_type >= IO_CBUS_BASE) && (bus_type < IO_BUS_MAX)) return regmap_update_bits(meson_reg_map[bus_type], reg, mask, val); else return -1; #endif if ((bus_type >= IO_CBUS_BASE) && (bus_type < IO_BUS_MAX)) { unsigned int tmp, orig; aml_reg_read(bus_type, reg, &orig); tmp = orig & ~mask; tmp |= val & mask; aml_reg_write(bus_type, reg, tmp); return 0; } else return -1; } EXPORT_SYMBOL(aml_regmap_update_bits); /* ** CBUS REG Read Write and Update some bits */ int aml_read_cbus(unsigned int reg) { int ret, val; ret = aml_reg_read(IO_CBUS_BASE, reg<<2, &val); if (ret) { pr_err("read cbus reg %x error %d\n", reg, ret); return -1; } else return val; } EXPORT_SYMBOL(aml_read_cbus); void aml_write_cbus(unsigned int reg, unsigned int val) { int ret; ret = aml_reg_write(IO_CBUS_BASE, reg<<2, val); if (ret) { pr_err("write cbus reg %x error %d\n", reg, ret); return; } else return; } EXPORT_SYMBOL(aml_write_cbus); void aml_cbus_update_bits(unsigned int reg, unsigned int mask, unsigned int val) { int ret; ret = aml_regmap_update_bits(IO_CBUS_BASE, reg<<2, mask, val); if (ret) { pr_err("write cbus reg %x error %d\n", reg, ret); return; } else return; } EXPORT_SYMBOL(aml_cbus_update_bits); /* ** AO REG Read Write and Update some bits */ int aml_read_aobus(unsigned int reg) { int ret, val; ret = aml_reg_read(IO_AOBUS_BASE, reg, &val); if (ret) { pr_err("read ao bus reg %x error %d\n", reg, ret); return -1; } else return val; } EXPORT_SYMBOL(aml_read_aobus); void aml_write_aobus(unsigned int reg, unsigned int val) { int ret; ret = aml_reg_write(IO_AOBUS_BASE, reg, val); if (ret) { pr_err("write ao bus reg %x error %d\n", reg, ret); return; } else return; } EXPORT_SYMBOL(aml_write_aobus); void aml_aobus_update_bits(unsigned int reg, unsigned int mask, unsigned int val) { int ret; ret = aml_regmap_update_bits(IO_AOBUS_BASE, reg, mask, val); if (ret) { pr_err("write aobus reg %x error %d\n", reg, ret); return; } else return; } EXPORT_SYMBOL(aml_aobus_update_bits); /* ** VCBUS Bus REG Read Write and Update some bits */ int aml_read_vcbus(unsigned int reg) { int ret, val; ret = aml_reg_read(IO_APB_BUS_BASE, (0x100000+(reg<<2)), &val); if (ret) { pr_err("read vcbus reg %x error %d\n", reg, ret); return -1; } else return val; } EXPORT_SYMBOL(aml_read_vcbus); void aml_write_vcbus(unsigned int reg, unsigned int val) { int ret; ret = aml_reg_write(IO_APB_BUS_BASE, (0x100000+(reg<<2)), val); if (ret) { pr_err("write vcbus reg %x error %d\n", reg, ret); return; } else return; } EXPORT_SYMBOL(aml_write_vcbus); void aml_vcbus_update_bits(unsigned int reg, unsigned int mask, unsigned int val) { int ret; ret = aml_regmap_update_bits(IO_APB_BUS_BASE, (0x100000+(reg<<2)), mask, val); if (ret) { pr_err("write vcbus reg %x error %d\n", reg, ret); return; } else return; } EXPORT_SYMBOL(aml_vcbus_update_bits); /* ** DOS BUS Bus REG Read Write and Update some bits */ int aml_read_dosbus(unsigned int reg) { int ret, val; ret = aml_reg_read(IO_APB_BUS_BASE, (0x50000+(reg<<2)), &val); if (ret) { pr_err("read vcbus reg %x error %d\n", reg, ret); return -1; } else return val; } EXPORT_SYMBOL(aml_read_dosbus); void aml_write_dosbus(unsigned int reg, unsigned int val) { int ret; ret = aml_reg_write(IO_APB_BUS_BASE, (0x50000+(reg<<2)), val); if (ret) { pr_err("write vcbus reg %x error %d\n", reg, ret); return; } else return; } EXPORT_SYMBOL(aml_write_dosbus); void aml_dosbus_update_bits(unsigned int reg, unsigned int mask, unsigned int val) { int ret; ret = aml_regmap_update_bits(IO_APB_BUS_BASE, (0x50000+(reg<<2)), mask, val); if (ret) { pr_err("write vcbus reg %x error %d\n", reg, ret); return; } else return; } EXPORT_SYMBOL(aml_dosbus_update_bits); #ifndef CONFIG_ARM64 static noinline int __invoke_sec_fn_smc(u32 function_id, u32 arg0, u32 arg1, u32 arg2) { asm volatile( __asmeq("%0", "r0") __asmeq("%1", "r1") __asmeq("%2", "r2") __asmeq("%3", "r3") __SMC(0) : "+r" (function_id) : "r" (arg0), "r" (arg1), "r" (arg2)); return function_id; } #else static noinline int __invoke_sec_fn_smc(u32 function_id, u32 arg0, u32 arg1, u32 arg2) { asm volatile( __asmeq("%0", "x0") __asmeq("%1", "x1") __asmeq("%2", "x2") __asmeq("%3", "x3") "smc #0\n" : "+r" (function_id) : "r" (arg0), "r" (arg1), "r" (arg2)); return function_id; } #endif int aml_read_sec_reg(unsigned int reg) { return __invoke_sec_fn_smc(0x82000035, reg, 0, 0); } void aml_write_sec_reg(unsigned int reg, unsigned int val) { __invoke_sec_fn_smc(0x82000036, reg, val, 0); } static int iomap_probe(struct platform_device *pdev) { int i = 0; /* void __iomem *base; */ struct resource res; struct device_node *np, *child; np = pdev->dev.of_node; for_each_child_of_node(np, child) { if (of_address_to_resource(child, 0, &res)) return -1; #if 0 base = ioremap(res.start, resource_size(&res)); meson_regmap_config.max_register = resource_size(&res) - 4; meson_regmap_config.name = child->name; meson_reg_map[i] = devm_regmap_init_mmio(&pdev->dev, base, &meson_regmap_config); if (IS_ERR(meson_reg_map[i])) { pr_err("iomap index %d registers not found\n", i); return PTR_ERR(meson_reg_map[i]); } #endif meson_reg_map[i] = ioremap(res.start, resource_size(&res)); i++; } pr_info("amlogic iomap probe done\n"); return 0; } static struct platform_driver iomap_platform_driver = { .probe = iomap_probe, .driver = { .owner = THIS_MODULE, .name = "iomap_version", .of_match_table = iomap_dt_match, }, }; int __init meson_iomap_version_init(void) { int ret; ret = platform_driver_register(&iomap_platform_driver); return ret; } core_initcall(meson_iomap_version_init);
wetek-enigma/linux-wetek-3.14.y
drivers/amlogic/iomap/iomap.c
C
gpl-2.0
8,241
/* * 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
// This file was written by Lukasz Piatkowski // [piontec -at- the well known google mail] // and is distributed under GPL v2.0 license // repo: https://github.com/piontec/esp_rest #include "common.h" #include "ets_sys.h" #include "osapi.h" #include "gpio.h" #include "os_type.h" #include "user_config.h" #include "private_user_config.h" #include "dht22.h" #include "uart_hw.h" #include "c_types.h" #include "mem.h" #include "ip_addr.h" #include "espconn.h" #include "config_store.h" #define user_procTaskPrio 0 #define user_procTaskQueueLen 1 os_event_t user_procTaskQueue[user_procTaskQueueLen]; static void user_procTask(os_event_t *events); static volatile ETSTimer sensor_timer; static volatile ETSTimer resetBtntimer; int lastTemp, lastHum; char lastTempTxt [8]; char lastHumTxt [8]; char payload[512]; static int resetCnt=0; static int totalCnt=0; static config_t* s_conf; static void ICACHE_FLASH_ATTR enable_sensors() { //Set LEDGPIO to HIGH gpio_output_set((1<<LEDGPIO), 0, (1<<LEDGPIO), 0); debug_print ("sensors enabled\n"); } static void ICACHE_FLASH_ATTR disable_sensors() { //Set LEDGPIO to LOW gpio_output_set(0, (1<<LEDGPIO), (1<<LEDGPIO), 0); debug_print ("sensors disabled\n"); } static void ICACHE_FLASH_ATTR convertToText (int dhtReading, char *buf, uint8 maxLength, uint8 decimalPlaces) { if (dhtReading == 0) strncpy(buf, "0.00", 4); char tmp [8]; os_bzero (tmp, 8); os_sprintf (tmp, "%d", dhtReading); uint8 len = os_strlen (tmp); uint8 beforeSep = len - decimalPlaces; os_strncpy(buf, tmp, beforeSep); buf [beforeSep] = '.'; os_strncpy (buf + beforeSep + 1, tmp + beforeSep, decimalPlaces); buf [len + 1] = 0; } static void ICACHE_FLASH_ATTR read_DHT22() { int retry = 0; float *r; do { if (retry++ > 0) { debug_print("DHT22 read fail, retrying, try %d/%d\n", retry, MAX_DHT_READ_RETRY); os_delay_us(DHT_READ_RETRY_DELAY_US); } r = readDHT(); } while ((r[0] == 0 && r[1] == 0) && retry < MAX_DHT_READ_RETRY); debug_print("DHT read done\n"); lastTemp=(int)(r[0] * 100); lastHum=(int)(r[1] * 100); convertToText (lastTemp, lastTempTxt, 8, 2); convertToText (lastHum, lastHumTxt, 8, 2); debug_print ("Temp = %s *C, Hum = %s %\n", lastTempTxt, lastHumTxt); } static void ICACHE_FLASH_ATTR at_tcpclient_sent_cb(void *arg) { debug_print("TCP sent callback\n"); //struct espconn *pespconn = (struct espconn *)arg; //espconn_disconnect(pespconn); // disable sensors power //disable_sensors(); // goto sleep ; gpio16 -> RST -- requires soldiering on ESP-03 //debug_print ("going to deep sleep for %ds\n", INTERVAL_S); //system_deep_sleep(INTERVAL_S*1000*1000); } static void ICACHE_FLASH_ATTR at_tcpclient_discon_cb(void *arg) { debug_print("TCP disconnect callback\n"); struct espconn *pespconn = (struct espconn *)arg; os_free(pespconn->proto.tcp); os_free(pespconn); debug_print ("going to deep sleep for %ds\n", INTERVAL_S); system_deep_sleep(INTERVAL_S*1000*1000); } static void ICACHE_FLASH_ATTR at_tcpclient_reconnect_cb(void *arg, sint8 errType) { struct espconn *pespconn = (struct espconn *) arg; debug_print("Reconnect callback - resending with delay...\n"); os_delay_us(1*1000*1000); debug_print ("now.\n"); espconn_sent(pespconn, payload, strlen(payload)); debug_print("resend done.\n"); } static void ICACHE_FLASH_ATTR at_tcpclient_read_cb(void *arg, char *data, unsigned short len) { char buf[128]; debug_print("Rcv callback: %d\n", os_strlen(data)); debug_print("%s\n", data); struct espconn *conn = arg; espconn_disconnect(conn); } static void ICACHE_FLASH_ATTR at_tcpclient_connect_cb(void *arg) { struct espconn *pespconn = (struct espconn *)arg; debug_print("TCP client connect\n"); espconn_regist_sentcb(pespconn, at_tcpclient_sent_cb); espconn_regist_disconcb(pespconn, at_tcpclient_discon_cb); espconn_regist_recvcb(pespconn, at_tcpclient_read_cb); os_sprintf(payload, "GET http://api.thingspeak.com/update?api_key=%s&field1=%s&field2=%s HTTP/1.1\r\nHost: api.thingspeak.com\r\nUser-agent: the best\r\nConnection: close\r\n\r\n", THINGSPEAK_KEY, lastTempTxt, lastHumTxt); espconn_sent(pespconn, payload, strlen(payload)); } static void ICACHE_FLASH_ATTR send_data() { struct espconn *pCon = (struct espconn *)os_zalloc(sizeof(struct espconn)); if (pCon == NULL) { os_printf("Error: TCP connect failed - memory allocation for conn failed\n"); return; } pCon->type = ESPCONN_TCP; pCon->state = ESPCONN_NONE; uint32_t ip = ipaddr_addr(REMOTE_IP); pCon->proto.tcp = (esp_tcp *)os_zalloc(sizeof(esp_tcp)); if (pCon->proto.tcp == NULL) { os_printf("Error: TCP connect failed - memory allocation for TCP failed\n"); return; } pCon->proto.tcp->local_port = espconn_port(); pCon->proto.tcp->remote_port = 80; //pCon->proto.tcp->remote_port = lwip_htons(80); os_memcpy(pCon->proto.tcp->remote_ip, &ip, 4); espconn_regist_connectcb(pCon, at_tcpclient_connect_cb); espconn_regist_reconcb(pCon, at_tcpclient_reconnect_cb); debug_print("TCP connecting...\n"); espconn_connect(pCon); } static void ICACHE_FLASH_ATTR sensor_timer_func(void *arg) { // enable sensors power enable_sensors(); // sleep and wait for sensors os_delay_us(SENSORS_READY_WAIT_US); // readDHT read_DHT22(); // read pressure // disable sensors disable_sensors (); // send data send_data(); } //Do nothing function static void ICACHE_FLASH_ATTR user_procTask(os_event_t *events) { os_delay_us(10); debug_print("In user_procTask\n"); } static void ICACHE_FLASH_ATTR initialize_timer() { os_timer_disarm(&sensor_timer); os_timer_setfn(&sensor_timer, (os_timer_func_t *)sensor_timer_func, NULL); os_timer_arm(&sensor_timer, 5000, 0); } static void ICACHE_FLASH_ATTR initialize_gpio() { // Initialize the GPIO subsystem. gpio_init(); //Set GPIO12 to input mode PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTCK_U, FUNC_GPIO13); //PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDI_U, FUNC_GPIO12); PIN_PULLUP_EN(PERIPHS_IO_MUX_MTCK_U); //PIN_PULLUP_EN(PERIPHS_IO_MUX_MTDI_U); gpio_output_set(0, 0, 0, (1<<BTNGPIO)); //Set GPIO2 to output mode PIN_FUNC_SELECT(PERIPHS_IO_MUX_GPIO2_U, FUNC_GPIO2); //Set GPIO2 low PIN_PULLUP_EN(PERIPHS_IO_MUX_GPIO2_U); gpio_output_set(0, BIT2, BIT2, 0); //Set GPIO13 to output mode PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTDI_U, FUNC_GPIO12); //PIN_FUNC_SELECT(PERIPHS_IO_MUX_MTCK_U, FUNC_GPIO13); //Set GPIO13 low gpio_output_set(0, (1<<LEDGPIO), (1<<LEDGPIO), 0); } static void ICACHE_FLASH_ATTR initialize_uart() { //Set baud rate and other serial parameters to 115200,n,8,1 uart_div_modify(0, UART_CLK_FREQ/BIT_RATE_115200); WRITE_PERI_REG(UART_CONF0(0), (STICK_PARITY_DIS)|(ONE_STOP_BIT << UART_STOP_BIT_NUM_S)| \ (EIGHT_BITS << UART_BIT_NUM_S)); //Reset tx & rx fifo SET_PERI_REG_MASK(UART_CONF0(0), UART_RXFIFO_RST|UART_TXFIFO_RST); CLEAR_PERI_REG_MASK(UART_CONF0(0), UART_RXFIFO_RST|UART_TXFIFO_RST); //Clear pending interrupts WRITE_PERI_REG(UART_INT_CLR(0), 0xffff); } static void ICACHE_FLASH_ATTR config_mode() { os_printf ("Starting config mode\n"); config_mode_start(); } static void ICACHE_FLASH_ATTR normal_mode() { os_printf ("Starting normal mode\n"); DHTInit(); debug_print ("DHT22 ready\n"); initialize_timer(); debug_print ("Timer ready\n"); os_printf ("Initialization complete, starting main task\n"); //Start os task system_os_task(user_procTask, user_procTaskPrio,user_procTaskQueue, user_procTaskQueueLen); } static void ICACHE_FLASH_ATTR boot() { if (s_conf->boot_config == 1) { if (wifi_get_opmode() == STATION_MODE) { wifi_set_opmode(CFG_WIFI_MODE); system_restart(); } else config_mode (); } else normal_mode (); } static void ICACHE_FLASH_ATTR resetBtnTimerCb(void *arg) { totalCnt++; if (!GPIO_INPUT_GET(BTNGPIO)) resetCnt++; debug_print ("reset counter %d/%d\n", resetCnt, totalCnt); if (totalCnt < 2) return; os_timer_disarm(&resetBtntimer); //int currentMode = wifi_get_opmode(); if (resetCnt>=2) { s_conf->boot_config = 1; config_save(); os_printf("Restarting system into config mode...\n"); wifi_station_disconnect(); wifi_set_opmode(CFG_WIFI_MODE); } else { boot(); } resetCnt=0; totalCnt=0; } static void ICACHE_FLASH_ATTR resetInit() { initialize_gpio(); s_conf = config_init(); os_printf("\n\nSoftware version: %s, config version: %d\n", SOFT_VERSION, CONFIG_VERSION); debug_print("Current wifi connect status: %d\n", wifi_station_get_connect_status()); debug_print("Current DHCP status: %d\n", wifi_station_dhcpc_status()); debug_print("Current wifi mode: %d\n", wifi_get_phy_mode()); os_timer_disarm(&resetBtntimer); os_timer_setfn(&resetBtntimer, resetBtnTimerCb, NULL); os_timer_arm(&resetBtntimer, 500, 1); } void ICACHE_FLASH_ATTR init_done() { debug_print("INIT IS DONE!\n"); resetInit(); } //Init function void ICACHE_FLASH_ATTR user_init() { initialize_uart(); system_init_done_cb(init_done); //resetInit (); }
piontec/esp_rest
user/user_main.c
C
gpl-2.0
9,564
/* -*- Mode: C; c-basic-offset:4 ; -*- */ /* * (C) 2001 by Argonne National Laboratory. * See COPYRIGHT in top-level directory. * * This file is automatically generated by buildiface * DO NOT EDIT */ #include "mpi_fortimpl.h" /* Begin MPI profiling block */ #if defined(USE_WEAK_SYMBOLS) && !defined(USE_ONLY_MPI_NAMES) #if defined(HAVE_MULTIPLE_PRAGMA_WEAK) extern FORT_DLL_SPEC void FORT_CALL MPI_STARTALL( MPI_Fint *, MPI_Fint [], MPI_Fint * ); extern FORT_DLL_SPEC void FORT_CALL mpi_startall__( MPI_Fint *, MPI_Fint [], MPI_Fint * ); extern FORT_DLL_SPEC void FORT_CALL mpi_startall( MPI_Fint *, MPI_Fint [], MPI_Fint * ); extern FORT_DLL_SPEC void FORT_CALL mpi_startall_( MPI_Fint *, MPI_Fint [], MPI_Fint * ); #if defined(F77_NAME_UPPER) #pragma weak MPI_STARTALL = PMPI_STARTALL #pragma weak mpi_startall__ = PMPI_STARTALL #pragma weak mpi_startall_ = PMPI_STARTALL #pragma weak mpi_startall = PMPI_STARTALL #elif defined(F77_NAME_LOWER_2USCORE) #pragma weak MPI_STARTALL = pmpi_startall__ #pragma weak mpi_startall__ = pmpi_startall__ #pragma weak mpi_startall_ = pmpi_startall__ #pragma weak mpi_startall = pmpi_startall__ #elif defined(F77_NAME_LOWER_USCORE) #pragma weak MPI_STARTALL = pmpi_startall_ #pragma weak mpi_startall__ = pmpi_startall_ #pragma weak mpi_startall_ = pmpi_startall_ #pragma weak mpi_startall = pmpi_startall_ #else #pragma weak MPI_STARTALL = pmpi_startall #pragma weak mpi_startall__ = pmpi_startall #pragma weak mpi_startall_ = pmpi_startall #pragma weak mpi_startall = pmpi_startall #endif #elif defined(HAVE_PRAGMA_WEAK) #if defined(F77_NAME_UPPER) extern FORT_DLL_SPEC void FORT_CALL MPI_STARTALL( MPI_Fint *, MPI_Fint [], MPI_Fint * ); #pragma weak MPI_STARTALL = PMPI_STARTALL #elif defined(F77_NAME_LOWER_2USCORE) extern FORT_DLL_SPEC void FORT_CALL mpi_startall__( MPI_Fint *, MPI_Fint [], MPI_Fint * ); #pragma weak mpi_startall__ = pmpi_startall__ #elif !defined(F77_NAME_LOWER_USCORE) extern FORT_DLL_SPEC void FORT_CALL mpi_startall( MPI_Fint *, MPI_Fint [], MPI_Fint * ); #pragma weak mpi_startall = pmpi_startall #else extern FORT_DLL_SPEC void FORT_CALL mpi_startall_( MPI_Fint *, MPI_Fint [], MPI_Fint * ); #pragma weak mpi_startall_ = pmpi_startall_ #endif #elif defined(HAVE_PRAGMA_HP_SEC_DEF) #if defined(F77_NAME_UPPER) #pragma _HP_SECONDARY_DEF PMPI_STARTALL MPI_STARTALL #elif defined(F77_NAME_LOWER_2USCORE) #pragma _HP_SECONDARY_DEF pmpi_startall__ mpi_startall__ #elif !defined(F77_NAME_LOWER_USCORE) #pragma _HP_SECONDARY_DEF pmpi_startall mpi_startall #else #pragma _HP_SECONDARY_DEF pmpi_startall_ mpi_startall_ #endif #elif defined(HAVE_PRAGMA_CRI_DUP) #if defined(F77_NAME_UPPER) #pragma _CRI duplicate MPI_STARTALL as PMPI_STARTALL #elif defined(F77_NAME_LOWER_2USCORE) #pragma _CRI duplicate mpi_startall__ as pmpi_startall__ #elif !defined(F77_NAME_LOWER_USCORE) #pragma _CRI duplicate mpi_startall as pmpi_startall #else #pragma _CRI duplicate mpi_startall_ as pmpi_startall_ #endif #endif /* HAVE_PRAGMA_WEAK */ #endif /* USE_WEAK_SYMBOLS */ /* End MPI profiling block */ /* These definitions are used only for generating the Fortran wrappers */ #if defined(USE_WEAK_SYMBOLS) && defined(HAVE_MULTIPLE_PRAGMA_WEAK) && \ defined(USE_ONLY_MPI_NAMES) extern FORT_DLL_SPEC void FORT_CALL MPI_STARTALL( MPI_Fint *, MPI_Fint [], MPI_Fint * ); extern FORT_DLL_SPEC void FORT_CALL mpi_startall__( MPI_Fint *, MPI_Fint [], MPI_Fint * ); extern FORT_DLL_SPEC void FORT_CALL mpi_startall( MPI_Fint *, MPI_Fint [], MPI_Fint * ); extern FORT_DLL_SPEC void FORT_CALL mpi_startall_( MPI_Fint *, MPI_Fint [], MPI_Fint * ); #if defined(F77_NAME_UPPER) #pragma weak mpi_startall__ = MPI_STARTALL #pragma weak mpi_startall_ = MPI_STARTALL #pragma weak mpi_startall = MPI_STARTALL #elif defined(F77_NAME_LOWER_2USCORE) #pragma weak MPI_STARTALL = mpi_startall__ #pragma weak mpi_startall_ = mpi_startall__ #pragma weak mpi_startall = mpi_startall__ #elif defined(F77_NAME_LOWER_USCORE) #pragma weak MPI_STARTALL = mpi_startall_ #pragma weak mpi_startall__ = mpi_startall_ #pragma weak mpi_startall = mpi_startall_ #else #pragma weak MPI_STARTALL = mpi_startall #pragma weak mpi_startall__ = mpi_startall #pragma weak mpi_startall_ = mpi_startall #endif #endif /* Map the name to the correct form */ #ifndef MPICH_MPI_FROM_PMPI #if defined(USE_WEAK_SYMBOLS) && defined(HAVE_MULTIPLE_PRAGMA_WEAK) /* Define the weak versions of the PMPI routine*/ #ifndef F77_NAME_UPPER extern FORT_DLL_SPEC void FORT_CALL PMPI_STARTALL( MPI_Fint *, MPI_Fint [], MPI_Fint * ); #endif #ifndef F77_NAME_LOWER_2USCORE extern FORT_DLL_SPEC void FORT_CALL pmpi_startall__( MPI_Fint *, MPI_Fint [], MPI_Fint * ); #endif #ifndef F77_NAME_LOWER_USCORE extern FORT_DLL_SPEC void FORT_CALL pmpi_startall_( MPI_Fint *, MPI_Fint [], MPI_Fint * ); #endif #ifndef F77_NAME_LOWER extern FORT_DLL_SPEC void FORT_CALL pmpi_startall( MPI_Fint *, MPI_Fint [], MPI_Fint * ); #endif #if defined(F77_NAME_UPPER) #pragma weak pmpi_startall__ = PMPI_STARTALL #pragma weak pmpi_startall_ = PMPI_STARTALL #pragma weak pmpi_startall = PMPI_STARTALL #elif defined(F77_NAME_LOWER_2USCORE) #pragma weak PMPI_STARTALL = pmpi_startall__ #pragma weak pmpi_startall_ = pmpi_startall__ #pragma weak pmpi_startall = pmpi_startall__ #elif defined(F77_NAME_LOWER_USCORE) #pragma weak PMPI_STARTALL = pmpi_startall_ #pragma weak pmpi_startall__ = pmpi_startall_ #pragma weak pmpi_startall = pmpi_startall_ #else #pragma weak PMPI_STARTALL = pmpi_startall #pragma weak pmpi_startall__ = pmpi_startall #pragma weak pmpi_startall_ = pmpi_startall #endif /* Test on name mapping */ #endif /* Use multiple pragma weak */ #ifdef F77_NAME_UPPER #define mpi_startall_ PMPI_STARTALL #elif defined(F77_NAME_LOWER_2USCORE) #define mpi_startall_ pmpi_startall__ #elif !defined(F77_NAME_LOWER_USCORE) #define mpi_startall_ pmpi_startall #else #define mpi_startall_ pmpi_startall_ #endif /* Test on name mapping */ /* This defines the routine that we call, which must be the PMPI version since we're renaming the Fortran entry as the pmpi version. The MPI name must be undefined first to prevent any conflicts with previous renamings. */ #undef MPI_Startall #define MPI_Startall PMPI_Startall #else #ifdef F77_NAME_UPPER #define mpi_startall_ MPI_STARTALL #elif defined(F77_NAME_LOWER_2USCORE) #define mpi_startall_ mpi_startall__ #elif !defined(F77_NAME_LOWER_USCORE) #define mpi_startall_ mpi_startall /* Else leave name alone */ #endif #endif /* MPICH_MPI_FROM_PMPI */ /* Prototypes for the Fortran interfaces */ #include "fproto.h" FORT_DLL_SPEC void FORT_CALL mpi_startall_ ( MPI_Fint *v1, MPI_Fint v2[], MPI_Fint *ierr ){ *ierr = MPI_Startall( (int)*v1, (MPI_Request *)(v2) ); }
qingu/WRF-Libraries
src/mpich-3.0.1/src/binding/f77/startallf.c
C
gpl-2.0
6,728
# # $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
#!/bin/sh logger "Called $0" exit 0
olvrlrnz/exec_process
scripts/ret0.sh
Shell
gpl-2.0
37
<?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
/** @file CbmStsSensorTypeDssdIdeal.h ** @author Volker Friese <v.friese@gsi.de> ** @date 02.05.2013 **/ #ifndef CBMSTSSENSORTYPEDSSDIDEAL_H #define CBMSTSSENSORTYPEDSSDIDEAL_H 1 #include "CbmStsSensorTypeDssd.h" /** @class CbmStsSensorTypeDssdIdeal ** @brief Class describing double-sided silicon strip sensors with ideal response. ** @author V.Friese <v.friese@gsi.de> ** @version 1.0 ** ** This class describes the ideal response of double-sided silicon ** strip sensors in the STS. All charge is collected on one strip on ** both the front and the back side. For more information, see ** the mother class CbmStsSensorTypeDssd. ** **/ class CbmStsSensorTypeDssdIdeal : public CbmStsSensorTypeDssd { public: /** Constructor **/ CbmStsSensorTypeDssdIdeal(); /** Destructor **/ virtual ~CbmStsSensorTypeDssdIdeal() { }; private: /** Produce charge on front or back side from a CbmStsPoint ** @param point Pointer to CbmStsSensorType object ** @param side 0 = front, 1 = back side ** @param sensor Pointer to sensor object ** @return Number of generated charge signals (active strips) ** ** Re-implements CbmStsSensorTypeDssd::ProduceCharge **/ virtual Int_t ProduceCharge(CbmStsSensorPoint* point, Int_t side, const CbmStsSensor* sensor) const; ClassDef(CbmStsSensorTypeDssdIdeal,1); }; #endif
desdemonda/cbmroot
sts/digitize/CbmStsSensorTypeDssdIdeal.h
C
gpl-2.0
1,436
/* 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
/* drivers/rtc/rtc-msm7x00a.c * * Copyright (C) 2008 Google, Inc. * Author: San Mehat <san@google.com> * * This software is licensed under the terms of the GNU General Public * License version 2, as published by the Free Software Foundation, and * may be copied, distributed, and modified under those terms. * * 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. * */ #include <linux/module.h> #include <linux/version.h> #include <linux/kernel.h> #include <linux/platform_device.h> #include <linux/init.h> #include <linux/types.h> #include <linux/rtc.h> #include <linux/msm_rpcrouter.h> #include <linux/slab.h> #include <mach/msm_rpcrouter.h> #define RTC_DEBUG 0 extern void msm_pm_set_max_sleep_time(int64_t sleep_time_ns); static const char *rpc_versions[] = { #if !defined(CONFIG_MSM_LEGACY_7X00A_AMSS) #if (CONFIG_MSM_AMSS_VERSION == 4735) "rs30000048:00010004", #else "rs30000048:00040000", "rs30000048:00010000", #endif #else "rs30000048:0da5b528", #endif }; #define TIMEREMOTE_PROCEEDURE_SET_JULIAN 6 #define TIMEREMOTE_PROCEEDURE_GET_JULIAN 7 struct rpc_time_julian { uint32_t year; uint32_t month; uint32_t day; uint32_t hour; uint32_t minute; uint32_t second; uint32_t day_of_week; }; static struct msm_rpc_endpoint *ep; static struct rtc_device *rtc; static unsigned long rtcalarm_time; static int msmrtc_timeremote_set_time(struct device *dev, struct rtc_time *tm) { int rc; struct timeremote_set_julian_req { struct rpc_request_hdr hdr; uint32_t opt_arg; struct rpc_time_julian time; } req; struct timeremote_set_julian_rep { struct rpc_reply_hdr hdr; } rep; if (tm->tm_year < 1900) tm->tm_year += 1900; if (tm->tm_year < 1970) return -EINVAL; #if RTC_DEBUG printk(KERN_DEBUG "%s: %.2u/%.2u/%.4u %.2u:%.2u:%.2u (%.2u)\n", __func__, tm->tm_mon, tm->tm_mday, tm->tm_year, tm->tm_hour, tm->tm_min, tm->tm_sec, tm->tm_wday); #endif req.opt_arg = cpu_to_be32(1); req.time.year = cpu_to_be32(tm->tm_year); req.time.month = cpu_to_be32(tm->tm_mon + 1); req.time.day = cpu_to_be32(tm->tm_mday); req.time.hour = cpu_to_be32(tm->tm_hour); req.time.minute = cpu_to_be32(tm->tm_min); req.time.second = cpu_to_be32(tm->tm_sec); req.time.day_of_week = cpu_to_be32(tm->tm_wday); rc = msm_rpc_call_reply(ep, TIMEREMOTE_PROCEEDURE_SET_JULIAN, &req, sizeof(req), &rep, sizeof(rep), 5 * HZ); if (rc < 0) pr_err("%s: msm_rpc_call_reply fail (%d)\n", __func__, rc); return rc; } static int msmrtc_timeremote_read_time(struct device *dev, struct rtc_time *tm) { int rc; struct timeremote_get_julian_req { struct rpc_request_hdr hdr; uint32_t julian_time_not_null; } req; struct timeremote_get_julian_rep { struct rpc_reply_hdr hdr; uint32_t opt_arg; struct rpc_time_julian time; } rep; req.julian_time_not_null = cpu_to_be32(1); rc = msm_rpc_call_reply(ep, TIMEREMOTE_PROCEEDURE_GET_JULIAN, &req, sizeof(req), &rep, sizeof(rep), 5 * HZ); if (rc < 0) { pr_err("%s: msm_rpc_call_reply fail (%d)\n", __func__, rc); return rc; } if (!be32_to_cpu(rep.opt_arg)) { printk(KERN_ERR "%s: No data from RTC\n", __func__); return -ENODATA; } tm->tm_year = be32_to_cpu(rep.time.year); tm->tm_mon = be32_to_cpu(rep.time.month); tm->tm_mday = be32_to_cpu(rep.time.day); tm->tm_hour = be32_to_cpu(rep.time.hour); tm->tm_min = be32_to_cpu(rep.time.minute); tm->tm_sec = be32_to_cpu(rep.time.second); tm->tm_wday = be32_to_cpu(rep.time.day_of_week); #if RTC_DEBUG printk(KERN_DEBUG "%s: %.2u/%.2u/%.4u %.2u:%.2u:%.2u (%.2u)\n", __func__, tm->tm_mon, tm->tm_mday, tm->tm_year, tm->tm_hour, tm->tm_min, tm->tm_sec, tm->tm_wday); #endif tm->tm_year -= 1900; /* RTC layer expects years to start at 1900 */ tm->tm_mon--; /* RTC layer expects mons to be 0 based */ if (rtc_valid_tm(tm) < 0) { dev_err(dev, "retrieved date/time is not valid.\n"); rtc_time_to_tm(0, tm); } return 0; } static int msmrtc_virtual_alarm_set(struct device *dev, struct rtc_wkalrm *a) { unsigned long now = get_seconds(); if (!a->enabled) { rtcalarm_time = 0; return 0; } else rtc_tm_to_time(&a->time, &rtcalarm_time); if (now > rtcalarm_time) { printk(KERN_ERR "%s: Attempt to set alarm in the past\n", __func__); rtcalarm_time = 0; return -EINVAL; } return 0; } #if RTC_DEBUG printk(KERN_DEBUG "%s ticks to ns: %lld\n", __func__, timespec_to_ns(ticks)); #endif static struct rtc_class_ops msm_rtc_ops = { .read_time = msmrtc_timeremote_read_time, .set_time = msmrtc_timeremote_set_time, .set_alarm = msmrtc_virtual_alarm_set, }; static void msmrtc_alarmtimer_expired(unsigned long _data) { #if RTC_DEBUG printk(KERN_DEBUG "%s: Generating alarm event (src %lu)\n", rtc->name, _data); #endif rtc_update_irq(rtc, 1, RTC_IRQF | RTC_AF); rtcalarm_time = 0; } static int msmrtc_probe(struct platform_device *pdev) { struct rpcsvr_platform_device *rdev = container_of(pdev, struct rpcsvr_platform_device, base); if (rtc) return -EBUSY; ep = msm_rpc_connect(rdev->prog, rdev->vers, 0); if (IS_ERR(ep)) { printk(KERN_ERR "%s: init rpc failed! rc = %ld\n", __func__, PTR_ERR(ep)); return PTR_ERR(ep); } rtc = rtc_device_register("msm_rtc", &pdev->dev, &msm_rtc_ops, THIS_MODULE); if (IS_ERR(rtc)) { printk(KERN_ERR "%s: Can't register RTC device (%ld)\n", pdev->name, PTR_ERR(rtc)); return PTR_ERR(rtc); } return 0; } static unsigned long msmrtc_get_seconds(void) { struct rtc_time tm; unsigned long now; msmrtc_timeremote_read_time(NULL, &tm); rtc_tm_to_time(&tm, &now); return now; } static int msmrtc_suspend(struct platform_device *dev, pm_message_t state) { if (rtcalarm_time) { unsigned long now = msmrtc_get_seconds(); int diff = rtcalarm_time - now; if (diff <= 0) { msmrtc_alarmtimer_expired(1); msm_pm_set_max_sleep_time(0); return 0; } msm_pm_set_max_sleep_time((int64_t) ((int64_t) diff * NSEC_PER_SEC)); } else msm_pm_set_max_sleep_time(0); return 0; } static int msmrtc_resume(struct platform_device *dev) { if (rtcalarm_time) { unsigned long now = msmrtc_get_seconds(); int diff = rtcalarm_time - now; if (diff <= 0) msmrtc_alarmtimer_expired(2); } return 0; } static int __init msmrtc_init(void) { int i; int ret; struct platform_driver *pdrv[ARRAY_SIZE(rpc_versions)]; rtcalarm_time = 0; /* register the devices for all the major versions we support, only * one should match */ for (i = 0; i < ARRAY_SIZE(rpc_versions); i++) { pdrv[i] = kzalloc(sizeof(struct platform_driver), GFP_KERNEL); if (!pdrv[i]) { ret = -ENOMEM; goto err; } pdrv[i]->probe = msmrtc_probe; pdrv[i]->suspend = msmrtc_suspend; pdrv[i]->resume = msmrtc_resume; pdrv[i]->driver.name = rpc_versions[i]; pdrv[i]->driver.owner = THIS_MODULE; ret = platform_driver_register(pdrv[i]); if (ret) { kfree(pdrv[i]); goto err; } } return 0; err: for (--i; i >= 0; i--) platform_driver_unregister(pdrv[i]); return ret; } module_init(msmrtc_init); MODULE_DESCRIPTION("RTC driver for Qualcomm MSM7x00a chipsets"); MODULE_AUTHOR("San Mehat <san@android.com>"); MODULE_LICENSE("GPL");
Ca1ne/Underworld-Sense-Kernel
drivers/rtc/rtc-msm7x00a.c
C
gpl-2.0
7,386
# # 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
/* Copyright 2012, Stanford University. This file is licensed under GPL v2 plus a special exception, as described in included LICENSE_EXCEPTION.txt. Author: mchang@cs.stanford.com (Michael Chang) peyman.kazemian@gmail.com (Peyman Kazemian) */ #include "array.h" #include <limits.h> #define SIZE(L) ( DIV_ROUND_UP (2 * (L), sizeof (array_t)) ) /* If using anything larger than 64-bit, these need to be changed. */ #define EVEN_MASK ( (array_t) 0xaaaaaaaaaaaaaaaaull ) #define ODD_MASK ( (array_t) 0x5555555555555555ull ) static inline bool has_x (array_t x) { return x & (x >> 1) & ODD_MASK; } static inline bool has_z (array_t x) { return has_x (~x); } /* Convert X from two-bit representation to integer and writes string to OUT. X must contain only 0s and 1s (no x or z) or be all x. OUT must have space for 5 chars. Returns number of chars written. */ static int int_str (uint16_t x, char *out) { if (x == UINT16_MAX) return sprintf (out, "DX,"); x = (x >> 1) & 0x5555; x = (x | (x >> 1)) & 0x3333; x = (x | (x >> 2)) & 0x0f0f; x = (x | (x >> 4)) & 0x00ff; return sprintf (out, "D%d,", x); } static inline int x_count (array_t a, array_t mask) { array_t tmp = a & (a >> 1) & mask & ODD_MASK; return __builtin_popcountll (tmp); } array_t * array_create (int len, enum bit_val val) { int alen = SIZE (len); /* TODO: Alignment */ array_t *res = xmalloc (alen * sizeof *res); if (val != BIT_UNDEF) memset (res, val * 0x55, 2 * len); memset ((uint8_t *) res + 2 * len, 0xff, alen * sizeof *res - 2 * len); return res; } void array_free (array_t *a) { free (a); } array_t * array_copy (const array_t *a, int len) { array_t *res = array_create (len, BIT_UNDEF); memcpy (res, a, 2 * len); return res; } array_t * array_from_str (const char *s) { bool commas = strchr (s, ','); int div = CHAR_BIT + commas; int len = strlen (s) + commas; assert (len % div == 0); len /= div; const char *cur = s; array_t *res = array_create (len, BIT_UNDEF); uint8_t *rcur = (uint8_t *) res; for (int i = 0; i < 2 * len; i++) { uint8_t tmp = 0; for (int j = 0; j < CHAR_BIT / 2; j++, cur++) { enum bit_val val; switch (*cur) { case 'z': case 'Z': val = BIT_Z; break; case '0': val = BIT_0; break; case '1': val = BIT_1; break; case 'x': case 'X': val = BIT_X; break; default: errx (1, "Invalid character '%c' in \"%s\".", *cur, s); } tmp <<= 2; tmp |= val; } *rcur++ = tmp; if (commas && (i % 2)) { assert (!*cur || *cur == ','); cur++; } } return res; } char * array_to_str (const array_t *a, int len, bool decimal) { if (!a) return NULL; int slen = len * (CHAR_BIT + 1); char buf[slen]; char *cur = buf; const uint8_t *acur = (const uint8_t *) a; for (int i = 0; i < len; i++, acur += 2) { uint8_t tmp[] = {acur[0], acur[1]}; uint16_t byte = tmp[0] << CHAR_BIT | tmp[1]; if (decimal && (!has_x (byte) || byte == UINT16_MAX)) { cur += int_str (byte, cur); continue; } for (int j = 0; j < 2; j++) { char *next = cur + CHAR_BIT / 2 - 1; for (int k = 0; k < CHAR_BIT / 2; k++) { static char chars[] = "z01x"; *next-- = chars[tmp[j] & BIT_X]; tmp[j] >>= 2; } cur += CHAR_BIT / 2; } *cur++ = ','; } cur[-1] = 0; return xstrdup (buf); } bool array_has_x (const array_t *a, int len) { for (int i = 0; i < SIZE (len); i++) { array_t tmp = a[i]; if (i == SIZE (len) - 1) tmp &= ~((1ull << (len % (sizeof *a / 2))) - 1); if (has_x (a[i])) return true; } return false; } bool array_has_z (const array_t *a, int len) { for (int i = 0; i < SIZE (len); i++) if (has_z (a[i])) return true; return false; } bool array_is_eq (const array_t *a, const array_t *b, int len) { return !memcmp (a, b, SIZE (len) * sizeof *a); } bool array_is_sub (const array_t *a, const array_t *b, int len) { for (int i = 0; i < SIZE (len); i++) if (b[i] & ~a[i]) return false; return true; } int array_one_bit_subtract (array_t *a, array_t *b, int len ) { int total_diff = 0; array_t diffs[len]; for (int i = 0; i < SIZE (len); i++) { array_t c = b[i] & ~a[i]; diffs[i] = c; total_diff += __builtin_popcountll(c); if (total_diff > 1) return total_diff; } if (total_diff == 1) { for (int i = 0; i < SIZE (len); i++) { if (diffs[i]) { if (diffs[i] & EVEN_MASK) b[i] = b[i] & ~(diffs[i] >> 1); else b[i] = b[i] & ~(diffs[i] << 1); } } } return total_diff; } void array_combine(array_t **_a, array_t **_b, array_t **extra, const array_t *mask, int len) { array_t *a = *_a; array_t *b = *_b; bool equal = true; bool aSubb = true; bool bSuba = true; int diff_count = 0; array_t tmp[SIZE (len)]; for (int i = 0; i < SIZE (len); i++) { if (equal && a[i] != b[i]) equal = false; if (!equal && bSuba && (b[i] & ~a[i])) bSuba = false; if (!equal && aSubb && (a[i] & ~b[i])) aSubb = false; if (mask && diff_count <= 1) { if (bSuba) tmp[i] = b[i]; else if (aSubb) tmp[i] = a[i]; else { array_t isect = a[i] & b[i]; array_t diffs = ((isect | (isect >> 1)) & ODD_MASK) | ((isect | (isect << 1)) & EVEN_MASK); diffs = ~diffs; if (diffs & mask[i] & EVEN_MASK) {*extra = NULL; return;} int count = __builtin_popcountll(diffs) / 2; if (count == 0) tmp[i] = isect; else { diff_count += count; if (diff_count == 1) tmp[i] = isect | diffs; } } // in case of no combine, if no subset detected, return. } else if (!mask && !bSuba && !aSubb) {*extra = NULL; return;} // more than one non-intersecting bits - no combine. if (diff_count > 1) {*extra = NULL; return;} } // keep a if equal or b is subset of a if (equal || bSuba) {free(b); *_b = NULL; *extra = NULL;} // keep b if a is subset of b else if (aSubb) {free(a); *_a = NULL; *extra = NULL; } // keep b and a untouched if there is no merge. e.g. 100x u 1xx0 else if (diff_count == 0) {*extra = NULL;} // or we will have a combine: else { bool b1 = array_is_sub(tmp,a,len); bool b2 = array_is_sub(tmp,b,len); // e.g. 10x0 U 10x1 --> 10xx if (b1 && b2) { free(a); free(b); *_a = NULL; *_b = NULL; *extra = array_copy(tmp,len); } // e.g. 1001 U 1xx0 --> 100x U 1xx0 else if (b1) { free(a); *_a = NULL; *extra = array_copy(tmp,len);} // e.g. 1xx0 U 1001 --> 1xx0 U 100x else if (b2) { free(b); *_b = NULL; *extra = array_copy(tmp,len);} // e.g. 10x1 U 1x00 --> 10x1 U 1x00 U 100X else {*extra = array_copy(tmp,len);} } } enum bit_val array_get_bit (const array_t *a, int byte, int bit) { const uint8_t *p = (const uint8_t *) a; uint8_t x = p[2 * byte + bit / (CHAR_BIT / 2)]; int shift = 2 * (CHAR_BIT / 2 - (bit % (CHAR_BIT / 2)) - 1); return x >> shift; } uint16_t array_get_byte (const array_t *a, int byte) { const uint8_t *p = (const uint8_t *) a; return (p[2 * byte] << CHAR_BIT) | p[2 * byte + 1]; } void array_set_bit (array_t *a, enum bit_val val, int byte, int bit) { uint8_t *p = (uint8_t *) a; int idx = 2 * byte + bit / (CHAR_BIT / 2); int shift = 2 * (CHAR_BIT / 2 - (bit % (CHAR_BIT / 2)) - 1); uint8_t mask = BIT_X >> shift; p[idx] = (p[idx] & ~mask) | (val << shift); } void array_set_byte (array_t *a, uint16_t val, int byte) { uint8_t *p = (uint8_t *) a; p[2 * byte] = val >> CHAR_BIT; a[2 * byte + 1] = val & 0xff; } void array_and (const array_t *a, const array_t *b, int len, array_t *res) { for (int i = 0; i < SIZE (len); i++) res[i] = ((a[i] | b[i]) & ODD_MASK) | (a[i] & b[i] & EVEN_MASK); } bool array_cmpl (const array_t *a, int len, int *n, array_t **res) { *n = 0; for (int i = 0; i < SIZE (len); i++) { array_t cur = ~a[i]; while (cur) { array_t next = cur & (cur - 1); array_t bit = cur & ~next; bit = ((bit >> 1) & ODD_MASK) | ((bit << 1) & EVEN_MASK); res[*n] = array_create (len, BIT_X); res[*n][i] &= ~bit; ++*n; cur = next; } } return *n; } bool array_diff (const array_t *a, const array_t *b, int len, int *n, array_t **res) { int n_cmpl; if (!array_cmpl (b, len, &n_cmpl, res)) return false; *n = 0; for (int i = 0; i < n_cmpl; i++) if (array_isect (a, res[i], len, res[*n])) ++*n; for (int i = *n; i < n_cmpl; i++) array_free (res[i]); return *n; } bool array_isect (const array_t *a, const array_t *b, int len, array_t *res) { for (int i = 0; i < SIZE (len); i++) { res[i] = a[i] & b[i]; if (has_z (res[i])) return false; } return true; } void array_not (const array_t *a, int len, array_t *res) { for (int i = 0; i < SIZE (len); i++) res[i] = ((a[i] >> 1) & ODD_MASK) | ((a[i] << 1) & EVEN_MASK); } void array_or (const array_t *a, const array_t *b, int len, array_t *res) { for (int i = 0; i < SIZE (len); i++) res[i] = (a[i] & b[i] & ODD_MASK) | ((a[i] | b[i]) & EVEN_MASK); } /* Rewrite A using MASK and REWRITE. Returns number of x's in result. */ int array_rewrite (array_t *a, const array_t *mask, const array_t *rewrite, int len) { int n = 0; for (int i = 0; i < SIZE (len); i++) { n += x_count (a[i], mask[i]); a[i] = (((a[i] | mask[i]) & rewrite[i]) & ODD_MASK) | (((a[i] & mask[i]) | rewrite[i]) & EVEN_MASK); } return n; } int array_x_count (const array_t *a, const array_t *mask, int len) { int n = 0; for (int i = 0; i < SIZE (len); i++) n += x_count (a[i], mask[i]); return n; } array_t * array_and_a (const array_t *a, const array_t *b, int len) { array_t *res = array_create (len, BIT_UNDEF); array_and (a, b, len, res); return res; } array_t ** array_cmpl_a (const array_t *a, int len, int *n) { array_t *tmp[len * CHAR_BIT]; if (!array_cmpl (a, len, n, tmp)) return NULL; array_t **res = xmemdup (tmp, *n * sizeof *res); return res; } array_t ** array_diff_a (const array_t *a, const array_t *b, int len, int *n) { array_t *tmp[len * CHAR_BIT]; if (!array_diff (a, b, len, n, tmp)) return NULL; array_t **res = xmemdup (tmp, *n * sizeof *res); return res; } //TODO: Move HS optimization here array_t * array_isect_a (const array_t *a, const array_t *b, int len) { array_t *res = array_create (len, BIT_UNDEF); if (!array_isect (a, b, len, res)) { free (res); return NULL; } return res; } array_t * array_not_a (const array_t *a, int len) { array_t *res = array_create (len, BIT_UNDEF); array_not (a, len, res); return res; } array_t * array_or_a (const array_t *a, const array_t *b, int len) { array_t *res = array_create (len, BIT_UNDEF); array_or (a, b, len, res); return res; } void array_shift_left (array_t *a, int len, int start, int shift, enum bit_val val) { assert (start % 4 == 0 && shift % 4 == 0); assert (start / 4 + shift / 4 <= len * 2); uint8_t *p = (uint8_t *) a; int bytes = 2 * len - start / 4 - shift / 4; memmove (p + start / 4, p + start / 4 + shift / 4, bytes); memset (p + 2 * len - shift / 4, 0x55 * val, shift / 4); } void array_shift_right (array_t *a, int len, int start, int shift, enum bit_val val) { assert (start % 4 == 0 && shift % 4 == 0); assert (start / 4 + shift / 4 <= len * 2); uint8_t *p = (uint8_t *) a; int bytes = 2 * len - start / 4 - shift / 4; memmove (p + start / 4 + shift / 4, p + start / 4, bytes); memset (p + start / 4, 0x55 * val, shift / 4); }
bovenyan/hsa
net_plumber/src/headerspace/array.c
C
gpl-2.0
11,581
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
/* * linux/drivers/message/fusion/mptlan.c * IP Over Fibre Channel device driver. * For use with LSI Fibre Channel PCI chip/adapters * running LSI Fusion MPT (Message Passing Technology) firmware. * * Copyright (c) 2000-2008 LSI Corporation * (mailto:DL-MPTFusionLinux@lsi.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; 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. NO WARRANTY THE PROGRAM IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED INCLUDING, WITHOUT LIMITATION, ANY WARRANTIES OR CONDITIONS OF TITLE, NON-INFRINGEMENT, MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Each Recipient is solely responsible for determining the appropriateness of using and distributing the Program and assumes all risks associated with its exercise of rights under this Agreement, including but not limited to the risks and costs of program errors, damage to or loss of data, programs or equipment, and unavailability or interruption of operations. DISCLAIMER OF LIABILITY NEITHER RECIPIENT NOR ANY CONTRIBUTORS SHALL HAVE ANY LIABILITY FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING WITHOUT LIMITATION LOST PROFITS), HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OR DISTRIBUTION OF THE PROGRAM OR THE EXERCISE OF ANY RIGHTS GRANTED HEREUNDER, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGES 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 */ /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /* * Define statements used for debugging */ //#define MPT_LAN_IO_DEBUG /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ #include "mptlan.h" #include <linux/init.h> #include <linux/module.h> #include <linux/fs.h> #define my_VERSION MPT_LINUX_VERSION_COMMON #define MYNAM "mptlan" MODULE_LICENSE("GPL"); MODULE_VERSION(my_VERSION); /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /* * MPT LAN message sizes without variable part. */ #define MPT_LAN_RECEIVE_POST_REQUEST_SIZE \ (sizeof(LANReceivePostRequest_t) - sizeof(SGE_MPI_UNION)) #define MPT_LAN_TRANSACTION32_SIZE \ (sizeof(SGETransaction32_t) - sizeof(u32)) /* * Fusion MPT LAN private structures */ struct BufferControl { struct sk_buff *skb; dma_addr_t dma; unsigned int len; }; struct mpt_lan_priv { MPT_ADAPTER *mpt_dev; u8 pnum; /* Port number in the IOC. This is not a Unix network port! */ atomic_t buckets_out; /* number of unused buckets on IOC */ int bucketthresh; /* Send more when this many left */ int *mpt_txfidx; /* Free Tx Context list */ int mpt_txfidx_tail; spinlock_t txfidx_lock; int *mpt_rxfidx; /* Free Rx Context list */ int mpt_rxfidx_tail; spinlock_t rxfidx_lock; struct BufferControl *RcvCtl; /* Receive BufferControl structs */ struct BufferControl *SendCtl; /* Send BufferControl structs */ int max_buckets_out; /* Max buckets to send to IOC */ int tx_max_out; /* IOC's Tx queue len */ u32 total_posted; u32 total_received; struct net_device_stats stats; /* Per device statistics */ struct delayed_work post_buckets_task; struct net_device *dev; unsigned long post_buckets_active; }; struct mpt_lan_ohdr { u16 dtype; u8 daddr[FC_ALEN]; u16 stype; u8 saddr[FC_ALEN]; }; /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /* * Forward protos... */ static int lan_reply (MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf, MPT_FRAME_HDR *reply); static int mpt_lan_open(struct net_device *dev); static int mpt_lan_reset(struct net_device *dev); static int mpt_lan_close(struct net_device *dev); static void mpt_lan_post_receive_buckets(struct mpt_lan_priv *priv); static void mpt_lan_wake_post_buckets_task(struct net_device *dev, int priority); static int mpt_lan_receive_post_turbo(struct net_device *dev, u32 tmsg); static int mpt_lan_receive_post_reply(struct net_device *dev, LANReceivePostReply_t *pRecvRep); static int mpt_lan_send_turbo(struct net_device *dev, u32 tmsg); static int mpt_lan_send_reply(struct net_device *dev, LANSendReply_t *pSendRep); static int mpt_lan_ioc_reset(MPT_ADAPTER *ioc, int reset_phase); static int mpt_lan_event_process(MPT_ADAPTER *ioc, EventNotificationReply_t *pEvReply); static unsigned short mpt_lan_type_trans(struct sk_buff *skb, struct net_device *dev); /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /* * Fusion MPT LAN private data */ static u8 LanCtx = MPT_MAX_PROTOCOL_DRIVERS; static u32 max_buckets_out = 127; static u32 tx_max_out_p = 127 - 16; /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /** * lan_reply - Handle all data sent from the hardware. * @ioc: Pointer to MPT_ADAPTER structure * @mf: Pointer to original MPT request frame (NULL if TurboReply) * @reply: Pointer to MPT reply frame * * Returns 1 indicating original alloc'd request frame ptr * should be freed, or 0 if it shouldn't. */ static int lan_reply (MPT_ADAPTER *ioc, MPT_FRAME_HDR *mf, MPT_FRAME_HDR *reply) { struct net_device *dev = ioc->netdev; int FreeReqFrame = 0; dioprintk((KERN_INFO MYNAM ": %s/%s: Got reply.\n", IOC_AND_NETDEV_NAMES_s_s(dev))); // dioprintk((KERN_INFO MYNAM "@lan_reply: mf = %p, reply = %p\n", // mf, reply)); if (mf == NULL) { u32 tmsg = CAST_PTR_TO_U32(reply); dioprintk((KERN_INFO MYNAM ": %s/%s: @lan_reply, tmsg %08x\n", IOC_AND_NETDEV_NAMES_s_s(dev), tmsg)); switch (GET_LAN_FORM(tmsg)) { // NOTE! (Optimization) First case here is now caught in // mptbase.c::mpt_interrupt() routine and callcack here // is now skipped for this case! #if 0 case LAN_REPLY_FORM_MESSAGE_CONTEXT: // dioprintk((KERN_INFO MYNAM "/lan_reply: " // "MessageContext turbo reply received\n")); FreeReqFrame = 1; break; #endif case LAN_REPLY_FORM_SEND_SINGLE: // dioprintk((MYNAM "/lan_reply: " // "calling mpt_lan_send_reply (turbo)\n")); // Potential BUG here? // FreeReqFrame = mpt_lan_send_turbo(dev, tmsg); // If/when mpt_lan_send_turbo would return 1 here, // calling routine (mptbase.c|mpt_interrupt) // would Oops because mf has already been set // to NULL. So after return from this func, // mpt_interrupt() will attempt to put (NULL) mf ptr // item back onto its adapter FreeQ - Oops!:-( // It's Ok, since mpt_lan_send_turbo() *currently* // always returns 0, but..., just in case: (void) mpt_lan_send_turbo(dev, tmsg); FreeReqFrame = 0; break; case LAN_REPLY_FORM_RECEIVE_SINGLE: // dioprintk((KERN_INFO MYNAM "@lan_reply: " // "rcv-Turbo = %08x\n", tmsg)); mpt_lan_receive_post_turbo(dev, tmsg); break; default: printk (KERN_ERR MYNAM "/lan_reply: Got a turbo reply " "that I don't know what to do with\n"); /* CHECKME! Hmmm... FreeReqFrame is 0 here; is that right? */ break; } return FreeReqFrame; } // msg = (u32 *) reply; // dioprintk((KERN_INFO MYNAM "@lan_reply: msg = %08x %08x %08x %08x\n", // le32_to_cpu(msg[0]), le32_to_cpu(msg[1]), // le32_to_cpu(msg[2]), le32_to_cpu(msg[3]))); // dioprintk((KERN_INFO MYNAM "@lan_reply: Function = %02xh\n", // reply->u.hdr.Function)); switch (reply->u.hdr.Function) { case MPI_FUNCTION_LAN_SEND: { LANSendReply_t *pSendRep; pSendRep = (LANSendReply_t *) reply; FreeReqFrame = mpt_lan_send_reply(dev, pSendRep); break; } case MPI_FUNCTION_LAN_RECEIVE: { LANReceivePostReply_t *pRecvRep; pRecvRep = (LANReceivePostReply_t *) reply; if (pRecvRep->NumberOfContexts) { mpt_lan_receive_post_reply(dev, pRecvRep); if (!(pRecvRep->MsgFlags & MPI_MSGFLAGS_CONTINUATION_REPLY)) FreeReqFrame = 1; } else dioprintk((KERN_INFO MYNAM "@lan_reply: zero context " "ReceivePostReply received.\n")); break; } case MPI_FUNCTION_LAN_RESET: /* Just a default reply. Might want to check it to * make sure that everything went ok. */ FreeReqFrame = 1; break; case MPI_FUNCTION_EVENT_NOTIFICATION: case MPI_FUNCTION_EVENT_ACK: /* _EVENT_NOTIFICATION should NOT come down this path any more. * Should be routed to mpt_lan_event_process(), but just in case... */ FreeReqFrame = 1; break; default: printk (KERN_ERR MYNAM "/lan_reply: Got a non-turbo " "reply that I don't know what to do with\n"); /* CHECKME! Hmmm... FreeReqFrame is 0 here; is that right? */ FreeReqFrame = 1; break; } return FreeReqFrame; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static int mpt_lan_ioc_reset(MPT_ADAPTER *ioc, int reset_phase) { struct net_device *dev = ioc->netdev; struct mpt_lan_priv *priv; if (dev == NULL) return(1); else priv = netdev_priv(dev); dlprintk((KERN_INFO MYNAM ": IOC %s_reset routed to LAN driver!\n", reset_phase==MPT_IOC_SETUP_RESET ? "setup" : ( reset_phase==MPT_IOC_PRE_RESET ? "pre" : "post"))); if (priv->mpt_rxfidx == NULL) return (1); if (reset_phase == MPT_IOC_SETUP_RESET) { ; } else if (reset_phase == MPT_IOC_PRE_RESET) { int i; unsigned long flags; netif_stop_queue(dev); dlprintk ((KERN_INFO "mptlan/ioc_reset: called netif_stop_queue for %s.\n", dev->name)); atomic_set(&priv->buckets_out, 0); /* Reset Rx Free Tail index and re-populate the queue. */ spin_lock_irqsave(&priv->rxfidx_lock, flags); priv->mpt_rxfidx_tail = -1; for (i = 0; i < priv->max_buckets_out; i++) priv->mpt_rxfidx[++priv->mpt_rxfidx_tail] = i; spin_unlock_irqrestore(&priv->rxfidx_lock, flags); } else { mpt_lan_post_receive_buckets(priv); netif_wake_queue(dev); } return 1; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static int mpt_lan_event_process(MPT_ADAPTER *ioc, EventNotificationReply_t *pEvReply) { dlprintk((KERN_INFO MYNAM ": MPT event routed to LAN driver!\n")); switch (le32_to_cpu(pEvReply->Event)) { case MPI_EVENT_NONE: /* 00 */ case MPI_EVENT_LOG_DATA: /* 01 */ case MPI_EVENT_STATE_CHANGE: /* 02 */ case MPI_EVENT_UNIT_ATTENTION: /* 03 */ case MPI_EVENT_IOC_BUS_RESET: /* 04 */ case MPI_EVENT_EXT_BUS_RESET: /* 05 */ case MPI_EVENT_RESCAN: /* 06 */ /* Ok, do we need to do anything here? As far as I can tell, this is when a new device gets added to the loop. */ case MPI_EVENT_LINK_STATUS_CHANGE: /* 07 */ case MPI_EVENT_LOOP_STATE_CHANGE: /* 08 */ case MPI_EVENT_LOGOUT: /* 09 */ case MPI_EVENT_EVENT_CHANGE: /* 0A */ default: break; } /* * NOTE: pEvent->AckRequired handling now done in mptbase.c; * Do NOT do it here now! */ return 1; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static int mpt_lan_open(struct net_device *dev) { struct mpt_lan_priv *priv = netdev_priv(dev); int i; if (mpt_lan_reset(dev) != 0) { MPT_ADAPTER *mpt_dev = priv->mpt_dev; printk (KERN_WARNING MYNAM "/lan_open: lan_reset failed."); if (mpt_dev->active) printk ("The ioc is active. Perhaps it needs to be" " reset?\n"); else printk ("The ioc in inactive, most likely in the " "process of being reset. Please try again in " "a moment.\n"); } priv->mpt_txfidx = kmalloc(priv->tx_max_out * sizeof(int), GFP_KERNEL); if (priv->mpt_txfidx == NULL) goto out; priv->mpt_txfidx_tail = -1; priv->SendCtl = kcalloc(priv->tx_max_out, sizeof(struct BufferControl), GFP_KERNEL); if (priv->SendCtl == NULL) goto out_mpt_txfidx; for (i = 0; i < priv->tx_max_out; i++) priv->mpt_txfidx[++priv->mpt_txfidx_tail] = i; dlprintk((KERN_INFO MYNAM "@lo: Finished initializing SendCtl\n")); priv->mpt_rxfidx = kmalloc(priv->max_buckets_out * sizeof(int), GFP_KERNEL); if (priv->mpt_rxfidx == NULL) goto out_SendCtl; priv->mpt_rxfidx_tail = -1; priv->RcvCtl = kcalloc(priv->max_buckets_out, sizeof(struct BufferControl), GFP_KERNEL); if (priv->RcvCtl == NULL) goto out_mpt_rxfidx; for (i = 0; i < priv->max_buckets_out; i++) priv->mpt_rxfidx[++priv->mpt_rxfidx_tail] = i; /**/ dlprintk((KERN_INFO MYNAM "/lo: txfidx contains - ")); /**/ for (i = 0; i < priv->tx_max_out; i++) /**/ dlprintk((" %xh", priv->mpt_txfidx[i])); /**/ dlprintk(("\n")); dlprintk((KERN_INFO MYNAM "/lo: Finished initializing RcvCtl\n")); mpt_lan_post_receive_buckets(priv); printk(KERN_INFO MYNAM ": %s/%s: interface up & active\n", IOC_AND_NETDEV_NAMES_s_s(dev)); if (mpt_event_register(LanCtx, mpt_lan_event_process) != 0) { printk (KERN_WARNING MYNAM "/lo: Unable to register for Event" " Notifications. This is a bad thing! We're not going " "to go ahead, but I'd be leery of system stability at " "this point.\n"); } netif_start_queue(dev); dlprintk((KERN_INFO MYNAM "/lo: Done.\n")); return 0; out_mpt_rxfidx: kfree(priv->mpt_rxfidx); priv->mpt_rxfidx = NULL; out_SendCtl: kfree(priv->SendCtl); priv->SendCtl = NULL; out_mpt_txfidx: kfree(priv->mpt_txfidx); priv->mpt_txfidx = NULL; out: return -ENOMEM; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /* Send a LanReset message to the FW. This should result in the FW returning any buckets it still has. */ static int mpt_lan_reset(struct net_device *dev) { MPT_FRAME_HDR *mf; LANResetRequest_t *pResetReq; struct mpt_lan_priv *priv = netdev_priv(dev); mf = mpt_get_msg_frame(LanCtx, priv->mpt_dev); if (mf == NULL) { /* dlprintk((KERN_ERR MYNAM "/reset: Evil funkiness abounds! " "Unable to allocate a request frame.\n")); */ return -1; } pResetReq = (LANResetRequest_t *) mf; pResetReq->Function = MPI_FUNCTION_LAN_RESET; pResetReq->ChainOffset = 0; pResetReq->Reserved = 0; pResetReq->PortNumber = priv->pnum; pResetReq->MsgFlags = 0; pResetReq->Reserved2 = 0; mpt_put_msg_frame(LanCtx, priv->mpt_dev, mf); return 0; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static int mpt_lan_close(struct net_device *dev) { struct mpt_lan_priv *priv = netdev_priv(dev); MPT_ADAPTER *mpt_dev = priv->mpt_dev; unsigned long timeout; int i; dlprintk((KERN_INFO MYNAM ": mpt_lan_close called\n")); mpt_event_deregister(LanCtx); dlprintk((KERN_INFO MYNAM ":lan_close: Posted %d buckets " "since driver was loaded, %d still out\n", priv->total_posted,atomic_read(&priv->buckets_out))); netif_stop_queue(dev); mpt_lan_reset(dev); timeout = jiffies + 2 * HZ; while (atomic_read(&priv->buckets_out) && time_before(jiffies, timeout)) schedule_timeout_interruptible(1); for (i = 0; i < priv->max_buckets_out; i++) { if (priv->RcvCtl[i].skb != NULL) { /**/ dlprintk((KERN_INFO MYNAM "/lan_close: bucket %05x " /**/ "is still out\n", i)); pci_unmap_single(mpt_dev->pcidev, priv->RcvCtl[i].dma, priv->RcvCtl[i].len, PCI_DMA_FROMDEVICE); dev_kfree_skb(priv->RcvCtl[i].skb); } } kfree(priv->RcvCtl); kfree(priv->mpt_rxfidx); for (i = 0; i < priv->tx_max_out; i++) { if (priv->SendCtl[i].skb != NULL) { pci_unmap_single(mpt_dev->pcidev, priv->SendCtl[i].dma, priv->SendCtl[i].len, PCI_DMA_TODEVICE); dev_kfree_skb(priv->SendCtl[i].skb); } } kfree(priv->SendCtl); kfree(priv->mpt_txfidx); atomic_set(&priv->buckets_out, 0); printk(KERN_INFO MYNAM ": %s/%s: interface down & inactive\n", IOC_AND_NETDEV_NAMES_s_s(dev)); return 0; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static struct net_device_stats * mpt_lan_get_stats(struct net_device *dev) { struct mpt_lan_priv *priv = netdev_priv(dev); return (struct net_device_stats *) &priv->stats; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static int mpt_lan_change_mtu(struct net_device *dev, int new_mtu) { if ((new_mtu < MPT_LAN_MIN_MTU) || (new_mtu > MPT_LAN_MAX_MTU)) return -EINVAL; dev->mtu = new_mtu; return 0; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /* Tx timeout handler. */ static void mpt_lan_tx_timeout(struct net_device *dev) { struct mpt_lan_priv *priv = netdev_priv(dev); MPT_ADAPTER *mpt_dev = priv->mpt_dev; if (mpt_dev->active) { dlprintk (("mptlan/tx_timeout: calling netif_wake_queue for %s.\n", dev->name)); netif_wake_queue(dev); } } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ //static inline int static int mpt_lan_send_turbo(struct net_device *dev, u32 tmsg) { struct mpt_lan_priv *priv = netdev_priv(dev); MPT_ADAPTER *mpt_dev = priv->mpt_dev; struct sk_buff *sent; unsigned long flags; u32 ctx; ctx = GET_LAN_BUFFER_CONTEXT(tmsg); sent = priv->SendCtl[ctx].skb; priv->stats.tx_packets++; priv->stats.tx_bytes += sent->len; dioprintk((KERN_INFO MYNAM ": %s/%s: @%s, skb %p sent.\n", IOC_AND_NETDEV_NAMES_s_s(dev), __func__, sent)); priv->SendCtl[ctx].skb = NULL; pci_unmap_single(mpt_dev->pcidev, priv->SendCtl[ctx].dma, priv->SendCtl[ctx].len, PCI_DMA_TODEVICE); dev_kfree_skb_irq(sent); spin_lock_irqsave(&priv->txfidx_lock, flags); priv->mpt_txfidx[++priv->mpt_txfidx_tail] = ctx; spin_unlock_irqrestore(&priv->txfidx_lock, flags); netif_wake_queue(dev); return 0; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static int mpt_lan_send_reply(struct net_device *dev, LANSendReply_t *pSendRep) { struct mpt_lan_priv *priv = netdev_priv(dev); MPT_ADAPTER *mpt_dev = priv->mpt_dev; struct sk_buff *sent; unsigned long flags; int FreeReqFrame = 0; u32 *pContext; u32 ctx; u8 count; count = pSendRep->NumberOfContexts; dioprintk((KERN_INFO MYNAM ": send_reply: IOCStatus: %04x\n", le16_to_cpu(pSendRep->IOCStatus))); /* Add check for Loginfo Flag in IOCStatus */ switch (le16_to_cpu(pSendRep->IOCStatus) & MPI_IOCSTATUS_MASK) { case MPI_IOCSTATUS_SUCCESS: priv->stats.tx_packets += count; break; case MPI_IOCSTATUS_LAN_CANCELED: case MPI_IOCSTATUS_LAN_TRANSMIT_ABORTED: break; case MPI_IOCSTATUS_INVALID_SGL: priv->stats.tx_errors += count; printk (KERN_ERR MYNAM ": %s/%s: ERROR - Invalid SGL sent to IOC!\n", IOC_AND_NETDEV_NAMES_s_s(dev)); goto out; default: priv->stats.tx_errors += count; break; } pContext = &pSendRep->BufferContext; spin_lock_irqsave(&priv->txfidx_lock, flags); while (count > 0) { ctx = GET_LAN_BUFFER_CONTEXT(le32_to_cpu(*pContext)); sent = priv->SendCtl[ctx].skb; priv->stats.tx_bytes += sent->len; dioprintk((KERN_INFO MYNAM ": %s/%s: @%s, skb %p sent.\n", IOC_AND_NETDEV_NAMES_s_s(dev), __func__, sent)); priv->SendCtl[ctx].skb = NULL; pci_unmap_single(mpt_dev->pcidev, priv->SendCtl[ctx].dma, priv->SendCtl[ctx].len, PCI_DMA_TODEVICE); dev_kfree_skb_irq(sent); priv->mpt_txfidx[++priv->mpt_txfidx_tail] = ctx; pContext++; count--; } spin_unlock_irqrestore(&priv->txfidx_lock, flags); out: if (!(pSendRep->MsgFlags & MPI_MSGFLAGS_CONTINUATION_REPLY)) FreeReqFrame = 1; netif_wake_queue(dev); return FreeReqFrame; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static int mpt_lan_sdu_send (struct sk_buff *skb, struct net_device *dev) { struct mpt_lan_priv *priv = netdev_priv(dev); MPT_ADAPTER *mpt_dev = priv->mpt_dev; MPT_FRAME_HDR *mf; LANSendRequest_t *pSendReq; SGETransaction32_t *pTrans; SGESimple64_t *pSimple; const unsigned char *mac; dma_addr_t dma; unsigned long flags; int ctx; u16 cur_naa = 0x1000; dioprintk((KERN_INFO MYNAM ": %s called, skb_addr = %p\n", __func__, skb)); spin_lock_irqsave(&priv->txfidx_lock, flags); if (priv->mpt_txfidx_tail < 0) { netif_stop_queue(dev); spin_unlock_irqrestore(&priv->txfidx_lock, flags); printk (KERN_ERR "%s: no tx context available: %u\n", __func__, priv->mpt_txfidx_tail); return 1; } mf = mpt_get_msg_frame(LanCtx, mpt_dev); if (mf == NULL) { netif_stop_queue(dev); spin_unlock_irqrestore(&priv->txfidx_lock, flags); printk (KERN_ERR "%s: Unable to alloc request frame\n", __func__); return 1; } ctx = priv->mpt_txfidx[priv->mpt_txfidx_tail--]; spin_unlock_irqrestore(&priv->txfidx_lock, flags); // dioprintk((KERN_INFO MYNAM ": %s/%s: Creating new msg frame (send).\n", // IOC_AND_NETDEV_NAMES_s_s(dev))); pSendReq = (LANSendRequest_t *) mf; /* Set the mac.raw pointer, since this apparently isn't getting * done before we get the skb. Pull the data pointer past the mac data. */ skb_reset_mac_header(skb); skb_pull(skb, 12); dma = pci_map_single(mpt_dev->pcidev, skb->data, skb->len, PCI_DMA_TODEVICE); priv->SendCtl[ctx].skb = skb; priv->SendCtl[ctx].dma = dma; priv->SendCtl[ctx].len = skb->len; /* Message Header */ pSendReq->Reserved = 0; pSendReq->Function = MPI_FUNCTION_LAN_SEND; pSendReq->ChainOffset = 0; pSendReq->Reserved2 = 0; pSendReq->MsgFlags = 0; pSendReq->PortNumber = priv->pnum; /* Transaction Context Element */ pTrans = (SGETransaction32_t *) pSendReq->SG_List; /* No Flags, 8 bytes of Details, 32bit Context (bloody turbo replies) */ pTrans->ContextSize = sizeof(u32); pTrans->DetailsLength = 2 * sizeof(u32); pTrans->Flags = 0; pTrans->TransactionContext[0] = cpu_to_le32(ctx); // dioprintk((KERN_INFO MYNAM ": %s/%s: BC = %08x, skb = %p, buff = %p\n", // IOC_AND_NETDEV_NAMES_s_s(dev), // ctx, skb, skb->data)); mac = skb_mac_header(skb); pTrans->TransactionDetails[0] = cpu_to_le32((cur_naa << 16) | (mac[0] << 8) | (mac[1] << 0)); pTrans->TransactionDetails[1] = cpu_to_le32((mac[2] << 24) | (mac[3] << 16) | (mac[4] << 8) | (mac[5] << 0)); pSimple = (SGESimple64_t *) &pTrans->TransactionDetails[2]; /* If we ever decide to send more than one Simple SGE per LANSend, then we will need to make sure that LAST_ELEMENT only gets set on the last one. Otherwise, bad voodoo and evil funkiness will commence. */ pSimple->FlagsLength = cpu_to_le32( ((MPI_SGE_FLAGS_LAST_ELEMENT | MPI_SGE_FLAGS_END_OF_BUFFER | MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_SYSTEM_ADDRESS | MPI_SGE_FLAGS_HOST_TO_IOC | MPI_SGE_FLAGS_64_BIT_ADDRESSING | MPI_SGE_FLAGS_END_OF_LIST) << MPI_SGE_FLAGS_SHIFT) | skb->len); pSimple->Address.Low = cpu_to_le32((u32) dma); if (sizeof(dma_addr_t) > sizeof(u32)) pSimple->Address.High = cpu_to_le32((u32) ((u64) dma >> 32)); else pSimple->Address.High = 0; mpt_put_msg_frame (LanCtx, mpt_dev, mf); dev->trans_start = jiffies; dioprintk((KERN_INFO MYNAM ": %s/%s: Sending packet. FlagsLength = %08x.\n", IOC_AND_NETDEV_NAMES_s_s(dev), le32_to_cpu(pSimple->FlagsLength))); return 0; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static void mpt_lan_wake_post_buckets_task(struct net_device *dev, int priority) /* * @priority: 0 = put it on the timer queue, 1 = put it on the immediate queue */ { struct mpt_lan_priv *priv = netdev_priv(dev); if (test_and_set_bit(0, &priv->post_buckets_active) == 0) { if (priority) { schedule_delayed_work(&priv->post_buckets_task, 0); } else { schedule_delayed_work(&priv->post_buckets_task, 1); dioprintk((KERN_INFO MYNAM ": post_buckets queued on " "timer.\n")); } dioprintk((KERN_INFO MYNAM ": %s/%s: Queued post_buckets task.\n", IOC_AND_NETDEV_NAMES_s_s(dev) )); } } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static int mpt_lan_receive_skb(struct net_device *dev, struct sk_buff *skb) { struct mpt_lan_priv *priv = netdev_priv(dev); skb->protocol = mpt_lan_type_trans(skb, dev); dioprintk((KERN_INFO MYNAM ": %s/%s: Incoming packet (%d bytes) " "delivered to upper level.\n", IOC_AND_NETDEV_NAMES_s_s(dev), skb->len)); priv->stats.rx_bytes += skb->len; priv->stats.rx_packets++; skb->dev = dev; netif_rx(skb); dioprintk((MYNAM "/receive_skb: %d buckets remaining\n", atomic_read(&priv->buckets_out))); if (atomic_read(&priv->buckets_out) < priv->bucketthresh) mpt_lan_wake_post_buckets_task(dev, 1); dioprintk((KERN_INFO MYNAM "/receive_post_reply: %d buckets " "remaining, %d received back since sod\n", atomic_read(&priv->buckets_out), priv->total_received)); return 0; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ //static inline int static int mpt_lan_receive_post_turbo(struct net_device *dev, u32 tmsg) { struct mpt_lan_priv *priv = netdev_priv(dev); MPT_ADAPTER *mpt_dev = priv->mpt_dev; struct sk_buff *skb, *old_skb; unsigned long flags; u32 ctx, len; ctx = GET_LAN_BUCKET_CONTEXT(tmsg); skb = priv->RcvCtl[ctx].skb; len = GET_LAN_PACKET_LENGTH(tmsg); if (len < MPT_LAN_RX_COPYBREAK) { old_skb = skb; skb = (struct sk_buff *)dev_alloc_skb(len); if (!skb) { printk (KERN_ERR MYNAM ": %s/%s: ERROR - Can't allocate skb! (%s@%d)\n", IOC_AND_NETDEV_NAMES_s_s(dev), __FILE__, __LINE__); return -ENOMEM; } pci_dma_sync_single_for_cpu(mpt_dev->pcidev, priv->RcvCtl[ctx].dma, priv->RcvCtl[ctx].len, PCI_DMA_FROMDEVICE); skb_copy_from_linear_data(old_skb, skb_put(skb, len), len); pci_dma_sync_single_for_device(mpt_dev->pcidev, priv->RcvCtl[ctx].dma, priv->RcvCtl[ctx].len, PCI_DMA_FROMDEVICE); goto out; } skb_put(skb, len); priv->RcvCtl[ctx].skb = NULL; pci_unmap_single(mpt_dev->pcidev, priv->RcvCtl[ctx].dma, priv->RcvCtl[ctx].len, PCI_DMA_FROMDEVICE); out: spin_lock_irqsave(&priv->rxfidx_lock, flags); priv->mpt_rxfidx[++priv->mpt_rxfidx_tail] = ctx; spin_unlock_irqrestore(&priv->rxfidx_lock, flags); atomic_dec(&priv->buckets_out); priv->total_received++; return mpt_lan_receive_skb(dev, skb); } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static int mpt_lan_receive_post_free(struct net_device *dev, LANReceivePostReply_t *pRecvRep) { struct mpt_lan_priv *priv = netdev_priv(dev); MPT_ADAPTER *mpt_dev = priv->mpt_dev; unsigned long flags; struct sk_buff *skb; u32 ctx; int count; int i; count = pRecvRep->NumberOfContexts; /**/ dlprintk((KERN_INFO MYNAM "/receive_post_reply: " "IOC returned %d buckets, freeing them...\n", count)); spin_lock_irqsave(&priv->rxfidx_lock, flags); for (i = 0; i < count; i++) { ctx = le32_to_cpu(pRecvRep->BucketContext[i]); skb = priv->RcvCtl[ctx].skb; // dlprintk((KERN_INFO MYNAM ": %s: dev_name = %s\n", // IOC_AND_NETDEV_NAMES_s_s(dev))); // dlprintk((KERN_INFO MYNAM "@rpr[2], priv = %p, buckets_out addr = %p", // priv, &(priv->buckets_out))); // dlprintk((KERN_INFO MYNAM "@rpr[2] TC + 3\n")); priv->RcvCtl[ctx].skb = NULL; pci_unmap_single(mpt_dev->pcidev, priv->RcvCtl[ctx].dma, priv->RcvCtl[ctx].len, PCI_DMA_FROMDEVICE); dev_kfree_skb_any(skb); priv->mpt_rxfidx[++priv->mpt_rxfidx_tail] = ctx; } spin_unlock_irqrestore(&priv->rxfidx_lock, flags); atomic_sub(count, &priv->buckets_out); // for (i = 0; i < priv->max_buckets_out; i++) // if (priv->RcvCtl[i].skb != NULL) // dlprintk((KERN_INFO MYNAM "@rpr: bucket %03x " // "is still out\n", i)); /* dlprintk((KERN_INFO MYNAM "/receive_post_reply: freed %d buckets\n", count)); */ /**/ dlprintk((KERN_INFO MYNAM "@receive_post_reply: %d buckets " /**/ "remaining, %d received back since sod.\n", /**/ atomic_read(&priv->buckets_out), priv->total_received)); return 0; } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static int mpt_lan_receive_post_reply(struct net_device *dev, LANReceivePostReply_t *pRecvRep) { struct mpt_lan_priv *priv = netdev_priv(dev); MPT_ADAPTER *mpt_dev = priv->mpt_dev; struct sk_buff *skb, *old_skb; unsigned long flags; u32 len, ctx, offset; u32 remaining = le32_to_cpu(pRecvRep->BucketsRemaining); int count; int i, l; dioprintk((KERN_INFO MYNAM ": mpt_lan_receive_post_reply called\n")); dioprintk((KERN_INFO MYNAM ": receive_post_reply: IOCStatus: %04x\n", le16_to_cpu(pRecvRep->IOCStatus))); if ((le16_to_cpu(pRecvRep->IOCStatus) & MPI_IOCSTATUS_MASK) == MPI_IOCSTATUS_LAN_CANCELED) return mpt_lan_receive_post_free(dev, pRecvRep); len = le32_to_cpu(pRecvRep->PacketLength); if (len == 0) { printk (KERN_ERR MYNAM ": %s/%s: ERROR - Got a non-TURBO " "ReceivePostReply w/ PacketLength zero!\n", IOC_AND_NETDEV_NAMES_s_s(dev)); printk (KERN_ERR MYNAM ": MsgFlags = %02x, IOCStatus = %04x\n", pRecvRep->MsgFlags, le16_to_cpu(pRecvRep->IOCStatus)); return -1; } ctx = le32_to_cpu(pRecvRep->BucketContext[0]); count = pRecvRep->NumberOfContexts; skb = priv->RcvCtl[ctx].skb; offset = le32_to_cpu(pRecvRep->PacketOffset); // if (offset != 0) { // printk (KERN_INFO MYNAM ": %s/%s: Got a ReceivePostReply " // "w/ PacketOffset %u\n", // IOC_AND_NETDEV_NAMES_s_s(dev), // offset); // } dioprintk((KERN_INFO MYNAM ": %s/%s: @rpr, offset = %d, len = %d\n", IOC_AND_NETDEV_NAMES_s_s(dev), offset, len)); if (count > 1) { int szrem = len; // dioprintk((KERN_INFO MYNAM ": %s/%s: Multiple buckets returned " // "for single packet, concatenating...\n", // IOC_AND_NETDEV_NAMES_s_s(dev))); skb = (struct sk_buff *)dev_alloc_skb(len); if (!skb) { printk (KERN_ERR MYNAM ": %s/%s: ERROR - Can't allocate skb! (%s@%d)\n", IOC_AND_NETDEV_NAMES_s_s(dev), __FILE__, __LINE__); return -ENOMEM; } spin_lock_irqsave(&priv->rxfidx_lock, flags); for (i = 0; i < count; i++) { ctx = le32_to_cpu(pRecvRep->BucketContext[i]); old_skb = priv->RcvCtl[ctx].skb; l = priv->RcvCtl[ctx].len; if (szrem < l) l = szrem; // dioprintk((KERN_INFO MYNAM ": %s/%s: Buckets = %d, len = %u\n", // IOC_AND_NETDEV_NAMES_s_s(dev), // i, l)); pci_dma_sync_single_for_cpu(mpt_dev->pcidev, priv->RcvCtl[ctx].dma, priv->RcvCtl[ctx].len, PCI_DMA_FROMDEVICE); skb_copy_from_linear_data(old_skb, skb_put(skb, l), l); pci_dma_sync_single_for_device(mpt_dev->pcidev, priv->RcvCtl[ctx].dma, priv->RcvCtl[ctx].len, PCI_DMA_FROMDEVICE); priv->mpt_rxfidx[++priv->mpt_rxfidx_tail] = ctx; szrem -= l; } spin_unlock_irqrestore(&priv->rxfidx_lock, flags); } else if (len < MPT_LAN_RX_COPYBREAK) { old_skb = skb; skb = (struct sk_buff *)dev_alloc_skb(len); if (!skb) { printk (KERN_ERR MYNAM ": %s/%s: ERROR - Can't allocate skb! (%s@%d)\n", IOC_AND_NETDEV_NAMES_s_s(dev), __FILE__, __LINE__); return -ENOMEM; } pci_dma_sync_single_for_cpu(mpt_dev->pcidev, priv->RcvCtl[ctx].dma, priv->RcvCtl[ctx].len, PCI_DMA_FROMDEVICE); skb_copy_from_linear_data(old_skb, skb_put(skb, len), len); pci_dma_sync_single_for_device(mpt_dev->pcidev, priv->RcvCtl[ctx].dma, priv->RcvCtl[ctx].len, PCI_DMA_FROMDEVICE); spin_lock_irqsave(&priv->rxfidx_lock, flags); priv->mpt_rxfidx[++priv->mpt_rxfidx_tail] = ctx; spin_unlock_irqrestore(&priv->rxfidx_lock, flags); } else { spin_lock_irqsave(&priv->rxfidx_lock, flags); priv->RcvCtl[ctx].skb = NULL; pci_unmap_single(mpt_dev->pcidev, priv->RcvCtl[ctx].dma, priv->RcvCtl[ctx].len, PCI_DMA_FROMDEVICE); priv->RcvCtl[ctx].dma = 0; priv->mpt_rxfidx[++priv->mpt_rxfidx_tail] = ctx; spin_unlock_irqrestore(&priv->rxfidx_lock, flags); skb_put(skb,len); } atomic_sub(count, &priv->buckets_out); priv->total_received += count; if (priv->mpt_rxfidx_tail >= MPT_LAN_MAX_BUCKETS_OUT) { printk (KERN_ERR MYNAM ": %s/%s: Yoohoo! mpt_rxfidx_tail = %d, " "MPT_LAN_MAX_BUCKETS_OUT = %d\n", IOC_AND_NETDEV_NAMES_s_s(dev), priv->mpt_rxfidx_tail, MPT_LAN_MAX_BUCKETS_OUT); return -1; } if (remaining == 0) printk (KERN_WARNING MYNAM ": %s/%s: WARNING - IOC out of buckets! " "(priv->buckets_out = %d)\n", IOC_AND_NETDEV_NAMES_s_s(dev), atomic_read(&priv->buckets_out)); else if (remaining < 10) printk (KERN_INFO MYNAM ": %s/%s: IOC says %d buckets left. " "(priv->buckets_out = %d)\n", IOC_AND_NETDEV_NAMES_s_s(dev), remaining, atomic_read(&priv->buckets_out)); if ((remaining < priv->bucketthresh) && ((atomic_read(&priv->buckets_out) - remaining) > MPT_LAN_BUCKETS_REMAIN_MISMATCH_THRESH)) { printk (KERN_WARNING MYNAM " Mismatch between driver's " "buckets_out count and fw's BucketsRemaining " "count has crossed the threshold, issuing a " "LanReset to clear the fw's hashtable. You may " "want to check your /var/log/messages for \"CRC " "error\" event notifications.\n"); mpt_lan_reset(dev); mpt_lan_wake_post_buckets_task(dev, 0); } return mpt_lan_receive_skb(dev, skb); } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ /* Simple SGE's only at the moment */ static void mpt_lan_post_receive_buckets(struct mpt_lan_priv *priv) { struct net_device *dev = priv->dev; MPT_ADAPTER *mpt_dev = priv->mpt_dev; MPT_FRAME_HDR *mf; LANReceivePostRequest_t *pRecvReq; SGETransaction32_t *pTrans; SGESimple64_t *pSimple; struct sk_buff *skb; dma_addr_t dma; u32 curr, buckets, count, max; u32 len = (dev->mtu + dev->hard_header_len + 4); unsigned long flags; int i; curr = atomic_read(&priv->buckets_out); buckets = (priv->max_buckets_out - curr); dioprintk((KERN_INFO MYNAM ": %s/%s: @%s, Start_buckets = %u, buckets_out = %u\n", IOC_AND_NETDEV_NAMES_s_s(dev), __func__, buckets, curr)); max = (mpt_dev->req_sz - MPT_LAN_RECEIVE_POST_REQUEST_SIZE) / (MPT_LAN_TRANSACTION32_SIZE + sizeof(SGESimple64_t)); while (buckets) { mf = mpt_get_msg_frame(LanCtx, mpt_dev); if (mf == NULL) { printk (KERN_ERR "%s: Unable to alloc request frame\n", __func__); dioprintk((KERN_ERR "%s: %u buckets remaining\n", __func__, buckets)); goto out; } pRecvReq = (LANReceivePostRequest_t *) mf; i = le16_to_cpu(mf->u.frame.hwhdr.msgctxu.fld.req_idx); mpt_dev->RequestNB[i] = 0; count = buckets; if (count > max) count = max; pRecvReq->Function = MPI_FUNCTION_LAN_RECEIVE; pRecvReq->ChainOffset = 0; pRecvReq->MsgFlags = 0; pRecvReq->PortNumber = priv->pnum; pTrans = (SGETransaction32_t *) pRecvReq->SG_List; pSimple = NULL; for (i = 0; i < count; i++) { int ctx; spin_lock_irqsave(&priv->rxfidx_lock, flags); if (priv->mpt_rxfidx_tail < 0) { printk (KERN_ERR "%s: Can't alloc context\n", __func__); spin_unlock_irqrestore(&priv->rxfidx_lock, flags); break; } ctx = priv->mpt_rxfidx[priv->mpt_rxfidx_tail--]; skb = priv->RcvCtl[ctx].skb; if (skb && (priv->RcvCtl[ctx].len != len)) { pci_unmap_single(mpt_dev->pcidev, priv->RcvCtl[ctx].dma, priv->RcvCtl[ctx].len, PCI_DMA_FROMDEVICE); dev_kfree_skb(priv->RcvCtl[ctx].skb); skb = priv->RcvCtl[ctx].skb = NULL; } if (skb == NULL) { skb = dev_alloc_skb(len); if (skb == NULL) { printk (KERN_WARNING MYNAM "/%s: Can't alloc skb\n", __func__); priv->mpt_rxfidx[++priv->mpt_rxfidx_tail] = ctx; spin_unlock_irqrestore(&priv->rxfidx_lock, flags); break; } dma = pci_map_single(mpt_dev->pcidev, skb->data, len, PCI_DMA_FROMDEVICE); priv->RcvCtl[ctx].skb = skb; priv->RcvCtl[ctx].dma = dma; priv->RcvCtl[ctx].len = len; } spin_unlock_irqrestore(&priv->rxfidx_lock, flags); pTrans->ContextSize = sizeof(u32); pTrans->DetailsLength = 0; pTrans->Flags = 0; pTrans->TransactionContext[0] = cpu_to_le32(ctx); pSimple = (SGESimple64_t *) pTrans->TransactionDetails; pSimple->FlagsLength = cpu_to_le32( ((MPI_SGE_FLAGS_END_OF_BUFFER | MPI_SGE_FLAGS_SIMPLE_ELEMENT | MPI_SGE_FLAGS_64_BIT_ADDRESSING) << MPI_SGE_FLAGS_SHIFT) | len); pSimple->Address.Low = cpu_to_le32((u32) priv->RcvCtl[ctx].dma); if (sizeof(dma_addr_t) > sizeof(u32)) pSimple->Address.High = cpu_to_le32((u32) ((u64) priv->RcvCtl[ctx].dma >> 32)); else pSimple->Address.High = 0; pTrans = (SGETransaction32_t *) (pSimple + 1); } if (pSimple == NULL) { /**/ printk (KERN_WARNING MYNAM "/%s: No buckets posted\n", /**/ __func__); mpt_free_msg_frame(mpt_dev, mf); goto out; } pSimple->FlagsLength |= cpu_to_le32(MPI_SGE_FLAGS_END_OF_LIST << MPI_SGE_FLAGS_SHIFT); pRecvReq->BucketCount = cpu_to_le32(i); /* printk(KERN_INFO MYNAM ": posting buckets\n "); * for (i = 0; i < j + 2; i ++) * printk (" %08x", le32_to_cpu(msg[i])); * printk ("\n"); */ mpt_put_msg_frame(LanCtx, mpt_dev, mf); priv->total_posted += i; buckets -= i; atomic_add(i, &priv->buckets_out); } out: dioprintk((KERN_INFO MYNAM "/%s: End_buckets = %u, priv->buckets_out = %u\n", __func__, buckets, atomic_read(&priv->buckets_out))); dioprintk((KERN_INFO MYNAM "/%s: Posted %u buckets and received %u back\n", __func__, priv->total_posted, priv->total_received)); clear_bit(0, &priv->post_buckets_active); } static void mpt_lan_post_receive_buckets_work(struct work_struct *work) { mpt_lan_post_receive_buckets(container_of(work, struct mpt_lan_priv, post_buckets_task.work)); } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static struct net_device * mpt_register_lan_device (MPT_ADAPTER *mpt_dev, int pnum) { struct net_device *dev; struct mpt_lan_priv *priv; u8 HWaddr[FC_ALEN], *a; dev = alloc_fcdev(sizeof(struct mpt_lan_priv)); if (!dev) return NULL; dev->mtu = MPT_LAN_MTU; priv = netdev_priv(dev); priv->dev = dev; priv->mpt_dev = mpt_dev; priv->pnum = pnum; INIT_DELAYED_WORK(&priv->post_buckets_task, mpt_lan_post_receive_buckets_work); priv->post_buckets_active = 0; dlprintk((KERN_INFO MYNAM "@%d: bucketlen = %d\n", __LINE__, dev->mtu + dev->hard_header_len + 4)); atomic_set(&priv->buckets_out, 0); priv->total_posted = 0; priv->total_received = 0; priv->max_buckets_out = max_buckets_out; if (mpt_dev->pfacts[0].MaxLanBuckets < max_buckets_out) priv->max_buckets_out = mpt_dev->pfacts[0].MaxLanBuckets; dlprintk((KERN_INFO MYNAM "@%d: MaxLanBuckets=%d, max_buckets_out/priv=%d/%d\n", __LINE__, mpt_dev->pfacts[0].MaxLanBuckets, max_buckets_out, priv->max_buckets_out)); priv->bucketthresh = priv->max_buckets_out * 2 / 3; spin_lock_init(&priv->txfidx_lock); spin_lock_init(&priv->rxfidx_lock); /* Grab pre-fetched LANPage1 stuff. :-) */ a = (u8 *) &mpt_dev->lan_cnfg_page1.HardwareAddressLow; HWaddr[0] = a[5]; HWaddr[1] = a[4]; HWaddr[2] = a[3]; HWaddr[3] = a[2]; HWaddr[4] = a[1]; HWaddr[5] = a[0]; dev->addr_len = FC_ALEN; memcpy(dev->dev_addr, HWaddr, FC_ALEN); memset(dev->broadcast, 0xff, FC_ALEN); /* The Tx queue is 127 deep on the 909. * Give ourselves some breathing room. */ priv->tx_max_out = (tx_max_out_p <= MPT_TX_MAX_OUT_LIM) ? tx_max_out_p : MPT_TX_MAX_OUT_LIM; dev->open = mpt_lan_open; dev->stop = mpt_lan_close; dev->get_stats = mpt_lan_get_stats; dev->set_multicast_list = NULL; dev->change_mtu = mpt_lan_change_mtu; dev->hard_start_xmit = mpt_lan_sdu_send; /* Not in 2.3.42. Need 2.3.45+ */ dev->tx_timeout = mpt_lan_tx_timeout; dev->watchdog_timeo = MPT_LAN_TX_TIMEOUT; dlprintk((KERN_INFO MYNAM ": Finished registering dev " "and setting initial values\n")); if (register_netdev(dev) != 0) { free_netdev(dev); dev = NULL; } return dev; } static int mptlan_probe(struct pci_dev *pdev, const struct pci_device_id *id) { MPT_ADAPTER *ioc = pci_get_drvdata(pdev); struct net_device *dev; int i; for (i = 0; i < ioc->facts.NumberOfPorts; i++) { printk(KERN_INFO MYNAM ": %s: PortNum=%x, " "ProtocolFlags=%02Xh (%c%c%c%c)\n", ioc->name, ioc->pfacts[i].PortNumber, ioc->pfacts[i].ProtocolFlags, MPT_PROTOCOL_FLAGS_c_c_c_c( ioc->pfacts[i].ProtocolFlags)); if (!(ioc->pfacts[i].ProtocolFlags & MPI_PORTFACTS_PROTOCOL_LAN)) { printk(KERN_INFO MYNAM ": %s: Hmmm... LAN protocol " "seems to be disabled on this adapter port!\n", ioc->name); continue; } dev = mpt_register_lan_device(ioc, i); if (!dev) { printk(KERN_ERR MYNAM ": %s: Unable to register " "port%d as a LAN device\n", ioc->name, ioc->pfacts[i].PortNumber); continue; } printk(KERN_INFO MYNAM ": %s: Fusion MPT LAN device " "registered as '%s'\n", ioc->name, dev->name); printk(KERN_INFO MYNAM ": %s/%s: " "LanAddr = %pM\n", IOC_AND_NETDEV_NAMES_s_s(dev), dev->dev_addr); ioc->netdev = dev; return 0; } return -ENODEV; } static void mptlan_remove(struct pci_dev *pdev) { MPT_ADAPTER *ioc = pci_get_drvdata(pdev); struct net_device *dev = ioc->netdev; if(dev != NULL) { unregister_netdev(dev); free_netdev(dev); } } static struct mpt_pci_driver mptlan_driver = { .probe = mptlan_probe, .remove = mptlan_remove, }; static int __init mpt_lan_init (void) { show_mptmod_ver(LANAME, LANVER); if ((LanCtx = mpt_register(lan_reply, MPTLAN_DRIVER)) <= 0) { printk (KERN_ERR MYNAM ": Failed to register with MPT base driver\n"); return -EBUSY; } dlprintk((KERN_INFO MYNAM ": assigned context of %d\n", LanCtx)); if (mpt_reset_register(LanCtx, mpt_lan_ioc_reset)) { printk(KERN_ERR MYNAM ": Eieee! unable to register a reset " "handler with mptbase! The world is at an end! " "Everything is fading to black! Goodbye.\n"); return -EBUSY; } dlprintk((KERN_INFO MYNAM ": Registered for IOC reset notifications\n")); mpt_device_driver_register(&mptlan_driver, MPTLAN_DRIVER); return 0; } static void __exit mpt_lan_exit(void) { mpt_device_driver_deregister(MPTLAN_DRIVER); mpt_reset_deregister(LanCtx); if (LanCtx) { mpt_deregister(LanCtx); LanCtx = MPT_MAX_PROTOCOL_DRIVERS; } } module_init(mpt_lan_init); module_exit(mpt_lan_exit); /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/ static unsigned short mpt_lan_type_trans(struct sk_buff *skb, struct net_device *dev) { struct mpt_lan_ohdr *fch = (struct mpt_lan_ohdr *)skb->data; struct fcllc *fcllc; skb_reset_mac_header(skb); skb_pull(skb, sizeof(struct mpt_lan_ohdr)); if (fch->dtype == htons(0xffff)) { u32 *p = (u32 *) fch; swab32s(p + 0); swab32s(p + 1); swab32s(p + 2); swab32s(p + 3); printk (KERN_WARNING MYNAM ": %s: WARNING - Broadcast swap F/W bug detected!\n", NETDEV_PTR_TO_IOC_NAME_s(dev)); printk (KERN_WARNING MYNAM ": Please update sender @ MAC_addr = %pM\n", fch->saddr); } if (*fch->daddr & 1) { if (!memcmp(fch->daddr, dev->broadcast, FC_ALEN)) { skb->pkt_type = PACKET_BROADCAST; } else { skb->pkt_type = PACKET_MULTICAST; } } else { if (memcmp(fch->daddr, dev->dev_addr, FC_ALEN)) { skb->pkt_type = PACKET_OTHERHOST; } else { skb->pkt_type = PACKET_HOST; } } fcllc = (struct fcllc *)skb->data; /* Strip the SNAP header from ARP packets since we don't * pass them through to the 802.2/SNAP layers. */ if (fcllc->dsap == EXTENDED_SAP && (fcllc->ethertype == htons(ETH_P_IP) || fcllc->ethertype == htons(ETH_P_ARP))) { skb_pull(skb, sizeof(struct fcllc)); return fcllc->ethertype; } return htons(ETH_P_802_2); } /*=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=*/
broonie/regulator-2.6
drivers/message/fusion/mptlan.c
C
gpl-2.0
44,185
/** * 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
/* * list.h: header for list.c * * Written By Michael Sandrof * * Copyright(c) 1990 * * See the COPYRIGHT file, or do a HELP IRCII COPYRIGHT * * @(#)$Id$ */ #ifndef LIST_H #define LIST_H #define REMOVE_FROM_LIST 1 #define USE_WILDCARDS 1 struct list { struct list *next; char *name; }; /* TODO: last arg should be void, not char */ typedef int (cmp_fn) (struct list *, const char *); /* list.c */ int list_strnicmp(struct list *item1, const char *str); void add_to_list_ext(struct list **list, struct list *add, cmp_fn * cmp_func); void add_to_list(struct list **list, struct list *add); struct list *find_in_list_ext(struct list **list, char *name, int wild, cmp_fn * cmp_func); struct list *find_in_list(struct list **list, char *name, int wild); struct list *remove_from_list_ext(struct list **list, const char *name, cmp_fn * cmp_func); struct list *remove_from_list(struct list **list, const char *name); struct list *list_lookup_ext(struct list **list, char *name, int wild, int delete, cmp_fn * cmp_func); struct list *list_lookup(struct list **list, char *name, int wild, int delete); #endif /* LIST_H */
laeos/xaric
list.h
C
gpl-2.0
1,143
/* * 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
/* * sysobj - https://github.com/bp0/verbose-spork * Copyright (C) 2018 Burt P. <pburt0@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. * */ #ifndef URI_HANDLER_H #define URI_HANDLER_H #include <glib.h> typedef gboolean (*uri_handler)(const gchar *uri); void uri_set_function(uri_handler f); gboolean uri_open(const gchar *uri); gboolean uri_open_default(const gchar *uri); /* uses xdg-open */ #endif
lpereira/hardinfo
deps/sysobj_early/gui/uri_handler.h
C
gpl-2.0
1,096
<?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
/* * linux/init/main.c * * Copyright (C) 1991, 1992 Linus Torvalds * * GK 2/5/95 - Changed to support mounting root fs via NFS * Added initrd & change_root: Werner Almesberger & Hans Lermen, Feb '96 * Moan early if gcc is old, avoiding bogus kernels - Paul Gortmaker, May '96 * Simplified starting of init: Michael A. Griffith <grif@acm.org> */ #include <linux/types.h> #include <linux/module.h> #include <linux/proc_fs.h> #include <linux/kernel.h> #include <linux/syscalls.h> #include <linux/stackprotector.h> #include <linux/string.h> #include <linux/ctype.h> #include <linux/delay.h> #include <linux/ioport.h> #include <linux/init.h> #include <linux/initrd.h> #include <linux/bootmem.h> #include <linux/acpi.h> #include <linux/tty.h> #include <linux/percpu.h> #include <linux/kmod.h> #include <linux/vmalloc.h> #include <linux/kernel_stat.h> #include <linux/start_kernel.h> #include <linux/security.h> #include <linux/smp.h> #include <linux/profile.h> #include <linux/rcupdate.h> #include <linux/moduleparam.h> #include <linux/kallsyms.h> #include <linux/writeback.h> #include <linux/cpu.h> #include <linux/cpuset.h> #include <linux/cgroup.h> #include <linux/efi.h> #include <linux/tick.h> #include <linux/interrupt.h> #include <linux/taskstats_kern.h> #include <linux/delayacct.h> #include <linux/unistd.h> #include <linux/rmap.h> #include <linux/mempolicy.h> #include <linux/key.h> #include <linux/buffer_head.h> #include <linux/page_cgroup.h> #include <linux/debug_locks.h> #include <linux/debugobjects.h> #include <linux/lockdep.h> #include <linux/kmemleak.h> #include <linux/pid_namespace.h> #include <linux/device.h> #include <linux/kthread.h> #include <linux/sched.h> #include <linux/signal.h> #include <linux/idr.h> #include <linux/kgdb.h> #include <linux/ftrace.h> #include <linux/async.h> #include <linux/kmemcheck.h> #include <linux/sfi.h> #include <linux/shmem_fs.h> #include <linux/slab.h> #include <linux/perf_event.h> #include <linux/file.h> #include <linux/ptrace.h> #include <linux/blkdev.h> #include <linux/elevator.h> #include <asm/io.h> #include <asm/bugs.h> #include <asm/setup.h> #include <asm/sections.h> #include <asm/cacheflush.h> #ifdef CONFIG_X86_LOCAL_APIC #include <asm/smp.h> #endif static int kernel_init(void *); extern void init_IRQ(void); extern void fork_init(unsigned long); extern void mca_init(void); extern void sbus_init(void); extern void radix_tree_init(void); #ifndef CONFIG_DEBUG_RODATA static inline void mark_rodata_ro(void) { } #endif #ifdef CONFIG_TC extern void tc_init(void); #endif /* * Debug helper: via this flag we know that we are in 'early bootup code' * where only the boot processor is running with IRQ disabled. This means * two things - IRQ must not be enabled before the flag is cleared and some * operations which are not allowed with IRQ disabled are allowed while the * flag is set. */ bool early_boot_irqs_disabled __read_mostly; enum system_states system_state __read_mostly; EXPORT_SYMBOL(system_state); /* * Boot command-line arguments */ #define MAX_INIT_ARGS CONFIG_INIT_ENV_ARG_LIMIT #define MAX_INIT_ENVS CONFIG_INIT_ENV_ARG_LIMIT extern void time_init(void); /* Default late time init is NULL. archs can override this later. */ void (*__initdata late_time_init)(void); extern void softirq_init(void); /* Untouched command line saved by arch-specific code. */ char __initdata boot_command_line[COMMAND_LINE_SIZE]; /* Untouched saved command line (eg. for /proc) */ char *saved_command_line; /* Command line for parameter parsing */ static char *static_command_line; static char *execute_command; static char *ramdisk_execute_command; /* * If set, this is an indication to the drivers that reset the underlying * device before going ahead with the initialization otherwise driver might * rely on the BIOS and skip the reset operation. * * This is useful if kernel is booting in an unreliable environment. * For ex. kdump situaiton where previous kernel has crashed, BIOS has been * skipped and devices will be in unknown state. */ unsigned int reset_devices; EXPORT_SYMBOL(reset_devices); static int __init set_reset_devices(char *str) { reset_devices = 1; return 1; } __setup("reset_devices", set_reset_devices); static const char * argv_init[MAX_INIT_ARGS+2] = { "init", NULL, }; const char * envp_init[MAX_INIT_ENVS+2] = { "HOME=/", "TERM=linux", NULL, }; static const char *panic_later, *panic_param; extern const struct obs_kernel_param __setup_start[], __setup_end[]; static int __init obsolete_checksetup(char *line) { const struct obs_kernel_param *p; int had_early_param = 0; p = __setup_start; do { int n = strlen(p->str); if (parameqn(line, p->str, n)) { if (p->early) { /* Already done in parse_early_param? * (Needs exact match on param part). * Keep iterating, as we can have early * params and __setups of same names 8( */ if (line[n] == '\0' || line[n] == '=') had_early_param = 1; } else if (!p->setup_func) { printk(KERN_WARNING "Parameter %s is obsolete," " ignored\n", p->str); return 1; } else if (p->setup_func(line + n)) return 1; } p++; } while (p < __setup_end); return had_early_param; } /* * This should be approx 2 Bo*oMips to start (note initial shift), and will * still work even if initially too large, it will just take slightly longer */ unsigned long loops_per_jiffy = (1<<12); EXPORT_SYMBOL(loops_per_jiffy); static int __init debug_kernel(char *str) { console_loglevel = 10; return 0; } static int __init quiet_kernel(char *str) { console_loglevel = 4; return 0; } early_param("debug", debug_kernel); early_param("quiet", quiet_kernel); static int __init loglevel(char *str) { int newlevel; /* * Only update loglevel value when a correct setting was passed, * to prevent blind crashes (when loglevel being set to 0) that * are quite hard to debug */ if (get_option(&str, &newlevel)) { console_loglevel = newlevel; return 0; } return -EINVAL; } early_param("loglevel", loglevel); /* Change NUL term back to "=", to make "param" the whole string. */ static int __init repair_env_string(char *param, char *val, const char *unused) { if (val) { /* param=val or param="val"? */ if (val == param+strlen(param)+1) val[-1] = '='; else if (val == param+strlen(param)+2) { val[-2] = '='; memmove(val-1, val, strlen(val)+1); val--; } else BUG(); } return 0; } /* * Unknown boot options get handed to init, unless they look like * unused parameters (modprobe will find them in /proc/cmdline). */ static int __init unknown_bootoption(char *param, char *val, const char *unused) { repair_env_string(param, val, unused); /* Handle obsolete-style parameters */ if (obsolete_checksetup(param)) return 0; /* Unused module parameter. */ if (strchr(param, '.') && (!val || strchr(param, '.') < val)) return 0; if (panic_later) return 0; if (val) { /* Environment option */ unsigned int i; for (i = 0; envp_init[i]; i++) { if (i == MAX_INIT_ENVS) { panic_later = "Too many boot env vars at `%s'"; panic_param = param; } if (!strncmp(param, envp_init[i], val - param)) break; } envp_init[i] = param; } else { /* Command line option */ unsigned int i; for (i = 0; argv_init[i]; i++) { if (i == MAX_INIT_ARGS) { panic_later = "Too many boot init vars at `%s'"; panic_param = param; } } argv_init[i] = param; } return 0; } static int __init init_setup(char *str) { unsigned int i; execute_command = str; /* * In case LILO is going to boot us with default command line, * it prepends "auto" before the whole cmdline which makes * the shell think it should execute a script with such name. * So we ignore all arguments entered _before_ init=... [MJ] */ for (i = 1; i < MAX_INIT_ARGS; i++) argv_init[i] = NULL; return 1; } __setup("init=", init_setup); static int __init rdinit_setup(char *str) { unsigned int i; ramdisk_execute_command = str; /* See "auto" comment in init_setup */ for (i = 1; i < MAX_INIT_ARGS; i++) argv_init[i] = NULL; return 1; } __setup("rdinit=", rdinit_setup); #ifndef CONFIG_SMP static const unsigned int setup_max_cpus = NR_CPUS; #ifdef CONFIG_X86_LOCAL_APIC static void __init smp_init(void) { APIC_init_uniprocessor(); } #else #define smp_init() do { } while (0) #endif static inline void setup_nr_cpu_ids(void) { } static inline void smp_prepare_cpus(unsigned int maxcpus) { } #endif /* * We need to store the untouched command line for future reference. * We also need to store the touched command line since the parameter * parsing is performed in place, and we should allow a component to * store reference of name/value for future reference. */ static void __init setup_command_line(char *command_line) { saved_command_line = alloc_bootmem(strlen (boot_command_line)+1); static_command_line = alloc_bootmem(strlen (command_line)+1); strcpy (saved_command_line, boot_command_line); strcpy (static_command_line, command_line); } /* * We need to finalize in a non-__init function or else race conditions * between the root thread and the init thread may cause start_kernel to * be reaped by free_initmem before the root thread has proceeded to * cpu_idle. * * gcc-3.4 accidentally inlines this function, so use noinline. */ static __initdata DECLARE_COMPLETION(kthreadd_done); static noinline void __init_refok rest_init(void) { int pid; rcu_scheduler_starting(); /* * We need to spawn init first so that it obtains pid 1, however * the init task will end up wanting to create kthreads, which, if * we schedule it before we create kthreadd, will OOPS. */ kernel_thread(kernel_init, NULL, CLONE_FS | CLONE_SIGHAND); numa_default_policy(); pid = kernel_thread(kthreadd, NULL, CLONE_FS | CLONE_FILES); rcu_read_lock(); kthreadd_task = find_task_by_pid_ns(pid, &init_pid_ns); rcu_read_unlock(); complete(&kthreadd_done); /* * The boot idle thread must execute schedule() * at least once to get things moving: */ init_idle_bootup_task(current); schedule_preempt_disabled(); /* Call into cpu_idle with preempt disabled */ cpu_idle(); } /* Check for early params. */ static int __init do_early_param(char *param, char *val, const char *unused) { const struct obs_kernel_param *p; for (p = __setup_start; p < __setup_end; p++) { if ((p->early && parameq(param, p->str)) || (strcmp(param, "console") == 0 && strcmp(p->str, "earlycon") == 0) ) { if (p->setup_func(val) != 0) printk(KERN_WARNING "Malformed early option '%s'\n", param); } } /* We accept everything at this stage. */ return 0; } void __init parse_early_options(char *cmdline) { parse_args("early options", cmdline, NULL, 0, 0, 0, do_early_param); } /* Arch code calls this early on, or if not, just before other parsing. */ void __init parse_early_param(void) { static __initdata int done = 0; static __initdata char tmp_cmdline[COMMAND_LINE_SIZE]; if (done) return; /* All fall through to do_early_param. */ strlcpy(tmp_cmdline, boot_command_line, COMMAND_LINE_SIZE); parse_early_options(tmp_cmdline); done = 1; } /* * Activate the first processor. */ static void __init boot_cpu_init(void) { int cpu = smp_processor_id(); /* Mark the boot cpu "present", "online" etc for SMP and UP case */ set_cpu_online(cpu, true); set_cpu_active(cpu, true); set_cpu_present(cpu, true); set_cpu_possible(cpu, true); } void __init __weak smp_setup_processor_id(void) { } # if THREAD_SIZE >= PAGE_SIZE void __init __weak thread_info_cache_init(void) { } #endif /* * Set up kernel memory allocators */ static void __init mm_init(void) { /* * page_cgroup requires contiguous pages, * bigger than MAX_ORDER unless SPARSEMEM. */ page_cgroup_init_flatmem(); mem_init(); kmem_cache_init(); percpu_init_late(); pgtable_cache_init(); vmalloc_init(); } asmlinkage void __init start_kernel(void) { char * command_line; extern const struct kernel_param __start___param[], __stop___param[]; /* * Need to run as early as possible, to initialize the * lockdep hash: */ lockdep_init(); smp_setup_processor_id(); debug_objects_early_init(); /* * Set up the the initial canary ASAP: */ boot_init_stack_canary(); cgroup_init_early(); local_irq_disable(); early_boot_irqs_disabled = true; /* * Interrupts are still disabled. Do necessary setups, then * enable them */ tick_init(); boot_cpu_init(); page_address_init(); printk(KERN_NOTICE "%s", linux_banner); setup_arch(&command_line); mm_init_owner(&init_mm, &init_task); mm_init_cpumask(&init_mm); setup_command_line(command_line); setup_nr_cpu_ids(); setup_per_cpu_areas(); smp_prepare_boot_cpu(); /* arch-specific boot-cpu hooks */ build_all_zonelists(NULL, NULL); page_alloc_init(); printk(KERN_NOTICE "Kernel command line: %s\n", boot_command_line); parse_early_param(); parse_args("Booting kernel", static_command_line, __start___param, __stop___param - __start___param, -1, -1, &unknown_bootoption); jump_label_init(); /* * These use large bootmem allocations and must precede * kmem_cache_init() */ setup_log_buf(0); pidhash_init(); vfs_caches_init_early(); sort_main_extable(); trap_init(); mm_init(); /* * Set up the scheduler prior starting any interrupts (such as the * timer interrupt). Full topology setup happens at smp_init() * time - but meanwhile we still have a functioning scheduler. */ sched_init(); /* * Disable preemption - early bootup scheduling is extremely * fragile until we cpu_idle() for the first time. */ preempt_disable(); if (!irqs_disabled()) { printk(KERN_WARNING "start_kernel(): bug: interrupts were " "enabled *very* early, fixing it\n"); local_irq_disable(); } idr_init_cache(); perf_event_init(); rcu_init(); radix_tree_init(); /* init some links before init_ISA_irqs() */ early_irq_init(); init_IRQ(); init_timers(); hrtimers_init(); softirq_init(); timekeeping_init(); time_init(); profile_init(); call_function_init(); if (!irqs_disabled()) printk(KERN_CRIT "start_kernel(): bug: interrupts were " "enabled early\n"); early_boot_irqs_disabled = false; local_irq_enable(); kmem_cache_init_late(); /* * HACK ALERT! This is early. We're enabling the console before * we've done PCI setups etc, and console_init() must be aware of * this. But we do want output early, in case something goes wrong. */ console_init(); if (panic_later) panic(panic_later, panic_param); lockdep_info(); /* * Need to run this when irqs are enabled, because it wants * to self-test [hard/soft]-irqs on/off lock inversion bugs * too: */ locking_selftest(); #ifdef CONFIG_BLK_DEV_INITRD if (initrd_start && !initrd_below_start_ok && page_to_pfn(virt_to_page((void *)initrd_start)) < min_low_pfn) { printk(KERN_CRIT "initrd overwritten (0x%08lx < 0x%08lx) - " "disabling it.\n", page_to_pfn(virt_to_page((void *)initrd_start)), min_low_pfn); initrd_start = 0; } #endif page_cgroup_init(); debug_objects_mem_init(); kmemleak_init(); setup_per_cpu_pageset(); numa_policy_init(); if (late_time_init) late_time_init(); sched_clock_init(); calibrate_delay(); pidmap_init(); anon_vma_init(); #ifdef CONFIG_X86 if (efi_enabled) efi_enter_virtual_mode(); #endif thread_info_cache_init(); cred_init(); fork_init(totalram_pages); proc_caches_init(); buffer_init(); key_init(); security_init(); dbg_late_init(); vfs_caches_init(totalram_pages); signals_init(); /* rootfs populating might need page-writeback */ page_writeback_init(); #ifdef CONFIG_PROC_FS proc_root_init(); #endif cgroup_init(); cpuset_init(); taskstats_init_early(); delayacct_init(); check_bugs(); acpi_early_init(); /* before LAPIC and SMP init */ sfi_init_late(); if (efi_enabled) { efi_late_init(); efi_free_boot_services(); } ftrace_init(); /* Do the rest non-__init'ed, we're now alive */ rest_init(); } /* Call all constructor functions linked into the kernel. */ static void __init do_ctors(void) { #ifdef CONFIG_CONSTRUCTORS ctor_fn_t *fn = (ctor_fn_t *) __ctors_start; for (; fn < (ctor_fn_t *) __ctors_end; fn++) (*fn)(); #endif } bool initcall_debug; core_param(initcall_debug, initcall_debug, bool, 0644); static char msgbuf[64]; static int __init_or_module do_one_initcall_debug(initcall_t fn) { ktime_t calltime, delta, rettime; unsigned long long duration; int ret; printk(KERN_DEBUG "calling %pF @ %i\n", fn, task_pid_nr(current)); calltime = ktime_get(); ret = fn(); rettime = ktime_get(); delta = ktime_sub(rettime, calltime); duration = (unsigned long long) ktime_to_ns(delta) >> 10; printk(KERN_DEBUG "initcall %pF returned %d after %lld usecs\n", fn, ret, duration); return ret; } int __init_or_module do_one_initcall(initcall_t fn) { int count = preempt_count(); int ret; if (initcall_debug) ret = do_one_initcall_debug(fn); else ret = fn(); msgbuf[0] = 0; if (ret && ret != -ENODEV && initcall_debug) sprintf(msgbuf, "error code %d ", ret); if (preempt_count() != count) { strlcat(msgbuf, "preemption imbalance ", sizeof(msgbuf)); preempt_count() = count; } if (irqs_disabled()) { strlcat(msgbuf, "disabled interrupts ", sizeof(msgbuf)); local_irq_enable(); } if (msgbuf[0]) { printk("initcall %pF returned with %s\n", fn, msgbuf); } return ret; } extern initcall_t __initcall_start[]; extern initcall_t __initcall0_start[]; extern initcall_t __initcall1_start[]; extern initcall_t __initcall2_start[]; extern initcall_t __initcall3_start[]; extern initcall_t __initcall4_start[]; extern initcall_t __initcall5_start[]; extern initcall_t __initcall6_start[]; extern initcall_t __initcall7_start[]; extern initcall_t __initcall_end[]; static initcall_t *initcall_levels[] __initdata = { __initcall0_start, __initcall1_start, __initcall2_start, __initcall3_start, __initcall4_start, __initcall5_start, __initcall6_start, __initcall7_start, __initcall_end, }; /* Keep these in sync with initcalls in include/linux/init.h */ static char *initcall_level_names[] __initdata = { "early", "core", "postcore", "arch", "subsys", "fs", "device", "late", }; static void __init do_initcall_level(int level) { extern const struct kernel_param __start___param[], __stop___param[]; initcall_t *fn; strcpy(static_command_line, saved_command_line); parse_args(initcall_level_names[level], static_command_line, __start___param, __stop___param - __start___param, level, level, &repair_env_string); for (fn = initcall_levels[level]; fn < initcall_levels[level+1]; fn++) do_one_initcall(*fn); } static void __init do_initcalls(void) { int level; for (level = 0; level < ARRAY_SIZE(initcall_levels) - 1; level++) do_initcall_level(level); } /* * Ok, the machine is now initialized. None of the devices * have been touched yet, but the CPU subsystem is up and * running, and memory and process management works. * * Now we can finally start doing some real work.. */ static void __init do_basic_setup(void) { cpuset_init_smp(); usermodehelper_init(); shmem_init(); driver_init(); init_irq_proc(); do_ctors(); usermodehelper_enable(); do_initcalls(); } static void __init do_pre_smp_initcalls(void) { initcall_t *fn; for (fn = __initcall_start; fn < __initcall0_start; fn++) do_one_initcall(*fn); } /* * This function requests modules which should be loaded by default and is * called twice right after initrd is mounted and right before init is * exec'd. If such modules are on either initrd or rootfs, they will be * loaded before control is passed to userland. */ void __init load_default_modules(void) { load_default_elevator_module(); } static int run_init_process(const char *init_filename) { argv_init[0] = init_filename; return do_execve(init_filename, (const char __user *const __user *)argv_init, (const char __user *const __user *)envp_init); } static noinline void __init kernel_init_freeable(void); static int __ref kernel_init(void *unused) { kernel_init_freeable(); /* need to finish all async __init code before freeing the memory */ async_synchronize_full(); free_initmem(); mark_rodata_ro(); system_state = SYSTEM_RUNNING; numa_default_policy(); flush_delayed_fput(); if (ramdisk_execute_command) { if (!run_init_process(ramdisk_execute_command)) return 0; printk(KERN_WARNING "Failed to execute %s\n", ramdisk_execute_command); } /* * We try each of these until one succeeds. * * The Bourne shell can be used instead of init if we are * trying to recover a really broken machine. */ if (execute_command) { if (!run_init_process(execute_command)) return 0; printk(KERN_WARNING "Failed to execute %s. Attempting " "defaults...\n", execute_command); } if (!run_init_process("/sbin/init") || !run_init_process("/etc/init") || !run_init_process("/bin/init") || !run_init_process("/bin/sh")) return 0; panic("No init found. Try passing init= option to kernel. " "See Linux Documentation/init.txt for guidance."); } static noinline void __init kernel_init_freeable(void) { /* * Wait until kthreadd is all set-up. */ wait_for_completion(&kthreadd_done); /* Now the scheduler is fully set up and can do blocking allocations */ gfp_allowed_mask = __GFP_BITS_MASK; /* * init can allocate pages on any node */ set_mems_allowed(node_states[N_MEMORY]); /* * init can run on any cpu. */ set_cpus_allowed_ptr(current, cpu_all_mask); cad_pid = task_pid(current); smp_prepare_cpus(setup_max_cpus); do_pre_smp_initcalls(); lockup_detector_init(); smp_init(); sched_init_smp(); do_basic_setup(); /* Open the /dev/console on the rootfs, this should never fail */ if (sys_open((const char __user *) "/dev/console", O_RDWR, 0) < 0) printk(KERN_WARNING "Warning: unable to open an initial console.\n"); (void) sys_dup(0); (void) sys_dup(0); /* * check if there is an early userspace init. If yes, let it do all * the work */ if (!ramdisk_execute_command) ramdisk_execute_command = "/init"; if (sys_access((const char __user *) ramdisk_execute_command, 0) != 0) { ramdisk_execute_command = NULL; prepare_namespace(); } /* * Ok, we have completed the initial bootup, and * we're essentially up and running. Get rid of the * initmem segments and start the user-mode stuff.. */ /* rootfs is available now, try loading default modules */ load_default_modules(); }
Oleh-Kravchenko/asusp535
init/main.c
C
gpl-2.0
22,593
<?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
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <meta http-equiv="content-type" content="text/html; charset=utf-8" /> <meta name="generator" content="JsDoc Toolkit" /> <title>JsDoc Reference - gui.SessionView</title> <style type="text/css"> /* default.css */ body { font: 12px "Lucida Grande", Tahoma, Arial, Helvetica, sans-serif; width: 800px; } .header { clear: both; background-color: #ccc; padding: 8px; } h1 { font-size: 150%; font-weight: bold; padding: 0; margin: 1em 0 0 .3em; } hr { border: none 0; border-top: 1px solid #7F8FB1; height: 1px; } pre.code { display: block; padding: 8px; border: 1px dashed #ccc; } #index { margin-top: 24px; float: left; width: 160px; position: absolute; left: 8px; background-color: #F3F3F3; padding: 8px; } #content { margin-left: 190px; width: 600px; } .classList { list-style-type: none; padding: 0; margin: 0 0 0 8px; font-family: arial, sans-serif; font-size: 1em; overflow: auto; } .classList li { padding: 0; margin: 0 0 8px 0; } .summaryTable { width: 100%; } h1.classTitle { font-size:170%; line-height:130%; } h2 { font-size: 110%; } caption, div.sectionTitle { background-color: #7F8FB1; color: #fff; font-size:130%; text-align: left; padding: 2px 6px 2px 6px; border: 1px #7F8FB1 solid; } div.sectionTitle { margin-bottom: 8px; } .summaryTable thead { display: none; } .summaryTable td { vertical-align: top; padding: 4px; border-bottom: 1px #7F8FB1 solid; border-right: 1px #7F8FB1 solid; } /*col#summaryAttributes {}*/ .summaryTable td.attributes { border-left: 1px #7F8FB1 solid; width: 140px; text-align: right; } td.attributes, .fixedFont { line-height: 15px; color: #002EBE; font-family: "Courier New",Courier,monospace; font-size: 13px; } .summaryTable td.nameDescription { text-align: left; font-size: 13px; line-height: 15px; } .summaryTable td.nameDescription, .description { line-height: 15px; padding: 4px; padding-left: 4px; } .summaryTable { margin-bottom: 8px; } ul.inheritsList { list-style: square; margin-left: 20px; padding-left: 0; } .detailList { margin-left: 20px; line-height: 15px; } .detailList dt { margin-left: 20px; } .detailList .heading { font-weight: bold; padding-bottom: 6px; margin-left: 0; } .light, td.attributes, .light a:link, .light a:visited { color: #777; font-style: italic; } .fineprint { text-align: right; font-size: 10px; } </style> </head> <body> <!-- ============================== header ================================= --> <!-- begin static/header.html --> <div id="header"> </div> <!-- end static/header.html --> <!-- ============================== classes index ============================ --> <div id="index"> <!-- begin publish.classesIndex --> <div align="center"><a href="../index.html">Class Index</a> | <a href="../files.html">File Index</a></div> <hr /> <h2>Classes</h2> <ul class="classList"> <li><i><a href="../symbols/_global_.html">_global_</a></i></li> <li><a href="../symbols/BrowserRuntime.html">BrowserRuntime</a></li> <li><a href="../symbols/core.html">core</a></li> <li><a href="../symbols/core.Base64.html">core.Base64</a></li> <li><a href="../symbols/core.ByteArray.html">core.ByteArray</a></li> <li><a href="../symbols/core.ByteArrayWriter.html">core.ByteArrayWriter</a></li> <li><a href="../symbols/core.CSSUnits.html">core.CSSUnits</a></li> <li><a href="../symbols/core.Cursor.html">core.Cursor</a></li> <li><a href="../symbols/core.DomUtils.html">core.DomUtils</a></li> <li><a href="../symbols/core.EventNotifier.html">core.EventNotifier</a></li> <li><a href="../symbols/core.LazyProperty.html">core.LazyProperty</a></li> <li><a href="../symbols/core.LoopWatchDog.html">core.LoopWatchDog</a></li> <li><a href="../symbols/core.PositionFilterChain.html">core.PositionFilterChain</a></li> <li><a href="../symbols/core.PositionIterator.html">core.PositionIterator</a></li> <li><a href="../symbols/core.PositionIterator-EmptyTextNodeFilter.html">core.PositionIterator-EmptyTextNodeFilter</a></li> <li><a href="../symbols/core.PositionIterator-FilteredEmptyTextNodeFilter.html">core.PositionIterator-FilteredEmptyTextNodeFilter</a></li> <li><a href="../symbols/core.ScheduledTask.html">core.ScheduledTask</a></li> <li><a href="../symbols/core.StepIterator.html">core.StepIterator</a></li> <li><a href="../symbols/core.UnitTester.html">core.UnitTester</a></li> <li><a href="../symbols/core.UnitTestLogger.html">core.UnitTestLogger</a></li> <li><a href="../symbols/core.UnitTestRunner.html">core.UnitTestRunner</a></li> <li><a href="../symbols/core.Utils.html">core.Utils</a></li> <li><a href="../symbols/core.Zip.html">core.Zip</a></li> <li><a href="../symbols/core.Zip-ZipEntry.html">core.Zip-ZipEntry</a></li> <li><a href="../symbols/createXPathSingleton-AllChildElementIterator.html">createXPathSingleton-AllChildElementIterator</a></li> <li><a href="../symbols/createXPathSingleton-AttributeIterator.html">createXPathSingleton-AttributeIterator</a></li> <li><a href="../symbols/createXPathSingleton-ConditionIterator.html">createXPathSingleton-ConditionIterator</a></li> <li><a href="../symbols/createXPathSingleton-XPathNodeIterator.html">createXPathSingleton-XPathNodeIterator</a></li> <li><a href="../symbols/gui.html">gui</a></li> <li><a href="../symbols/gui.AnnotatableCanvas.html">gui.AnnotatableCanvas</a></li> <li><a href="../symbols/gui.AnnotationController.html">gui.AnnotationController</a></li> <li><a href="../symbols/gui.AnnotationViewManager.html">gui.AnnotationViewManager</a></li> <li><a href="../symbols/gui.Avatar.html">gui.Avatar</a></li> <li><a href="../symbols/gui.Caret.html">gui.Caret</a></li> <li><a href="../symbols/gui.CaretManager.html">gui.CaretManager</a></li> <li><a href="../symbols/gui.Clipboard.html">gui.Clipboard</a></li> <li><a href="../symbols/gui.DirectFormattingController.html">gui.DirectFormattingController</a></li> <li><a href="../symbols/gui.EditInfoHandle.html">gui.EditInfoHandle</a></li> <li><a href="../symbols/gui.EditInfoMarker.html">gui.EditInfoMarker</a></li> <li><a href="../symbols/gui.EventManager.html">gui.EventManager</a></li> <li><a href="../symbols/gui.EventManager-CompoundEvent.html">gui.EventManager-CompoundEvent</a></li> <li><a href="../symbols/gui.EventManager-ElementScrollState.html">gui.EventManager-ElementScrollState</a></li> <li><a href="../symbols/gui.EventManager-EventDelegate.html">gui.EventManager-EventDelegate</a></li> <li><a href="../symbols/gui.EventManager-WindowScrollState.html">gui.EventManager-WindowScrollState</a></li> <li><a href="../symbols/gui.GuiStepUtils.html">gui.GuiStepUtils</a></li> <li><a href="../symbols/gui.HyperlinkClickHandler.html">gui.HyperlinkClickHandler</a></li> <li><a href="../symbols/gui.HyperlinkController.html">gui.HyperlinkController</a></li> <li><a href="../symbols/gui.HyperlinkTooltipView.html">gui.HyperlinkTooltipView</a></li> <li><a href="../symbols/gui.ImageController.html">gui.ImageController</a></li> <li><a href="../symbols/gui.ImageSelector.html">gui.ImageSelector</a></li> <li><a href="../symbols/gui.InputMethodEditor.html">gui.InputMethodEditor</a></li> <li><a href="../symbols/gui.IOSSafariSupport.html">gui.IOSSafariSupport</a></li> <li><a href="../symbols/gui.KeyboardHandler.html">gui.KeyboardHandler</a></li> <li><a href="../symbols/gui.MetadataController.html">gui.MetadataController</a></li> <li><a href="../symbols/gui.MimeDataExporter.html">gui.MimeDataExporter</a></li> <li><a href="../symbols/gui.PasteController.html">gui.PasteController</a></li> <li><a href="../symbols/gui.SelectionController.html">gui.SelectionController</a></li> <li><a href="../symbols/gui.SelectionMover.html">gui.SelectionMover</a></li> <li><a href="../symbols/gui.SelectionMover.createPositionIterator-CursorFilter.html">gui.SelectionMover.createPositionIterator-CursorFilter</a></li> <li><a href="../symbols/gui.SelectionViewManager.html">gui.SelectionViewManager</a></li> <li><a href="../symbols/gui.SessionConstraints.html">gui.SessionConstraints</a></li> <li><a href="../symbols/gui.SessionContext.html">gui.SessionContext</a></li> <li><a href="../symbols/gui.SessionController.html">gui.SessionController</a></li> <li><a href="../symbols/gui.SessionControllerOptions.html">gui.SessionControllerOptions</a></li> <li><a href="../symbols/gui.SessionView.html">gui.SessionView</a></li> <li><a href="../symbols/gui.SessionViewOptions.html">gui.SessionViewOptions</a></li> <li><a href="../symbols/gui.ShadowCursor.html">gui.ShadowCursor</a></li> <li><a href="../symbols/gui.StyleSummary.html">gui.StyleSummary</a></li> <li><a href="../symbols/gui.SvgSelectionView.html">gui.SvgSelectionView</a></li> <li><a href="../symbols/gui.TextController.html">gui.TextController</a></li> <li><a href="../symbols/gui.TrivialUndoManager.html">gui.TrivialUndoManager</a></li> <li><a href="../symbols/gui.UndoStateRules.html">gui.UndoStateRules</a></li> <li><a href="../symbols/gui.UndoStateRules-ReverseIterator.html">gui.UndoStateRules-ReverseIterator</a></li> <li><a href="../symbols/gui.ZoomHelper.html">gui.ZoomHelper</a></li> <li><a href="../symbols/NodeJSRuntime.html">NodeJSRuntime</a></li> <li><a href="../symbols/odf.html">odf</a></li> <li><a href="../symbols/odf.AnnotationElement.html">odf.AnnotationElement</a></li> <li><a href="../symbols/odf.CollapsingRules.html">odf.CollapsingRules</a></li> <li><a href="../symbols/odf.ComputedGraphicProperties.html">odf.ComputedGraphicProperties</a></li> <li><a href="../symbols/odf.ComputedGraphicStyle.html">odf.ComputedGraphicStyle</a></li> <li><a href="../symbols/odf.ComputedParagraphProperties.html">odf.ComputedParagraphProperties</a></li> <li><a href="../symbols/odf.ComputedParagraphStyle.html">odf.ComputedParagraphStyle</a></li> <li><a href="../symbols/odf.ComputedTextProperties.html">odf.ComputedTextProperties</a></li> <li><a href="../symbols/odf.ComputedTextStyle.html">odf.ComputedTextStyle</a></li> <li><a href="../symbols/odf.FontLoader.html">odf.FontLoader</a></li> <li><a href="../symbols/odf.Formatting.html">odf.Formatting</a></li> <li><a href="../symbols/odf.GraphicProperties.html">odf.GraphicProperties</a></li> <li><a href="../symbols/odf.LazyStyleProperties.html">odf.LazyStyleProperties</a></li> <li><a href="../symbols/odf.ListStyleToCss.html">odf.ListStyleToCss</a></li> <li><a href="../symbols/odf.MasterPage.html">odf.MasterPage</a></li> <li><a href="../symbols/odf.ObjectNameGenerator.html">odf.ObjectNameGenerator</a></li> <li><a href="../symbols/odf.ObjectNameGenerator-NameGenerator.html">odf.ObjectNameGenerator-NameGenerator</a></li> <li><a href="../symbols/odf.OdfCanvas.html">odf.OdfCanvas</a></li> <li><a href="../symbols/odf.OdfContainer.html">odf.OdfContainer</a></li> <li><a href="../symbols/odf.ODFDocumentElement.html">odf.ODFDocumentElement</a></li> <li><a href="../symbols/odf.ODFElement.html">odf.ODFElement</a></li> <li><a href="../symbols/odf.OdfNodeFilter.html">odf.OdfNodeFilter</a></li> <li><a href="../symbols/odf.OdfPart.html">odf.OdfPart</a></li> <li><a href="../symbols/odf.OdfUtils.html">odf.OdfUtils</a></li> <li><a href="../symbols/odf.PageLayout.html">odf.PageLayout</a></li> <li><a href="../symbols/odf.PageLayoutProperties.html">odf.PageLayoutProperties</a></li> <li><a href="../symbols/odf.ParagraphProperties.html">odf.ParagraphProperties</a></li> <li><a href="../symbols/odf.StepUtils.html">odf.StepUtils</a></li> <li><a href="../symbols/odf.Style2CSS.html">odf.Style2CSS</a></li> <li><a href="../symbols/odf.StyleCache.html">odf.StyleCache</a></li> <li><a href="../symbols/odf.StyleInfo.html">odf.StyleInfo</a></li> <li><a href="../symbols/odf.StyleInfo%23UsedStyleList.html">odf.StyleInfo#UsedStyleList</a></li> <li><a href="../symbols/odf.StyleInfo-StyleDefinition.html">odf.StyleInfo-StyleDefinition</a></li> <li><a href="../symbols/odf.StyleParseUtils.html">odf.StyleParseUtils</a></li> <li><a href="../symbols/odf.StylePile.html">odf.StylePile</a></li> <li><a href="../symbols/odf.StylePileEntry.html">odf.StylePileEntry</a></li> <li><a href="../symbols/odf.StyleTree.html">odf.StyleTree</a></li> <li><a href="../symbols/odf.StyleTreeNode.html">odf.StyleTreeNode</a></li> <li><a href="../symbols/odf.TextProperties.html">odf.TextProperties</a></li> <li><a href="../symbols/odf.TextSerializer.html">odf.TextSerializer</a></li> <li><a href="../symbols/odf.TextStyleApplicator.html">odf.TextStyleApplicator</a></li> <li><a href="../symbols/odf.TextStyleApplicator-StyleLookup.html">odf.TextStyleApplicator-StyleLookup</a></li> <li><a href="../symbols/odf.TextStyleApplicator-StyleManager.html">odf.TextStyleApplicator-StyleManager</a></li> <li><a href="../symbols/odf.WordBoundaryFilter.html">odf.WordBoundaryFilter</a></li> <li><a href="../symbols/ops.html">ops</a></li> <li><a href="../symbols/ops.EditInfo.html">ops.EditInfo</a></li> <li><a href="../symbols/ops.Member.html">ops.Member</a></li> <li><a href="../symbols/ops.MemberProperties.html">ops.MemberProperties</a></li> <li><a href="../symbols/ops.OdtCursor.html">ops.OdtCursor</a></li> <li><a href="../symbols/ops.OdtDocument.html">ops.OdtDocument</a></li> <li><a href="../symbols/ops.OdtDocument-RootFilter.html">ops.OdtDocument-RootFilter</a></li> <li><a href="../symbols/ops.OdtStepsTranslator.html">ops.OdtStepsTranslator</a></li> <li><a href="../symbols/ops.OpAddAnnotation.html">ops.OpAddAnnotation</a></li> <li><a href="../symbols/ops.OpAddCursor.html">ops.OpAddCursor</a></li> <li><a href="../symbols/ops.OpAddMember.html">ops.OpAddMember</a></li> <li><a href="../symbols/ops.OpAddStyle.html">ops.OpAddStyle</a></li> <li><a href="../symbols/ops.OpApplyDirectStyling.html">ops.OpApplyDirectStyling</a></li> <li><a href="../symbols/ops.OpApplyHyperlink.html">ops.OpApplyHyperlink</a></li> <li><a href="../symbols/ops.OperationFactory.html">ops.OperationFactory</a></li> <li><a href="../symbols/ops.OperationTransformer.html">ops.OperationTransformer</a></li> <li><a href="../symbols/ops.OperationTransformMatrix.html">ops.OperationTransformMatrix</a></li> <li><a href="../symbols/ops.OpInsertImage.html">ops.OpInsertImage</a></li> <li><a href="../symbols/ops.OpInsertTable.html">ops.OpInsertTable</a></li> <li><a href="../symbols/ops.OpInsertText.html">ops.OpInsertText</a></li> <li><a href="../symbols/ops.OpMergeParagraph.html">ops.OpMergeParagraph</a></li> <li><a href="../symbols/ops.OpMoveCursor.html">ops.OpMoveCursor</a></li> <li><a href="../symbols/ops.OpRemoveAnnotation.html">ops.OpRemoveAnnotation</a></li> <li><a href="../symbols/ops.OpRemoveBlob.html">ops.OpRemoveBlob</a></li> <li><a href="../symbols/ops.OpRemoveCursor.html">ops.OpRemoveCursor</a></li> <li><a href="../symbols/ops.OpRemoveHyperlink.html">ops.OpRemoveHyperlink</a></li> <li><a href="../symbols/ops.OpRemoveMember.html">ops.OpRemoveMember</a></li> <li><a href="../symbols/ops.OpRemoveStyle.html">ops.OpRemoveStyle</a></li> <li><a href="../symbols/ops.OpRemoveText.html">ops.OpRemoveText</a></li> <li><a href="../symbols/ops.OpSetBlob.html">ops.OpSetBlob</a></li> <li><a href="../symbols/ops.OpSetParagraphStyle.html">ops.OpSetParagraphStyle</a></li> <li><a href="../symbols/ops.OpSplitParagraph.html">ops.OpSplitParagraph</a></li> <li><a href="../symbols/ops.OpUpdateMember.html">ops.OpUpdateMember</a></li> <li><a href="../symbols/ops.OpUpdateMetadata.html">ops.OpUpdateMetadata</a></li> <li><a href="../symbols/ops.OpUpdateParagraphStyle.html">ops.OpUpdateParagraphStyle</a></li> <li><a href="../symbols/ops.Session.html">ops.Session</a></li> <li><a href="../symbols/ops.StepsCache.html">ops.StepsCache</a></li> <li><a href="../symbols/ops.StepsCache-NodeBookmark.html">ops.StepsCache-NodeBookmark</a></li> <li><a href="../symbols/ops.StepsCache-RootBookmark.html">ops.StepsCache-RootBookmark</a></li> <li><a href="../symbols/ops.TextPositionFilter.html">ops.TextPositionFilter</a></li> <li><a href="../symbols/ops.TrivialOperationRouter.html">ops.TrivialOperationRouter</a></li> <li><a href="../symbols/RhinoRuntime.html">RhinoRuntime</a></li> <li><a href="../symbols/Runtime.html">Runtime</a></li> <li><a href="../symbols/webodf.html">webodf</a></li> <li><a href="../symbols/xmldom.html">xmldom</a></li> <li><a href="../symbols/xmldom.LSSerializer.html">xmldom.LSSerializer</a></li> <li><a href="../symbols/xmldom.LSSerializer-Namespaces.html">xmldom.LSSerializer-Namespaces</a></li> <li><a href="../symbols/xmldom.XPathIterator.html">xmldom.XPathIterator</a></li> </ul> <hr /> <!-- end publish.classesIndex --> </div> <div id="content"> <!-- ============================== class title ============================ --> <h1 class="classTitle"> Class gui.SessionView </h1> <!-- ============================== class summary ========================== --> <p class="description"> <br /><i>Defined in: </i> <a href="../symbols/src/lib_gui_SessionView.js.html">SessionView.js</a>. </p> <!-- ============================== constructor summary ==================== --> <table class="summaryTable" cellspacing="0" summary="A summary of the constructor documented in the class gui.SessionView."> <caption>Class Summary</caption> <thead> <tr> <th scope="col">Constructor Attributes</th> <th scope="col">Constructor Name and Description</th> </tr> </thead> <tbody> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription" > <div class="fixedFont"> <b><a href="../symbols/gui.SessionView.html#constructor">gui.SessionView</a></b>(viewOptions, localMemberId, session, sessionConstraints, caretManager, selectionViewManager) </div> <div class="description">TODO: We really don't want to let SessionView be aware of localMemberId, so eventually we'll need to refactor this.</div> </td> </tr> </tbody> </table> <!-- ============================== properties summary ===================== --> <!-- ============================== methods summary ======================== --> <table class="summaryTable" cellspacing="0" summary="A summary of the methods documented in the class gui.SessionView."> <caption>Method Summary</caption> <thead> <tr> <th scope="col">Method Attributes</th> <th scope="col">Method Name and Description</th> </tr> </thead> <tbody> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-createAvatarInfoNodeMatch">createAvatarInfoNodeMatch</a></b>(nodeName, memberId, pseudoClass) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#destroy">destroy</a></b>(callback,) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-destroy">destroy</a></b>(callback) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-getAvatarInfoStyle">getAvatarInfoStyle</a></b>(nodeName, memberId, pseudoClass) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#getCaret">getCaret</a></b>(memberid) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#getSession">getSession</a></b>() </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#hideCaretAvatars">hideCaretAvatars</a></b>() </div> <div class="description">Hide member avatars above the cursor</div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#hideEditInfoMarkers">hideEditInfoMarkers</a></b>() </div> <div class="description">Hide edit information markers displayed near edited paragraphs</div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-highlightEdit">highlightEdit</a></b>(element, memberId, timestamp) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-newStyleSheet">newStyleSheet</a></b>() </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-onCursorAdded">onCursorAdded</a></b>(cursor) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-onCursorMoved">onCursorMoved</a></b>(cursor) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-onCursorRemoved">onCursorRemoved</a></b>(memberid) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-onParagraphChanged">onParagraphChanged</a></b>(info) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-refreshHighlights">refreshHighlights</a></b>() </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-renderMemberData">renderMemberData</a></b>(member) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-setAvatarInfoStyle">setAvatarInfoStyle</a></b>(memberId, name, color) </div> <div class="description"></div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-setCaretAvatarVisibility">setCaretAvatarVisibility</a></b>(visible) </div> <div class="description">Updates the visibility on all existing avatars</div> </td> </tr> <tr> <td class="attributes">&lt;inner&gt; &nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#-setEditInfoMarkerVisibility">setEditInfoMarkerVisibility</a></b>(visible) </div> <div class="description">Updates the visibility on all existing editInfo entries</div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#showCaretAvatars">showCaretAvatars</a></b>() </div> <div class="description">Show member avatars above the cursor</div> </td> </tr> <tr> <td class="attributes">&nbsp;</td> <td class="nameDescription"> <div class="fixedFont"><b><a href="../symbols/gui.SessionView.html#showEditInfoMarkers">showEditInfoMarkers</a></b>() </div> <div class="description">Show edit information markers displayed near edited paragraphs</div> </td> </tr> </tbody> </table> <!-- ============================== events summary ======================== --> <!-- ============================== constructor details ==================== --> <div class="details"><a name="constructor"> </a> <div class="sectionTitle"> Class Detail </div> <div class="fixedFont"> <b>gui.SessionView</b>(viewOptions, localMemberId, session, sessionConstraints, caretManager, selectionViewManager) </div> <div class="description"> TODO: We really don't want to let SessionView be aware of localMemberId, so eventually we'll need to refactor this. It is only here so that the id can be matched with the memberids for which CSS is generated, to generate the same CSS for shadow cursors. </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!<a href="../symbols/gui.SessionViewOptions.html">gui.SessionViewOptions</a>}</span> <b>viewOptions</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{string}</span> <b>localMemberId</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{!<a href="../symbols/ops.Session.html">ops.Session</a>}</span> <b>session</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{!<a href="../symbols/gui.SessionConstraints.html">gui.SessionConstraints</a>}</span> <b>sessionConstraints</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{!<a href="../symbols/gui.CaretManager.html">gui.CaretManager</a>}</span> <b>caretManager</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{!<a href="../symbols/gui.SelectionViewManager.html">gui.SelectionViewManager</a>}</span> <b>selectionViewManager</b> </dt> <dd></dd> </dl> </div> <!-- ============================== field details ========================== --> <!-- ============================== method details ========================= --> <div class="sectionTitle"> Method Detail </div> <a name="-createAvatarInfoNodeMatch"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{!string}</span> <b>createAvatarInfoNodeMatch</b>(nodeName, memberId, pseudoClass) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!string}</span> <b>nodeName</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{!string}</span> <b>memberId</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{!string}</span> <b>pseudoClass</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{!string}</span> </dd> </dl> <hr /> <a name="destroy"> </a> <div class="fixedFont"> <span class="light">{undefined}</span> <b>destroy</b>(callback,) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!function(!Error=)}</span> <b>callback,</b> </dt> <dd>passing an error object in case of error</dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-destroy"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{undefined}</span> <b>destroy</b>(callback) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!function(!Error=)}</span> <b>callback</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-getAvatarInfoStyle"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{?Node}</span> <b>getAvatarInfoStyle</b>(nodeName, memberId, pseudoClass) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!string}</span> <b>nodeName</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{!string}</span> <b>memberId</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{string}</span> <b>pseudoClass</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{?Node}</span> </dd> </dl> <hr /> <a name="getCaret"> </a> <div class="fixedFont"> <span class="light">{?<a href="../symbols/gui.Caret.html">gui.Caret</a>}</span> <b>getCaret</b>(memberid) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!string}</span> <b>memberid</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{?<a href="../symbols/gui.Caret.html">gui.Caret</a>}</span> </dd> </dl> <hr /> <a name="getSession"> </a> <div class="fixedFont"> <span class="light">{!<a href="../symbols/ops.Session.html">ops.Session</a>}</span> <b>getSession</b>() </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{!<a href="../symbols/ops.Session.html">ops.Session</a>}</span> </dd> </dl> <hr /> <a name="hideCaretAvatars"> </a> <div class="fixedFont"> <span class="light">{undefined}</span> <b>hideCaretAvatars</b>() </div> <div class="description"> Hide member avatars above the cursor </div> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="hideEditInfoMarkers"> </a> <div class="fixedFont"> <span class="light">{undefined}</span> <b>hideEditInfoMarkers</b>() </div> <div class="description"> Hide edit information markers displayed near edited paragraphs </div> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-highlightEdit"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{undefined}</span> <b>highlightEdit</b>(element, memberId, timestamp) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!Element}</span> <b>element</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{!string}</span> <b>memberId</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{!number}</span> <b>timestamp</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-newStyleSheet"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{!HTMLStyleElement}</span> <b>newStyleSheet</b>() </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{!HTMLStyleElement}</span> </dd> </dl> <hr /> <a name="-onCursorAdded"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{undefined}</span> <b>onCursorAdded</b>(cursor) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!<a href="../symbols/ops.OdtCursor.html">ops.OdtCursor</a>}</span> <b>cursor</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-onCursorMoved"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{undefined}</span> <b>onCursorMoved</b>(cursor) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!<a href="../symbols/ops.OdtCursor.html">ops.OdtCursor</a>}</span> <b>cursor</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-onCursorRemoved"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{undefined}</span> <b>onCursorRemoved</b>(memberid) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!string}</span> <b>memberid</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-onParagraphChanged"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{undefined}</span> <b>onParagraphChanged</b>(info) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!{paragraphElement:!Element|memberId:string|timeStamp:number}}</span> <b>info</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-refreshHighlights"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{undefined}</span> <b>refreshHighlights</b>() </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-renderMemberData"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{undefined}</span> <b>renderMemberData</b>(member) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!<a href="../symbols/ops.Member.html">ops.Member</a>}</span> <b>member</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-setAvatarInfoStyle"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{undefined}</span> <b>setAvatarInfoStyle</b>(memberId, name, color) </div> <div class="description"> </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!string}</span> <b>memberId</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{!string}</span> <b>name</b> </dt> <dd></dd> <dt> <span class="light fixedFont">{!string}</span> <b>color</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-setCaretAvatarVisibility"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{undefined}</span> <b>setCaretAvatarVisibility</b>(visible) </div> <div class="description"> Updates the visibility on all existing avatars </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!boolean}</span> <b>visible</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="-setEditInfoMarkerVisibility"> </a> <div class="fixedFont">&lt;inner&gt; <span class="light">{undefined}</span> <b>setEditInfoMarkerVisibility</b>(visible) </div> <div class="description"> Updates the visibility on all existing editInfo entries </div> <dl class="detailList"> <dt class="heading">Parameters:</dt> <dt> <span class="light fixedFont">{!boolean}</span> <b>visible</b> </dt> <dd></dd> </dl> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="showCaretAvatars"> </a> <div class="fixedFont"> <span class="light">{undefined}</span> <b>showCaretAvatars</b>() </div> <div class="description"> Show member avatars above the cursor </div> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <hr /> <a name="showEditInfoMarkers"> </a> <div class="fixedFont"> <span class="light">{undefined}</span> <b>showEditInfoMarkers</b>() </div> <div class="description"> Show edit information markers displayed near edited paragraphs </div> <dl class="detailList"> <dt class="heading">Returns:</dt> <dd><span class="light fixedFont">{undefined}</span> </dd> </dl> <!-- ============================== event details ========================= --> <hr /> </div> <!-- ============================== footer ================================= --> <div class="fineprint" style="clear:both"> Documentation generated by <a href="http://code.google.com/p/jsdoc-toolkit/" target="_blank">JsDoc Toolkit</a> 2.4.0 on Mon Jun 30 2014 13:19:30 GMT+0200 (MESZ) </div> </body> </html>
wunderlins/learning
js/webodf/webodf.js-0.5.0/docs/symbols/gui.SessionView.html
HTML
gpl-2.0
44,483
<?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
# # Makefile for the linux kernel. # AFLAGS_head.o := -DTEXT_OFFSET=$(TEXT_OFFSET) # Object file lists. obj-y := compat.o entry-armv.o entry-common.o irq.o \ process.o ptrace.o semaphore.o setup.o signal.o sys_arm.o \ time.o traps.o obj-$(CONFIG_ISA_DMA_API) += dma.o obj-$(CONFIG_ARCH_ACORN) += ecard.o obj-$(CONFIG_FIQ) += fiq.o obj-$(CONFIG_MODULES) += armksyms.o module.o obj-$(CONFIG_ARTHUR) += arthur.o obj-$(CONFIG_ISA_DMA) += dma-isa.o obj-$(CONFIG_PCI) += bios32.o isa.o obj-$(CONFIG_SMP) += smp.o obj-$(CONFIG_KEXEC) += machine_kexec.o relocate_kernel.o obj-$(CONFIG_OABI_COMPAT) += sys_oabi-compat.o obj-$(CONFIG_KGDB) += kgdb.o kgdb-jmp.o obj-$(CONFIG_CRUNCH) += crunch.o crunch-bits.o AFLAGS_crunch-bits.o := -Wa,-mcpu=ep9312 obj-$(CONFIG_CPU_XSCALE) += xscale-cp0.o obj-$(CONFIG_CPU_XSC3) += xscale-cp0.o obj-$(CONFIG_IWMMXT) += iwmmxt.o AFLAGS_iwmmxt.o := -Wa,-mcpu=iwmmxt ifneq ($(CONFIG_ARCH_EBSA110),y) obj-y += io.o endif head-y := head$(MMUEXT).o obj-$(CONFIG_DEBUG_LL) += debug.o extra-y := $(head-y) init_task.o vmlinux.lds
cyox93/s3c-linux-2.6.21
arch/arm/kernel/Makefile
Makefile
gpl-2.0
1,086
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
/* Add icon for the "Add element" elements selection popup */ .wpb-layout-element-button .icon-vc_icon_tabs { background-image: url(img/tabs-icon.jpg); } /* Add background for our shortcode in the Visual Composer backend editor */ .wpb_bartag .icon-vc_icon_tabs { background-image: url(img/tabs-icon.jpg); } .wpb_el_type_inp_hidden { display: none; } .vcit_select_font_window i { border: 1px solid #ddd; box-sizing: content-box; cursor: pointer; display: inline-block; height: 40px; margin: 2px; min-width: 40px; padding: 5px; text-align: center; vertical-align: middle; } /* Tabs ---------------------------------------------------------- */ .wpb_vc_icon_tabs li i{ position: absolute; top: 14px; left: 12px; font-size: 20px; } .wpb_vc_icon_tabs .ui-tabs .ui-tabs-nav li a{ padding: 1.5em 3em; } .wpb_vc_icon_tab > .controls_column{ text-align: center; position: relative; width: 100%; top: 4px; line-height: 1px; } .wpb_vc_icon_tab > .controls_column{ text-align: center; position: relative; width: 100%; top: 4px; line-height: 1px; } .wpb_vc_icon_tab > .controls_column a {display: inline-block; width: 12px; height: 16px; margin-left: 3px; background-position: center center; background-repeat: no-repeat; } .wpb_vc_icon_tabs > .wpb_element_wrapper { padding: 0px !important; background: none !important; border: none !important; height: auto !important; } .wpb_vc_icon_tabs > .wpb_element_wrapper .wpb_tabs_holder, .wpb_vc_icon_tabs > .wpb_element_wrapper .tabs_controls { padding: 0; } .wpb_vc_icon_tabs > .wpb_element_wrapper .ui-tabs .ui-tabs-nav { position: relative; top: 1px; z-index: 2; } .wpb_vc_icon_tabs > .wpb_element_wrapper .ui-tabs .ui-tabs-nav li { margin: 0 -1px 0 0; background: #f1f1f1; background-image: -webkit-gradient(linear, left bottom, left top, from(#ececec), to(#f9f9f9)); background-image: -webkit-linear-gradient(bottom, #ececec, #f9f9f9); background-image: -moz-linear-gradient(bottom, #ececec, #f9f9f9); background-image: -o-linear-gradient(bottom, #ececec, #f9f9f9); background-image: linear-gradient(to top, #ececec, #f9f9f9); border: 1px solid #dfdfdf !important; -webkit-box-shadow: inset 0 1px 0 #fff; box-shadow: inset 0 1px 0 #fff; } .wpb_vc_icon_tabs > .wpb_element_wrapper .ui-tabs .ui-tabs-nav li.ui-tabs-active { background: #ffffff; border: 1px dashed #CCCCCC; border-bottom: 1px solid #FFFFFF !important; } /* Tabs, Tour, Accordion controls position */ .wpb_vc_icon_tab > .bottom-controls{ top: auto; } .wpb_vc_icon_tab .empty_container { background-position: center center; } .wpb_content_element .wpb_tabs_holder > .wpb_vc_icon_tab { border: 1px dashed #CCCCCC; background-color: #FFFFFF; padding: 0; } .wpb_edit_form_elements .vc-tabs > ul li a { color: #949494; float: left; padding: 11px 15px; text-decoration: none; outline: none; font-size: 12px; } .wpb_edit_form_elements .vc-tabs > ul li.ui-state-active { background: #ffffff; font-weight: normal; color: #595959; } .wpb_edit_form_elements .vc-tabs > ul li.ui-state-active a { color: #595959; } .wpb_edit_form_elements .vc-tabs > ul > :first-child { margin-left: 6px; } .wpb_edit_form_elements .vc-tabs > div { display: none; } .wpb_edit_form_elements .vc-tabs { margin-top: -28px; } .wpb_edit_form_elements .vc-tabs .ui-tabs-nav { margin-left: -15px; padding-right: 30px; } .wpb_vc_icon_tab > .controls_column .column_add { background-image: url(img/add_grey.png); } .wpb_vc_icon_tab > .controls_column .column_edit { background-image: url(img/edit_grey.png); } .wpb_vc_icon_tab > .controls_column .column_clone { background-image: url(img/clone_grey.png); } .wpb_vc_icon_tab > .controls_column .column_delete { background-image: url(img/remove_grey.png); } .wpb_vc_icon_tab > .bottom-controls { top: auto; bottom: 4px; } /* Tabs, Tour, Accordion controls position */ .wpb_vc_icon_tab > .bottom-controls{ top: auto; } .wpb_vc_icon_tab .empty_container { background-position: center center; }
javalidigital/riema
wp-content/plugins/vc-icon-tabs/deprecated/vc_extend-admin.css
CSS
gpl-2.0
4,080
/* * drivers/base/core.c - core driver model code (device registration, etc) * * Copyright (c) 2002-3 Patrick Mochel * Copyright (c) 2002-3 Open Source Development Labs * Copyright (c) 2006 Greg Kroah-Hartman <gregkh@suse.de> * Copyright (c) 2006 Novell, Inc. * * This file is released under the GPLv2 * */ #include <linux/device.h> #include <linux/err.h> #include <linux/fwnode.h> #include <linux/init.h> #include <linux/module.h> #include <linux/slab.h> #include <linux/string.h> #include <linux/kdev_t.h> #include <linux/notifier.h> #include <linux/of.h> #include <linux/of_device.h> #include <linux/genhd.h> #include <linux/kallsyms.h> #include <linux/mutex.h> #include <linux/pm_runtime.h> #include <linux/netdevice.h> #include <linux/sysfs.h> #include "base.h" #include "power/power.h" #ifdef CONFIG_SYSFS_DEPRECATED #ifdef CONFIG_SYSFS_DEPRECATED_V2 long sysfs_deprecated = 1; #else long sysfs_deprecated = 0; #endif static int __init sysfs_deprecated_setup(char *arg) { return kstrtol(arg, 10, &sysfs_deprecated); } early_param("sysfs.deprecated", sysfs_deprecated_setup); #endif int (*platform_notify)(struct device *dev) = NULL; int (*platform_notify_remove)(struct device *dev) = NULL; static struct kobject *dev_kobj; struct kobject *sysfs_dev_char_kobj; struct kobject *sysfs_dev_block_kobj; static DEFINE_MUTEX(device_hotplug_lock); void lock_device_hotplug(void) { mutex_lock(&device_hotplug_lock); } void unlock_device_hotplug(void) { mutex_unlock(&device_hotplug_lock); } int lock_device_hotplug_sysfs(void) { if (mutex_trylock(&device_hotplug_lock)) return 0; /* Avoid busy looping (5 ms of sleep should do). */ msleep(5); return restart_syscall(); } #ifdef CONFIG_BLOCK static inline int device_is_not_partition(struct device *dev) { return !(dev->type == &part_type); } #else static inline int device_is_not_partition(struct device *dev) { return 1; } #endif /** * dev_driver_string - Return a device's driver name, if at all possible * @dev: struct device to get the name of * * Will return the device's driver's name if it is bound to a device. If * the device is not bound to a driver, it will return the name of the bus * it is attached to. If it is not attached to a bus either, an empty * string will be returned. */ const char *dev_driver_string(const struct device *dev) { struct device_driver *drv; /* dev->driver can change to NULL underneath us because of unbinding, * so be careful about accessing it. dev->bus and dev->class should * never change once they are set, so they don't need special care. */ drv = ACCESS_ONCE(dev->driver); return drv ? drv->name : (dev->bus ? dev->bus->name : (dev->class ? dev->class->name : "")); } EXPORT_SYMBOL(dev_driver_string); #define to_dev_attr(_attr) container_of(_attr, struct device_attribute, attr) static ssize_t dev_attr_show(struct kobject *kobj, struct attribute *attr, char *buf) { struct device_attribute *dev_attr = to_dev_attr(attr); struct device *dev = kobj_to_dev(kobj); ssize_t ret = -EIO; if (dev_attr->show) ret = dev_attr->show(dev, dev_attr, buf); if (ret >= (ssize_t)PAGE_SIZE) { print_symbol("dev_attr_show: %s returned bad count\n", (unsigned long)dev_attr->show); } return ret; } static ssize_t dev_attr_store(struct kobject *kobj, struct attribute *attr, const char *buf, size_t count) { struct device_attribute *dev_attr = to_dev_attr(attr); struct device *dev = kobj_to_dev(kobj); ssize_t ret = -EIO; if (dev_attr->store) ret = dev_attr->store(dev, dev_attr, buf, count); return ret; } static const struct sysfs_ops dev_sysfs_ops = { .show = dev_attr_show, .store = dev_attr_store, }; #define to_ext_attr(x) container_of(x, struct dev_ext_attribute, attr) ssize_t device_store_ulong(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct dev_ext_attribute *ea = to_ext_attr(attr); char *end; unsigned long new = simple_strtoul(buf, &end, 0); if (end == buf) return -EINVAL; *(unsigned long *)(ea->var) = new; /* Always return full write size even if we didn't consume all */ return size; } EXPORT_SYMBOL_GPL(device_store_ulong); ssize_t device_show_ulong(struct device *dev, struct device_attribute *attr, char *buf) { struct dev_ext_attribute *ea = to_ext_attr(attr); return snprintf(buf, PAGE_SIZE, "%lx\n", *(unsigned long *)(ea->var)); } EXPORT_SYMBOL_GPL(device_show_ulong); ssize_t device_store_int(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct dev_ext_attribute *ea = to_ext_attr(attr); char *end; long new = simple_strtol(buf, &end, 0); if (end == buf || new > INT_MAX || new < INT_MIN) return -EINVAL; *(int *)(ea->var) = new; /* Always return full write size even if we didn't consume all */ return size; } EXPORT_SYMBOL_GPL(device_store_int); ssize_t device_show_int(struct device *dev, struct device_attribute *attr, char *buf) { struct dev_ext_attribute *ea = to_ext_attr(attr); return snprintf(buf, PAGE_SIZE, "%d\n", *(int *)(ea->var)); } EXPORT_SYMBOL_GPL(device_show_int); ssize_t device_store_bool(struct device *dev, struct device_attribute *attr, const char *buf, size_t size) { struct dev_ext_attribute *ea = to_ext_attr(attr); if (strtobool(buf, ea->var) < 0) return -EINVAL; return size; } EXPORT_SYMBOL_GPL(device_store_bool); ssize_t device_show_bool(struct device *dev, struct device_attribute *attr, char *buf) { struct dev_ext_attribute *ea = to_ext_attr(attr); return snprintf(buf, PAGE_SIZE, "%d\n", *(bool *)(ea->var)); } EXPORT_SYMBOL_GPL(device_show_bool); /** * device_release - free device structure. * @kobj: device's kobject. * * This is called once the reference count for the object * reaches 0. We forward the call to the device's release * method, which should handle actually freeing the structure. */ static void device_release(struct kobject *kobj) { struct device *dev = kobj_to_dev(kobj); struct device_private *p = dev->p; /* * Some platform devices are driven without driver attached * and managed resources may have been acquired. Make sure * all resources are released. * * Drivers still can add resources into device after device * is deleted but alive, so release devres here to avoid * possible memory leak. */ devres_release_all(dev); if (dev->release) dev->release(dev); else if (dev->type && dev->type->release) dev->type->release(dev); else if (dev->class && dev->class->dev_release) dev->class->dev_release(dev); else WARN(1, KERN_ERR "Device '%s' does not have a release() " "function, it is broken and must be fixed.\n", dev_name(dev)); kfree(p); } static const void *device_namespace(struct kobject *kobj) { struct device *dev = kobj_to_dev(kobj); const void *ns = NULL; if (dev->class && dev->class->ns_type) ns = dev->class->namespace(dev); return ns; } static struct kobj_type device_ktype = { .release = device_release, .sysfs_ops = &dev_sysfs_ops, .namespace = device_namespace, }; static int dev_uevent_filter(struct kset *kset, struct kobject *kobj) { struct kobj_type *ktype = get_ktype(kobj); if (ktype == &device_ktype) { struct device *dev = kobj_to_dev(kobj); if (dev->bus) return 1; if (dev->class) return 1; } return 0; } static const char *dev_uevent_name(struct kset *kset, struct kobject *kobj) { struct device *dev = kobj_to_dev(kobj); if (dev->bus) return dev->bus->name; if (dev->class) return dev->class->name; return NULL; } static int dev_uevent(struct kset *kset, struct kobject *kobj, struct kobj_uevent_env *env) { struct device *dev = kobj_to_dev(kobj); int retval = 0; /* add device node properties if present */ if (MAJOR(dev->devt)) { const char *tmp; const char *name; umode_t mode = 0; kuid_t uid = GLOBAL_ROOT_UID; kgid_t gid = GLOBAL_ROOT_GID; add_uevent_var(env, "MAJOR=%u", MAJOR(dev->devt)); add_uevent_var(env, "MINOR=%u", MINOR(dev->devt)); name = device_get_devnode(dev, &mode, &uid, &gid, &tmp); if (name) { add_uevent_var(env, "DEVNAME=%s", name); if (mode) add_uevent_var(env, "DEVMODE=%#o", mode & 0777); if (!uid_eq(uid, GLOBAL_ROOT_UID)) add_uevent_var(env, "DEVUID=%u", from_kuid(&init_user_ns, uid)); if (!gid_eq(gid, GLOBAL_ROOT_GID)) add_uevent_var(env, "DEVGID=%u", from_kgid(&init_user_ns, gid)); kfree(tmp); } } if (dev->type && dev->type->name) add_uevent_var(env, "DEVTYPE=%s", dev->type->name); if (dev->driver) add_uevent_var(env, "DRIVER=%s", dev->driver->name); /* Add common DT information about the device */ of_device_uevent(dev, env); /* have the bus specific function add its stuff */ if (dev->bus && dev->bus->uevent) { retval = dev->bus->uevent(dev, env); if (retval) pr_debug("device: '%s': %s: bus uevent() returned %d\n", dev_name(dev), __func__, retval); } /* have the class specific function add its stuff */ if (dev->class && dev->class->dev_uevent) { retval = dev->class->dev_uevent(dev, env); if (retval) pr_debug("device: '%s': %s: class uevent() " "returned %d\n", dev_name(dev), __func__, retval); } /* have the device type specific function add its stuff */ if (dev->type && dev->type->uevent) { retval = dev->type->uevent(dev, env); if (retval) pr_debug("device: '%s': %s: dev_type uevent() " "returned %d\n", dev_name(dev), __func__, retval); } return retval; } static const struct kset_uevent_ops device_uevent_ops = { .filter = dev_uevent_filter, .name = dev_uevent_name, .uevent = dev_uevent, }; static ssize_t uevent_show(struct device *dev, struct device_attribute *attr, char *buf) { struct kobject *top_kobj; struct kset *kset; struct kobj_uevent_env *env = NULL; int i; size_t count = 0; int retval; /* search the kset, the device belongs to */ top_kobj = &dev->kobj; while (!top_kobj->kset && top_kobj->parent) top_kobj = top_kobj->parent; if (!top_kobj->kset) goto out; kset = top_kobj->kset; if (!kset->uevent_ops || !kset->uevent_ops->uevent) goto out; /* respect filter */ if (kset->uevent_ops && kset->uevent_ops->filter) if (!kset->uevent_ops->filter(kset, &dev->kobj)) goto out; env = kzalloc(sizeof(struct kobj_uevent_env), GFP_KERNEL); if (!env) return -ENOMEM; /* let the kset specific function add its keys */ retval = kset->uevent_ops->uevent(kset, &dev->kobj, env); if (retval) goto out; /* copy keys to file */ for (i = 0; i < env->envp_idx; i++) count += sprintf(&buf[count], "%s\n", env->envp[i]); out: kfree(env); return count; } static ssize_t uevent_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { enum kobject_action action; if (kobject_action_type(buf, count, &action) == 0) kobject_uevent(&dev->kobj, action); else dev_err(dev, "uevent: unknown action-string\n"); return count; } static DEVICE_ATTR_RW(uevent); static ssize_t online_show(struct device *dev, struct device_attribute *attr, char *buf) { bool val; device_lock(dev); val = !dev->offline; device_unlock(dev); return sprintf(buf, "%u\n", val); } static ssize_t online_store(struct device *dev, struct device_attribute *attr, const char *buf, size_t count) { bool val; int ret; ret = strtobool(buf, &val); if (ret < 0) return ret; ret = lock_device_hotplug_sysfs(); if (ret) return ret; ret = val ? device_online(dev) : device_offline(dev); unlock_device_hotplug(); return ret < 0 ? ret : count; } static DEVICE_ATTR_RW(online); int device_add_groups(struct device *dev, const struct attribute_group **groups) { return sysfs_create_groups(&dev->kobj, groups); } void device_remove_groups(struct device *dev, const struct attribute_group **groups) { sysfs_remove_groups(&dev->kobj, groups); } static int device_add_attrs(struct device *dev) { struct class *class = dev->class; const struct device_type *type = dev->type; int error; if (class) { error = device_add_groups(dev, class->dev_groups); if (error) return error; } if (type) { error = device_add_groups(dev, type->groups); if (error) goto err_remove_class_groups; } error = device_add_groups(dev, dev->groups); if (error) goto err_remove_type_groups; if (device_supports_offline(dev) && !dev->offline_disabled) { error = device_create_file(dev, &dev_attr_online); if (error) goto err_remove_dev_groups; } return 0; err_remove_dev_groups: device_remove_groups(dev, dev->groups); err_remove_type_groups: if (type) device_remove_groups(dev, type->groups); err_remove_class_groups: if (class) device_remove_groups(dev, class->dev_groups); return error; } static void device_remove_attrs(struct device *dev) { struct class *class = dev->class; const struct device_type *type = dev->type; device_remove_file(dev, &dev_attr_online); device_remove_groups(dev, dev->groups); if (type) device_remove_groups(dev, type->groups); if (class) device_remove_groups(dev, class->dev_groups); } static ssize_t dev_show(struct device *dev, struct device_attribute *attr, char *buf) { return print_dev_t(buf, dev->devt); } static DEVICE_ATTR_RO(dev); /* /sys/devices/ */ struct kset *devices_kset; /** * devices_kset_move_before - Move device in the devices_kset's list. * @deva: Device to move. * @devb: Device @deva should come before. */ static void devices_kset_move_before(struct device *deva, struct device *devb) { if (!devices_kset) return; pr_debug("devices_kset: Moving %s before %s\n", dev_name(deva), dev_name(devb)); spin_lock(&devices_kset->list_lock); list_move_tail(&deva->kobj.entry, &devb->kobj.entry); spin_unlock(&devices_kset->list_lock); } /** * devices_kset_move_after - Move device in the devices_kset's list. * @deva: Device to move * @devb: Device @deva should come after. */ static void devices_kset_move_after(struct device *deva, struct device *devb) { if (!devices_kset) return; pr_debug("devices_kset: Moving %s after %s\n", dev_name(deva), dev_name(devb)); spin_lock(&devices_kset->list_lock); list_move(&deva->kobj.entry, &devb->kobj.entry); spin_unlock(&devices_kset->list_lock); } /** * devices_kset_move_last - move the device to the end of devices_kset's list. * @dev: device to move */ void devices_kset_move_last(struct device *dev) { if (!devices_kset) return; pr_debug("devices_kset: Moving %s to end of list\n", dev_name(dev)); spin_lock(&devices_kset->list_lock); list_move_tail(&dev->kobj.entry, &devices_kset->list); spin_unlock(&devices_kset->list_lock); } /** * device_create_file - create sysfs attribute file for device. * @dev: device. * @attr: device attribute descriptor. */ int device_create_file(struct device *dev, const struct device_attribute *attr) { int error = 0; if (dev) { WARN(((attr->attr.mode & S_IWUGO) && !attr->store), "Attribute %s: write permission without 'store'\n", attr->attr.name); WARN(((attr->attr.mode & S_IRUGO) && !attr->show), "Attribute %s: read permission without 'show'\n", attr->attr.name); error = sysfs_create_file(&dev->kobj, &attr->attr); } return error; } EXPORT_SYMBOL_GPL(device_create_file); /** * device_remove_file - remove sysfs attribute file. * @dev: device. * @attr: device attribute descriptor. */ void device_remove_file(struct device *dev, const struct device_attribute *attr) { if (dev) sysfs_remove_file(&dev->kobj, &attr->attr); } EXPORT_SYMBOL_GPL(device_remove_file); /** * device_remove_file_self - remove sysfs attribute file from its own method. * @dev: device. * @attr: device attribute descriptor. * * See kernfs_remove_self() for details. */ bool device_remove_file_self(struct device *dev, const struct device_attribute *attr) { if (dev) return sysfs_remove_file_self(&dev->kobj, &attr->attr); else return false; } EXPORT_SYMBOL_GPL(device_remove_file_self); /** * device_create_bin_file - create sysfs binary attribute file for device. * @dev: device. * @attr: device binary attribute descriptor. */ int device_create_bin_file(struct device *dev, const struct bin_attribute *attr) { int error = -EINVAL; if (dev) error = sysfs_create_bin_file(&dev->kobj, attr); return error; } EXPORT_SYMBOL_GPL(device_create_bin_file); /** * device_remove_bin_file - remove sysfs binary attribute file * @dev: device. * @attr: device binary attribute descriptor. */ void device_remove_bin_file(struct device *dev, const struct bin_attribute *attr) { if (dev) sysfs_remove_bin_file(&dev->kobj, attr); } EXPORT_SYMBOL_GPL(device_remove_bin_file); static void klist_children_get(struct klist_node *n) { struct device_private *p = to_device_private_parent(n); struct device *dev = p->device; get_device(dev); } static void klist_children_put(struct klist_node *n) { struct device_private *p = to_device_private_parent(n); struct device *dev = p->device; put_device(dev); } /** * device_initialize - init device structure. * @dev: device. * * This prepares the device for use by other layers by initializing * its fields. * It is the first half of device_register(), if called by * that function, though it can also be called separately, so one * may use @dev's fields. In particular, get_device()/put_device() * may be used for reference counting of @dev after calling this * function. * * All fields in @dev must be initialized by the caller to 0, except * for those explicitly set to some other value. The simplest * approach is to use kzalloc() to allocate the structure containing * @dev. * * NOTE: Use put_device() to give up your reference instead of freeing * @dev directly once you have called this function. */ void device_initialize(struct device *dev) { dev->kobj.kset = devices_kset; kobject_init(&dev->kobj, &device_ktype); INIT_LIST_HEAD(&dev->dma_pools); mutex_init(&dev->mutex); lockdep_set_novalidate_class(&dev->mutex); spin_lock_init(&dev->devres_lock); INIT_LIST_HEAD(&dev->devres_head); device_pm_init(dev); set_dev_node(dev, -1); #ifdef CONFIG_GENERIC_MSI_IRQ INIT_LIST_HEAD(&dev->msi_list); #endif } EXPORT_SYMBOL_GPL(device_initialize); struct kobject *virtual_device_parent(struct device *dev) { static struct kobject *virtual_dir = NULL; if (!virtual_dir) virtual_dir = kobject_create_and_add("virtual", &devices_kset->kobj); return virtual_dir; } struct class_dir { struct kobject kobj; struct class *class; }; #define to_class_dir(obj) container_of(obj, struct class_dir, kobj) static void class_dir_release(struct kobject *kobj) { struct class_dir *dir = to_class_dir(kobj); kfree(dir); } static const struct kobj_ns_type_operations *class_dir_child_ns_type(struct kobject *kobj) { struct class_dir *dir = to_class_dir(kobj); return dir->class->ns_type; } static struct kobj_type class_dir_ktype = { .release = class_dir_release, .sysfs_ops = &kobj_sysfs_ops, .child_ns_type = class_dir_child_ns_type }; static struct kobject * class_dir_create_and_add(struct class *class, struct kobject *parent_kobj) { struct class_dir *dir; int retval; dir = kzalloc(sizeof(*dir), GFP_KERNEL); if (!dir) return NULL; dir->class = class; kobject_init(&dir->kobj, &class_dir_ktype); dir->kobj.kset = &class->p->glue_dirs; retval = kobject_add(&dir->kobj, parent_kobj, "%s", class->name); if (retval < 0) { kobject_put(&dir->kobj); return NULL; } return &dir->kobj; } static DEFINE_MUTEX(gdp_mutex); static struct kobject *get_device_parent(struct device *dev, struct device *parent) { if (dev->class) { struct kobject *kobj = NULL; struct kobject *parent_kobj; struct kobject *k; #ifdef CONFIG_BLOCK /* block disks show up in /sys/block */ if (sysfs_deprecated && dev->class == &block_class) { if (parent && parent->class == &block_class) return &parent->kobj; return &block_class.p->subsys.kobj; } #endif /* * If we have no parent, we live in "virtual". * Class-devices with a non class-device as parent, live * in a "glue" directory to prevent namespace collisions. */ if (parent == NULL) parent_kobj = virtual_device_parent(dev); else if (parent->class && !dev->class->ns_type) return &parent->kobj; else parent_kobj = &parent->kobj; mutex_lock(&gdp_mutex); /* find our class-directory at the parent and reference it */ spin_lock(&dev->class->p->glue_dirs.list_lock); list_for_each_entry(k, &dev->class->p->glue_dirs.list, entry) if (k->parent == parent_kobj) { kobj = kobject_get(k); break; } spin_unlock(&dev->class->p->glue_dirs.list_lock); if (kobj) { mutex_unlock(&gdp_mutex); return kobj; } /* or create a new class-directory at the parent device */ k = class_dir_create_and_add(dev->class, parent_kobj); /* do not emit an uevent for this simple "glue" directory */ mutex_unlock(&gdp_mutex); return k; } /* subsystems can specify a default root directory for their devices */ if (!parent && dev->bus && dev->bus->dev_root) return &dev->bus->dev_root->kobj; if (parent) return &parent->kobj; return NULL; } static inline bool live_in_glue_dir(struct kobject *kobj, struct device *dev) { if (!kobj || !dev->class || kobj->kset != &dev->class->p->glue_dirs) return false; return true; } static inline struct kobject *get_glue_dir(struct device *dev) { return dev->kobj.parent; } /* * make sure cleaning up dir as the last step, we need to make * sure .release handler of kobject is run with holding the * global lock */ static void cleanup_glue_dir(struct device *dev, struct kobject *glue_dir) { /* see if we live in a "glue" directory */ if (!live_in_glue_dir(glue_dir, dev)) return; mutex_lock(&gdp_mutex); kobject_put(glue_dir); mutex_unlock(&gdp_mutex); } static int device_add_class_symlinks(struct device *dev) { struct device_node *of_node = dev_of_node(dev); int error; if (of_node) { error = sysfs_create_link(&dev->kobj, &of_node->kobj,"of_node"); if (error) dev_warn(dev, "Error %d creating of_node link\n",error); /* An error here doesn't warrant bringing down the device */ } if (!dev->class) return 0; error = sysfs_create_link(&dev->kobj, &dev->class->p->subsys.kobj, "subsystem"); if (error) goto out_devnode; if (dev->parent && device_is_not_partition(dev)) { error = sysfs_create_link(&dev->kobj, &dev->parent->kobj, "device"); if (error) goto out_subsys; } #ifdef CONFIG_BLOCK /* /sys/block has directories and does not need symlinks */ if (sysfs_deprecated && dev->class == &block_class) return 0; #endif /* link in the class directory pointing to the device */ error = sysfs_create_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev)); if (error) goto out_device; return 0; out_device: sysfs_remove_link(&dev->kobj, "device"); out_subsys: sysfs_remove_link(&dev->kobj, "subsystem"); out_devnode: sysfs_remove_link(&dev->kobj, "of_node"); return error; } static void device_remove_class_symlinks(struct device *dev) { if (dev_of_node(dev)) sysfs_remove_link(&dev->kobj, "of_node"); if (!dev->class) return; if (dev->parent && device_is_not_partition(dev)) sysfs_remove_link(&dev->kobj, "device"); sysfs_remove_link(&dev->kobj, "subsystem"); #ifdef CONFIG_BLOCK if (sysfs_deprecated && dev->class == &block_class) return; #endif sysfs_delete_link(&dev->class->p->subsys.kobj, &dev->kobj, dev_name(dev)); } /** * dev_set_name - set a device name * @dev: device * @fmt: format string for the device's name */ int dev_set_name(struct device *dev, const char *fmt, ...) { va_list vargs; int err; va_start(vargs, fmt); err = kobject_set_name_vargs(&dev->kobj, fmt, vargs); va_end(vargs); return err; } EXPORT_SYMBOL_GPL(dev_set_name); /** * device_to_dev_kobj - select a /sys/dev/ directory for the device * @dev: device * * By default we select char/ for new entries. Setting class->dev_obj * to NULL prevents an entry from being created. class->dev_kobj must * be set (or cleared) before any devices are registered to the class * otherwise device_create_sys_dev_entry() and * device_remove_sys_dev_entry() will disagree about the presence of * the link. */ static struct kobject *device_to_dev_kobj(struct device *dev) { struct kobject *kobj; if (dev->class) kobj = dev->class->dev_kobj; else kobj = sysfs_dev_char_kobj; return kobj; } static int device_create_sys_dev_entry(struct device *dev) { struct kobject *kobj = device_to_dev_kobj(dev); int error = 0; char devt_str[15]; if (kobj) { format_dev_t(devt_str, dev->devt); error = sysfs_create_link(kobj, &dev->kobj, devt_str); } return error; } static void device_remove_sys_dev_entry(struct device *dev) { struct kobject *kobj = device_to_dev_kobj(dev); char devt_str[15]; if (kobj) { format_dev_t(devt_str, dev->devt); sysfs_remove_link(kobj, devt_str); } } int device_private_init(struct device *dev) { dev->p = kzalloc(sizeof(*dev->p), GFP_KERNEL); if (!dev->p) return -ENOMEM; dev->p->device = dev; klist_init(&dev->p->klist_children, klist_children_get, klist_children_put); INIT_LIST_HEAD(&dev->p->deferred_probe); return 0; } /** * device_add - add device to device hierarchy. * @dev: device. * * This is part 2 of device_register(), though may be called * separately _iff_ device_initialize() has been called separately. * * This adds @dev to the kobject hierarchy via kobject_add(), adds it * to the global and sibling lists for the device, then * adds it to the other relevant subsystems of the driver model. * * Do not call this routine or device_register() more than once for * any device structure. The driver model core is not designed to work * with devices that get unregistered and then spring back to life. * (Among other things, it's very hard to guarantee that all references * to the previous incarnation of @dev have been dropped.) Allocate * and register a fresh new struct device instead. * * NOTE: _Never_ directly free @dev after calling this function, even * if it returned an error! Always use put_device() to give up your * reference instead. */ int device_add(struct device *dev) { struct device *parent = NULL; struct kobject *kobj; struct class_interface *class_intf; int error = -EINVAL; struct kobject *glue_dir = NULL; dev = get_device(dev); if (!dev) goto done; if (!dev->p) { error = device_private_init(dev); if (error) goto done; } /* * for statically allocated devices, which should all be converted * some day, we need to initialize the name. We prevent reading back * the name, and force the use of dev_name() */ if (dev->init_name) { dev_set_name(dev, "%s", dev->init_name); dev->init_name = NULL; } /* subsystems can specify simple device enumeration */ if (!dev_name(dev) && dev->bus && dev->bus->dev_name) dev_set_name(dev, "%s%u", dev->bus->dev_name, dev->id); if (!dev_name(dev)) { error = -EINVAL; goto name_error; } pr_debug("device: '%s': %s\n", dev_name(dev), __func__); parent = get_device(dev->parent); kobj = get_device_parent(dev, parent); if (kobj) dev->kobj.parent = kobj; /* use parent numa_node */ if (parent && (dev_to_node(dev) == NUMA_NO_NODE)) set_dev_node(dev, dev_to_node(parent)); /* first, register with generic layer. */ /* we require the name to be set before, and pass NULL */ error = kobject_add(&dev->kobj, dev->kobj.parent, NULL); if (error) { glue_dir = get_glue_dir(dev); goto Error; } /* notify platform of device entry */ if (platform_notify) platform_notify(dev); error = device_create_file(dev, &dev_attr_uevent); if (error) goto attrError; error = device_add_class_symlinks(dev); if (error) goto SymlinkError; error = device_add_attrs(dev); if (error) goto AttrsError; error = bus_add_device(dev); if (error) goto BusError; error = dpm_sysfs_add(dev); if (error) goto DPMError; device_pm_add(dev); if (MAJOR(dev->devt)) { error = device_create_file(dev, &dev_attr_dev); if (error) goto DevAttrError; error = device_create_sys_dev_entry(dev); if (error) goto SysEntryError; devtmpfs_create_node(dev); } /* Notify clients of device addition. This call must come * after dpm_sysfs_add() and before kobject_uevent(). */ if (dev->bus) blocking_notifier_call_chain(&dev->bus->p->bus_notifier, BUS_NOTIFY_ADD_DEVICE, dev); kobject_uevent(&dev->kobj, KOBJ_ADD); bus_probe_device(dev); if (parent) klist_add_tail(&dev->p->knode_parent, &parent->p->klist_children); if (dev->class) { mutex_lock(&dev->class->p->mutex); /* tie the class to the device */ klist_add_tail(&dev->knode_class, &dev->class->p->klist_devices); /* notify any interfaces that the device is here */ list_for_each_entry(class_intf, &dev->class->p->interfaces, node) if (class_intf->add_dev) class_intf->add_dev(dev, class_intf); mutex_unlock(&dev->class->p->mutex); } done: put_device(dev); return error; SysEntryError: if (MAJOR(dev->devt)) device_remove_file(dev, &dev_attr_dev); DevAttrError: device_pm_remove(dev); dpm_sysfs_remove(dev); DPMError: bus_remove_device(dev); BusError: device_remove_attrs(dev); AttrsError: device_remove_class_symlinks(dev); SymlinkError: device_remove_file(dev, &dev_attr_uevent); attrError: kobject_uevent(&dev->kobj, KOBJ_REMOVE); glue_dir = get_glue_dir(dev); kobject_del(&dev->kobj); Error: cleanup_glue_dir(dev, glue_dir); put_device(parent); name_error: kfree(dev->p); dev->p = NULL; goto done; } EXPORT_SYMBOL_GPL(device_add); /** * device_register - register a device with the system. * @dev: pointer to the device structure * * This happens in two clean steps - initialize the device * and add it to the system. The two steps can be called * separately, but this is the easiest and most common. * I.e. you should only call the two helpers separately if * have a clearly defined need to use and refcount the device * before it is added to the hierarchy. * * For more information, see the kerneldoc for device_initialize() * and device_add(). * * NOTE: _Never_ directly free @dev after calling this function, even * if it returned an error! Always use put_device() to give up the * reference initialized in this function instead. */ int device_register(struct device *dev) { device_initialize(dev); return device_add(dev); } EXPORT_SYMBOL_GPL(device_register); /** * get_device - increment reference count for device. * @dev: device. * * This simply forwards the call to kobject_get(), though * we do take care to provide for the case that we get a NULL * pointer passed in. */ struct device *get_device(struct device *dev) { return dev ? kobj_to_dev(kobject_get(&dev->kobj)) : NULL; } EXPORT_SYMBOL_GPL(get_device); /** * put_device - decrement reference count. * @dev: device in question. */ void put_device(struct device *dev) { /* might_sleep(); */ if (dev) kobject_put(&dev->kobj); } EXPORT_SYMBOL_GPL(put_device); /** * device_del - delete device from system. * @dev: device. * * This is the first part of the device unregistration * sequence. This removes the device from the lists we control * from here, has it removed from the other driver model * subsystems it was added to in device_add(), and removes it * from the kobject hierarchy. * * NOTE: this should be called manually _iff_ device_add() was * also called manually. */ void device_del(struct device *dev) { struct device *parent = dev->parent; struct kobject *glue_dir = NULL; struct class_interface *class_intf; /* Notify clients of device removal. This call must come * before dpm_sysfs_remove(). */ if (dev->bus) blocking_notifier_call_chain(&dev->bus->p->bus_notifier, BUS_NOTIFY_DEL_DEVICE, dev); dpm_sysfs_remove(dev); if (parent) klist_del(&dev->p->knode_parent); if (MAJOR(dev->devt)) { devtmpfs_delete_node(dev); device_remove_sys_dev_entry(dev); device_remove_file(dev, &dev_attr_dev); } if (dev->class) { device_remove_class_symlinks(dev); mutex_lock(&dev->class->p->mutex); /* notify any interfaces that the device is now gone */ list_for_each_entry(class_intf, &dev->class->p->interfaces, node) if (class_intf->remove_dev) class_intf->remove_dev(dev, class_intf); /* remove the device from the class list */ klist_del(&dev->knode_class); mutex_unlock(&dev->class->p->mutex); } device_remove_file(dev, &dev_attr_uevent); device_remove_attrs(dev); bus_remove_device(dev); device_pm_remove(dev); driver_deferred_probe_del(dev); device_remove_properties(dev); /* Notify the platform of the removal, in case they * need to do anything... */ if (platform_notify_remove) platform_notify_remove(dev); if (dev->bus) blocking_notifier_call_chain(&dev->bus->p->bus_notifier, BUS_NOTIFY_REMOVED_DEVICE, dev); kobject_uevent(&dev->kobj, KOBJ_REMOVE); glue_dir = get_glue_dir(dev); kobject_del(&dev->kobj); cleanup_glue_dir(dev, glue_dir); put_device(parent); } EXPORT_SYMBOL_GPL(device_del); /** * device_unregister - unregister device from system. * @dev: device going away. * * We do this in two parts, like we do device_register(). First, * we remove it from all the subsystems with device_del(), then * we decrement the reference count via put_device(). If that * is the final reference count, the device will be cleaned up * via device_release() above. Otherwise, the structure will * stick around until the final reference to the device is dropped. */ void device_unregister(struct device *dev) { pr_debug("device: '%s': %s\n", dev_name(dev), __func__); device_del(dev); put_device(dev); } EXPORT_SYMBOL_GPL(device_unregister); static struct device *prev_device(struct klist_iter *i) { struct klist_node *n = klist_prev(i); struct device *dev = NULL; struct device_private *p; if (n) { p = to_device_private_parent(n); dev = p->device; } return dev; } static struct device *next_device(struct klist_iter *i) { struct klist_node *n = klist_next(i); struct device *dev = NULL; struct device_private *p; if (n) { p = to_device_private_parent(n); dev = p->device; } return dev; } /** * device_get_devnode - path of device node file * @dev: device * @mode: returned file access mode * @uid: returned file owner * @gid: returned file group * @tmp: possibly allocated string * * Return the relative path of a possible device node. * Non-default names may need to allocate a memory to compose * a name. This memory is returned in tmp and needs to be * freed by the caller. */ const char *device_get_devnode(struct device *dev, umode_t *mode, kuid_t *uid, kgid_t *gid, const char **tmp) { char *s; *tmp = NULL; /* the device type may provide a specific name */ if (dev->type && dev->type->devnode) *tmp = dev->type->devnode(dev, mode, uid, gid); if (*tmp) return *tmp; /* the class may provide a specific name */ if (dev->class && dev->class->devnode) *tmp = dev->class->devnode(dev, mode); if (*tmp) return *tmp; /* return name without allocation, tmp == NULL */ if (strchr(dev_name(dev), '!') == NULL) return dev_name(dev); /* replace '!' in the name with '/' */ s = kstrdup(dev_name(dev), GFP_KERNEL); if (!s) return NULL; strreplace(s, '!', '/'); return *tmp = s; } /** * device_for_each_child - device child iterator. * @parent: parent struct device. * @fn: function to be called for each device. * @data: data for the callback. * * Iterate over @parent's child devices, and call @fn for each, * passing it @data. * * We check the return of @fn each time. If it returns anything * other than 0, we break out and return that value. */ int device_for_each_child(struct device *parent, void *data, int (*fn)(struct device *dev, void *data)) { struct klist_iter i; struct device *child; int error = 0; if (!parent->p) return 0; klist_iter_init(&parent->p->klist_children, &i); while ((child = next_device(&i)) && !error) error = fn(child, data); klist_iter_exit(&i); return error; } EXPORT_SYMBOL_GPL(device_for_each_child); /** * device_for_each_child_reverse - device child iterator in reversed order. * @parent: parent struct device. * @fn: function to be called for each device. * @data: data for the callback. * * Iterate over @parent's child devices, and call @fn for each, * passing it @data. * * We check the return of @fn each time. If it returns anything * other than 0, we break out and return that value. */ int device_for_each_child_reverse(struct device *parent, void *data, int (*fn)(struct device *dev, void *data)) { struct klist_iter i; struct device *child; int error = 0; if (!parent->p) return 0; klist_iter_init(&parent->p->klist_children, &i); while ((child = prev_device(&i)) && !error) error = fn(child, data); klist_iter_exit(&i); return error; } EXPORT_SYMBOL_GPL(device_for_each_child_reverse); /** * device_find_child - device iterator for locating a particular device. * @parent: parent struct device * @match: Callback function to check device * @data: Data to pass to match function * * This is similar to the device_for_each_child() function above, but it * returns a reference to a device that is 'found' for later use, as * determined by the @match callback. * * The callback should return 0 if the device doesn't match and non-zero * if it does. If the callback returns non-zero and a reference to the * current device can be obtained, this function will return to the caller * and not iterate over any more devices. * * NOTE: you will need to drop the reference with put_device() after use. */ struct device *device_find_child(struct device *parent, void *data, int (*match)(struct device *dev, void *data)) { struct klist_iter i; struct device *child; if (!parent) return NULL; klist_iter_init(&parent->p->klist_children, &i); while ((child = next_device(&i))) if (match(child, data) && get_device(child)) break; klist_iter_exit(&i); return child; } EXPORT_SYMBOL_GPL(device_find_child); int __init devices_init(void) { devices_kset = kset_create_and_add("devices", &device_uevent_ops, NULL); if (!devices_kset) return -ENOMEM; dev_kobj = kobject_create_and_add("dev", NULL); if (!dev_kobj) goto dev_kobj_err; sysfs_dev_block_kobj = kobject_create_and_add("block", dev_kobj); if (!sysfs_dev_block_kobj) goto block_kobj_err; sysfs_dev_char_kobj = kobject_create_and_add("char", dev_kobj); if (!sysfs_dev_char_kobj) goto char_kobj_err; return 0; char_kobj_err: kobject_put(sysfs_dev_block_kobj); block_kobj_err: kobject_put(dev_kobj); dev_kobj_err: kset_unregister(devices_kset); return -ENOMEM; } static int device_check_offline(struct device *dev, void *not_used) { int ret; ret = device_for_each_child(dev, NULL, device_check_offline); if (ret) return ret; return device_supports_offline(dev) && !dev->offline ? -EBUSY : 0; } /** * device_offline - Prepare the device for hot-removal. * @dev: Device to be put offline. * * Execute the device bus type's .offline() callback, if present, to prepare * the device for a subsequent hot-removal. If that succeeds, the device must * not be used until either it is removed or its bus type's .online() callback * is executed. * * Call under device_hotplug_lock. */ int device_offline(struct device *dev) { int ret; if (dev->offline_disabled) return -EPERM; ret = device_for_each_child(dev, NULL, device_check_offline); if (ret) return ret; device_lock(dev); if (device_supports_offline(dev)) { if (dev->offline) { ret = 1; } else { ret = dev->bus->offline(dev); if (!ret) { kobject_uevent(&dev->kobj, KOBJ_OFFLINE); dev->offline = true; } } } device_unlock(dev); return ret; } /** * device_online - Put the device back online after successful device_offline(). * @dev: Device to be put back online. * * If device_offline() has been successfully executed for @dev, but the device * has not been removed subsequently, execute its bus type's .online() callback * to indicate that the device can be used again. * * Call under device_hotplug_lock. */ int device_online(struct device *dev) { int ret = 0; device_lock(dev); if (device_supports_offline(dev)) { if (dev->offline) { ret = dev->bus->online(dev); if (!ret) { kobject_uevent(&dev->kobj, KOBJ_ONLINE); dev->offline = false; } } else { ret = 1; } } device_unlock(dev); return ret; } struct root_device { struct device dev; struct module *owner; }; static inline struct root_device *to_root_device(struct device *d) { return container_of(d, struct root_device, dev); } static void root_device_release(struct device *dev) { kfree(to_root_device(dev)); } /** * __root_device_register - allocate and register a root device * @name: root device name * @owner: owner module of the root device, usually THIS_MODULE * * This function allocates a root device and registers it * using device_register(). In order to free the returned * device, use root_device_unregister(). * * Root devices are dummy devices which allow other devices * to be grouped under /sys/devices. Use this function to * allocate a root device and then use it as the parent of * any device which should appear under /sys/devices/{name} * * The /sys/devices/{name} directory will also contain a * 'module' symlink which points to the @owner directory * in sysfs. * * Returns &struct device pointer on success, or ERR_PTR() on error. * * Note: You probably want to use root_device_register(). */ struct device *__root_device_register(const char *name, struct module *owner) { struct root_device *root; int err = -ENOMEM; root = kzalloc(sizeof(struct root_device), GFP_KERNEL); if (!root) return ERR_PTR(err); err = dev_set_name(&root->dev, "%s", name); if (err) { kfree(root); return ERR_PTR(err); } root->dev.release = root_device_release; err = device_register(&root->dev); if (err) { put_device(&root->dev); return ERR_PTR(err); } #ifdef CONFIG_MODULES /* gotta find a "cleaner" way to do this */ if (owner) { struct module_kobject *mk = &owner->mkobj; err = sysfs_create_link(&root->dev.kobj, &mk->kobj, "module"); if (err) { device_unregister(&root->dev); return ERR_PTR(err); } root->owner = owner; } #endif return &root->dev; } EXPORT_SYMBOL_GPL(__root_device_register); /** * root_device_unregister - unregister and free a root device * @dev: device going away * * This function unregisters and cleans up a device that was created by * root_device_register(). */ void root_device_unregister(struct device *dev) { struct root_device *root = to_root_device(dev); if (root->owner) sysfs_remove_link(&root->dev.kobj, "module"); device_unregister(dev); } EXPORT_SYMBOL_GPL(root_device_unregister); static void device_create_release(struct device *dev) { pr_debug("device: '%s': %s\n", dev_name(dev), __func__); kfree(dev); } static struct device * device_create_groups_vargs(struct class *class, struct device *parent, dev_t devt, void *drvdata, const struct attribute_group **groups, const char *fmt, va_list args) { struct device *dev = NULL; int retval = -ENODEV; if (class == NULL || IS_ERR(class)) goto error; /* OyTao: 创建一个device object */ dev = kzalloc(sizeof(*dev), GFP_KERNEL); if (!dev) { retval = -ENOMEM; goto error; } device_initialize(dev); dev->devt = devt; dev->class = class; dev->parent = parent; dev->groups = groups; dev->release = device_create_release; dev_set_drvdata(dev, drvdata); retval = kobject_set_name_vargs(&dev->kobj, fmt, args); if (retval) goto error; /* OyTao: 添加device至Kobject */ retval = device_add(dev); if (retval) goto error; return dev; error: put_device(dev); return ERR_PTR(retval); } /** * device_create_vargs - creates a device and registers it with sysfs * @class: pointer to the struct class that this device should be registered to * @parent: pointer to the parent struct device of this new device, if any * @devt: the dev_t for the char device to be added * @drvdata: the data to be added to the device for callbacks * @fmt: string for the device's name * @args: va_list for the device's name * * This function can be used by char device classes. A struct device * will be created in sysfs, registered to the specified class. * * A "dev" file will be created, showing the dev_t for the device, if * the dev_t is not 0,0. * If a pointer to a parent struct device is passed in, the newly created * struct device will be a child of that device in sysfs. * The pointer to the struct device will be returned from the call. * Any further sysfs files that might be required can be created using this * pointer. * * Returns &struct device pointer on success, or ERR_PTR() on error. * * Note: the struct class passed to this function must have previously * been created with a call to class_create(). */ struct device *device_create_vargs(struct class *class, struct device *parent, dev_t devt, void *drvdata, const char *fmt, va_list args) { return device_create_groups_vargs(class, parent, devt, drvdata, NULL, fmt, args); } EXPORT_SYMBOL_GPL(device_create_vargs); /** * device_create - creates a device and registers it with sysfs * @class: pointer to the struct class that this device should be registered to * @parent: pointer to the parent struct device of this new device, if any * @devt: the dev_t for the char device to be added * @drvdata: the data to be added to the device for callbacks * @fmt: string for the device's name * * This function can be used by char device classes. A struct device * will be created in sysfs, registered to the specified class. * * A "dev" file will be created, showing the dev_t for the device, if * the dev_t is not 0,0. * If a pointer to a parent struct device is passed in, the newly created * struct device will be a child of that device in sysfs. * The pointer to the struct device will be returned from the call. * Any further sysfs files that might be required can be created using this * pointer. * * Returns &struct device pointer on success, or ERR_PTR() on error. * * Note: the struct class passed to this function must have previously * been created with a call to class_create(). */ struct device *device_create(struct class *class, struct device *parent, dev_t devt, void *drvdata, const char *fmt, ...) { va_list vargs; struct device *dev; va_start(vargs, fmt); dev = device_create_vargs(class, parent, devt, drvdata, fmt, vargs); va_end(vargs); return dev; } EXPORT_SYMBOL_GPL(device_create); /** * device_create_with_groups - creates a device and registers it with sysfs * @class: pointer to the struct class that this device should be registered to * @parent: pointer to the parent struct device of this new device, if any * @devt: the dev_t for the char device to be added * @drvdata: the data to be added to the device for callbacks * @groups: NULL-terminated list of attribute groups to be created * @fmt: string for the device's name * * This function can be used by char device classes. A struct device * will be created in sysfs, registered to the specified class. * Additional attributes specified in the groups parameter will also * be created automatically. * * A "dev" file will be created, showing the dev_t for the device, if * the dev_t is not 0,0. * If a pointer to a parent struct device is passed in, the newly created * struct device will be a child of that device in sysfs. * The pointer to the struct device will be returned from the call. * Any further sysfs files that might be required can be created using this * pointer. * * Returns &struct device pointer on success, or ERR_PTR() on error. * * Note: the struct class passed to this function must have previously * been created with a call to class_create(). */ struct device *device_create_with_groups(struct class *class, struct device *parent, dev_t devt, void *drvdata, const struct attribute_group **groups, const char *fmt, ...) { va_list vargs; struct device *dev; va_start(vargs, fmt); dev = device_create_groups_vargs(class, parent, devt, drvdata, groups, fmt, vargs); va_end(vargs); return dev; } EXPORT_SYMBOL_GPL(device_create_with_groups); static int __match_devt(struct device *dev, const void *data) { const dev_t *devt = data; return dev->devt == *devt; } /** * device_destroy - removes a device that was created with device_create() * @class: pointer to the struct class that this device was registered with * @devt: the dev_t of the device that was previously registered * * This call unregisters and cleans up a device that was created with a * call to device_create(). */ void device_destroy(struct class *class, dev_t devt) { struct device *dev; dev = class_find_device(class, NULL, &devt, __match_devt); if (dev) { put_device(dev); device_unregister(dev); } } EXPORT_SYMBOL_GPL(device_destroy); /** * device_rename - renames a device * @dev: the pointer to the struct device to be renamed * @new_name: the new name of the device * * It is the responsibility of the caller to provide mutual * exclusion between two different calls of device_rename * on the same device to ensure that new_name is valid and * won't conflict with other devices. * * Note: Don't call this function. Currently, the networking layer calls this * function, but that will change. The following text from Kay Sievers offers * some insight: * * Renaming devices is racy at many levels, symlinks and other stuff are not * replaced atomically, and you get a "move" uevent, but it's not easy to * connect the event to the old and new device. Device nodes are not renamed at * all, there isn't even support for that in the kernel now. * * In the meantime, during renaming, your target name might be taken by another * driver, creating conflicts. Or the old name is taken directly after you * renamed it -- then you get events for the same DEVPATH, before you even see * the "move" event. It's just a mess, and nothing new should ever rely on * kernel device renaming. Besides that, it's not even implemented now for * other things than (driver-core wise very simple) network devices. * * We are currently about to change network renaming in udev to completely * disallow renaming of devices in the same namespace as the kernel uses, * because we can't solve the problems properly, that arise with swapping names * of multiple interfaces without races. Means, renaming of eth[0-9]* will only * be allowed to some other name than eth[0-9]*, for the aforementioned * reasons. * * Make up a "real" name in the driver before you register anything, or add * some other attributes for userspace to find the device, or use udev to add * symlinks -- but never rename kernel devices later, it's a complete mess. We * don't even want to get into that and try to implement the missing pieces in * the core. We really have other pieces to fix in the driver core mess. :) */ int device_rename(struct device *dev, const char *new_name) { struct kobject *kobj = &dev->kobj; char *old_device_name = NULL; int error; dev = get_device(dev); if (!dev) return -EINVAL; dev_dbg(dev, "renaming to %s\n", new_name); old_device_name = kstrdup(dev_name(dev), GFP_KERNEL); if (!old_device_name) { error = -ENOMEM; goto out; } if (dev->class) { error = sysfs_rename_link_ns(&dev->class->p->subsys.kobj, kobj, old_device_name, new_name, kobject_namespace(kobj)); if (error) goto out; } error = kobject_rename(kobj, new_name); if (error) goto out; out: put_device(dev); kfree(old_device_name); return error; } EXPORT_SYMBOL_GPL(device_rename); static int device_move_class_links(struct device *dev, struct device *old_parent, struct device *new_parent) { int error = 0; if (old_parent) sysfs_remove_link(&dev->kobj, "device"); if (new_parent) error = sysfs_create_link(&dev->kobj, &new_parent->kobj, "device"); return error; } /** * device_move - moves a device to a new parent * @dev: the pointer to the struct device to be moved * @new_parent: the new parent of the device (can by NULL) * @dpm_order: how to reorder the dpm_list */ int device_move(struct device *dev, struct device *new_parent, enum dpm_order dpm_order) { int error; struct device *old_parent; struct kobject *new_parent_kobj; dev = get_device(dev); if (!dev) return -EINVAL; device_pm_lock(); new_parent = get_device(new_parent); new_parent_kobj = get_device_parent(dev, new_parent); pr_debug("device: '%s': %s: moving to '%s'\n", dev_name(dev), __func__, new_parent ? dev_name(new_parent) : "<NULL>"); error = kobject_move(&dev->kobj, new_parent_kobj); if (error) { cleanup_glue_dir(dev, new_parent_kobj); put_device(new_parent); goto out; } old_parent = dev->parent; dev->parent = new_parent; if (old_parent) klist_remove(&dev->p->knode_parent); if (new_parent) { klist_add_tail(&dev->p->knode_parent, &new_parent->p->klist_children); set_dev_node(dev, dev_to_node(new_parent)); } if (dev->class) { error = device_move_class_links(dev, old_parent, new_parent); if (error) { /* We ignore errors on cleanup since we're hosed anyway... */ device_move_class_links(dev, new_parent, old_parent); if (!kobject_move(&dev->kobj, &old_parent->kobj)) { if (new_parent) klist_remove(&dev->p->knode_parent); dev->parent = old_parent; if (old_parent) { klist_add_tail(&dev->p->knode_parent, &old_parent->p->klist_children); set_dev_node(dev, dev_to_node(old_parent)); } } cleanup_glue_dir(dev, new_parent_kobj); put_device(new_parent); goto out; } } switch (dpm_order) { case DPM_ORDER_NONE: break; case DPM_ORDER_DEV_AFTER_PARENT: device_pm_move_after(dev, new_parent); devices_kset_move_after(dev, new_parent); break; case DPM_ORDER_PARENT_BEFORE_DEV: device_pm_move_before(new_parent, dev); devices_kset_move_before(new_parent, dev); break; case DPM_ORDER_DEV_LAST: device_pm_move_last(dev); devices_kset_move_last(dev); break; } put_device(old_parent); out: device_pm_unlock(); put_device(dev); return error; } EXPORT_SYMBOL_GPL(device_move); /** * device_shutdown - call ->shutdown() on each device to shutdown. */ void device_shutdown(void) { struct device *dev, *parent; spin_lock(&devices_kset->list_lock); /* * Walk the devices list backward, shutting down each in turn. * Beware that device unplug events may also start pulling * devices offline, even as the system is shutting down. */ while (!list_empty(&devices_kset->list)) { dev = list_entry(devices_kset->list.prev, struct device, kobj.entry); /* * hold reference count of device's parent to * prevent it from being freed because parent's * lock is to be held */ parent = get_device(dev->parent); get_device(dev); /* * Make sure the device is off the kset list, in the * event that dev->*->shutdown() doesn't remove it. */ list_del_init(&dev->kobj.entry); spin_unlock(&devices_kset->list_lock); /* hold lock to avoid race with probe/release */ if (parent) device_lock(parent); device_lock(dev); /* Don't allow any more runtime suspends */ pm_runtime_get_noresume(dev); pm_runtime_barrier(dev); if (dev->bus && dev->bus->shutdown) { if (initcall_debug) dev_info(dev, "shutdown\n"); dev->bus->shutdown(dev); } else if (dev->driver && dev->driver->shutdown) { if (initcall_debug) dev_info(dev, "shutdown\n"); dev->driver->shutdown(dev); } device_unlock(dev); if (parent) device_unlock(parent); put_device(dev); put_device(parent); spin_lock(&devices_kset->list_lock); } spin_unlock(&devices_kset->list_lock); } /* * Device logging functions */ #ifdef CONFIG_PRINTK static int create_syslog_header(const struct device *dev, char *hdr, size_t hdrlen) { const char *subsys; size_t pos = 0; if (dev->class) subsys = dev->class->name; else if (dev->bus) subsys = dev->bus->name; else return 0; pos += snprintf(hdr + pos, hdrlen - pos, "SUBSYSTEM=%s", subsys); if (pos >= hdrlen) goto overflow; /* * Add device identifier DEVICE=: * b12:8 block dev_t * c127:3 char dev_t * n8 netdev ifindex * +sound:card0 subsystem:devname */ if (MAJOR(dev->devt)) { char c; if (strcmp(subsys, "block") == 0) c = 'b'; else c = 'c'; pos++; pos += snprintf(hdr + pos, hdrlen - pos, "DEVICE=%c%u:%u", c, MAJOR(dev->devt), MINOR(dev->devt)); } else if (strcmp(subsys, "net") == 0) { struct net_device *net = to_net_dev(dev); pos++; pos += snprintf(hdr + pos, hdrlen - pos, "DEVICE=n%u", net->ifindex); } else { pos++; pos += snprintf(hdr + pos, hdrlen - pos, "DEVICE=+%s:%s", subsys, dev_name(dev)); } if (pos >= hdrlen) goto overflow; return pos; overflow: dev_WARN(dev, "device/subsystem name too long"); return 0; } int dev_vprintk_emit(int level, const struct device *dev, const char *fmt, va_list args) { char hdr[128]; size_t hdrlen; hdrlen = create_syslog_header(dev, hdr, sizeof(hdr)); return vprintk_emit(0, level, hdrlen ? hdr : NULL, hdrlen, fmt, args); } EXPORT_SYMBOL(dev_vprintk_emit); int dev_printk_emit(int level, const struct device *dev, const char *fmt, ...) { va_list args; int r; va_start(args, fmt); r = dev_vprintk_emit(level, dev, fmt, args); va_end(args); return r; } EXPORT_SYMBOL(dev_printk_emit); static void __dev_printk(const char *level, const struct device *dev, struct va_format *vaf) { if (dev) dev_printk_emit(level[1] - '0', dev, "%s %s: %pV", dev_driver_string(dev), dev_name(dev), vaf); else printk("%s(NULL device *): %pV", level, vaf); } void dev_printk(const char *level, const struct device *dev, const char *fmt, ...) { struct va_format vaf; va_list args; va_start(args, fmt); vaf.fmt = fmt; vaf.va = &args; __dev_printk(level, dev, &vaf); va_end(args); } EXPORT_SYMBOL(dev_printk); #define define_dev_printk_level(func, kern_level) \ void func(const struct device *dev, const char *fmt, ...) \ { \ struct va_format vaf; \ va_list args; \ \ va_start(args, fmt); \ \ vaf.fmt = fmt; \ vaf.va = &args; \ \ __dev_printk(kern_level, dev, &vaf); \ \ va_end(args); \ } \ EXPORT_SYMBOL(func); define_dev_printk_level(dev_emerg, KERN_EMERG); define_dev_printk_level(dev_alert, KERN_ALERT); define_dev_printk_level(dev_crit, KERN_CRIT); define_dev_printk_level(dev_err, KERN_ERR); define_dev_printk_level(dev_warn, KERN_WARNING); define_dev_printk_level(dev_notice, KERN_NOTICE); define_dev_printk_level(_dev_info, KERN_INFO); #endif static inline bool fwnode_is_primary(struct fwnode_handle *fwnode) { return fwnode && !IS_ERR(fwnode->secondary); } /** * set_primary_fwnode - Change the primary firmware node of a given device. * @dev: Device to handle. * @fwnode: New primary firmware node of the device. * * Set the device's firmware node pointer to @fwnode, but if a secondary * firmware node of the device is present, preserve it. */ void set_primary_fwnode(struct device *dev, struct fwnode_handle *fwnode) { if (fwnode) { struct fwnode_handle *fn = dev->fwnode; if (fwnode_is_primary(fn)) fn = fn->secondary; if (fn) { WARN_ON(fwnode->secondary); fwnode->secondary = fn; } dev->fwnode = fwnode; } else { dev->fwnode = fwnode_is_primary(dev->fwnode) ? dev->fwnode->secondary : NULL; } } EXPORT_SYMBOL_GPL(set_primary_fwnode); /** * set_secondary_fwnode - Change the secondary firmware node of a given device. * @dev: Device to handle. * @fwnode: New secondary firmware node of the device. * * If a primary firmware node of the device is present, set its secondary * pointer to @fwnode. Otherwise, set the device's firmware node pointer to * @fwnode. */ void set_secondary_fwnode(struct device *dev, struct fwnode_handle *fwnode) { if (fwnode) fwnode->secondary = ERR_PTR(-ENODEV); if (fwnode_is_primary(dev->fwnode)) dev->fwnode->secondary = fwnode; else dev->fwnode = fwnode; }
OyTao/linux-4.9-src
drivers/base/core.c
C
gpl-2.0
60,563
! ! Copyright (C) 2004 PWSCF group ! This file is distributed under the terms of the ! GNU General Public License. See the file `License' ! in the root directory of the present distribution, ! or http://www.gnu.org/copyleft/gpl.txt . ! ! !----------------------------------------------------------------------- subroutine set_rho_core !----------------------------------------------------------------------- ! ! input : all-electron wavefunctions + valence states ! output: smoothed core charge for r > rcore ! use kinds, only : dp use constants, only : pi use io_global, only : stdout, ionode, ionode_id use mp, only : mp_bcast use mp_world, only : world_comm use ld1inc, only : nlcc, grid, rhoc, aeccharge, psccharge, rcore, & nwf, oc, rel, core_state, psi, file_core, new_core_ps,& lpaw, lnc2paw, aectau, aevtau, isw implicit none real(DP) :: drho, const, br1, br2, & eps1, eps2, br12, xc(8), a, b, eps12, totrho real(DP), allocatable:: rhov(:) real(DP), allocatable:: gradpsi(:,:), gradrho(:) real(DP), external :: int_0_inf_dr integer :: i, ik, n, ns, ios, is if (nlcc) then write(stdout,'(/,5x,'' Computing core charge for nlcc: '')') else if (lpaw) write(stdout,'(/,5x,'' Computing core charge for PAW: '')') end if allocate (rhov(grid%mesh)) ! ! calculates core charge density ! do n=1,grid%mesh rhov(n) = 0.0_dp rhoc(n) = 0.0_dp do ns=1,nwf if (rel==2) then if (core_state(ns)) then rhoc(n)=rhoc(n)+oc(ns)*(psi(n,1,ns)**2+psi(n,2,ns)**2) else rhov(n)=rhov(n)+oc(ns)*(psi(n,1,ns)**2+psi(n,2,ns)**2) endif else if (core_state(ns)) then rhoc(n) = rhoc(n) + oc(ns)*psi(n,1,ns)**2 else rhov(n) = rhov(n) + oc(ns)*psi(n,1,ns)**2 endif endif enddo enddo totrho = int_0_inf_dr(rhoc,grid,grid%mesh,2) if (totrho<1.d-6.and.lpaw) then ! ! All valence charge for this atom (mainly for H) ! aeccharge(1:grid%mesh) = 0.0_DP psccharge(1:grid%mesh) = 0.0_DP goto 1100 endif ! ! calculates core tau density ! allocate( gradpsi(grid%mesh,2), gradrho(grid%mesh) ) aevtau=0.0_DP aectau=0.0_DP do ns=1,nwf if (oc(ns)>0.0_DP) then is=isw(ns) call grad_log(psi(1,1,ns), gradpsi(1,1), grid%rm1, grid%dx, grid%mesh, 4) call grad_log(psi(1,2,ns), gradpsi(1,2), grid%rm1, grid%dx, grid%mesh, 4) do n=1,grid%mesh if (rel==2) then if (core_state(ns)) then aectau(n)=aectau(n) & +oc(ns)*( gradpsi(n,1)**2 + gradpsi(n,2)**2 ) else aevtau(n,is)=aevtau(n,is)+oc(ns)*(gradpsi(n,1)**2 & + gradpsi(n,2)**2) endif else if (core_state(ns)) then aectau(n) = aectau(n) + oc(ns)*gradpsi(n,1)**2 else aevtau(n,is) = aevtau(n,is) + oc(ns)*gradpsi(n,1)**2 endif endif enddo endif enddo ! write(stdout,'("Integrated core charge",f15.10)') totrho aeccharge(1:grid%mesh) = rhoc(1:grid%mesh) ! if (rcore > 0.0_dp) then ! rcore read on input do ik=1,grid%mesh if (grid%r(ik) > rcore) go to 100 enddo call infomsg('set_rho_core','rcore too big') return else ! rcore determined by the condition rhoc(rcore) = 2*rhov(rcore) do ik=1,grid%mesh if (rhoc(ik) < 2.0 * rhov(ik)) go to 100 enddo end if 100 rcore=grid%r(ik) drho = ( rhoc(ik+1)/grid%r2(ik+1) - rhoc(ik)/grid%r2(ik) ) / grid%dx / grid%r(ik) ! ! true_rho = rhoc(r)/r**2/4 pi ! (factor 1/r from logarithmic mesh) ! smoothened core charge density for nonlinear core correction: ! rhoc(r) = core charge for r > rcore ! rhoc(r) = r^2 a sin(b r)/r for r < rcore ! if (new_core_ps) then call compute_phius(1,ik,aeccharge,rhoc,xc,0,' ') else if (drho > 0.0_dp) then call infomsg('set_rho_core','d rho/ d r > 0') return endif const= grid%r(ik)*drho / ( rhoc(ik)/grid%r2(ik) ) + 1.0_dp if (const > 0.0_dp) then br1 = 0.00001_dp br2 = pi/2.0_dp-0.00001_dp else br1 = pi/2.0_dp+0.00001_dp br2 = pi end if do n=1, 15 eps1 = br1 - const*tan(br1) eps2 = br2 - const*tan(br2) br12 = (br1+br2)/2.0_dp eps12 = br12 - const*tan(br12) if(eps1*eps12 < 0.0_dp) then br2 = br12 else if(eps12*eps2 < 0.0_dp) then br1 = br12 else call errore('set_rho_core','error in bisection',n) end if end do b = br12/grid%r(ik) a = ( rhoc(ik)/grid%r2(ik) ) * grid%r(ik)/sin(br12) do n=1,ik rhoc(n) = a*sin(b*grid%r(n))/grid%r(n) * grid%r2(n) end do endif if (lpaw) then if (lnc2paw) then ! Mimic NC calculation. If NLCC, the pseudized core charge. if (nlcc) then aeccharge(1:grid%mesh) = rhoc(1:grid%mesh) ! Here one could set another pseudized ccharge, for ! example with a larger matching radius. Right now, ! just take the same as the AE (ie NC) one: psccharge(1:grid%mesh) = rhoc(1:grid%mesh) else ! Reference NC calculation does not have core charge. aeccharge(1:grid%mesh) = 0._dp psccharge(1:grid%mesh) = 0._dp end if else ! aeccharge(1:grid%mesh) = rhoc(1:grid%mesh) if (nlcc) then psccharge(1:grid%mesh) = rhoc(1:grid%mesh) else psccharge(1:grid%mesh) = 0._dp end if end if end if write(stdout,'(/,5x,'' r > '',f4.2,'' : true rho core'')') grid%r(ik) if (new_core_ps) then write(stdout,'(6x,"Core charge pseudized with two Bessel functions")') else write(stdout,110) grid%r(ik), a, b endif 110 format (5x, ' r < ',f4.2,' : rho core = a sin(br)/r', & ' a=',f7.2,' b=',f7.2/) 1100 continue if (file_core .ne. ' ') then write(stdout,'(6x, "***Writing file ",a, " ***")') trim(file_core) if (ionode) & open(unit=26,file=file_core, status='unknown', iostat=ios, err=300 ) 300 call mp_bcast(ios, ionode_id, world_comm) call errore('set_rho_core','opening file '//file_core,abs(ios)) if (ionode) then if (totrho>1.d-6) then do n=1,grid%mesh write(26,'(4f20.10)') grid%r(n),rhoc(n),rhov(n),aeccharge(n) enddo else do n=1,grid%mesh write(26,'(2f20.10)') grid%r(n),rhov(n) enddo endif close(26) endif if (ionode) open(unit=26,file=trim(file_core)//'_tau', status='unknown', iostat=ios, err=301 ) 301 call mp_bcast(ios, ionode_id, world_comm) call errore('set_rho_core','opening file '//file_core//'_tau',abs(ios)) if (ionode) then call grad_log(rhoc(:)+rhov(:), gradrho(:), grid%rm1, grid%dx, grid%mesh, 4) do n=1,grid%mesh write(26,'(5f20.10)') grid%r(n), max(rhoc(n)+rhov(n),1d-10), gradrho(n)**2.d0, aectau(n), aevtau(n,1)+aevtau(n,2) enddo close(26) endif endif totrho = int_0_inf_dr(rhoc,grid,grid%mesh,2) write(stdout,'(6x,''Integrated core pseudo-charge : '',f6.2)') totrho if (.not.nlcc) rhoc(1:grid%mesh) = 0.0_dp deallocate (rhov) return end subroutine set_rho_core
dceresoli/ce-espresso
atomic/src/set_rho_core.f90
FORTRAN
gpl-2.0
7,601
<?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
// SONIC ROBO BLAST 2 //----------------------------------------------------------------------------- // Copyright (C) 1998-2000 by DooM Legacy Team. // Copyright (C) 1999-2019 by Sonic Team Junior. // // This program is free software distributed under the // terms of the GNU General Public License, version 2. // See the 'LICENSE' file for more details. //----------------------------------------------------------------------------- /// \file r_splats.h /// \brief Flat sprites & splats effects #ifndef __R_SPLATS_H__ #define __R_SPLATS_H__ #include "r_defs.h" //#define WALLSPLATS // comment this out to compile without splat effects /*#ifdef USEASM #define FLOORSPLATS #endif*/ #define MAXLEVELSPLATS 1024 // splat flags #define SPLATDRAWMODE_MASK 0x03 // mask to get drawmode from flags #define SPLATDRAWMODE_OPAQUE 0x00 #define SPLATDRAWMODE_SHADE 0x01 #define SPLATDRAWMODE_TRANS 0x02 // ========================================================================== // DEFINITIONS // ========================================================================== // WALL SPLATS are patches drawn on top of wall segs typedef struct wallsplat_s { lumpnum_t patch; // lump id. vertex_t v1, v2; // vertices along the linedef fixed_t top; fixed_t offset; // offset in columns<<FRACBITS from start of linedef to start of splat INT32 flags; fixed_t *yoffset; line_t *line; // the parent line of the splat seg struct wallsplat_s *next; } wallsplat_t; // FLOOR SPLATS are pic_t (raw horizontally stored) drawn on top of the floor or ceiling typedef struct floorsplat_s { lumpnum_t pic; // a pic_t lump id INT32 flags; INT32 size; // 64, 128, 256, etc. vertex_t verts[4]; // (x,y) as viewn from above on map fixed_t z; // z (height) is constant for all the floorsplats subsector_t *subsector; // the parent subsector mobj_t *mobj; // Mobj it is tied to struct floorsplat_s *next; struct floorsplat_s *nextvis; } floorsplat_t; // p_setup.c fixed_t P_SegLength(seg_t *seg); // call at P_SetupLevel() void R_ClearLevelSplats(void); #ifdef WALLSPLATS void R_AddWallSplat(line_t *wallline, INT16 sectorside, const char *patchname, fixed_t top, fixed_t wallfrac, INT32 flags); #endif #ifdef FLOORSPLATS void R_AddFloorSplat(subsector_t *subsec, mobj_t *mobj, const char *picname, fixed_t x, fixed_t y, fixed_t z, INT32 flags); #endif void R_ClearVisibleFloorSplats(void); void R_AddVisibleFloorSplats(subsector_t *subsec); void R_DrawVisibleFloorSplats(void); #endif /*__R_SPLATS_H__*/
Yukitty/SRB2
src/r_splats.h
C
gpl-2.0
2,514
@import "jquery-ui.custom.modified.css"; .ui-menu .ui-menu-item { padding: 3px 0 3px 0; } .ui-menu .ui-menu-item .ui-menu-item-wrapper { display: block; } .ui-menu .ui-menu-item .ui-state-active { border: none; margin: 0; text-decoration: none; } .ui-menu .ui-menu-item:hover, .ui-menu .ui-menu-item:hover .ui-state-active { background: #CFDEFF; }
bestpractical/rt
share/static/css/elevator-light/jquery-ui.css
CSS
gpl-2.0
364
<?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
-- Make mrbs_entry.repeat_id a foreign key -- Previously repeat_id was set to zero if there was no repeat. -- However this breaks our foreign key constraint so we have to modify -- the repeat_id column before we can create the foreign key. ALTER TABLE %DB_TBL_PREFIX%entry ALTER COLUMN repeat_id DROP DEFAULT, ALTER COLUMN repeat_id DROP NOT NULL, ALTER COLUMN repeat_id SET DEFAULT NULL; UPDATE %DB_TBL_PREFIX%entry SET repeat_id=NULL WHERE repeat_id=0; -- Tidy up the database getting rid of any zombie rows which would prevent -- the foreign key being created. Note that these rows will not be visible to users -- and admins through MRBS. They have most likely been created when a row has been -- deleted from a table using a database admin tool, rather than through MRBS. Of course, -- foreign keys will stop this happening in the future. DELETE FROM %DB_TBL_PREFIX%entry WHERE repeat_id IS NOT NULL AND repeat_id NOT IN (SELECT id FROM %DB_TBL_PREFIX%repeat); -- Also, while we're at it, get rid of any redundant entries in the repeat table, ie rows -- that are not referenced by a row in the entry table. DELETE FROM %DB_TBL_PREFIX%repeat WHERE id NOT IN (SELECT repeat_id FROM %DB_TBL_PREFIX%entry WHERE repeat_id IS NOT NULL); ALTER TABLE %DB_TBL_PREFIX%entry ADD FOREIGN KEY (repeat_id) REFERENCES %DB_TBL_PREFIX%repeat(id) ON UPDATE CASCADE ON DELETE CASCADE;
bingliang-zh/KUJIALE-mrbs
mrbs-1.6.1/web/upgrade/41/pgsql.sql
SQL
gpl-2.0
1,422
27 mtime=1392885435.711233 27 atime=1392905854.839854 30 ctime=1392905854.839854587
heidiao/i2c_test_tool
eepromer/PaxHeaders.30826/eepromer.c
C
gpl-2.0
84
/* packet-lapd.c * Routines for LAPD frame disassembly * Gilbert Ramirez <gram@alumni.rice.edu> * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 * * 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. */ /* * LAPD bitstream over RTP handling * Copyright 2008, Ericsson AB * Written by Balint Reczey <balint.reczey@ericsson.com> * * ISDN/LAPD references: * * http://www.cisco.com/univercd/cc/td/doc/cisintwk/ito_doc/isdn.htm * http://www.ece.wpi.edu/courses/ee535/hwk11cd95/agrebe/agrebe.html * http://www.acacia-net.com/Clarinet/Protocol/q9213o84.htm * http://www.itu.int/rec/T-REC-Q.921/en * Base Station Controller - Base Transceiver Station (BSC - BTS) interface; Layer 2 specification * http://www.3gpp.org/ftp/Specs/html-info/48056.htm */ #include "config.h" #include <epan/packet.h> #include <epan/conversation.h> #include <epan/xdlc.h> #include <epan/crc16-tvb.h> #include <epan/prefs.h> #include <wiretap/wtap.h> #include <epan/lapd_sapi.h> #include <epan/expert.h> #include "packet-l2tp.h" void proto_register_lapd(void); void proto_reg_handoff_lapd(void); static int proto_lapd = -1; static int hf_lapd_direction = -1; static int hf_lapd_address = -1; static int hf_lapd_sapi = -1; static int hf_lapd_gsm_sapi = -1; static int hf_lapd_cr = -1; static int hf_lapd_ea1 = -1; static int hf_lapd_tei = -1; static int hf_lapd_ea2 = -1; static int hf_lapd_control = -1; static int hf_lapd_n_r = -1; static int hf_lapd_n_s = -1; static int hf_lapd_p = -1; static int hf_lapd_p_ext = -1; static int hf_lapd_f = -1; static int hf_lapd_f_ext = -1; static int hf_lapd_s_ftype = -1; static int hf_lapd_u_modifier_cmd = -1; static int hf_lapd_u_modifier_resp = -1; static int hf_lapd_ftype_i = -1; static int hf_lapd_ftype_s_u = -1; static int hf_lapd_ftype_s_u_ext = -1; static int hf_lapd_checksum = -1; static int hf_lapd_checksum_good = -1; static int hf_lapd_checksum_bad = -1; static gint ett_lapd = -1; static gint ett_lapd_address = -1; static gint ett_lapd_control = -1; static gint ett_lapd_checksum = -1; static gint pref_lapd_rtp_payload_type = 0; static expert_field ei_lapd_abort = EI_INIT; static expert_field ei_lapd_checksum_bad = EI_INIT; static dissector_table_t lapd_sapi_dissector_table; static dissector_table_t lapd_gsm_sapi_dissector_table; /* Whether to use GSM SAPI vals or not */ static gboolean global_lapd_gsm_sapis = FALSE; static dissector_handle_t data_handle; /* * Bits in the address field. */ #define LAPD_SAPI 0xfc00 /* Service Access Point Identifier */ #define LAPD_SAPI_SHIFT 10 #define LAPD_CR 0x0200 /* Command/Response bit */ #define LAPD_EA1 0x0100 /* First Address Extension bit */ #define LAPD_TEI 0x00fe /* Terminal Endpoint Identifier */ #define LAPD_TEI_SHIFT 1 #define LAPD_EA2 0x0001 /* Second Address Extension bit */ static const value_string lapd_direction_vals[] = { { P2P_DIR_RECV, "Network->User"}, { P2P_DIR_SENT, "User->Network"}, { 0, NULL } }; static const value_string lapd_sapi_vals[] = { { LAPD_SAPI_Q931, "Q.931 Call control procedure" }, { LAPD_SAPI_PM_Q931, "Packet mode Q.931 Call control procedure" }, { LAPD_SAPI_X25, "X.25 Level 3 procedures" }, { LAPD_SAPI_L2, "Layer 2 management procedures" }, { 0, NULL } }; static const value_string lapd_gsm_sapi_vals[] = { { LAPD_GSM_SAPI_RA_SIG_PROC, "Radio signalling procedures" }, { LAPD_GSM_SAPI_NOT_USED_1, "(Not used in GSM PLMN)" }, { LAPD_GSM_SAPI_NOT_USED_16, "(Not used in GSM PLMN)" }, { LAPD_GSM_SAPI_OM_PROC, "Operation and maintenance procedure" }, { LAPD_SAPI_L2, "Layer 2 management procedures" }, { 0, NULL } }; /* Used only for U frames */ static const xdlc_cf_items lapd_cf_items = { NULL, NULL, &hf_lapd_p, &hf_lapd_f, NULL, &hf_lapd_u_modifier_cmd, &hf_lapd_u_modifier_resp, NULL, &hf_lapd_ftype_s_u }; /* Used only for I and S frames */ static const xdlc_cf_items lapd_cf_items_ext = { &hf_lapd_n_r, &hf_lapd_n_s, &hf_lapd_p_ext, &hf_lapd_f_ext, &hf_lapd_s_ftype, NULL, NULL, &hf_lapd_ftype_i, &hf_lapd_ftype_s_u_ext }; #define MAX_LAPD_PACKET_LEN 1024 /* LAPD frame detection state */ enum lapd_bitstream_states {OUT_OF_SYNC, FLAGS, DATA}; typedef struct lapd_byte_state { enum lapd_bitstream_states state; /* frame detection state */ char full_byte; /* part of a full byte */ char bit_offset; /* number of bits already got in the full byte */ int ones; /* number of consecutive ones since the last zero */ char data[MAX_LAPD_PACKET_LEN]; int data_len; } lapd_byte_state_t; typedef struct lapd_ppi { gboolean has_crc; /* CRC is captured with LAPD the frames */ lapd_byte_state_t start_byte_state; /* LAPD bitstream byte state at the beginnigng of processing the packet */ } lapd_ppi_t; /* Fill values in lapd_byte_state struct */ static void fill_lapd_byte_state(lapd_byte_state_t *ptr, enum lapd_bitstream_states state, char full_byte, char bit_offset, int ones, char *data, int data_len) { ptr->state = state; ptr->full_byte = full_byte; ptr->bit_offset = bit_offset; ptr->ones = ones; ptr->data_len = MIN((int)sizeof(ptr->data), data_len); memcpy(ptr->data, data, ptr->data_len); } typedef struct lapd_convo_data { address addr_a; address addr_b; guint32 port_a; guint32 port_b; lapd_byte_state_t *byte_state_a; lapd_byte_state_t *byte_state_b; } lapd_convo_data_t; static void dissect_lapd_full(tvbuff_t*, packet_info*, proto_tree*, gboolean); /* got new LAPD frame byte */ static void new_byte(char full_byte, char data[], int *data_len) { if (*data_len < MAX_LAPD_PACKET_LEN) { data[*data_len] = full_byte; (*data_len)++; } else { /* XXX : we are not prepared for that big messages, drop the last byte */ } } static void lapd_log_abort(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, guint offset, const char *msg) { proto_item *ti; ti = proto_tree_add_item(tree, proto_lapd, tvb, offset, 1, ENC_NA); expert_add_info_format(pinfo, ti, &ei_lapd_abort, "%s", msg); } static int dissect_lapd_bitstream(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* dissector_data _U_) { guint8 byte, full_byte = 0x00, bit_offset = 0; gboolean bit; guint8 i, ones = 0, data[MAX_LAPD_PACKET_LEN]; int data_len = 0; gint offset = 0, available; guint8 *buff; tvbuff_t *new_tvb; enum lapd_bitstream_states state = OUT_OF_SYNC; lapd_ppi_t *lapd_ppi; conversation_t *conversation = NULL; lapd_convo_data_t *convo_data = NULL; lapd_byte_state_t *lapd_byte_state, *prev_byte_state = NULL; gboolean forward_stream = TRUE; /* get remaining data from previous packets */ conversation = find_or_create_conversation(pinfo); lapd_ppi = (lapd_ppi_t*)p_get_proto_data(wmem_file_scope(), pinfo, proto_lapd, 0); if (lapd_ppi) { prev_byte_state = &lapd_ppi->start_byte_state; if (prev_byte_state) { state = prev_byte_state->state; full_byte = prev_byte_state->full_byte; bit_offset = prev_byte_state->bit_offset; ones = prev_byte_state->ones; memcpy(data, prev_byte_state->data, prev_byte_state->data_len); data_len = prev_byte_state->data_len; } } else if (conversation) { convo_data = (lapd_convo_data_t*)conversation_get_proto_data(conversation, proto_lapd); if (NULL != convo_data) { if (addresses_equal(&convo_data->addr_a, &pinfo->src) && addresses_equal(&convo_data->addr_b, &pinfo->dst) && convo_data-> port_a == pinfo->srcport && convo_data-> port_b == pinfo->destport) { /* "forward" direction */ forward_stream = TRUE; prev_byte_state = convo_data->byte_state_a; } else if (addresses_equal(&convo_data-> addr_b, &pinfo->src) && addresses_equal(&convo_data->addr_a, &pinfo->dst) && convo_data-> port_b == pinfo->srcport && convo_data-> port_a == pinfo->destport) { /* "backward" direction */ forward_stream = FALSE; prev_byte_state = convo_data->byte_state_b; } } if (prev_byte_state) { state = prev_byte_state->state; full_byte = prev_byte_state->full_byte; bit_offset = prev_byte_state->bit_offset; ones = prev_byte_state->ones; memcpy(data, prev_byte_state->data, prev_byte_state->data_len); data_len = prev_byte_state->data_len; } } /* Consume tvb bytes */ available = tvb_reported_length_remaining(tvb, offset); while (offset < available) { byte = tvb_get_guint8(tvb,offset); offset++; for (i=0; i < 8; i++) { /* cycle through bits */ bit = byte & (0x80 >> i) ? TRUE : FALSE; /* consume a bit */ if (bit) { ones++; full_byte |= (1 << bit_offset++); } else { if (ones == 5 && state == DATA) { /* we don't increase bit_offset, it is an inserted zero */ } else if (ones == 6 && state == DATA) { /* probably starting flag sequence */ buff = (guint8 *)g_memdup(data, data_len); /* Allocate new tvb for the LAPD frame */ new_tvb = tvb_new_child_real_data(tvb, buff, data_len, data_len); tvb_set_free_cb(new_tvb, g_free); add_new_data_source(pinfo, new_tvb, "Decoded LAPD bitstream"); data_len = 0; state = FLAGS; bit_offset++; if (full_byte != 0x7E) { data_len = 0; state = OUT_OF_SYNC; lapd_log_abort(tvb, pinfo, tree, offset, "Abort! 6 ones that don't match 0x7e!"); } dissect_lapd_full(new_tvb, pinfo, tree, TRUE); } else if (ones >= 7) { /* frame reset or 11111111 flag byte */ data_len = 0; state = OUT_OF_SYNC; bit_offset++; lapd_log_abort(tvb, pinfo, tree, offset, "Abort! 7 ones!"); } else { bit_offset++; } ones = 0; } if (bit_offset == 8) { /* we have a new complete byte */ switch (state) { case OUT_OF_SYNC: if (full_byte == 0x7E) { /* we have a flag byte */ state = FLAGS; full_byte = 0x00; bit_offset = 0; } else { /* no sync yet, wait for a new byte */ full_byte = (full_byte >> 1) & 0x7F; bit_offset--; } break; case FLAGS: if (full_byte == 0x7E) { /* we have a flag byte */ full_byte = 0x00; bit_offset = 0; } else { /* we got the first data byte */ state = DATA; new_byte(full_byte, data, &data_len); full_byte = 0x00; bit_offset = 0; } break; case DATA: /* we got a new data byte */ new_byte(full_byte, data, &data_len); full_byte = 0x00; bit_offset = 0; break; } } } } { if (NULL == p_get_proto_data(wmem_file_scope(), pinfo, proto_lapd, 0)) { /* Per packet information */ lapd_ppi = wmem_new(wmem_file_scope(), lapd_ppi_t); lapd_ppi->has_crc = TRUE; if (prev_byte_state) fill_lapd_byte_state(&lapd_ppi->start_byte_state, prev_byte_state->state, prev_byte_state->full_byte, prev_byte_state->bit_offset, prev_byte_state->ones, prev_byte_state->data, prev_byte_state->data_len); else fill_lapd_byte_state(&lapd_ppi->start_byte_state, OUT_OF_SYNC, 0x00, 0, 0, data, 0); p_add_proto_data(wmem_file_scope(), pinfo, proto_lapd, 0, lapd_ppi); /* Conversation info*/ if (conversation) { if (convo_data) { /* already have lapd convo data */ if (forward_stream) fill_lapd_byte_state(convo_data->byte_state_a, state, full_byte, bit_offset, ones, data, data_len); else { if (!convo_data->byte_state_b) convo_data->byte_state_b = wmem_new(wmem_file_scope(), lapd_byte_state_t); fill_lapd_byte_state(convo_data->byte_state_b, state, full_byte, bit_offset, ones, data, data_len); } } else { /* lapd convo data has to be created */ lapd_byte_state = wmem_new(wmem_file_scope(), lapd_byte_state_t); fill_lapd_byte_state(lapd_byte_state, state, full_byte, bit_offset, ones, data, data_len); convo_data = wmem_new(wmem_file_scope(), lapd_convo_data_t); copy_address(&convo_data->addr_a, &pinfo->src); copy_address(&convo_data->addr_b, &pinfo->dst); convo_data->port_a = pinfo->srcport; convo_data->port_b = pinfo->destport; convo_data->byte_state_a = lapd_byte_state; convo_data->byte_state_b = NULL; conversation_add_proto_data(conversation, proto_lapd, convo_data); } } } } return tvb_captured_length(tvb); } static int dissect_lapd(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, void* data _U_) { dissect_lapd_full(tvb, pinfo, tree, FALSE); return tvb_captured_length(tvb); } static void dissect_lapd_full(tvbuff_t *tvb, packet_info *pinfo, proto_tree *tree, gboolean has_crc) { proto_tree *lapd_tree, *addr_tree, *checksum_tree; proto_item *lapd_ti, *addr_ti, *checksum_ti; int direction; guint16 control, checksum, checksum_calculated; int lapd_header_len, checksum_offset; guint16 addr, cr, sapi, tei; gboolean is_response = 0; tvbuff_t *next_tvb; const char *srcname = "?"; const char *dstname = "?"; col_set_str(pinfo->cinfo, COL_PROTOCOL, "LAPD"); col_clear(pinfo->cinfo, COL_INFO); addr = tvb_get_ntohs(tvb, 0); cr = addr & LAPD_CR; tei = (addr & LAPD_TEI) >> LAPD_TEI_SHIFT; sapi = (addr & LAPD_SAPI) >> LAPD_SAPI_SHIFT; lapd_header_len = 2; /* addr */ col_add_fstr(pinfo->cinfo, COL_TEI, "%u", tei); /* Append TEI to info field */ col_append_fstr(pinfo->cinfo, COL_INFO, "TEI:%02u ", tei); col_set_fence(pinfo->cinfo, COL_INFO); if (pinfo->fd->lnk_t == WTAP_ENCAP_LINUX_LAPD) { /* frame is captured via libpcap */ if (pinfo->pseudo_header->lapd.pkttype == 4 /*PACKET_OUTGOING*/) { if (pinfo->pseudo_header->lapd.we_network) { is_response = cr ? FALSE : TRUE; srcname = "Local Network"; dstname = "Remote User"; direction = P2P_DIR_RECV; /* Network->User */ } else { srcname = "Local User"; dstname = "Remote Network"; direction = P2P_DIR_SENT; /* User->Network */ } } else if (pinfo->pseudo_header->lapd.pkttype == 3 /*PACKET_OTHERHOST*/) { /* We must be a TE, sniffing what other TE transmit */ is_response = cr ? TRUE : FALSE; srcname = "Remote User"; dstname = "Remote Network"; direction = P2P_DIR_SENT; /* User->Network */ } else { /* The frame is incoming */ if (pinfo->pseudo_header->lapd.we_network) { is_response = cr ? TRUE : FALSE; srcname = "Remote User"; dstname = "Local Network"; direction = P2P_DIR_SENT; /* User->Network */ } else { is_response = cr ? FALSE : TRUE; srcname = "Remote Network"; dstname = "Local User"; direction = P2P_DIR_RECV; /* Network->User */ } } } else { direction = pinfo->p2p_dir; if (pinfo->p2p_dir == P2P_DIR_RECV) { is_response = cr ? FALSE : TRUE; srcname = "Network"; dstname = "User"; } else if (pinfo->p2p_dir == P2P_DIR_SENT) { is_response = cr ? TRUE : FALSE; srcname = "User"; dstname = "Network"; } } col_set_str(pinfo->cinfo, COL_RES_DL_SRC, srcname); col_set_str(pinfo->cinfo, COL_RES_DL_DST, dstname); if (tree) { proto_item *direction_ti; lapd_ti = proto_tree_add_item(tree, proto_lapd, tvb, 0, -1, ENC_NA); lapd_tree = proto_item_add_subtree(lapd_ti, ett_lapd); /* * Don't show the direction if we don't know it. */ if (direction != P2P_DIR_UNKNOWN) { direction_ti = proto_tree_add_uint(lapd_tree, hf_lapd_direction, tvb, 0, 0, pinfo->p2p_dir); PROTO_ITEM_SET_GENERATED(direction_ti); } addr_ti = proto_tree_add_uint(lapd_tree, hf_lapd_address, tvb, 0, 2, addr); addr_tree = proto_item_add_subtree(addr_ti, ett_lapd_address); if(global_lapd_gsm_sapis){ proto_tree_add_uint(addr_tree, hf_lapd_gsm_sapi,tvb, 0, 1, addr); }else{ proto_tree_add_uint(addr_tree, hf_lapd_sapi,tvb, 0, 1, addr); } proto_tree_add_uint(addr_tree, hf_lapd_cr, tvb, 0, 1, addr); proto_tree_add_uint(addr_tree, hf_lapd_ea1, tvb, 0, 1, addr); proto_tree_add_uint(addr_tree, hf_lapd_tei, tvb, 1, 1, addr); proto_tree_add_uint(addr_tree, hf_lapd_ea2, tvb, 1, 1, addr); } else { lapd_ti = NULL; lapd_tree = NULL; } control = dissect_xdlc_control(tvb, 2, pinfo, lapd_tree, hf_lapd_control, ett_lapd_control, &lapd_cf_items, &lapd_cf_items_ext, NULL, NULL, is_response, TRUE, FALSE); lapd_header_len += XDLC_CONTROL_LEN(control, TRUE); if (tree) proto_item_set_len(lapd_ti, lapd_header_len); if (has_crc) { /* check checksum */ checksum_offset = tvb_reported_length(tvb) - 2; checksum = tvb_get_guint8(tvb, checksum_offset); /* high byte */ checksum <<= 8; checksum |= tvb_get_guint8(tvb, checksum_offset+1) & 0x00FF; /* low byte */ checksum_calculated = crc16_ccitt_tvb(tvb, tvb_reported_length(tvb) - 2); checksum_calculated = g_htons(checksum_calculated); /* Note: g_htons() macro may eval arg multiple times */ if (checksum == checksum_calculated) { checksum_ti = proto_tree_add_uint_format_value(lapd_tree, hf_lapd_checksum, tvb, checksum_offset, 2, 0,"0x%04x [correct]", checksum); checksum_tree = proto_item_add_subtree(checksum_ti, ett_lapd_checksum); proto_tree_add_boolean(checksum_tree, hf_lapd_checksum_good, tvb, checksum_offset, 2, TRUE); proto_tree_add_boolean(checksum_tree, hf_lapd_checksum_bad, tvb, checksum_offset, 2, FALSE); } else { proto_item *pi; checksum_ti = proto_tree_add_uint_format_value(lapd_tree, hf_lapd_checksum, tvb, checksum_offset, 2, 0,"0x%04x [incorrect, should be 0x%04x]", checksum, checksum_calculated); checksum_tree = proto_item_add_subtree(checksum_ti, ett_lapd_checksum); proto_tree_add_boolean(checksum_tree, hf_lapd_checksum_good, tvb, checksum_offset, 2, FALSE); pi = proto_tree_add_boolean(checksum_tree, hf_lapd_checksum_bad, tvb, checksum_offset, 2, TRUE); expert_add_info(pinfo, pi, &ei_lapd_checksum_bad); } next_tvb = tvb_new_subset_length(tvb, lapd_header_len, tvb_reported_length_remaining(tvb,lapd_header_len) - 2); } else next_tvb = tvb_new_subset_remaining(tvb, lapd_header_len); /* Dissection done, append " | " to COL_INFO */ col_append_str(pinfo->cinfo, COL_INFO, " | "); col_set_fence(pinfo->cinfo, COL_INFO); if (XDLC_IS_INFORMATION(control)) { /* call next protocol */ if(global_lapd_gsm_sapis){ if (!dissector_try_uint(lapd_gsm_sapi_dissector_table, sapi, next_tvb, pinfo, tree)) call_dissector(data_handle,next_tvb, pinfo, tree); }else{ if (!dissector_try_uint(lapd_sapi_dissector_table, sapi, next_tvb, pinfo, tree)) call_dissector(data_handle,next_tvb, pinfo, tree); } } else call_dissector(data_handle,next_tvb, pinfo, tree); } static gboolean dissect_udp_lapd(tvbuff_t *tvb, packet_info *pinfo _U_ , proto_tree *tree, void *data _U_) { if (pinfo->srcport < 3001 || pinfo->srcport > 3015 || pinfo->destport < 3001 || pinfo->destport > 3015 || pinfo->destport != pinfo->srcport) return FALSE; /* * XXX - check for a valid LAPD address field. */ /* * OK, check whether the control field looks valid. */ if (!check_xdlc_control(tvb, 2, NULL, NULL, FALSE, FALSE)) return FALSE; dissect_lapd(tvb, pinfo, tree, data); return TRUE; } void proto_register_lapd(void) { static hf_register_info hf[] = { { &hf_lapd_direction, { "Direction", "lapd.direction", FT_UINT8, BASE_DEC, VALS(lapd_direction_vals), 0x0, NULL, HFILL }}, { &hf_lapd_address, { "Address Field", "lapd.address", FT_UINT16, BASE_HEX, NULL, 0x0, "Address", HFILL }}, { &hf_lapd_sapi, { "SAPI", "lapd.sapi", FT_UINT16, BASE_DEC, VALS(lapd_sapi_vals), LAPD_SAPI, "Service Access Point Identifier", HFILL }}, { &hf_lapd_gsm_sapi, { "SAPI", "lapd.sapi", FT_UINT16, BASE_DEC, VALS(lapd_gsm_sapi_vals), LAPD_SAPI, "Service Access Point Identifier", HFILL }}, { &hf_lapd_cr, { "C/R", "lapd.cr", FT_UINT16, BASE_DEC, NULL, LAPD_CR, "Command/Response bit", HFILL }}, { &hf_lapd_ea1, { "EA1", "lapd.ea1", FT_UINT16, BASE_DEC, NULL, LAPD_EA1, "First Address Extension bit", HFILL }}, { &hf_lapd_tei, { "TEI", "lapd.tei", FT_UINT16, BASE_DEC, NULL, LAPD_TEI, "Terminal Endpoint Identifier", HFILL }}, { &hf_lapd_ea2, { "EA2", "lapd.ea2", FT_UINT16, BASE_DEC, NULL, LAPD_EA2, "Second Address Extension bit", HFILL }}, { &hf_lapd_control, { "Control Field", "lapd.control", FT_UINT16, BASE_HEX, NULL, 0x0, NULL, HFILL }}, { &hf_lapd_n_r, { "N(R)", "lapd.control.n_r", FT_UINT16, BASE_DEC, NULL, XDLC_N_R_EXT_MASK, NULL, HFILL }}, { &hf_lapd_n_s, { "N(S)", "lapd.control.n_s", FT_UINT16, BASE_DEC, NULL, XDLC_N_S_EXT_MASK, NULL, HFILL }}, { &hf_lapd_p, { "Poll", "lapd.control.p", FT_BOOLEAN, 8, TFS(&tfs_set_notset), XDLC_P_F, NULL, HFILL }}, { &hf_lapd_p_ext, { "Poll", "lapd.control.p", FT_BOOLEAN, 16, TFS(&tfs_set_notset), XDLC_P_F_EXT, NULL, HFILL }}, { &hf_lapd_f, { "Final", "lapd.control.f", FT_BOOLEAN, 8, TFS(&tfs_set_notset), XDLC_P_F, NULL, HFILL }}, { &hf_lapd_f_ext, { "Final", "lapd.control.f", FT_BOOLEAN, 16, TFS(&tfs_set_notset), XDLC_P_F_EXT, NULL, HFILL }}, { &hf_lapd_s_ftype, { "Supervisory frame type", "lapd.control.s_ftype", FT_UINT16, BASE_HEX, VALS(stype_vals), XDLC_S_FTYPE_MASK, NULL, HFILL }}, { &hf_lapd_u_modifier_cmd, { "Command", "lapd.control.u_modifier_cmd", FT_UINT8, BASE_HEX, VALS(modifier_vals_cmd), XDLC_U_MODIFIER_MASK, NULL, HFILL }}, { &hf_lapd_u_modifier_resp, { "Response", "lapd.control.u_modifier_resp", FT_UINT8, BASE_HEX, VALS(modifier_vals_resp), XDLC_U_MODIFIER_MASK, NULL, HFILL }}, { &hf_lapd_ftype_i, { "Frame type", "lapd.control.ftype", FT_UINT16, BASE_HEX, VALS(ftype_vals), XDLC_I_MASK, NULL, HFILL }}, { &hf_lapd_ftype_s_u, { "Frame type", "lapd.control.ftype", FT_UINT8, BASE_HEX, VALS(ftype_vals), XDLC_S_U_MASK, NULL, HFILL }}, { &hf_lapd_ftype_s_u_ext, { "Frame type", "lapd.control.ftype", FT_UINT16, BASE_HEX, VALS(ftype_vals), XDLC_S_U_MASK, NULL, HFILL }}, { &hf_lapd_checksum, { "Checksum", "lapd.checksum", FT_UINT16, BASE_HEX, NULL, 0x0, "Details at: http://www.wireshark.org/docs/wsug_html_chunked/ChAdvChecksums.html", HFILL }}, { &hf_lapd_checksum_good, { "Good Checksum", "lapd.checksum_good", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "True: checksum matches packet content; False: doesn't match content or not checked", HFILL }}, { &hf_lapd_checksum_bad, { "Bad Checksum", "lapd.checksum_bad", FT_BOOLEAN, BASE_NONE, NULL, 0x0, "True: checksum doesn't match packet content; False: matches content or not checked", HFILL }}, }; static gint *ett[] = { &ett_lapd, &ett_lapd_address, &ett_lapd_control, &ett_lapd_checksum }; static ei_register_info ei[] = { { &ei_lapd_abort, { "lapd.abort.expert", PI_PROTOCOL, PI_ERROR, "Formatted message", EXPFILL }}, { &ei_lapd_checksum_bad, { "lapd.checksum_bad.expert", PI_CHECKSUM, PI_WARN, "Bad FCS", EXPFILL }}, }; module_t *lapd_module; expert_module_t* expert_lapd; proto_lapd = proto_register_protocol("Link Access Procedure, Channel D (LAPD)", "LAPD", "lapd"); proto_register_field_array (proto_lapd, hf, array_length(hf)); proto_register_subtree_array(ett, array_length(ett)); expert_lapd = expert_register_protocol(proto_lapd); expert_register_field_array(expert_lapd, ei, array_length(ei)); register_dissector("lapd", dissect_lapd, proto_lapd); lapd_sapi_dissector_table = register_dissector_table("lapd.sapi", "LAPD SAPI", FT_UINT16, BASE_DEC, DISSECTOR_TABLE_NOT_ALLOW_DUPLICATE); lapd_gsm_sapi_dissector_table = register_dissector_table("lapd.gsm.sapi", "LAPD GSM SAPI", FT_UINT16, BASE_DEC, DISSECTOR_TABLE_NOT_ALLOW_DUPLICATE); lapd_module = prefs_register_protocol(proto_lapd, proto_reg_handoff_lapd); prefs_register_bool_preference(lapd_module, "use_gsm_sapi_values", "Use GSM SAPI values", "Use SAPI values as specified in TS 48 056", &global_lapd_gsm_sapis); prefs_register_uint_preference(lapd_module, "rtp_payload_type", "RTP payload type for embedded LAPD", "RTP payload type for embedded LAPD. It must be one of the dynamic types " "from 96 to 127. Set it to 0 to disable.", 10, &pref_lapd_rtp_payload_type); } void proto_reg_handoff_lapd(void) { static gboolean init = FALSE; static dissector_handle_t lapd_bitstream_handle; static gint lapd_rtp_payload_type; if (!init) { dissector_handle_t lapd_handle; lapd_handle = find_dissector("lapd"); dissector_add_uint("wtap_encap", WTAP_ENCAP_LINUX_LAPD, lapd_handle); dissector_add_uint("wtap_encap", WTAP_ENCAP_LAPD, lapd_handle); dissector_add_uint("l2tp.pw_type", L2TPv3_PROTOCOL_LAPD, lapd_handle); heur_dissector_add("udp", dissect_udp_lapd, "LAPD over UDP", "lapd_udp", proto_lapd, HEURISTIC_ENABLE); register_dissector("lapd-bitstream", dissect_lapd_bitstream, proto_lapd); lapd_bitstream_handle = find_dissector("lapd-bitstream"); data_handle = find_dissector("data"); init = TRUE; } else { if ((lapd_rtp_payload_type > 95) && (lapd_rtp_payload_type < 128)) dissector_delete_uint("rtp.pt", lapd_rtp_payload_type, lapd_bitstream_handle); } lapd_rtp_payload_type = pref_lapd_rtp_payload_type; if ((lapd_rtp_payload_type > 95) && (lapd_rtp_payload_type < 128)) dissector_add_uint("rtp.pt", lapd_rtp_payload_type, lapd_bitstream_handle); } /* * Editor modelines - http://www.wireshark.org/tools/modelines.html * * Local variables: * c-basic-offset: 8 * tab-width: 8 * indent-tabs-mode: t * End: * * vi: set shiftwidth=8 tabstop=8 noexpandtab: * :indentSize=8:tabSize=8:noTabs=false: */
lemenkov/wireshark
epan/dissectors/packet-lapd.c
C
gpl-2.0
26,245
/* * (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
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <!-- NewPage --> <html lang="en"> <head> <!-- Generated by javadoc (version 1.7.0_67) on Wed Aug 05 09:09:27 CEST 2015 --> <title>Uses of Class negotiator.boaframework.acceptanceconditions.other.AC_CombiProbDiscounted (Genius GUI Documentation)</title> <meta name="date" content="2015-08-05"> <link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style"> </head> <body> <script type="text/javascript"><!-- if (location.href.indexOf('is-external=true') == -1) { parent.document.title="Uses of Class negotiator.boaframework.acceptanceconditions.other.AC_CombiProbDiscounted (Genius GUI Documentation)"; } //--> </script> <noscript> <div>JavaScript is disabled on your browser.</div> </noscript> <!-- ========= START OF TOP NAVBAR ======= --> <div class="topNav"><a name="navbar_top"> <!-- --> </a><a href="#skip-navbar_top" title="Skip navigation links"></a><a name="navbar_top_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../negotiator/boaframework/acceptanceconditions/other/AC_CombiProbDiscounted.html" title="class in negotiator.boaframework.acceptanceconditions.other">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?negotiator/boaframework/acceptanceconditions/other/class-use/AC_CombiProbDiscounted.html" target="_top">Frames</a></li> <li><a href="AC_CombiProbDiscounted.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_top"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_top"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_top"> <!-- --> </a></div> <!-- ========= END OF TOP NAVBAR ========= --> <div class="header"> <h2 title="Uses of Class negotiator.boaframework.acceptanceconditions.other.AC_CombiProbDiscounted" class="title">Uses of Class<br>negotiator.boaframework.acceptanceconditions.other.AC_CombiProbDiscounted</h2> </div> <div class="classUseContainer">No usage of negotiator.boaframework.acceptanceconditions.other.AC_CombiProbDiscounted</div> <!-- ======= START OF BOTTOM NAVBAR ====== --> <div class="bottomNav"><a name="navbar_bottom"> <!-- --> </a><a href="#skip-navbar_bottom" title="Skip navigation links"></a><a name="navbar_bottom_firstrow"> <!-- --> </a> <ul class="navList" title="Navigation"> <li><a href="../../../../../overview-summary.html">Overview</a></li> <li><a href="../package-summary.html">Package</a></li> <li><a href="../../../../../negotiator/boaframework/acceptanceconditions/other/AC_CombiProbDiscounted.html" title="class in negotiator.boaframework.acceptanceconditions.other">Class</a></li> <li class="navBarCell1Rev">Use</li> <li><a href="../package-tree.html">Tree</a></li> <li><a href="../../../../../deprecated-list.html">Deprecated</a></li> <li><a href="../../../../../index-all.html">Index</a></li> <li><a href="../../../../../help-doc.html">Help</a></li> </ul> </div> <div class="subNav"> <ul class="navList"> <li>Prev</li> <li>Next</li> </ul> <ul class="navList"> <li><a href="../../../../../index.html?negotiator/boaframework/acceptanceconditions/other/class-use/AC_CombiProbDiscounted.html" target="_top">Frames</a></li> <li><a href="AC_CombiProbDiscounted.html" target="_top">No Frames</a></li> </ul> <ul class="navList" id="allclasses_navbar_bottom"> <li><a href="../../../../../allclasses-noframe.html">All Classes</a></li> </ul> <div> <script type="text/javascript"><!-- allClassesLink = document.getElementById("allclasses_navbar_bottom"); if(window==top) { allClassesLink.style.display = "block"; } else { allClassesLink.style.display = "none"; } //--> </script> </div> <a name="skip-navbar_bottom"> <!-- --> </a></div> <!-- ======== END OF BOTTOM NAVBAR ======= --> </body> </html>
hendrahc/nego11
AI2015Group11assignment/javadoc/negotiator/boaframework/acceptanceconditions/other/class-use/AC_CombiProbDiscounted.html
HTML
gpl-2.0
4,583
/* * 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