code
stringlengths
4
1.01M
language
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.GamerServices; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Media; namespace PlaneGame { class ProgressBar { public Rectangle rc, fon; protected int maxValue; protected int value; protected Texture2D texture; protected int step; public int maxLenght; public ProgressBar(Texture2D textur, int height = 30, int value = 0, int maxValue = 100, int maxLenght = 200) { this.texture = textur; this.value = value; this.maxValue = maxValue; this.maxLenght = maxLenght; step = maxLenght / maxValue; rc = new Rectangle(0, 0, 1, height); fon = new Rectangle(0, 0, this.maxLenght, height); } public void setValue(int val) { this.value = val; this.rc.Width = (int)(value * step); if (this.rc.Width > this.maxLenght) { this.rc.Width = this.maxLenght; } if (this.rc.Width < 1) { this.rc.Width = 1; } } public void Draw(SpriteBatch sb,bool powernut, Color color, Color fonColor,float alpha,int x = 0, int y = 0) { if (powernut == true) { fon.X = rc.X = x; fon.Y = rc.Y = y; sb.Draw(texture, fon, null, fonColor * alpha, 0, Vector2.Zero, SpriteEffects.None, 0.9f); sb.Draw(texture, rc, null, color * alpha, 0, Vector2.Zero, SpriteEffects.None, 1); } else { fon.X = rc.X = x+this.maxLenght; fon.Y = rc.Y = y + this.fon.Height; sb.Draw(texture, fon, null, fonColor * alpha, MathHelper.Pi, new Vector2(0, 0), SpriteEffects.None, 0.9f); sb.Draw(texture, rc, null, color * alpha, MathHelper.Pi, new Vector2(0, 0), SpriteEffects.None, 1); } } } }
Java
<!DOCTYPE html> <html class="no-js" <?php language_attributes(); ?>> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title><?php wp_title(''); ?></title> <meta name="viewport" content="width=device-width, initial-scale=1"> <?php wp_head(); ?> <!--[if lt IE 9]><script src="<?php echo get_template_directory_uri(); ?>/assets/js/html5shiv.min.js"></script><![endif]--> <link rel="alternate" type="application/rss+xml" title="<?php echo get_bloginfo('name'); ?> Feed" href="<?php echo home_url(); ?>/feed/"> </head>
Java
/* dfilter_expr_dlg.h * Definitions for dialog boxes for display filter expression construction * * $Id: dfilter_expr_dlg.h 24034 2008-01-08 22:54:51Z stig $ * * Wireshark - Network traffic analyzer * By Gerald Combs <gerald@wireshark.org> * Copyright 1998 Gerald Combs * * * 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. */ #ifndef __DFILTER_EXPR_DLG_H__ #define __DFILTER_EXPR_DLG_H__ /** @file * "Add Expression" dialog box. * @ingroup dialog_group */ /** User requested the "Add Expression" dialog box by menu or toolbar. * * @param widget corresponding text entry widget * @return the newly created dialog widget */ GtkWidget *dfilter_expr_dlg_new(GtkWidget *widget); #endif /* dfilter_expr_dlg.h */
Java
<!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"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <meta http-equiv="X-UA-Compatible" content="IE=9"/> <meta name="generator" content="Doxygen 1.8.7"/> <title>oRTP: /Users/jehanmonnier/workspaces/workspace-iphone-port/linphone-iphone/submodules/linphone/oRTP/src Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <script type="text/javascript" src="jquery.js"></script> <script type="text/javascript" src="dynsections.js"></script> <link href="doxygen.css" rel="stylesheet" type="text/css" /> </head> <body> <div id="top"><!-- do not remove this div, it is closed by doxygen! --> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">oRTP &#160;<span id="projectnumber">0.24.0</span> </div> </td> </tr> </tbody> </table> </div> <!-- end header part --> <!-- Generated by Doxygen 1.8.7 --> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="annotated.html"><span>Data&#160;Structures</span></a></li> <li><a href="files.html"><span>Files</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_9e51036813d6151dfecc72d5fa7c02b3.html">Users</a></li><li class="navelem"><a class="el" href="dir_0086a5bc28c2c80fdd65429b30ec7201.html">jehanmonnier</a></li><li class="navelem"><a class="el" href="dir_b858f17e34ed058634411ab8c7d24549.html">workspaces</a></li><li class="navelem"><a class="el" href="dir_0b63d9ddac5e0eae8010f03443fa7c42.html">workspace-iphone-port</a></li><li class="navelem"><a class="el" href="dir_70e119ec7732bd017bc188a7129d48ee.html">linphone-iphone</a></li><li class="navelem"><a class="el" href="dir_cf4c98acb38bffd48d5ffefce9055b2c.html">submodules</a></li><li class="navelem"><a class="el" href="dir_b04f89f5a7f8ec29a0b9160f0e142536.html">linphone</a></li><li class="navelem"><a class="el" href="dir_868997901fe332c5ff1ebd4a06734a1f.html">oRTP</a></li><li class="navelem"><a class="el" href="dir_7559c465e4c3d013b6e747e2a6ffd6d9.html">src</a></li> </ul> </div> </div><!-- top --> <div class="header"> <div class="headertitle"> <div class="title">src Directory Reference</div> </div> </div><!--header--> <div class="contents"> <table class="memberdecls"> <tr class="heading"><td colspan="2"><h2 class="groupheader"><a name="files"></a> Files</h2></td></tr> <tr class="memitem:avprofile_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>avprofile.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:b64_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="b64_8c.html">b64.c</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:dll__entry_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>dll_entry.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:event_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>event.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:extremum_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>extremum.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:jitterctl_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>jitterctl.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:jitterctl_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>jitterctl.h</b> <a href="jitterctl_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:logging_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>logging.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:netsim_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>netsim.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:ortp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>ortp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:payloadtype_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>payloadtype.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:port_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>port.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:posixtimer_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>posixtimer.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcp_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcp.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcp__fb_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcp_fb.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcp__xr_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcp_xr.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtcpparse_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtcpparse.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpparse_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpparse.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpprofile_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpprofile.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession__inet_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession_inet.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsession__priv_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsession_priv.h</b> <a href="rtpsession__priv_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtpsignaltable_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtpsignaltable.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtptimer_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtptimer.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:rtptimer_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>rtptimer.h</b> <a href="rtptimer_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:scheduler_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>scheduler.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:scheduler_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>scheduler.h</b> <a href="scheduler_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:sessionset_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>sessionset.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:str__utils_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>str_utils.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:telephonyevents_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>telephonyevents.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:utils_8c"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>utils.c</b></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:utils_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>utils.h</b> <a href="utils_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> <tr class="memitem:winrttimer_8h"><td class="memItemLeft" align="right" valign="top">file &#160;</td><td class="memItemRight" valign="bottom"><b>winrttimer.h</b> <a href="winrttimer_8h_source.html">[code]</a></td></tr> <tr class="separator:"><td class="memSeparator" colspan="2">&#160;</td></tr> </table> </div><!-- contents --> <!-- start footer part --> <hr class="footer"/><address class="footer"><small> Generated on Mon Mar 23 2015 12:57:57 for oRTP by &#160;<a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/> </a> 1.8.7 </small></address> </body> </html>
Java
<?php /** * Shows a welcome or update message after the plugin is installed/updated */ class Tribe__Events__Activation_Page { /** @var self */ private static $instance = null; public function add_hooks() { add_action( 'admin_init', array( $this, 'maybe_redirect' ), 10, 0 ); add_action( 'admin_menu', array( $this, 'register_page' ), 100, 0 ); // come in after the default page is registered add_action( 'update_plugin_complete_actions', array( $this, 'update_complete_actions' ), 15, 2 ); add_action( 'update_bulk_plugins_complete_actions', array( $this, 'update_complete_actions' ), 15, 2 ); } /** * Filter the Default WordPress actions when updating the plugin to prevent users to be redirected if they have an * specfific intention of going back to the plugins page. * * @param array $actions The Array of links (html) * @param string $plugin Which plugins are been updated * @return array The filtered Links */ public function update_complete_actions( $actions, $plugin ) { $plugins = array(); if ( ! empty( $_GET['plugins'] ) ) { $plugins = explode( ',', esc_attr( $_GET['plugins'] ) ); } if ( ! in_array( Tribe__Events__Main::instance()->pluginDir . 'the-events-calendar.php', $plugins ) ){ return $actions; } if ( isset( $actions['plugins_page'] ) ) { $actions['plugins_page'] = '<a href="' . esc_url( self_admin_url( 'plugins.php?tec-skip-welcome' ) ) . '" title="' . esc_attr__( 'Go to plugins page' ) . '" target="_parent">' . esc_html__( 'Return to Plugins page' ) . '</a>'; if ( ! current_user_can( 'activate_plugins' ) ){ unset( $actions['plugins_page'] ); } } if ( isset( $actions['updates_page'] ) ) { $actions['updates_page'] = '<a href="' . esc_url( self_admin_url( 'update-core.php?tec-skip-welcome' ) ) . '" title="' . esc_attr__( 'Go to WordPress Updates page' ) . '" target="_parent">' . esc_html__( 'Return to WordPress Updates' ) . '</a>'; } return $actions; } public function maybe_redirect() { if ( ! empty( $_POST ) ) { return; // don't interrupt anything the user's trying to do } if ( ! is_admin() || defined( 'DOING_AJAX' ) ) { return; } if ( defined( 'IFRAME_REQUEST' ) && IFRAME_REQUEST ) { return; // probably the plugin update/install iframe } if ( isset( $_GET['tec-welcome-message'] ) || isset( $_GET['tec-update-message'] ) ) { return; // no infinite redirects } if ( isset( $_GET['tec-skip-welcome'] ) ) { return; // a way to skip these checks and } // bail if we aren't activating a plugin if ( ! get_transient( '_tribe_events_activation_redirect' ) ) { return; } delete_transient( '_tribe_events_activation_redirect' ); if ( ! current_user_can( Tribe__Events__Settings::instance()->requiredCap ) ){ return; } if ( $this->showed_update_message_for_current_version() ) { return; } // the redirect might be intercepted by another plugin, but // we'll go ahead and mark it as viewed right now, just in case // we end up in a redirect loop // see #31088 $this->log_display_of_message_page(); if ( $this->is_new_install() ) { $this->redirect_to_welcome_page(); } /* * TODO: determine if we wish to keep the update splash screen in the future else { $this->redirect_to_update_page(); } */ } /** * Have we shown the welcome/update message for the current version? * * @return bool */ protected function showed_update_message_for_current_version() { $tec = Tribe__Events__Main::instance(); $message_version_displayed = $tec->getOption( 'last-update-message' ); if ( empty( $message_version_displayed ) ) { return false; } if ( version_compare( $message_version_displayed, Tribe__Events__Main::VERSION, '<' ) ) { return false; } return true; } protected function log_display_of_message_page() { $tec = Tribe__Events__Main::instance(); $tec->setOption( 'last-update-message', Tribe__Events__Main::VERSION ); } /** * The previous_ecp_versions option will be empty or set to 0 * if the current version is the first version to be installed. * * @return bool * @see Tribe__Events__Main::maybeSetTECVersion() */ protected function is_new_install() { $tec = Tribe__Events__Main::instance(); $previous_versions = $tec->getOption( 'previous_ecp_versions' ); return empty( $previous_versions ) || ( end( $previous_versions ) == '0' ); } protected function redirect_to_welcome_page() { $url = $this->get_message_page_url( 'tec-welcome-message' ); wp_safe_redirect( $url ); exit(); } protected function redirect_to_update_page() { $url = $this->get_message_page_url( 'tec-update-message' ); wp_safe_redirect( $url ); exit(); } protected function get_message_page_url( $slug ) { $settings = Tribe__Events__Settings::instance(); // get the base settings page url $url = apply_filters( 'tribe_settings_url', add_query_arg( array( 'post_type' => Tribe__Events__Main::POSTTYPE, 'page' => $settings->adminSlug, ), admin_url( 'edit.php' ) ) ); $url = esc_url_raw( add_query_arg( $slug, 1, $url ) ); return $url; } public function register_page() { // tribe_events_page_tribe-events-calendar if ( isset( $_GET['tec-welcome-message'] ) ) { $this->disable_default_settings_page(); add_action( 'tribe_events_page_tribe-events-calendar', array( $this, 'display_welcome_page' ) ); } elseif ( isset( $_GET['tec-update-message'] ) ) { $this->disable_default_settings_page(); add_action( 'tribe_events_page_tribe-events-calendar', array( $this, 'display_update_page' ) ); } } protected function disable_default_settings_page() { remove_action( 'tribe_events_page_tribe-events-calendar', array( Tribe__Events__Settings::instance(), 'generatePage' ) ); } public function display_welcome_page() { do_action( 'tribe_settings_top' ); echo '<div class="tribe_settings tribe_welcome_page wrap">'; echo '<h1>'; echo $this->welcome_page_title(); echo '</h1>'; echo $this->welcome_page_content(); echo '</div>'; do_action( 'tribe_settings_bottom' ); $this->log_display_of_message_page(); } protected function welcome_page_title() { return __( 'Welcome to The Events Calendar', 'the-events-calendar' ); } protected function welcome_page_content() { return $this->load_template( 'admin-welcome-message' ); } public function display_update_page() { do_action( 'tribe_settings_top' ); echo '<div class="tribe_settings tribe_update_page wrap">'; echo '<h1>'; echo $this->update_page_title(); echo '</h1>'; echo $this->update_page_content(); echo '</div>'; do_action( 'tribe_settings_bottom' ); $this->log_display_of_message_page(); } protected function update_page_title() { return __( 'Thanks for Updating The Events Calendar', 'the-events-calendar' ); } protected function update_page_content() { return $this->load_template( 'admin-update-message' ); } protected function load_template( $name ) { ob_start(); include trailingslashit( Tribe__Events__Main::instance()->pluginPath ) . 'src/admin-views/' . $name . '.php'; return ob_get_clean(); } /** * Initialize the global instance of the class. */ public static function init() { self::instance()->add_hooks(); } /** * @return self */ public static function instance() { if ( empty( self::$instance ) ) { self::$instance = new self(); } return self::$instance; } }
Java
; size_t fread_unlocked(void *ptr, size_t size, size_t nmemb, FILE *stream) SECTION code_clib SECTION code_stdio PUBLIC fread_unlocked EXTERN asm_fread_unlocked fread_unlocked: pop af pop ix pop hl pop bc pop de push de push bc push hl push hl push af jp asm_fread_unlocked
Java
Audit Plugin Audit for GLPI Français Ce plugin vous permet créer des Scans des équipements des réseaux afin de visualiser les vulnerabilités et les failles sur un réseau donné. Génération de la liste des vulnerabilités pour tout type de matériel ayant une IP. Scan Mensuelles. Scan un équipement avec une adresse IP Bien précises. English This plugin allows you to create Network Equipment Scans to visualize vulnerabilities and vulnerabilities on a given network. Generation of the list of vulnerabilities for any type of hardware having an IP. Monthly Scan. Scan a device with an IP address.
Java
<?php /** * @version 1.0 $Id$ * @package Joomla * @subpackage redEVENT * @copyright redEVENT (C) 2008 redCOMPONENT.com / EventList (C) 2005 - 2008 Christoph Lukes * @license GNU/GPL, see LICENSE.php * redEVENT is based on EventList made by Christoph Lukes from schlu.net * redEVENT can be downloaded from www.redcomponent.com * redEVENT is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License 2 * as published by the Free Software Foundation. * redEVENT 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 redEVENT; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ defined('_JEXEC') or die('Restricted access'); ?> <form action="index.php" method="post" name="adminForm" id="adminForm"> <table class="adminform"> <tr> <td width="100%"> <?php echo JText::_('COM_REDEVENT_SEARCH' );?> <input type="text" name="search" id="search" value="<?php echo $this->lists['search']; ?>" class="text_area" onChange="document.adminForm.submit();" /> <button onclick="this.form.submit();"><?php echo JText::_('COM_REDEVENT_Go' ); ?></button> <button onclick="this.form.getElementById('search').value='';this.form.submit();"><?php echo JText::_('COM_REDEVENT_Reset' ); ?></button> </td> </tr> </table> <table class="adminlist" cellspacing="1"> <thead> <tr> <th width="5">#</th> <th width="20"><input type="checkbox" name="toggle" value="" onClick="checkAll(<?php echo count( $this->rows ); ?>);" /></th> <th width="30%" class="title"><?php echo JHTML::_('grid.sort', 'COM_REDEVENT_GROUP_NAME', 'name', $this->lists['order_Dir'], $this->lists['order'] ); ?></th> <th><?php echo JText::_('COM_REDEVENT_DESCRIPTION' ); ?></th> <th width="5"><?php echo JText::_('COM_REDEVENT_Default' ); ?></th> <th width="5"><?php echo JText::_('COM_REDEVENT_Members' ); ?></th> <th width="5"><?php echo JText::_('COM_REDEVENT_Group_ACL' ); ?></th> </tr> </thead> <tfoot> <tr> <td colspan="7"> <?php echo $this->pageNav->getListFooter(); ?> </td> </tr> </tfoot> <tbody> <?php $k = 0; for($i=0, $n=count( $this->rows ); $i < $n; $i++) { $row = &$this->rows[$i]; $link = 'index.php?option=com_redevent&amp;controller=groups&amp;task=edit&amp;cid[]='.$row->id; $checked = JHTML::_('grid.checkedout', $row, $i ); ?> <tr class="<?php echo "row$k"; ?>"> <td><?php echo $this->pageNav->getRowOffset( $i ); ?></td> <td><?php echo $checked; ?></td> <td> <?php if ( $row->checked_out && ( $row->checked_out != $this->user->get('id') ) ) { echo htmlspecialchars($row->name, ENT_QUOTES, 'UTF-8'); } else { ?> <span class="editlinktip hasTip" title="<?php echo JText::_('COM_REDEVENT_EDIT_GROUP' );?>::<?php echo $row->name; ?>"> <a href="<?php echo $link; ?>"> <?php echo htmlspecialchars($row->name, ENT_QUOTES, 'UTF-8'); ?> </a></span> <?php } ?> </td> <td><?php echo htmlspecialchars($row->description, ENT_QUOTES, 'UTF-8'); ?></td> <td><?php echo ($row->isdefault ? 'yes' : 'no'); ?></td> <td style="text-align:center;"><?php echo JHTML::link('index.php?option=com_redevent&amp;controller=groups&amp;task=editmembers&amp;group_id='.$row->id, $row->members . ' ' . JHTML::_( 'image', 'administrator/components/com_redevent/assets/images/groupmembers.png', JText::_('COM_REDEVENT_Edit_group_members' ), 'title= "'. JText::_('COM_REDEVENT_Edit_group_members' ) . '"' )); ?> </td> <td style="text-align:center;"><?php echo JHTML::link('index.php?option=com_redevent&amp;controller=groups&amp;task=groupacl&amp;group_id='.$row->id, JHTML::_( 'image', 'administrator/components/com_redevent/assets/images/icon-16-categories.png', JText::_('COM_REDEVENT_Edit_group_ACL' ), 'title= "'. JText::_('COM_REDEVENT_Edit_group_ACL' ) . '"' )); ?> </td> </tr> <?php $k = 1 - $k; } ?> </tbody> </table> <input type="hidden" name="boxchecked" value="0" /> <input type="hidden" name="option" value="com_redevent" /> <input type="hidden" name="controller" value="groups" /> <input type="hidden" name="view" value="groups" /> <input type="hidden" name="task" value="" /> <input type="hidden" name="filter_order" value="<?php echo $this->lists['order']; ?>" /> <input type="hidden" name="filter_order_Dir" value="<?php echo $this->lists['order_Dir']; ?>" /> </form>
Java
#!/usr/bin/env python # -*- coding: utf-8 -*- # # progreso.py # # Copyright 2010 Jesús Hómez <jesus@jesus-laptop> # # 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. import gtk, time import threading import thread import gobject #Iniciando el hilo sin usarlo gtk.gdk.threads_init() #La clase App hereda threading.Thread class App(threading.Thread): def __init__(self): #Método constructor, asociando los widgets self.glade_file = "progreso.glade" self.glade = gtk.Builder() self.glade.add_from_file(self.glade_file) self.window1 = self.glade.get_object('window1') self.togglebutton1 = self.glade.get_object('togglebutton1') self.button1 = self.glade.get_object('button1') self.progressbar1 = self.glade.get_object('progressbar1') self.new_val = 0.0 self.rango =60 #Definiendo el valor inicial de la barra de proceso, definiendo los saltos en 0.1 self.progressbar1.set_fraction(self.new_val) self.progressbar1.set_pulse_step(0.1) self.window1.connect("destroy",self.on_window1_destroy) self.button1.connect('clicked', self.on_button1_clicked) self.togglebutton1.connect('toggled',self.on_togglebutton1_toggled) #Iniciando el hilo en el constructor threading.Thread.__init__(self) self.window1.show_all() def __iteracion__(self): #Iteración en segundos cambiando el valor en la barra de progreso. for i in range(self.rango): if self.togglebutton1.get_active() == True: self.new_val = self.progressbar1.get_fraction() + 0.01 if self.new_val > 1.0: self.new_val = 0.0 self.togglebutton1.set_active(False) break else: time.sleep(1) self.x = self.new_val*100 self.progressbar1.set_text("%s" %self.x) self.progressbar1.set_fraction(self.new_val) else: return def on_togglebutton1_toggled(self,*args): #Si cambia el evento en el boton biestado se inicia la iteración entre los hilos. variable = self.togglebutton1.get_active() self.rango = 100 if variable == True: lock = thread.allocate_lock() lock.acquire() thread.start_new_thread( self.__iteracion__, ()) lock.release() else: #Se detiene la barra de progreso self.progressbar1.set_fraction(self.new_val) self.progressbar1.set_text("%s" %self.x)
Java
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2014 The XCSoar Project A detailed list of copyright holders can be found in the file "AUTHORS". 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 "Battery.hpp" #ifdef HAVE_BATTERY #if (defined(_WIN32_WCE) && !defined(GNAV)) #include <windows.h> namespace Power { namespace Battery{ unsigned Temperature = 0; unsigned RemainingPercent = 0; bool RemainingPercentValid = false; batterystatus Status = UNKNOWN; }; namespace External{ externalstatus Status = UNKNOWN; }; }; void UpdateBatteryInfo() { SYSTEM_POWER_STATUS_EX2 sps; // request the power status DWORD result = GetSystemPowerStatusEx2(&sps, sizeof(sps), TRUE); if (result >= sizeof(sps)) { if (sps.BatteryLifePercent != BATTERY_PERCENTAGE_UNKNOWN){ Power::Battery::RemainingPercent = sps.BatteryLifePercent; Power::Battery::RemainingPercentValid = true; } else Power::Battery::RemainingPercentValid = false; switch (sps.BatteryFlag) { case BATTERY_FLAG_HIGH: Power::Battery::Status = Power::Battery::HIGH; break; case BATTERY_FLAG_LOW: Power::Battery::Status = Power::Battery::LOW; break; case BATTERY_FLAG_CRITICAL: Power::Battery::Status = Power::Battery::CRITICAL; break; case BATTERY_FLAG_CHARGING: Power::Battery::Status = Power::Battery::CHARGING; break; case BATTERY_FLAG_NO_BATTERY: Power::Battery::Status = Power::Battery::NOBATTERY; break; case BATTERY_FLAG_UNKNOWN: default: Power::Battery::Status = Power::Battery::UNKNOWN; } switch (sps.ACLineStatus) { case AC_LINE_OFFLINE: Power::External::Status = Power::External::OFF; break; case AC_LINE_BACKUP_POWER: case AC_LINE_ONLINE: Power::External::Status = Power::External::ON; break; case AC_LINE_UNKNOWN: default: Power::External::Status = Power::External::UNKNOWN; } } else { Power::Battery::Status = Power::Battery::UNKNOWN; Power::External::Status = Power::External::UNKNOWN; } } #endif #ifdef KOBO #include "OS/FileUtil.hpp" #include <string.h> #include <stdlib.h> namespace Power { namespace Battery{ unsigned Temperature = 0; unsigned RemainingPercent = 0; bool RemainingPercentValid = false; batterystatus Status = UNKNOWN; }; namespace External{ externalstatus Status = UNKNOWN; }; }; void UpdateBatteryInfo() { // assume failure at entry Power::Battery::RemainingPercentValid = false; Power::Battery::Status = Power::Battery::UNKNOWN; Power::External::Status = Power::External::UNKNOWN; // code shamelessly copied from OS/SystemLoad.cpp char line[256]; if (!File::ReadString("/sys/bus/platform/drivers/pmic_battery/pmic_battery.1/power_supply/mc13892_bat/uevent", line, sizeof(line))) return; char field[80], value[80]; int n; char* ptr = line; while (sscanf(ptr, "%[^=]=%[^\n]\n%n", field, value, &n)==2) { ptr += n; if (!strcmp(field,"POWER_SUPPLY_STATUS")) { if (!strcmp(value,"Not charging") || !strcmp(value,"Charging")) { Power::External::Status = Power::External::ON; } else if (!strcmp(value,"Discharging")) { Power::External::Status = Power::External::OFF; } } else if (!strcmp(field,"POWER_SUPPLY_CAPACITY")) { int rem = atoi(value); Power::Battery::RemainingPercentValid = true; Power::Battery::RemainingPercent = rem; if (Power::External::Status == Power::External::OFF) { if (rem>30) { Power::Battery::Status = Power::Battery::HIGH; } else if (rem>10) { Power::Battery::Status = Power::Battery::LOW; } else if (rem<10) { Power::Battery::Status = Power::Battery::CRITICAL; } } else { Power::Battery::Status = Power::Battery::CHARGING; } } } } #endif #endif
Java
<?php /** * KohaRest ILS Driver * * PHP version 7 * * Copyright (C) The National Library of Finland 2017-2019. * * 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 * * @category VuFind * @package ILS_Drivers * @author Ere Maijala <ere.maijala@helsinki.fi> * @author Juha Luoma <juha.luoma@helsinki.fi> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki */ namespace Finna\ILS\Driver; use VuFind\Exception\ILS as ILSException; /** * VuFind Driver for Koha, using REST API * * Minimum Koha Version: work in progress as of 23 Jan 2017 * * @category VuFind * @package ILS_Drivers * @author Ere Maijala <ere.maijala@helsinki.fi> * @author Juha Luoma <juha.luoma@helsinki.fi> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development:plugins:ils_drivers Wiki */ class KohaRest extends \VuFind\ILS\Driver\KohaRest { /** * Mappings from Koha messaging preferences * * @var array */ protected $messagingPrefTypeMap = [ 'Advance_Notice' => 'dueDateAlert', 'Hold_Filled' => 'pickUpNotice', 'Item_Check_in' => 'checkinNotice', 'Item_Checkout' => 'checkoutNotice', 'Item_Due' => 'dueDateNotice' ]; /** * Whether to use location in addition to branch when grouping holdings * * @param bool */ protected $groupHoldingsByLocation; /** * Priority settings for the order of branches or branch/location combinations * * @var array */ protected $holdingsBranchOrder; /** * Priority settings for the order of locations (in branches) * * @var array */ protected $holdingsLocationOrder; /** * Initialize the driver. * * Validate configuration and perform all resource-intensive tasks needed to * make the driver active. * * @throws ILSException * @return void */ public function init() { parent::init(); $this->groupHoldingsByLocation = isset($this->config['Holdings']['group_by_location']) ? $this->config['Holdings']['group_by_location'] : ''; if (isset($this->config['Holdings']['holdings_branch_order'])) { $values = explode( ':', $this->config['Holdings']['holdings_branch_order'] ); foreach ($values as $i => $value) { $parts = explode('=', $value, 2); $idx = $parts[1] ?? $i; $this->holdingsBranchOrder[$parts[0]] = $idx; } } $this->holdingsLocationOrder = isset($this->config['Holdings']['holdings_location_order']) ? explode(':', $this->config['Holdings']['holdings_location_order']) : []; $this->holdingsLocationOrder = array_flip($this->holdingsLocationOrder); } /** * Get Holding * * This is responsible for retrieving the holding information of a certain * record. * * @param string $id The record id to retrieve the holdings for * @param array $patron Patron data * @param array $options Extra options * * @throws \VuFind\Exception\ILS * @return array On success, an associative array with the following * keys: id, availability (boolean), status, location, reserve, callnumber, * duedate, number, barcode. * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function getHolding($id, array $patron = null, array $options = []) { $data = parent::getHolding($id, $patron); if (!empty($data['holdings'])) { $summary = $this->getHoldingsSummary($data['holdings']); // Remove request counts before adding the summary if necessary if (isset($this->config['Holdings']['display_item_hold_counts']) && !$this->config['Holdings']['display_item_hold_counts'] ) { foreach ($data['holdings'] as &$item) { unset($item['requests_placed']); } } $data['holdings'][] = $summary; } return $data; } /** * Get Status * * This is responsible for retrieving the status information of a certain * record. * * @param string $id The record id to retrieve the holdings for * * @return array An associative array with the following keys: * id, availability (boolean), status, location, reserve, callnumber. */ public function getStatus($id) { $data = parent::getStatus($id); if (!empty($data)) { $summary = $this->getHoldingsSummary($data); $data[] = $summary; } return $data; } /** * Get Statuses * * This is responsible for retrieving the status information for a * collection of records. * * @param array $ids The array of record ids to retrieve the status for * * @return mixed An array of getStatus() return values on success. */ public function getStatuses($ids) { $items = []; foreach ($ids as $id) { $statuses = $this->getItemStatusesForBiblio($id); if (isset($statuses['holdings'])) { $items[] = array_merge( $statuses['holdings'], $statuses['electronic_holdings'] ); } else { $items[] = $statuses; } } return $items; } /** * Get Patron Fines * * This is responsible for retrieving all fines by a specific patron. * * @param array $patron The patron array from patronLogin * * @throws DateException * @throws ILSException * @return array Array of the patron's fines on success. */ public function getMyFines($patron) { $fines = parent::getMyFines($patron); foreach ($fines as &$fine) { $fine['payableOnline'] = true; } return $fines; } /** * Get Patron Profile * * This is responsible for retrieving the profile for a specific patron. * * @param array $patron The patron array * * @throws ILSException * @return array Array of the patron's profile data on success. */ public function getMyProfile($patron) { $result = $this->makeRequest( ['v1', 'patrons', $patron['id']], false, 'GET', $patron ); $expirationDate = !empty($result['dateexpiry']) ? $this->dateConverter->convertToDisplayDate( 'Y-m-d', $result['dateexpiry'] ) : ''; $guarantor = []; $guarantees = []; if (!empty($result['guarantorid'])) { $guarantorRecord = $this->makeRequest( ['v1', 'patrons', $result['guarantorid']], false, 'GET', $patron ); if ($guarantorRecord) { $guarantor['firstname'] = $guarantorRecord['firstname']; $guarantor['lastname'] = $guarantorRecord['surname']; } } else { // Assume patron can have guarantees only if there is no guarantor $guaranteeRecords = $this->makeRequest( ['v1', 'patrons'], ['guarantorid' => $patron['id']], 'GET', $patron ); foreach ($guaranteeRecords as $guarantee) { $guarantees[] = [ 'firstname' => $guarantee['firstname'], 'lastname' => $guarantee['surname'] ]; } } list($resultCode, $messagingPrefs) = $this->makeRequest( ['v1', 'messaging_preferences'], ['borrowernumber' => $patron['id']], 'GET', $patron, true ); $messagingSettings = []; if (200 === $resultCode) { foreach ($messagingPrefs as $type => $prefs) { $typeName = isset($this->messagingPrefTypeMap[$type]) ? $this->messagingPrefTypeMap[$type] : $type; $settings = [ 'type' => $typeName ]; if (isset($prefs['transport_types'])) { $settings['settings']['transport_types'] = [ 'type' => 'multiselect' ]; foreach ($prefs['transport_types'] as $key => $active) { $settings['settings']['transport_types']['options'][$key] = [ 'active' => $active ]; } } if (isset($prefs['digest'])) { $settings['settings']['digest'] = [ 'type' => 'boolean', 'name' => '', 'active' => $prefs['digest']['value'], 'readonly' => !$prefs['digest']['configurable'] ]; } if (isset($prefs['days_in_advance']) && ($prefs['days_in_advance']['configurable'] || null !== $prefs['days_in_advance']['value']) ) { $options = []; for ($i = 0; $i <= 30; $i++) { $options[$i] = [ 'name' => $this->translate( 1 === $i ? 'messaging_settings_num_of_days' : 'messaging_settings_num_of_days_plural', ['%%days%%' => $i] ), 'active' => $i == $prefs['days_in_advance']['value'] ]; } $settings['settings']['days_in_advance'] = [ 'type' => 'select', 'value' => $prefs['days_in_advance']['value'], 'options' => $options, 'readonly' => !$prefs['days_in_advance']['configurable'] ]; } $messagingSettings[$type] = $settings; } } $phoneField = isset($this->config['Profile']['phoneNumberField']) ? $this->config['Profile']['phoneNumberField'] : 'mobile'; return [ 'firstname' => $result['firstname'], 'lastname' => $result['surname'], 'phone' => $phoneField && !empty($result[$phoneField]) ? $result[$phoneField] : '', 'smsnumber' => $result['smsalertnumber'], 'email' => $result['email'], 'address1' => $result['address'], 'address2' => $result['address2'], 'zip' => $result['zipcode'], 'city' => $result['city'], 'country' => $result['country'], 'category' => $result['categorycode'] ?? '', 'expiration_date' => $expirationDate, 'hold_identifier' => $result['othernames'], 'guarantor' => $guarantor, 'guarantees' => $guarantees, 'loan_history' => $result['privacy'], 'messagingServices' => $messagingSettings, 'notes' => $result['opacnote'], 'full_data' => $result ]; } /** * Purge Patron Transaction History * * @param array $patron The patron array from patronLogin * * @throws ILSException * @return array Associative array of the results */ public function purgeTransactionHistory($patron) { list($code, $result) = $this->makeRequest( ['v1', 'checkouts', 'history'], ['borrowernumber' => $patron['id']], 'DELETE', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Purging the loan history failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => 'loan_history_purged', 'sys_message' => '' ]; } /** * Update Patron Transaction History State * * Enable or disable patron's transaction history * * @param array $patron The patron array from patronLogin * @param mixed $state Any of the configured values * * @return array Associative array of the results */ public function updateTransactionHistoryState($patron, $state) { $request = [ 'privacy' => (int)$state ]; list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the checkout history state failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Update patron's phone number * * @param array $patron Patron array * @param string $phone Phone number * * @throws ILSException * * @return array Associative array of the results */ public function updatePhone($patron, $phone) { $request = [ 'mobile' => $phone ]; list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the phone number failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Update patron's SMS alert number * * @param array $patron Patron array * @param string $number SMS alert number * * @throws ILSException * * @return array Associative array of the results */ public function updateSmsNumber($patron, $number) { $fields = !empty($this->config['updateSmsNumber']['fields']) ? explode(',', $this->config['updateSmsNumber']['fields']) : ['smsalertnumber']; $request = []; foreach ($fields as $field) { $request[$field] = $number; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the phone number failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Update patron's email address * * @param array $patron Patron array * @param String $email Email address * * @throws ILSException * * @return array Associative array of the results */ public function updateEmail($patron, $email) { $request = [ 'email' => $email ]; list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { return [ 'success' => false, 'status' => 'Changing the email address failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Update patron contact information * * @param array $patron Patron array * @param array $details Associative array of patron contact information * * @throws ILSException * * @return array Associative array of the results */ public function updateAddress($patron, $details) { $addressFields = []; $fieldConfig = isset($this->config['updateAddress']['fields']) ? $this->config['updateAddress']['fields'] : []; foreach ($fieldConfig as $field) { $parts = explode(':', $field, 2); if (isset($parts[1])) { $addressFields[$parts[1]] = $parts[0]; } } // Pick the configured fields from the request $request = []; foreach ($details as $key => $value) { if (isset($addressFields[$key])) { $request[$key] = $value; } } list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id']], json_encode($request), 'PATCH', $patron, true ); if (!in_array($code, [200, 202, 204])) { if (409 === $code && !empty($result['conflict'])) { $keys = array_keys($result['conflict']); $key = reset($keys); $fieldName = isset($addressFields[$key]) ? $this->translate($addressFields[$key]) : '???'; $status = $this->translate( 'request_change_value_already_in_use', ['%%field%%' => $fieldName] ); } else { $status = 'Changing the contact information failed'; } return [ 'success' => false, 'status' => $status, 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Update patron messaging settings * * @param array $patron Patron array * @param array $details Associative array of messaging settings * * @throws ILSException * * @return array Associative array of the results */ public function updateMessagingSettings($patron, $details) { $messagingPrefs = $this->makeRequest( ['v1', 'messaging_preferences'], ['borrowernumber' => $patron['id']], 'GET', $patron ); $messagingSettings = []; foreach ($details as $prefId => $pref) { $result = []; foreach ($pref['settings'] as $settingId => $setting) { if (!empty($setting['readonly'])) { continue; } if ('boolean' === $setting['type']) { $result[$settingId] = [ 'value' => $setting['active'] ]; } elseif ('select' === $setting['type']) { $result[$settingId] = [ 'value' => ctype_digit($setting['value']) ? (int)$setting['value'] : $setting['value'] ]; } else { foreach ($setting['options'] as $optionId => $option) { $result[$settingId][$optionId] = $option['active']; } } } $messagingSettings[$prefId] = $result; } list($code, $result) = $this->makeRequest( ['v1', 'messaging_preferences'], [ 'borrowernumber' => $patron['id'], '##body##' => json_encode($messagingSettings) ], 'PUT', $patron, true ); if ($code >= 300) { return [ 'success' => false, 'status' => 'Changing the preferences failed', 'sys_message' => $result['error'] ?? $code ]; } return [ 'success' => true, 'status' => $code == 202 ? 'request_change_done' : 'request_change_accepted', 'sys_message' => '' ]; } /** * Change pickup location * * This is responsible for changing the pickup location of a hold * * @param string $patron Patron array * @param string $holdDetails The request details * * @return array Associative array of the results */ public function changePickupLocation($patron, $holdDetails) { $requestId = $holdDetails['requestId']; $pickUpLocation = $holdDetails['pickupLocationId']; if (!$this->pickUpLocationIsValid($pickUpLocation, $patron, $holdDetails)) { return $this->holdError('hold_invalid_pickup'); } $request = [ 'branchcode' => $pickUpLocation ]; list($code, $result) = $this->makeRequest( ['v1', 'holds', $requestId], json_encode($request), 'PUT', $patron, true ); if ($code >= 300) { return $this->holdError($code, $result); } return ['success' => true]; } /** * Change request status * * This is responsible for changing the status of a hold request * * @param string $patron Patron array * @param string $holdDetails The request details (at the moment only 'frozen' * is supported) * * @return array Associative array of the results */ public function changeRequestStatus($patron, $holdDetails) { $requestId = $holdDetails['requestId']; $frozen = !empty($holdDetails['frozen']); $request = [ 'suspend' => $frozen ]; list($code, $result) = $this->makeRequest( ['v1', 'holds', $requestId], json_encode($request), 'PUT', $patron, true ); if ($code >= 300) { return $this->holdError($code, $result); } return ['success' => true]; } /** * Return total amount of fees that may be paid online. * * @param array $patron Patron * @param array $fines Patron's fines * * @throws ILSException * @return array Associative array of payment info, * false if an ILSException occurred. */ public function getOnlinePayableAmount($patron, $fines) { if (!empty($fines)) { $amount = 0; foreach ($fines as $fine) { $amount += $fine['balance']; } $config = $this->getConfig('onlinePayment'); $nonPayableReason = false; if (isset($config['minimumFee']) && $amount < $config['minimumFee']) { $nonPayableReason = 'online_payment_minimum_fee'; } $res = ['payable' => empty($nonPayableReason), 'amount' => $amount]; if ($nonPayableReason) { $res['reason'] = $nonPayableReason; } return $res; } return [ 'payable' => false, 'amount' => 0, 'reason' => 'online_payment_minimum_fee' ]; } /** * Mark fees as paid. * * This is called after a successful online payment. * * @param array $patron Patron * @param int $amount Amount to be registered as paid * @param string $transactionId Transaction ID * @param int $transactionNumber Internal transaction number * * @throws ILSException * @return boolean success */ public function markFeesAsPaid($patron, $amount, $transactionId, $transactionNumber ) { $request = [ 'amount' => $amount / 100, 'note' => "Online transaction $transactionId" ]; $operator = $patron; if (!empty($this->config['onlinePayment']['userId']) && !empty($this->config['onlinePayment']['userPassword']) ) { $operator = [ 'cat_username' => $this->config['onlinePayment']['userId'], 'cat_password' => $this->config['onlinePayment']['userPassword'] ]; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', $patron['id'], 'payment'], json_encode($request), 'POST', $operator, true ); if ($code != 204) { $error = "Failed to mark payment of $amount paid for patron" . " {$patron['id']}: $code: " . print_r($result, true); $this->error($error); throw new ILSException($error); } // Clear patron's block cache $cacheId = 'blocks|' . $patron['id']; $this->removeCachedData($cacheId); return true; } /** * Get a password recovery token for a user * * @param array $params Required params such as cat_username and email * * @return array Associative array of the results */ public function getPasswordRecoveryToken($params) { $request = [ 'cardnumber' => $params['cat_username'], 'email' => $params['email'], 'skip_email' => true ]; $operator = []; if (!empty($this->config['PasswordRecovery']['userId']) && !empty($this->config['PasswordRecovery']['userPassword']) ) { $operator = [ 'cat_username' => $this->config['PasswordRecovery']['userId'], 'cat_password' => $this->config['PasswordRecovery']['userPassword'] ]; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', 'password', 'recovery'], json_encode($request), 'POST', $operator, true ); if (201 != $code) { if (404 != $code) { throw new ILSException("Failed to get a recovery token: $code"); } return [ 'success' => false, 'error' => $result['error'] ]; } return [ 'success' => true, 'token' => $result['uuid'] ]; } /** * Recover user's password with a token from getPasswordRecoveryToken * * @param array $params Required params such as cat_username, token and new * password * * @return array Associative array of the results */ public function recoverPassword($params) { $request = [ 'uuid' => $params['token'], 'new_password' => $params['password'], 'confirm_new_password' => $params['password'] ]; $operator = []; if (!empty($this->config['passwordRecovery']['userId']) && !empty($this->config['passwordRecovery']['userPassword']) ) { $operator = [ 'cat_username' => $this->config['passwordRecovery']['userId'], 'cat_password' => $this->config['passwordRecovery']['userPassword'] ]; } list($code, $result) = $this->makeRequest( ['v1', 'patrons', 'password', 'recovery', 'complete'], json_encode($request), 'POST', $operator, true ); if (200 != $code) { return [ 'success' => false, 'error' => $result['error'] ]; } return [ 'success' => true ]; } /** * Get Patron Holds * * This is responsible for retrieving all holds by a specific patron. * * @param array $patron The patron array from patronLogin * * @throws DateException * @throws ILSException * @return array Array of the patron's holds on success. */ public function getMyHolds($patron) { $result = $this->makeRequest( ['v1', 'holds'], ['borrowernumber' => $patron['id']], 'GET', $patron ); if (!isset($result)) { return []; } $holds = []; foreach ($result as $entry) { $bibId = $entry['biblionumber'] ?? null; $itemId = $entry['itemnumber'] ?? null; $title = ''; $volume = ''; if ($itemId) { $item = $this->getItem($itemId); $bibId = $item['biblionumber'] ?? null; $volume = $item['enumchron'] ?? ''; } if (!empty($bibId)) { $bib = $this->getBibRecord($bibId); $title = $bib['title'] ?? ''; if (!empty($bib['title_remainder'])) { $title .= ' ' . $bib['title_remainder']; $title = trim($title); } } $frozen = false; if (!empty($entry['suspend'])) { $frozen = !empty($entry['suspend_until']) ? $entry['suspend_until'] : true; } $available = !empty($entry['waitingdate']); $inTransit = isset($entry['found']) && strtolower($entry['found']) == 't'; $holds[] = [ 'id' => $bibId, 'item_id' => $itemId ? $itemId : $entry['reserve_id'], 'location' => $entry['branchcode'], 'create' => $this->dateConverter->convertToDisplayDate( 'Y-m-d', $entry['reservedate'] ), 'expire' => !empty($entry['expirationdate']) ? $this->dateConverter->convertToDisplayDate( 'Y-m-d', $entry['expirationdate'] ) : '', 'position' => $entry['priority'], 'available' => $available, 'in_transit' => $inTransit, 'requestId' => $entry['reserve_id'], 'title' => $title, 'volume' => $volume, 'frozen' => $frozen, 'is_editable' => !$available && !$inTransit ]; } return $holds; } /** * Public Function which retrieves renew, hold and cancel settings from the * driver ini file. * * @param string $function The name of the feature to be checked * @param array $params Optional feature-specific parameters (array) * * @return array An array with key-value pairs. * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function getConfig($function, $params = null) { if ('getPasswordRecoveryToken' === $function || 'recoverPassword' === $function ) { return !empty($this->config['PasswordRecovery']['enabled']) ? $this->config['PasswordRecovery'] : false; } elseif ('getPatronStaffAuthorizationStatus' === $function) { return ['enabled' => true]; } $functionConfig = parent::getConfig($function, $params); if ($functionConfig && 'onlinePayment' === $function) { if (!isset($functionConfig['exactBalanceRequired'])) { $functionConfig['exactBalanceRequired'] = false; } } return $functionConfig; } /** * Check if patron belongs to staff. * * @param array $patron The patron array from patronLogin * * @return bool True if patron is staff, false if not */ public function getPatronStaffAuthorizationStatus($patron) { $username = $patron['cat_username']; if ($this->sessionCache->patron != $username) { if (!$this->renewPatronCookie($patron)) { return false; } } return !empty( array_intersect( ['superlibrarian', 'catalogue'], $this->sessionCache->patronPermissions ) ); } /** * Get Pick Up Locations * * This is responsible for gettting a list of valid library locations for * holds / recall retrieval * * @param array $patron Patron information returned by the patronLogin * method. * @param array $holdDetails Optional array, only passed in when getting a list * in the context of placing a hold; contains most of the same values passed to * placeHold, minus the patron data. May be used to limit the pickup options * or may be ignored. The driver must not add new options to the return array * based on this data or other areas of VuFind may behave incorrectly. * * @throws ILSException * @return array An array of associative arrays with locationID and * locationDisplay keys * * @SuppressWarnings(PHPMD.UnusedFormalParameter) */ public function getPickUpLocations($patron = false, $holdDetails = null) { $locations = []; $section = array_key_exists('StorageRetrievalRequest', $holdDetails ?? []) ? 'StorageRetrievalRequests' : 'Holds'; $excluded = isset($this->config[$section]['excludePickupLocations']) ? explode(':', $this->config[$section]['excludePickupLocations']) : []; $included = null; if (!empty($this->config['Catalog']['availabilitySupportsPickupLocations']) ) { $included = []; $level = isset($holdDetails['level']) && !empty($holdDetails['level']) ? $holdDetails['level'] : 'copy'; $bibId = $holdDetails['id']; $itemId = $holdDetails['item_id'] ?? false; if ('copy' === $level && false === $itemId) { return []; } // Collect branch codes that are to be included if ('copy' === $level) { $result = $this->makeRequest( ['v1', 'availability', 'item', 'hold'], [ 'itemnumber' => $itemId, 'borrowernumber' => (int)$patron['id'], 'query_pickup_locations' => 1 ], 'GET', $patron ); if (empty($result)) { return []; } $pickupLocs = $result[0]['availability']['notes']['Item::PickupLocations'] ?? []; } else { $result = $this->makeRequest( ['v1', 'availability', 'biblio', 'hold'], [ 'biblionumber' => $bibId, 'borrowernumber' => (int)$patron['id'], 'query_pickup_locations' => 1 ], 'GET', $patron ); if (empty($result)) { return []; } $pickupLocs = $result[0]['availability']['notes']['Biblio::PickupLocations'] ?? []; } foreach ($pickupLocs['to_libraries'] ?? [] as $code) { $included[] = $code; } } $result = $this->makeRequest( ['v1', 'libraries'], false, 'GET', $patron ); if (empty($result)) { return []; } foreach ($result as $location) { $code = $location['branchcode']; if ((null === $included && !$location['pickup_location']) || in_array($code, $excluded) || (null !== $included && !in_array($code, $included)) ) { continue; } $locations[] = [ 'locationID' => $code, 'locationDisplay' => $location['branchname'] ]; } // Do we need to sort pickup locations? If the setting is false, don't // bother doing any more work. If it's not set at all, default to // alphabetical order. $orderSetting = isset($this->config[$section]['pickUpLocationOrder']) ? $this->config[$section]['pickUpLocationOrder'] : 'default'; if (count($locations) > 1 && !empty($orderSetting)) { $locationOrder = $orderSetting === 'default' ? [] : array_flip(explode(':', $orderSetting)); $sortFunction = function ($a, $b) use ($locationOrder) { $aLoc = $a['locationID']; $bLoc = $b['locationID']; if (isset($locationOrder[$aLoc])) { if (isset($locationOrder[$bLoc])) { return $locationOrder[$aLoc] - $locationOrder[$bLoc]; } return -1; } if (isset($locationOrder[$bLoc])) { return 1; } return strcasecmp($a['locationDisplay'], $b['locationDisplay']); }; usort($locations, $sortFunction); } return $locations; } /** * Return summary of holdings items. * * @param array $holdings Parsed holdings items * * @return array summary */ protected function getHoldingsSummary($holdings) { $availableTotal = $itemsTotal = $reservationsTotal = 0; $requests = 0; $locations = []; foreach ($holdings as $item) { if (!empty($item['availability'])) { $availableTotal++; } if (strncmp($item['item_id'], 'HLD_', 4) !== 0) { $itemsTotal++; } $locations[$item['location']] = true; if ($item['requests_placed'] > $requests) { $requests = $item['requests_placed']; } } // Since summary data is appended to the holdings array as a fake item, // we need to add a few dummy-fields that VuFind expects to be // defined for all elements. // Use a stupid location name to make sure this doesn't get mixed with // real items that don't have a proper location. $result = [ 'available' => $availableTotal, 'total' => $itemsTotal, 'locations' => count($locations), 'availability' => null, 'callnumber' => null, 'location' => '__HOLDINGSSUMMARYLOCATION__' ]; if (!empty($this->config['Holdings']['display_total_hold_count'])) { $result['reservations'] = $requests; } return $result; } /** * Return a location for a Koha item * * @param array $item Item * * @return string */ protected function getItemLocationName($item) { $result = parent::getItemLocationName($item); if ($this->groupHoldingsByLocation) { $location = $this->translateLocation( $item['location'], !empty($item['location_description']) ? $item['location_description'] : $item['location'] ); if ($location) { // Empty translation will result in &#x200C $emptyChar = html_entity_decode('&#x200C;', ENT_NOQUOTES, 'UTF-8'); if ($result && $result !== $emptyChar) { $result .= ', '; } $result .= $location; } } return $result; } /** * Return a call number for a Koha item * * @param array $item Item * * @return string */ protected function getItemCallNumber($item) { $result = []; if (!empty($item['ccode']) && !empty($this->config['Holdings']['display_ccode']) ) { $result[] = $this->translateCollection( $item['ccode'], $item['ccode_description'] ?? $item['ccode'] ); } if (!$this->groupHoldingsByLocation) { $result[] = $this->translateLocation( $item['location'], !empty($item['location_description']) ? $item['location_description'] : $item['location'] ); } if ((!empty($item['itemcallnumber']) || !empty($item['itemcallnumber_display'])) && !empty($this->config['Holdings']['display_full_call_number']) ) { if (!empty($this->config['Holdings']['use_non_display_call_number'])) { $result[] = $item['itemcallnumber']; } else { $result[] = !empty($item['itemcallnumber_display']) ? $item['itemcallnumber_display'] : $item['itemcallnumber']; } } $str = implode(', ', $result); return $str; } /** * Place Hold * * Attempts to place a hold or recall on a particular item and returns * an array with result details or throws an exception on failure of support * classes * * @param array $holdDetails An array of item and patron data * * @throws ILSException * @return mixed An array of data on the request including * whether or not it was successful and a system message (if available) */ public function placeHold($holdDetails) { $patron = $holdDetails['patron']; $level = isset($holdDetails['level']) && !empty($holdDetails['level']) ? $holdDetails['level'] : 'copy'; $pickUpLocation = !empty($holdDetails['pickUpLocation']) ? $holdDetails['pickUpLocation'] : $this->defaultPickUpLocation; $itemId = $holdDetails['item_id'] ?? false; $comment = $holdDetails['comment'] ?? ''; $bibId = $holdDetails['id']; // Convert last interest date from Display Format to Koha's required format try { $lastInterestDate = $this->dateConverter->convertFromDisplayDate( 'Y-m-d', $holdDetails['requiredBy'] ); } catch (DateException $e) { // Hold Date is invalid return $this->holdError('hold_date_invalid'); } if ($level == 'copy' && empty($itemId)) { throw new ILSException("Hold level is 'copy', but item ID is empty"); } try { $checkTime = $this->dateConverter->convertFromDisplayDate( 'U', $holdDetails['requiredBy'] ); if (!is_numeric($checkTime)) { throw new DateException('Result should be numeric'); } } catch (DateException $e) { throw new ILSException('Problem parsing required by date.'); } if (time() > $checkTime) { // Hold Date is in the past return $this->holdError('hold_date_past'); } // Make sure pickup location is valid if (!$this->pickUpLocationIsValid($pickUpLocation, $patron, $holdDetails)) { return $this->holdError('hold_invalid_pickup'); } $request = [ 'biblionumber' => (int)$bibId, 'borrowernumber' => (int)$patron['id'], 'branchcode' => $pickUpLocation, 'reservenotes' => $comment, 'expirationdate' => $this->dateConverter->convertFromDisplayDate( 'Y-m-d', $holdDetails['requiredBy'] ) ]; if ($level == 'copy') { $request['itemnumber'] = (int)$itemId; } list($code, $result) = $this->makeRequest( ['v1', 'holds'], json_encode($request), 'POST', $patron, true ); if ($code >= 300) { return $this->holdError($code, $result); } return ['success' => true]; } /** * Get Item Statuses * * This is responsible for retrieving the status information of a certain * record. * * @param string $id The record id to retrieve the holdings for * @param array $patron Patron information, if available * * @return array An associative array with the following keys: * id, availability (boolean), status, location, reserve, callnumber. */ protected function getItemStatusesForBiblio($id, $patron = null) { $holdings = []; if (!empty($this->config['Holdings']['use_holding_records'])) { list($code, $holdingsResult) = $this->makeRequest( ['v1', 'biblios', $id, 'holdings'], [], 'GET', $patron, true ); if (404 === $code) { return []; } if ($code !== 200) { throw new ILSException('Problem with Koha REST API.'); } // Turn the holdings into a keyed array if (!empty($holdingsResult['holdings'])) { foreach ($holdingsResult['holdings'] as $holding) { $holdings[$holding['holding_id']] = $holding; } } } list($code, $result) = $this->makeRequest( ['v1', 'availability', 'biblio', 'search'], ['biblionumber' => $id], 'GET', $patron, true ); if (404 === $code) { return []; } if ($code !== 200) { throw new ILSException('Problem with Koha REST API.'); } $statuses = []; foreach ($result[0]['item_availabilities'] ?? [] as $i => $item) { // $holding is a reference! unset($holding); if (!empty($item['holding_id']) && isset($holdings[$item['holding_id']]) ) { $holding = &$holdings[$item['holding_id']]; if ($holding['suppress']) { continue; } } $avail = $item['availability']; $available = $avail['available']; $statusCodes = $this->getItemStatusCodes($item); $status = $this->pickStatus($statusCodes); if (isset($avail['unavailabilities']['Item::CheckedOut']['date_due'])) { $duedate = $this->dateConverter->convertToDisplayDate( 'Y-m-d\TH:i:sP', $avail['unavailabilities']['Item::CheckedOut']['date_due'] ); } else { $duedate = null; } $location = $this->getItemLocationName($item); $callnumber = $this->getItemCallNumber($item); $sublocation = $item['sub_description'] ?? ''; $branchId = (!$this->useHomeBranch && null !== $item['holdingbranch']) ? $item['holdingbranch'] : $item['homebranch']; $locationId = $item['location']; $entry = [ 'id' => $id, 'item_id' => $item['itemnumber'], 'location' => $location, 'department' => $sublocation, 'availability' => $available, 'status' => $status, 'status_array' => $statusCodes, 'reserve' => 'N', 'callnumber' => $callnumber, 'duedate' => $duedate, 'number' => $item['enumchron'], 'barcode' => $item['barcode'], 'sort' => $i, 'requests_placed' => max( [$item['hold_queue_length'], $result[0]['hold_queue_length']] ), 'branchId' => $branchId, 'locationId' => $locationId ]; if (!empty($item['itemnotes'])) { $entry['item_notes'] = [$item['itemnotes']]; } if ($patron && $this->itemHoldAllowed($item)) { $entry['is_holdable'] = true; $entry['level'] = 'copy'; $entry['addLink'] = 'check'; } else { $entry['is_holdable'] = false; } if ($patron && $this->itemArticleRequestAllowed($item)) { $entry['storageRetrievalRequest'] = 'auto'; $entry['addStorageRetrievalRequestLink'] = 'check'; } if (isset($holding)) { $entry += $this->getHoldingData($holding); $holding['_hasItems'] = true; } $statuses[] = $entry; } // $holding is a reference! unset($holding); if (!isset($i)) { $i = 0; } // Add holdings that don't have items if (!empty($holdings)) { foreach ($holdings as $holding) { if ($holding['suppress'] || !empty($holding['_hasItems'])) { continue; } $holdingData = $this->getHoldingData($holding, true); $i++; $entry = $this->createHoldingEntry($id, $holding, $i); $entry += $holdingData; $statuses[] = $entry; } } // See if there are links in holdings $electronic = []; if (!empty($holdings)) { foreach ($holdings as $holding) { $marc = $this->getHoldingMarc($holding); if (null === $marc) { continue; } $notes = []; if ($fields = $marc->getFields('852')) { foreach ($fields as $field) { if ($subfield = $field->getSubfield('z')) { $notes[] = $subfield->getData(); } } } if ($fields = $marc->getFields('856')) { foreach ($fields as $field) { if ($subfields = $field->getSubfields()) { $urls = []; $desc = []; $parts = []; foreach ($subfields as $code => $subfield) { if ('u' === $code) { $urls[] = $subfield->getData(); } elseif ('3' === $code) { $parts[] = $subfield->getData(); } elseif (in_array($code, ['y', 'z'])) { $desc[] = $subfield->getData(); } } foreach ($urls as $url) { ++$i; $entry = $this->createHoldingEntry($id, $holding, $i); $entry['availability'] = true; $entry['location'] = implode('. ', $desc); $entry['locationhref'] = $url; $entry['use_unknown_message'] = false; $entry['status'] = implode('. ', array_merge($parts, $notes)); $electronic[] = $entry; } } } } } } usort($statuses, [$this, 'statusSortFunction']); usort($electronic, [$this, 'statusSortFunction']); return [ 'holdings' => $statuses, 'electronic_holdings' => $electronic ]; } /** * Create a holding entry * * @param string $id Bib ID * @param array $holding Holding * @param int $sortKey Sort key * * @return array */ protected function createHoldingEntry($id, $holding, $sortKey) { $location = $this->getBranchName($holding['holdingbranch']); $callnumber = ''; if (!empty($holding['ccode']) && !empty($this->config['Holdings']['display_ccode']) ) { $callnumber = $this->translateCollection( $holding['ccode'], $holding['ccode_description'] ?? $holding['ccode'] ); } if ($this->groupHoldingsByLocation) { $holdingLoc = $this->translateLocation( $holding['location'], !empty($holding['location_description']) ? $holding['location_description'] : $holding['location'] ); if ($holdingLoc) { if ($location) { $location .= ', '; } $location .= $holdingLoc; } } else { if ($callnumber) { $callnumber .= ', '; } $callnumber .= $this->translateLocation( $holding['location'], !empty($holding['location_description']) ? $holding['location_description'] : $holding['location'] ); } if ($holding['callnumber']) { $callnumber .= ' ' . $holding['callnumber']; } $callnumber = trim($callnumber); $branchId = $holding['holdingbranch']; $locationId = $holding['location']; return [ 'id' => $id, 'item_id' => 'HLD_' . $holding['biblionumber'], 'location' => $location, 'requests_placed' => 0, 'status' => '', 'use_unknown_message' => true, 'availability' => false, 'duedate' => '', 'barcode' => '', 'callnumber' => $callnumber, 'sort' => $sortKey, 'branchId' => $branchId, 'locationId' => $locationId ]; } /** * Return a location for a Koha branch ID * * @param string $branchId Branch ID * * @return string */ protected function getBranchName($branchId) { $name = $this->translate("location_$branchId"); if ($name === "location_$branchId") { $branches = $this->getCachedData('branches'); if (null === $branches) { $result = $this->makeRequest( ['v1', 'libraries'], false, 'GET' ); $branches = []; foreach ($result as $branch) { $branches[$branch['branchcode']] = $branch['branchname']; } $this->putCachedData('branches', $branches); } $name = $branches[$branchId] ?? $branchId; } return $name; } /** * Get a MARC record for the given holding or null if not available * * @param array $holding Holding * * @return \File_MARCXML */ protected function getHoldingMarc(&$holding) { if (!isset($holding['_marcRecord'])) { foreach ($holding['holdings_metadata'] ?? [$holding['metadata']] as $metadata ) { if ('marcxml' === $metadata['format'] && 'MARC21' === $metadata['marcflavour'] ) { $marc = new \File_MARCXML( $metadata['metadata'], \File_MARCXML::SOURCE_STRING ); $holding['_marcRecord'] = $marc->next(); return $holding['_marcRecord']; } } $holding['_marcRecord'] = null; } return $holding['_marcRecord']; } /** * Get holding data from a holding record * * @param array $holding Holding record from Koha * * @return array */ protected function getHoldingData(&$holding) { $marc = $this->getHoldingMarc($holding); if (null === $marc) { return []; } $marcDetails = []; // Get Notes $data = $this->getMFHDData( $marc, isset($this->config['Holdings']['notes']) ? $this->config['Holdings']['notes'] : '852z' ); if ($data) { $marcDetails['notes'] = $data; } // Get Summary (may be multiple lines) $data = $this->getMFHDData( $marc, isset($this->config['Holdings']['summary']) ? $this->config['Holdings']['summary'] : '866a' ); if ($data) { $marcDetails['summary'] = $data; } // Get Supplements if (isset($this->config['Holdings']['supplements'])) { $data = $this->getMFHDData( $marc, $this->config['Holdings']['supplements'] ); if ($data) { $marcDetails['supplements'] = $data; } } // Get Indexes if (isset($this->config['Holdings']['indexes'])) { $data = $this->getMFHDData( $marc, $this->config['Holdings']['indexes'] ); if ($data) { $marcDetails['indexes'] = $data; } } // Get links if (isset($this->config['Holdings']['links'])) { $data = $this->getMFHDData( $marc, $this->config['Holdings']['links'] ); if ($data) { $marcDetails['links'] = $data; } } // Make sure to return an empty array unless we have details to display if (!empty($marcDetails)) { $marcDetails['holdings_id'] = $holding['holding_id']; } return $marcDetails; } /** * Get specified fields from an MFHD MARC Record * * @param object $record File_MARC object * @param array|string $fieldSpecs Array or colon-separated list of * field/subfield specifications (3 chars for field code and then subfields, * e.g. 866az) * * @return string|string[] Results as a string if single, array if multiple */ protected function getMFHDData($record, $fieldSpecs) { if (!is_array($fieldSpecs)) { $fieldSpecs = explode(':', $fieldSpecs); } $results = ''; foreach ($fieldSpecs as $fieldSpec) { $fieldCode = substr($fieldSpec, 0, 3); $subfieldCodes = substr($fieldSpec, 3); if ($fields = $record->getFields($fieldCode)) { foreach ($fields as $field) { if ($subfields = $field->getSubfields()) { $line = ''; foreach ($subfields as $code => $subfield) { if (!strstr($subfieldCodes, $code)) { continue; } if ($line) { $line .= ' '; } $line .= $subfield->getData(); } if ($line) { if (!$results) { $results = $line; } else { if (!is_array($results)) { $results = [$results]; } $results[] = $line; } } } } } } return $results; } /** * Translate location name * * @param string $location Location code * @param string $default Default value if translation is not available * * @return string */ protected function translateLocation($location, $default = null) { if (empty($location)) { return null !== $default ? $default : ''; } $prefix = $catPrefix = 'location_'; if (!empty($this->config['Catalog']['id'])) { $catPrefix .= $this->config['Catalog']['id'] . '_'; } return $this->translate( "$catPrefix$location", null, $this->translate( "$prefix$location", null, null !== $default ? $default : $location ) ); } /** * Translate collection name * * @param string $code Collection code * @param string $description Collection description * * @return string */ protected function translateCollection($code, $description) { $prefix = 'collection_'; if (!empty($this->config['Catalog']['id'])) { $prefix .= $this->config['Catalog']['id'] . '_'; } return $this->translate( "$prefix$code", null, $description ); } /** * Status item sort function * * @param array $a First status record to compare * @param array $b Second status record to compare * * @return int */ protected function statusSortFunction($a, $b) { $orderA = $this->holdingsBranchOrder[$a['branchId'] . '/' . $a['locationId']] ?? $this->holdingsBranchOrder[$a['branchId']] ?? 999; $orderB = $this->holdingsBranchOrder[$b['branchId'] . '/' . $b['locationId']] ?? $this->holdingsBranchOrder[$b['branchId']] ?? 999; $result = $orderA - $orderB; if (0 === $result) { $orderA = $this->holdingsLocationOrder[$a['locationId']] ?? 999; $orderB = $this->holdingsLocationOrder[$b['locationId']] ?? 999; $result = $orderA - $orderB; } if (0 === $result) { $result = strcmp($a['location'], $b['location']); } if (0 === $result && $this->sortItemsByEnumChron) { // Reverse chronological order $result = strnatcmp($b['number'] ?? '', $a['number'] ?? ''); } if (0 === $result) { $result = $a['sort'] - $b['sort']; } return $result; } }
Java
package com.github.esadmin.meta.model; import java.util.Date; import java.util.HashSet; import java.util.Set; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToMany; import javax.persistence.OneToMany; import javax.persistence.OrderBy; import javax.persistence.Table; import org.guess.core.orm.IdEntity; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import com.fasterxml.jackson.annotation.JsonIgnoreProperties; /** * 索引对象Entity * @author Joe.zhang * @version 2015-12-08 */ @Entity @Table(name = "meta_dbindex") @JsonIgnoreProperties(value = {"hibernateLazyInitializer","handler", "columns"}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) public class DBIndex extends IdEntity { /** * 数据表 */ @ManyToMany(cascade = { CascadeType.PERSIST, CascadeType.MERGE }, targetEntity = DBTable.class) @JoinTable(name = "meta_table_index", joinColumns = { @JoinColumn(name = "index_id") }, inverseJoinColumns = { @JoinColumn(name = "table_id") }) @JsonIgnoreProperties(value = { "hibernateLazyInitializer","handler","datasource"}) @Cache(usage = CacheConcurrencyStrategy.READ_WRITE) private Set<DBTable> tables = new HashSet<DBTable>(0); /** * 索引库名 */ @Column(name="index_name") private String index_name; /** * 索引表名 */ @Column(name="type_name") private String type_name; /** * 索引类别 */ @Column(name="index_type") private Integer indexType; /** * 建立者 */ @Column(name="createby_id") private Long createbyId; /** * 更新者 */ @Column(name="updateby_id") private Long updatebyId; /** * 建立世间 */ @Column(name="create_date") private Date createDate; /** * 更新世间 */ @Column(name="update_date") private Date updateDate; /** * 备注 */ @Column(name="remark") private String remark; @OneToMany(targetEntity = DbColumn.class, fetch = FetchType.LAZY, cascade = CascadeType.ALL,mappedBy="dbindex") @OrderBy("id ASC") private Set<DbColumn> columns; @Column(name="check_label") private Integer checkLabel; public Integer getCheckLabel() { return checkLabel; } public void setCheckLabel(Integer checkLabel) { this.checkLabel = checkLabel; } public Set<DBTable> getTables() { return tables; } public void setTables(Set<DBTable> tables) { this.tables = tables; } public String getIndex_name() { return index_name; } public void setIndex_name(String index_name) { this.index_name = index_name; } public String getType_name() { return type_name; } public void setType_name(String type_name) { this.type_name = type_name; } public Integer getIndexType() { return indexType; } public void setIndexType(Integer indexType) { this.indexType = indexType; } public Long getCreatebyId() { return createbyId; } public void setCreatebyId(Long createbyId) { this.createbyId = createbyId; } public Set<DbColumn> getColumns() { return columns; } public void setColumns(Set<DbColumn> columns) { this.columns = columns; } public Long getUpdatebyId() { return updatebyId; } public void setUpdatebyId(Long updatebyId) { this.updatebyId = updatebyId; } public Date getCreateDate() { return createDate; } public void setCreateDate(Date createDate) { this.createDate = createDate; } public Date getUpdateDate() { return updateDate; } public void setUpdateDate(Date updateDate) { this.updateDate = updateDate; } public String getRemark() { return remark; } public void setRemark(String remark) { this.remark = remark; } }
Java
# Copyright (c) 1998 Cygnus Support # # The authors hereby grant permission to use, copy, modify, distribute, # and license this software and its documentation for any purpose, provided # that existing copyright notices are retained in all copies and that this # notice is included verbatim in any distributions. No written agreement, # license, or royalty fee is required for any of the authorized uses. # Modifications to this software may be copyrighted by their authors # and need not follow the licensing terms described here, provided that # the new terms are clearly indicated on the first page of each file where # they apply. DESTDIR = VPATH = ../../.././libgloss/libnosys srcdir = ../../.././libgloss/libnosys objdir = . srcroot = $(srcdir)/../.. objroot = $(objdir)/../.. prefix = /usr/local exec_prefix = ${prefix} host_alias = arm-none-eabi target_alias = arm-none-eabi program_transform_name = s&^&arm-none-eabi-& bindir = ${exec_prefix}/bin libdir = ${exec_prefix}/lib tooldir = $(exec_prefix)/$(target_alias) # Multilib support variables. # TOP is used instead of MULTI{BUILD,SRC}TOP. MULTIDIRS = MULTISUBDIR = MULTIDO = true MULTICLEAN = true INSTALL = /usr/bin/install -c INSTALL_PROGRAM = /usr/bin/install -c INSTALL_DATA = /usr/bin/install -c -m 644 SHELL = /bin/sh CC = arm-none-eabi-gcc -B/sources/newlib/newlib-1.18.0/arm-none-eabi/newlib/ -isystem /sources/newlib/newlib-1.18.0/arm-none-eabi/newlib/targ-include -isystem /sources/newlib/newlib-1.18.0/newlib/libc/include -B/sources/newlib/newlib-1.18.0/arm-none-eabi/libgloss/arm -L/sources/newlib/newlib-1.18.0/arm-none-eabi/libgloss/libnosys -L/sources/newlib/newlib-1.18.0/libgloss/arm #AS = arm-none-eabi-as AS = `if [ -f ${objroot}/../gas/as-new ] ; \ then echo ${objroot}/../gas/as-new ; \ else echo as ; fi` AR = arm-none-eabi-ar #LD = arm-none-eabi-ld LD = `if [ -f ${objroot}/../ld/ld-new ] ; \ then echo ${objroot}/../ld/ld-new ; \ else echo ld ; fi` RANLIB = arm-none-eabi-ranlib OBJDUMP = `if [ -f ${objroot}/../binutils/objdump ] ; \ then echo ${objroot}/../binutils/objdump ; \ else t='$(program_transform_name)'; echo objdump | sed -e $$t ; fi` OBJCOPY = `if [ -f ${objroot}/../binutils/objcopy ] ; \ then echo ${objroot}/../binutils/objcopy ; \ else t='$(program_transform_name)'; echo objcopy | sed -e $$t ; fi` # object files needed OBJS = chown.o close.o environ.o errno.o execve.o fork.o fstat.o \ getpid.o gettod.o isatty.o kill.o link.o lseek.o open.o \ read.o readlink.o sbrk.o stat.o symlink.o times.o unlink.o \ wait.o write.o _exit.o # Object files specific to particular targets. EVALOBJS = ${OBJS} GCC_LDFLAGS = `if [ -d ${objroot}/../gcc ] ; \ then echo -L${objroot}/../gcc ; fi` OUTPUTS = libnosys.a NEWLIB_CFLAGS = `if [ -d ${objroot}/newlib ]; then echo -I${objroot}/newlib/targ-include -I${srcroot}/newlib/libc/include; fi` NEWLIB_LDFLAGS = `if [ -d ${objroot}/newlib ]; then echo -B${objroot}/newlib/ -L${objroot}/newlib/; fi` INCLUDES = -I. -I$(srcdir)/.. # Note that when building the library, ${MULTILIB} is not the way multilib # options are passed; they're passed in $(CFLAGS). CFLAGS_FOR_TARGET = ${MULTILIB} ${INCLUDES} ${NEWLIB_CFLAGS} LDFLAGS_FOR_TARGET = ${MULTILIB} ${NEWLIB_LDFLAGS} AR_FLAGS = qc .c.o: $(CC) $(CFLAGS_FOR_TARGET) -O2 $(INCLUDES) -c $(CFLAGS) $< .C.o: $(CC) $(CFLAGS_FOR_TARGET) -O2 $(INCLUDES) -c $(CFLAGS) $< .s.o: $(AS) $(ASFLAGS_FOR_TARGET) $(INCLUDES) $(ASFLAGS) -o $*.o $< # # GCC knows to run the preprocessor on .S files before it assembles them. # .S.o: $(CC) $(CFLAGS_FOR_TARGET) $(INCLUDES) $(CFLAGS) -c $< # # this is a bogus target that'll produce an assembler from the # C source with the right compiler options. this is so we can # track down code generation or debug symbol bugs. # .c.s: $(CC) $(CFLAGS_FOR_TARGET) -S $(INCLUDES) $(CFLAGS) $< all: ${OUTPUTS} # # here's where we build the library for each target # libnosys.a: $(EVALOBJS) ${AR} ${ARFLAGS} $@ $(EVALOBJS) ${RANLIB} $@ doc: clean mostlyclean: rm -f $(OUTPUTS) *.i *~ *.o *-test *.srec *.dis *.map *.x distclean maintainer-clean realclean: clean rm -f Makefile config.status $(OUTPUTS) .PHONY: install info install-info clean-info install: @for outputs in ${OUTPUTS}; do\ mkdir -p $(DESTDIR)$(tooldir)/lib${MULTISUBDIR}; \ $(INSTALL_PROGRAM) $${outputs} $(DESTDIR)$(tooldir)/lib${MULTISUBDIR}; \ done info: install-info: clean-info: Makefile: Makefile.in config.status ../../.././libgloss/libnosys/../config/default.mh $(SHELL) config.status config.status: configure $(SHELL) config.status --recheck
Java
<html> <head> <meta http-equiv="Content-Type" content="text/html; charset=US-ASCII"> <title>Struct base_unit_info&lt;imperial::ounce_base_unit&gt;</title> <link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css"> <meta name="generator" content="DocBook XSL Stylesheets V1.76.1"> <link rel="home" href="../../index.html" title="The Boost C++ Libraries BoostBook Documentation Subset"> <link rel="up" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.ounce_hpp" title="Header &lt;boost/units/base_units/imperial/ounce.hpp&gt;"> <link rel="prev" href="base_unit_info_imperial_id1623224.html" title="Struct base_unit_info&lt;imperial::mile_base_unit&gt;"> <link rel="next" href="imperial/pint_base_unit.html" title="Struct pint_base_unit"> </head> <body bgcolor="white" text="black" link="#0000FF" vlink="#840084" alink="#0000FF"> <table cellpadding="2" width="100%"><tr> <td valign="top"><img alt="Boost C++ Libraries" width="277" height="86" src="../../../../boost.png"></td> <td align="center"><a href="../../../../index.html">Home</a></td> <td align="center"><a href="../../../../libs/libraries.htm">Libraries</a></td> <td align="center"><a href="http://www.boost.org/users/people.html">People</a></td> <td align="center"><a href="http://www.boost.org/users/faq.html">FAQ</a></td> <td align="center"><a href="../../../../more/index.htm">More</a></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="base_unit_info_imperial_id1623224.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.ounce_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="imperial/pint_base_unit.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> <div class="refentry"> <a name="boost.units.base_unit_info_imperial_id1623277"></a><div class="titlepage"></div> <div class="refnamediv"> <h2><span class="refentrytitle">Struct base_unit_info&lt;imperial::ounce_base_unit&gt;</span></h2> <p>boost::units::base_unit_info&lt;imperial::ounce_base_unit&gt;</p> </div> <h2 xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv-title">Synopsis</h2> <div xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" class="refsynopsisdiv"><pre class="synopsis"><span class="comment">// In header: &lt;<a class="link" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.ounce_hpp" title="Header &lt;boost/units/base_units/imperial/ounce.hpp&gt;">boost/units/base_units/imperial/ounce.hpp</a>&gt; </span> <span class="keyword">struct</span> <a class="link" href="base_unit_info_imperial_id1623277.html" title="Struct base_unit_info&lt;imperial::ounce_base_unit&gt;">base_unit_info</a><span class="special">&lt;</span><span class="identifier">imperial</span><span class="special">::</span><span class="identifier">ounce_base_unit</span><span class="special">&gt;</span> <span class="special">{</span> <span class="comment">// <a class="link" href="base_unit_info_imperial_id1623277.html#id1623286-bb">public static functions</a></span> <span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="base_unit_info_imperial_id1623277.html#id1623289-bb"><span class="identifier">name</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span> <span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a class="link" href="base_unit_info_imperial_id1623277.html#id1623297-bb"><span class="identifier">symbol</span></a><span class="special">(</span><span class="special">)</span><span class="special">;</span> <span class="special">}</span><span class="special">;</span></pre></div> <div class="refsect1"> <a name="id3312168"></a><h2>Description</h2> <div class="refsect2"> <a name="id3312172"></a><h3> <a name="id1623286-bb"></a><code class="computeroutput">base_unit_info</code> public static functions</h3> <div class="orderedlist"><ol class="orderedlist" type="1"> <li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="id1623289-bb"></a><span class="identifier">name</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li> <li class="listitem"><pre class="literallayout"><span class="keyword">static</span> <span class="keyword">const</span> <span class="keyword">char</span> <span class="special">*</span> <a name="id1623297-bb"></a><span class="identifier">symbol</span><span class="special">(</span><span class="special">)</span><span class="special">;</span></pre></li> </ol></div> </div> </div> </div> <table xmlns:rev="http://www.cs.rpi.edu/~gregod/boost/tools/doc/revision" width="100%"><tr> <td align="left"></td> <td align="right"><div class="copyright-footer">Copyright &#169; 2003-2008 Matthias Christian Schabel<br>Copyright &#169; 2007-2010 Steven Watanabe<p> Distributed under the Boost Software License, Version 1.0. (See accompanying file LICENSE_1_0.txt or copy at <a href="http://www.boost.org/LICENSE_1_0.txt" target="_top">http://www.boost.org/LICENSE_1_0.txt</a>) </p> </div></td> </tr></table> <hr> <div class="spirit-nav"> <a accesskey="p" href="base_unit_info_imperial_id1623224.html"><img src="../../../../doc/src/images/prev.png" alt="Prev"></a><a accesskey="u" href="../../boost_units/Reference.html#header.boost.units.base_units.imperial.ounce_hpp"><img src="../../../../doc/src/images/up.png" alt="Up"></a><a accesskey="h" href="../../index.html"><img src="../../../../doc/src/images/home.png" alt="Home"></a><a accesskey="n" href="imperial/pint_base_unit.html"><img src="../../../../doc/src/images/next.png" alt="Next"></a> </div> </body> </html>
Java
\hypertarget{padlock_8h}{\section{C\-:/dev2/luambedtls/dependencies/mbedtls/include/mbedtls/padlock.h File Reference} \label{padlock_8h}\index{C\-:/dev2/luambedtls/dependencies/mbedtls/include/mbedtls/padlock.\-h@{C\-:/dev2/luambedtls/dependencies/mbedtls/include/mbedtls/padlock.\-h}} } V\-I\-A Pad\-Lock A\-C\-E for H\-W encryption/decryption supported by some processors. {\ttfamily \#include \char`\"{}aes.\-h\char`\"{}}\\* \subsection*{Macros} \begin{DoxyCompactItemize} \item \#define \hyperlink{padlock_8h_af5c37201b6033a4981bfbf5ebc51ba72}{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}~-\/0x0030 \end{DoxyCompactItemize} \subsection{Detailed Description} V\-I\-A Pad\-Lock A\-C\-E for H\-W encryption/decryption supported by some processors. Copyright (C) 2006-\/2015, A\-R\-M Limited, All Rights Reserved This file is part of mbed T\-L\-S (\href{https://tls.mbed.org}{\tt https\-://tls.\-mbed.\-org}) This program is free software; you can redistribute it and/or modify it under the terms of the G\-N\-U 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 W\-I\-T\-H\-O\-U\-T A\-N\-Y W\-A\-R\-R\-A\-N\-T\-Y; without even the implied warranty of M\-E\-R\-C\-H\-A\-N\-T\-A\-B\-I\-L\-I\-T\-Y or F\-I\-T\-N\-E\-S\-S F\-O\-R A P\-A\-R\-T\-I\-C\-U\-L\-A\-R P\-U\-R\-P\-O\-S\-E. See the G\-N\-U General Public License for more details. You should have received a copy of the G\-N\-U General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, M\-A 02110-\/1301 U\-S\-A. Definition in file \hyperlink{padlock_8h_source}{padlock.\-h}. \subsection{Macro Definition Documentation} \hypertarget{padlock_8h_af5c37201b6033a4981bfbf5ebc51ba72}{\index{padlock.\-h@{padlock.\-h}!M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D@{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}} \index{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D@{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}!padlock.h@{padlock.\-h}} \subsubsection[{M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D}]{\setlength{\rightskip}{0pt plus 5cm}\#define M\-B\-E\-D\-T\-L\-S\-\_\-\-E\-R\-R\-\_\-\-P\-A\-D\-L\-O\-C\-K\-\_\-\-D\-A\-T\-A\-\_\-\-M\-I\-S\-A\-L\-I\-G\-N\-E\-D~-\/0x0030}}\label{padlock_8h_af5c37201b6033a4981bfbf5ebc51ba72} Input data should be aligned. Definition at line 30 of file padlock.\-h.
Java
<?php /* core/themes/stable/templates/block/block--system-messages-block.html.twig */ class __TwigTemplate_0c8ec01fa0528f682259cd616ff9ee5ee8ceeeb5ec7cf0b3ece249a3727465d5 extends Twig_Template { public function __construct(Twig_Environment $env) { parent::__construct($env); $this->parent = false; $this->blocks = array( ); } protected function doDisplay(array $context, array $blocks = array()) { $tags = array(); $filters = array(); $functions = array(); try { $this->env->getExtension('sandbox')->checkSecurity( array(), array(), array() ); } catch (Twig_Sandbox_SecurityError $e) { $e->setTemplateFile($this->getTemplateName()); if ($e instanceof Twig_Sandbox_SecurityNotAllowedTagError && isset($tags[$e->getTagName()])) { $e->setTemplateLine($tags[$e->getTagName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFilterError && isset($filters[$e->getFilterName()])) { $e->setTemplateLine($filters[$e->getFilterName()]); } elseif ($e instanceof Twig_Sandbox_SecurityNotAllowedFunctionError && isset($functions[$e->getFunctionName()])) { $e->setTemplateLine($functions[$e->getFunctionName()]); } throw $e; } // line 13 echo $this->env->getExtension('sandbox')->ensureToStringAllowed($this->env->getExtension('drupal_core')->escapeFilter($this->env, (isset($context["content"]) ? $context["content"] : null), "html", null, true)); echo " "; } public function getTemplateName() { return "core/themes/stable/templates/block/block--system-messages-block.html.twig"; } public function isTraitable() { return false; } public function getDebugInfo() { return array ( 43 => 13,); } } /* {#*/ /* /***/ /* * @file*/ /* * Theme override for the messages block.*/ /* **/ /* * Removes wrapper elements from block so that empty block does not appear when*/ /* * there are no messages.*/ /* **/ /* * Available variables:*/ /* * - content: The content of this block.*/ /* *//* */ /* #}*/ /* {{ content }}*/ /* */
Java
import unittest from pyxt.mda import * from pyxt.chargen import CharacterGeneratorMock class MDATests(unittest.TestCase): def setUp(self): self.cg = CharacterGeneratorMock(width = 9, height = 14) self.mda = MonochromeDisplayAdapter(self.cg) # Hijack reset so it doesn't call into Pygame during the tests. self.reset_count = 0 self.mda.reset = self.reset_testable def reset_testable(self): self.reset_count += 1 def test_ports_list(self): self.assertEqual(self.mda.get_ports_list(), [0x03B0, 0x03B1, 0x03B2, 0x03B3, 0x03B4, 0x03B5, 0x03B6, 0x03B7, 0x03B8, 0x03B9, 0x03BA, 0x03BB]) def test_get_memory_size(self): self.assertEqual(self.mda.get_memory_size(), 4096) def test_initial_state(self): self.assertEqual(self.mda.control_reg, 0x00) self.assertEqual(self.mda.control_reg, 0x00) self.assertEqual(self.mda.screen, None) self.assertEqual(self.mda.char_generator, self.cg) self.assertEqual(len(self.mda.video_ram), 4096) def test_mem_write_byte_updates_video_ram(self): self.mda.mem_write_byte(0x0000, 0x41) self.assertEqual(self.mda.video_ram[0x0000], 0x41) def test_mem_write_byte_calls_char_generator_top_left(self): self.mda.mem_write_byte(0x0000, 0x41) self.assertEqual(self.cg.last_blit, (None, (0, 0), 0x41, MDA_GREEN, MDA_BLACK)) def test_mem_write_byte_calls_char_generator_bottom_right(self): self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_GREEN, MDA_BLACK)) def test_mem_write_byte_char_before_attribute(self): self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_GREEN, MDA_BLACK)) self.mda.mem_write_byte(3999, MDA_ATTR_INTENSITY) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_byte_attribute_before_char(self): self.mda.mem_write_byte(3999, MDA_ATTR_INTENSITY) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x00, MDA_BRIGHT_GREEN, MDA_BLACK)) self.mda.mem_write_byte(3998, 0xFF) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0xFF, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_byte_write_off_screen(self): self.mda.mem_write_byte(4000, 0xFF) self.assertEqual(self.cg.last_blit, None) def test_mem_read_byte(self): self.mda.video_ram[77] = 0xA5 self.assertEqual(self.mda.mem_read_byte(77), 0xA5) def test_mem_read_byte_off_screen(self): self.assertEqual(self.mda.mem_read_byte(4000), 0x00) @unittest.skip("We need to initialize Pygame exactly once at startup.") def test_reset_on_high_resolution_enable(self): self.assertEqual(self.reset_count, 0) self.mda.io_write_byte(0x3B8, 0x01) self.assertEqual(self.reset_count, 1) # Second write shouldn't call reset again. self.mda.io_write_byte(0x3B8, 0x01) self.assertEqual(self.reset_count, 1) def test_mem_write_word_at_top_left(self): self.mda.mem_write_word(0x0000, 0x0841) # 'A' with intensity. self.assertEqual(self.mda.video_ram[0x0000], 0x41) self.assertEqual(self.mda.video_ram[0x0001], 0x08) self.assertEqual(self.cg.last_blit, (None, (0, 0), 0x41, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_word_at_bottom_right(self): self.mda.mem_write_word(3998, 0x085A) # 'Z' with intensity. self.assertEqual(self.mda.video_ram[3998], 0x5A) self.assertEqual(self.mda.video_ram[3999], 0x08) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x5A, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_write_word_at_bottom_right_just_past(self): self.mda.mem_write_word(3999, 0xFF08) # 'Z' with intensity. self.assertEqual(self.mda.video_ram[3998], 0x00) # Should be unmodified. self.assertEqual(self.mda.video_ram[3999], 0x08) self.assertEqual(self.cg.last_blit, (None, (711, 336), 0x00, MDA_BRIGHT_GREEN, MDA_BLACK)) def test_mem_read_word(self): self.mda.video_ram[0x0000] = 0x41 self.mda.video_ram[0x0001] = 0x08 self.assertEqual(self.mda.mem_read_word(0x0000), 0x0841) def test_mem_read_word_just_past_the_end(self): self.mda.video_ram[3998] = 0x12 self.mda.video_ram[3999] = 0x34 self.assertEqual(self.mda.mem_read_word(3999), 0x0034) def test_horizontal_retrace_toggles(self): self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF0) self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF1) self.assertEqual(self.mda.io_read_byte(0x3BA), 0xF0) def test_current_pixel_updates_on_status_read(self): self.assertEqual(self.mda.current_pixel, [0, 0]) self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [1, 0]) def test_current_pixel_wraps_right(self): self.mda.current_pixel = [719, 0] self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [0, 1]) def test_current_pixel_wraps_bottom(self): self.mda.current_pixel = [719, 349] self.mda.io_read_byte(0x3BA) self.assertEqual(self.mda.current_pixel, [0, 0])
Java
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ ( function($) { } )( jQuery ); var waitForFinalEvent = (function () { var timers = {}; return function (callback, ms, uniqueId) { if (!uniqueId) { uniqueId = "Don't call this twice without a uniqueId"; } if (timers[uniqueId]) { clearTimeout (timers[uniqueId]); } timers[uniqueId] = setTimeout(callback, ms); }; })();
Java
/** * board/annapurna-labs/common/gpio_board_init.h * * Board GPIO initialization service * * Copyright (C) 2013 Annapurna Labs Ltd. * * 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 <asm/gpio.h> /* Board GPIO configuration entry */ struct gpio_cfg_ent { /* GPIO number */ int gpio_num; /* Configure GPIO as output */ int is_output; /* Initial output value for output */ int output_val; }; /** * Board GPIO Initialization * * @param[in] cfg * Board GPIO configuration entry array * * @param[in] cnt * Number of board GPIO configuration entries * * @return 0 upon success */ int gpio_board_init( const struct gpio_cfg_ent *cfg, int cnt);
Java
/* This file is part of the ScriptDev2 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 */ /* ScriptData SDName: Instance_Sunwell_Plateau SD%Complete: 70% SDComment: SDCategory: Sunwell_Plateau EndScriptData */ #include "precompiled.h" #include "sunwell_plateau.h" /* Sunwell Plateau: 0 - Kalecgos and Sathrovarr 1 - Brutallus 2 - Felmyst 3 - Eredar Twins (Alythess and Sacrolash) 4 - M'uru 5 - Kil'Jaeden */ static const DialogueEntry aFelmystOutroDialogue[] = { {NPC_KALECGOS_MADRIGOSA, 0, 10000}, {SAY_KALECGOS_OUTRO, NPC_KALECGOS_MADRIGOSA, 5000}, {NPC_FELMYST, 0, 5000}, {SPELL_OPEN_BACK_DOOR, 0, 9000}, {NPC_BRUTALLUS, 0, 0}, {0, 0, 0}, }; instance_sunwell_plateau::instance_sunwell_plateau(Map* pMap) : ScriptedInstance(pMap), DialogueHelper(aFelmystOutroDialogue), m_uiDeceiversKilled(0), m_uiSpectralRealmTimer(5000), m_uiKalecRespawnTimer(0), m_uiMuruBerserkTimer(0), m_uiKiljaedenYellTimer(90000) { Initialize(); } void instance_sunwell_plateau::Initialize() { memset(&m_auiEncounter, 0, sizeof(m_auiEncounter)); InitializeDialogueHelper(this); } bool instance_sunwell_plateau::IsEncounterInProgress() const { for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { if (m_auiEncounter[i] == IN_PROGRESS) return true; } return false; } void instance_sunwell_plateau::OnPlayerEnter(Player* pPlayer) { // Return if Felmyst already dead, or Brutallus alive if (m_auiEncounter[TYPE_BRUTALLUS] != DONE || m_auiEncounter[TYPE_FELMYST] == DONE) return; // Return if already summoned if (GetSingleCreatureFromStorage(NPC_FELMYST, true)) return; // Summon Felmyst in reload case pPlayer->SummonCreature(NPC_FELMYST, aMadrigosaLoc[0].m_fX, aMadrigosaLoc[0].m_fY, aMadrigosaLoc[0].m_fZ, aMadrigosaLoc[0].m_fO, TEMPSUMMON_DEAD_DESPAWN, 0); } void instance_sunwell_plateau::OnCreatureCreate(Creature* pCreature) { switch (pCreature->GetEntry()) { case NPC_KALECGOS_DRAGON: case NPC_KALECGOS_HUMAN: case NPC_SATHROVARR: case NPC_FLIGHT_TRIGGER_LEFT: case NPC_FLIGHT_TRIGGER_RIGHT: case NPC_MADRIGOSA: case NPC_BRUTALLUS: case NPC_FELMYST: case NPC_KALECGOS_MADRIGOSA: case NPC_ALYTHESS: case NPC_SACROLASH: case NPC_MURU: case NPC_ENTROPIUS: case NPC_KILJAEDEN_CONTROLLER: case NPC_KILJAEDEN: case NPC_KALECGOS: case NPC_ANVEENA: case NPC_VELEN: case NPC_LIADRIN: m_mNpcEntryGuidStore[pCreature->GetEntry()] = pCreature->GetObjectGuid(); break; case NPC_DECEIVER: m_lDeceiversGuidList.push_back(pCreature->GetObjectGuid()); break; case NPC_WORLD_TRIGGER: // sort triggers for flightpath if (pCreature->GetPositionZ() < 51.0f) m_lAllFlightTriggersList.push_back(pCreature->GetObjectGuid()); break; case NPC_WORLD_TRIGGER_LARGE: if (pCreature->GetPositionY() < 523.0f) m_lBackdoorTriggersList.push_back(pCreature->GetObjectGuid()); break; } } void instance_sunwell_plateau::OnCreatureDeath(Creature* pCreature) { if (pCreature->GetEntry() == NPC_DECEIVER) { ++m_uiDeceiversKilled; // Spawn Kiljaeden when all deceivers are killed if (m_uiDeceiversKilled == MAX_DECEIVERS) { if (Creature* pController = GetSingleCreatureFromStorage(NPC_KILJAEDEN_CONTROLLER)) { if (Creature* pKiljaeden = pController->SummonCreature(NPC_KILJAEDEN, pController->GetPositionX(), pController->GetPositionY(), pController->GetPositionZ(), pController->GetOrientation(), TEMPSUMMON_DEAD_DESPAWN, 0)) pKiljaeden->SetInCombatWithZone(); pController->RemoveAurasDueToSpell(SPELL_ANVEENA_DRAIN); } } } } void instance_sunwell_plateau::OnCreatureEvade(Creature* pCreature) { // Reset encounter if raid wipes at deceivers if (pCreature->GetEntry() == NPC_DECEIVER) SetData(TYPE_KILJAEDEN, FAIL); } void instance_sunwell_plateau::OnObjectCreate(GameObject* pGo) { switch (pGo->GetEntry()) { case GO_FORCEFIELD: case GO_BOSS_COLLISION_1: case GO_BOSS_COLLISION_2: case GO_ICE_BARRIER: break; case GO_FIRE_BARRIER: if (m_auiEncounter[TYPE_KALECGOS] == DONE && m_auiEncounter[TYPE_BRUTALLUS] == DONE && m_auiEncounter[TYPE_FELMYST] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_FIRST_GATE: break; case GO_SECOND_GATE: if (m_auiEncounter[TYPE_EREDAR_TWINS] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_MURU_ENTER_GATE: if (m_auiEncounter[TYPE_EREDAR_TWINS] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_MURU_EXIT_GATE: if (m_auiEncounter[TYPE_MURU] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_THIRD_GATE: if (m_auiEncounter[TYPE_MURU] == DONE) pGo->SetGoState(GO_STATE_ACTIVE); break; case GO_ORB_BLUE_FLIGHT_1: case GO_ORB_BLUE_FLIGHT_2: case GO_ORB_BLUE_FLIGHT_3: case GO_ORB_BLUE_FLIGHT_4: break; default: return; } m_mGoEntryGuidStore[pGo->GetEntry()] = pGo->GetObjectGuid(); } void instance_sunwell_plateau::SetData(uint32 uiType, uint32 uiData) { switch (uiType) { case TYPE_KALECGOS: m_auiEncounter[uiType] = uiData; // combat doors DoUseDoorOrButton(GO_FORCEFIELD); DoUseDoorOrButton(GO_BOSS_COLLISION_1); DoUseDoorOrButton(GO_BOSS_COLLISION_2); if (uiData == FAIL) { m_uiKalecRespawnTimer = 20000; if (Creature* pKalecDragon = GetSingleCreatureFromStorage(NPC_KALECGOS_DRAGON)) pKalecDragon->ForcedDespawn(); if (Creature* pKalecHuman = GetSingleCreatureFromStorage(NPC_KALECGOS_HUMAN)) pKalecHuman->ForcedDespawn(); if (Creature* pSathrovarr = GetSingleCreatureFromStorage(NPC_SATHROVARR)) pSathrovarr->AI()->EnterEvadeMode(); } break; case TYPE_BRUTALLUS: m_auiEncounter[uiType] = uiData; break; case TYPE_FELMYST: m_auiEncounter[uiType] = uiData; if (uiData == DONE) StartNextDialogueText(NPC_KALECGOS_MADRIGOSA); else if (uiData == IN_PROGRESS) DoSortFlightTriggers(); break; case TYPE_EREDAR_TWINS: m_auiEncounter[uiType] = uiData; if (uiData == DONE) { DoUseDoorOrButton(GO_SECOND_GATE); DoUseDoorOrButton(GO_MURU_ENTER_GATE); } break; case TYPE_MURU: m_auiEncounter[uiType] = uiData; // combat door DoUseDoorOrButton(GO_MURU_ENTER_GATE); if (uiData == DONE) { DoUseDoorOrButton(GO_MURU_EXIT_GATE); DoUseDoorOrButton(GO_THIRD_GATE); } else if (uiData == IN_PROGRESS) m_uiMuruBerserkTimer = 10 * MINUTE * IN_MILLISECONDS; break; case TYPE_KILJAEDEN: m_auiEncounter[uiType] = uiData; if (uiData == FAIL) { m_uiDeceiversKilled = 0; // Reset Orbs DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_1, GO_FLAG_NO_INTERACT, true); DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_2, GO_FLAG_NO_INTERACT, true); DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_3, GO_FLAG_NO_INTERACT, true); DoToggleGameObjectFlags(GO_ORB_BLUE_FLIGHT_4, GO_FLAG_NO_INTERACT, true); // Respawn deceivers for (GuidList::const_iterator itr = m_lDeceiversGuidList.begin(); itr != m_lDeceiversGuidList.end(); ++itr) { if (Creature* pDeceiver = instance->GetCreature(*itr)) { if (!pDeceiver->isAlive()) pDeceiver->Respawn(); } } } break; } if (uiData == DONE) { OUT_SAVE_INST_DATA; std::ostringstream saveStream; saveStream << m_auiEncounter[0] << " " << m_auiEncounter[1] << " " << m_auiEncounter[2] << " " << m_auiEncounter[3] << " " << m_auiEncounter[4] << " " << m_auiEncounter[5]; m_strInstData = saveStream.str(); SaveToDB(); OUT_SAVE_INST_DATA_COMPLETE; } } uint32 instance_sunwell_plateau::GetData(uint32 uiType) const { if (uiType < MAX_ENCOUNTER) return m_auiEncounter[uiType]; return 0; } void instance_sunwell_plateau::Update(uint32 uiDiff) { DialogueUpdate(uiDiff); if (m_uiKalecRespawnTimer) { if (m_uiKalecRespawnTimer <= uiDiff) { if (Creature* pKalecDragon = GetSingleCreatureFromStorage(NPC_KALECGOS_DRAGON)) pKalecDragon->Respawn(); if (Creature* pKalecHuman = GetSingleCreatureFromStorage(NPC_KALECGOS_HUMAN)) pKalecHuman->Respawn(); m_uiKalecRespawnTimer = 0; } else m_uiKalecRespawnTimer -= uiDiff; } // Muru berserk timer; needs to be done here because it involves two distinct creatures if (m_auiEncounter[TYPE_MURU] == IN_PROGRESS) { if (m_uiMuruBerserkTimer < uiDiff) { if (Creature* pEntrpius = GetSingleCreatureFromStorage(NPC_ENTROPIUS, true)) pEntrpius->CastSpell(pEntrpius, SPELL_MURU_BERSERK, true); else if (Creature* pMuru = GetSingleCreatureFromStorage(NPC_MURU)) pMuru->CastSpell(pMuru, SPELL_MURU_BERSERK, true); m_uiMuruBerserkTimer = 10 * MINUTE * IN_MILLISECONDS; } else m_uiMuruBerserkTimer -= uiDiff; } if (m_auiEncounter[TYPE_KILJAEDEN] == NOT_STARTED || m_auiEncounter[TYPE_KILJAEDEN] == FAIL) { if (m_uiKiljaedenYellTimer < uiDiff) { switch (urand(0, 4)) { case 0: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_1, NPC_KILJAEDEN_CONTROLLER); break; case 1: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_2, NPC_KILJAEDEN_CONTROLLER); break; case 2: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_3, NPC_KILJAEDEN_CONTROLLER); break; case 3: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_4, NPC_KILJAEDEN_CONTROLLER); break; case 4: DoOrSimulateScriptTextForThisInstance(SAY_ORDER_5, NPC_KILJAEDEN_CONTROLLER); break; } m_uiKiljaedenYellTimer = 90000; } else m_uiKiljaedenYellTimer -= uiDiff; } } void instance_sunwell_plateau::Load(const char* in) { if (!in) { OUT_LOAD_INST_DATA_FAIL; return; } OUT_LOAD_INST_DATA(in); std::istringstream loadStream(in); loadStream >> m_auiEncounter[0] >> m_auiEncounter[1] >> m_auiEncounter[2] >> m_auiEncounter[3] >> m_auiEncounter[4] >> m_auiEncounter[5]; for (uint8 i = 0; i < MAX_ENCOUNTER; ++i) { if (m_auiEncounter[i] == IN_PROGRESS) m_auiEncounter[i] = NOT_STARTED; } OUT_LOAD_INST_DATA_COMPLETE; } static bool sortByPositionX(Creature* pFirst, Creature* pSecond) { return pFirst && pSecond && pFirst->GetPositionX() > pSecond->GetPositionX(); } void instance_sunwell_plateau::DoSortFlightTriggers() { if (m_lAllFlightTriggersList.empty()) { script_error_log("Instance Sunwell Plateau: ERROR Failed to load flight triggers for creature id %u.", NPC_FELMYST); return; } std::list<Creature*> lTriggers; // Valid pointers, only used locally for (GuidList::const_iterator itr = m_lAllFlightTriggersList.begin(); itr != m_lAllFlightTriggersList.end(); ++itr) { if (Creature* pTrigger = instance->GetCreature(*itr)) lTriggers.push_back(pTrigger); } if (lTriggers.empty()) return; // sort the flight triggers; first by position X, then group them by Y (left and right) lTriggers.sort(sortByPositionX); for (std::list<Creature*>::iterator itr = lTriggers.begin(); itr != lTriggers.end(); ++itr) { if ((*itr)->GetPositionY() < 600.0f) m_vRightFlightTriggersVect.push_back((*itr)->GetObjectGuid()); else m_vLeftFlightTriggersVect.push_back((*itr)->GetObjectGuid()); } } ObjectGuid instance_sunwell_plateau::SelectFelmystFlightTrigger(bool bLeftSide, uint8 uiIndex) { // Return the flight trigger from the selected index GuidVector& vTemp = bLeftSide ? m_vLeftFlightTriggersVect : m_vRightFlightTriggersVect; if (uiIndex >= vTemp.size()) return ObjectGuid(); return vTemp[uiIndex]; } void instance_sunwell_plateau::DoEjectSpectralPlayers() { for (GuidSet::const_iterator itr = m_spectralRealmPlayers.begin(); itr != m_spectralRealmPlayers.end(); ++itr) { if (Player* pPlayer = instance->GetPlayer(*itr)) { if (!pPlayer->HasAura(SPELL_SPECTRAL_REALM_AURA)) continue; pPlayer->CastSpell(pPlayer, SPELL_TELEPORT_NORMAL_REALM, true); pPlayer->CastSpell(pPlayer, SPELL_SPECTRAL_EXHAUSTION, true); pPlayer->RemoveAurasDueToSpell(SPELL_SPECTRAL_REALM_AURA); } } } void instance_sunwell_plateau::JustDidDialogueStep(int32 iEntry) { switch (iEntry) { case NPC_KALECGOS_MADRIGOSA: if (Creature* pTrigger = GetSingleCreatureFromStorage(NPC_FLIGHT_TRIGGER_LEFT)) { if (Creature* pKalec = pTrigger->SummonCreature(NPC_KALECGOS_MADRIGOSA, aKalecLoc[0].m_fX, aKalecLoc[0].m_fY, aKalecLoc[0].m_fZ, aKalecLoc[0].m_fO, TEMPSUMMON_CORPSE_DESPAWN, 0)) { pKalec->SetWalk(false); pKalec->SetLevitate(true); pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[1].m_fX, aKalecLoc[1].m_fY, aKalecLoc[1].m_fZ, false); } } break; case NPC_FELMYST: if (Creature* pKalec = GetSingleCreatureFromStorage(NPC_KALECGOS_MADRIGOSA)) pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[2].m_fX, aKalecLoc[2].m_fY, aKalecLoc[2].m_fZ, false); break; case SPELL_OPEN_BACK_DOOR: if (Creature* pKalec = GetSingleCreatureFromStorage(NPC_KALECGOS_MADRIGOSA)) { // ToDo: update this when the AoE spell targeting will support many explicit target. Kalec should target all creatures from the list if (Creature* pTrigger = instance->GetCreature(m_lBackdoorTriggersList.front())) pKalec->CastSpell(pTrigger, SPELL_OPEN_BACK_DOOR, true); } break; case NPC_BRUTALLUS: if (Creature* pKalec = GetSingleCreatureFromStorage(NPC_KALECGOS_MADRIGOSA)) { pKalec->ForcedDespawn(10000); pKalec->GetMotionMaster()->MovePoint(0, aKalecLoc[3].m_fX, aKalecLoc[3].m_fY, aKalecLoc[3].m_fZ, false); } break; } } InstanceData* GetInstanceData_instance_sunwell_plateau(Map* pMap) { return new instance_sunwell_plateau(pMap); } bool AreaTrigger_at_sunwell_plateau(Player* pPlayer, AreaTriggerEntry const* pAt) { if (pAt->id == AREATRIGGER_TWINS) { if (pPlayer->isGameMaster() || pPlayer->isDead()) return false; instance_sunwell_plateau* pInstance = (instance_sunwell_plateau*)pPlayer->GetInstanceData(); if (pInstance && pInstance->GetData(TYPE_EREDAR_TWINS) == NOT_STARTED) pInstance->SetData(TYPE_EREDAR_TWINS, SPECIAL); } return false; } void AddSC_instance_sunwell_plateau() { Script* pNewScript; pNewScript = new Script; pNewScript->Name = "instance_sunwell_plateau"; pNewScript->GetInstanceData = &GetInstanceData_instance_sunwell_plateau; pNewScript->RegisterSelf(); pNewScript = new Script; pNewScript->Name = "at_sunwell_plateau"; pNewScript->pAreaTrigger = &AreaTrigger_at_sunwell_plateau; pNewScript->RegisterSelf(); }
Java
package com.cluit.util.dataTypes; import java.util.ArrayList; import java.util.HashSet; import java.util.Set; import com.cluit.util.Const; import com.cluit.util.AoP.MethodMapper; import com.cluit.util.methods.ClusteringUtils; import com.cluit.util.structures.KeyPriorityQueue_Max; import com.cluit.util.structures.Pair; /**A cluster is a collection of entries. * * The class has a lot of utility functions related to clusters such as calculating centoid, finding the entry furthest * from the centoid and so on. * * @author Simon * */ public class Cluster { //******************************************************************************************************* //region VARIABLES //******************************************************************************************************* private Entry centoid; public Pair<Double, Entry> cache = new Pair<Double, Entry>( 0.0, new Entry() ); private final int dimensions; private final Set<Entry> members = new HashSet<>(); private final KeyPriorityQueue_Max<Entry> distanceQueue = new KeyPriorityQueue_Max<Entry>(); //endregion ********************************************************************************************* //region CUNSTRUCTOR //******************************************************************************************************* /** * * @param position * @param centoidIsMember */ public Cluster(double[] position) { if( position.length < 1){ API_Exeption("A cluster's position must be defined and have 1 or more dimenstions!"); } this.centoid = new Entry(position); this.dimensions = centoid.getDimensions(); }; //endregion ********************************************************************************************* //region STATIC METHODS //******************************************************************************************************* /**Calculates a central point (centoid) from a collection of entries. Not that all entries must have the same dimensionality. * * @param entries * @return A new entry, with a position that is the mean of all parameter entries (NULL if entries.lenght == 0) */ public static Entry calculateCentoid(Entry[] entries){ if( entries.length == 0) return null; //Fetch dimensionality for the entries and set up the coordinate array int dim = entries[0].getDimensions(); double[] centoidCoordinates = new double[dim]; //Add all entries positions together (for example, add all entries x-values together in one array slot, //and all y-values together in the next array slot). for( Entry p : entries ){ for( int i = 0; i < p.getDimensions(); i++ ) centoidCoordinates[i] += p.getCoordinateAt(i); } //Divide each position by the number of entries (to get the mean of each dimension's position for( int i = 0; i < centoidCoordinates.length; i++) centoidCoordinates[i] /= entries.length; return new Entry(centoidCoordinates); } /**Calculates the sum of squared errors for a given set of entries, given a centoid.<br> * The calculation is simply: For each point, calculate the euclidian distance from that point to the centoid, and square the distance * * @param centoid The mean position of the entries (see @link {@link Cluster.calculateCentoid} ) * @param entries * @return */ public static double calculateSquaredError(Entry centoid, Entry[] entries){ double out = 0; double dist = 0; for(Entry e : entries ){ dist = ClusteringUtils.eucDistance(centoid, e); out += (dist*dist); } return out; } //endregion ********************************************************************************************* //region PUBLIC //******************************************************************************************************* public int getNumberOfMembers(){ return distanceQueue.size() == members.size() ? distanceQueue.size() : -1; } /**Returns the distance to the centoid for the point which is farthest from the centoid * * @return The distance, if there are any members of the cluster. -1 otherwise */ public double getFurthestMembersDistance(){ if( distanceQueue.size() == 0 ) return -1; return distanceQueue.peekKey(); } /** Calculates a new centoid for the cluster. This method also update each points distance to the centoid * <br><br> * Complexity = <b>O(n * d)</b>, * where <b>n</b> is the number of elements in the cluster * where <b>d</b> the number of dimensions for each point */ public void calculateCentoid(){ int dim = centoid.getDimensions(); double[] newCentoidCoordinates = new double[dim]; for( Entry p : distanceQueue.values() ){ for( int i = 0; i < p.getDimensions(); i++ ) newCentoidCoordinates[i] += p.getCoordinateAt(i); } for( int i = 0; i < newCentoidCoordinates.length; i++) newCentoidCoordinates[i] /= distanceQueue.size(); centoid = new Entry(newCentoidCoordinates ); updateMemberDistances(); } /**Fetches a <b>copy</b> of the centoid of the cluster * * @return A new Entry, which is a copy of the cluster's centoid */ public Entry getCentoid(){ return new Entry(centoid); } /**Adds an entry to the cluster. The same entry cannot be added twice to the same cluster. * This does not automatically update the cluster centoid. To do that, call "UpdateCentoid" * * @param e * @return True if the entry was added, false if it was not */ public boolean add(Entry e){ if( e.getDimensions() != dimensions ){ API_Exeption("An entry cannot be added to a cluster if their dimenstions does not match! Cluster.dim = "+dimensions+" Entry.dim = "+e.getDimensions() ); return false; } if( members.contains(e) ){ API_Exeption("An entry cannot be added to a cluster twice! The entry "+e+" is already present in the cluster" ); return false; } double dist; if( e == cache.right ) dist = cache.left; else dist = ClusteringUtils.eucDistance(e, centoid); boolean a = distanceQueue.put(dist, e); boolean b = members.add(e); return a & b; } /**Removes a point from the cluster * * @param e The point to be removed * @return True if it was found. False if the point wasn't found. */ public boolean removeEntry(Entry e){ boolean a = distanceQueue.remove(e); boolean b = members.remove(e); return a & b; } /**Calculates a points distance to the clusters centoid. * The result is cached (the cache stores only 1 element), to prevent * the result from having to be re-computed in the near future. * <br>It is therefore recommended that whenever a point checks its distance to * all clusters, it should be added to a cluster before another point checks * it's distances. * * @param p The point * @return Distance to the centoid */ public double distanceToCentoid(Entry p){ double dist = ClusteringUtils.eucDistance(p, centoid); cache = new Pair<Double, Entry>(dist, p); return dist; } /**Checks whether a given point is member of this cluster or not * * @param p The point * @return True if the point is found within the cluster */ public boolean isMember(Entry e) { return members.contains(e); } /**Fetches an array of all entries that are present within this cluster. This array can have a lenght of 0, in case no * entries are registered within this cluster */ public Entry[] getMembers() { return members.toArray( new Entry[0] ); } /**Calculates the sum of squared errors for this cluster * * @return */ public double getSquaredError(){ return Cluster.calculateSquaredError(centoid, getMembers()) ; } public String toString(){ String out = "[ "; for( Entry e : members ){ out += e.toString() + " : "; } return members.size() > 0 ? out.substring(0, out.length() - 3) + " ]" : "[ ]"; } //endregion ********************************************************************************************* //region PRIVATE //******************************************************************************************************* /**Update each member's distance to the centoid * */ private void updateMemberDistances() { ArrayList<Entry> list = distanceQueue.values(); distanceQueue.clear(); for(Entry p : list){ double newDistance = ClusteringUtils.eucDistance(centoid, p); distanceQueue.add(newDistance, p); } } private int API_Exeption(String s){ MethodMapper.invoke(Const.METHOD_EXCEPTION_GENERAL, "Error in Cluster.java! " + s +" " + com.cluit.util.methods.MiscUtils.getStackPos(), new Exception() ); return -1; } //endregion ********************************************************************************************* //******************************************************************************************************* }
Java
SUBROUTINE STPTRS( UPLO, TRANS, DIAG, N, NRHS, AP, B, LDB, INFO ) * * -- LAPACK routine (version 3.2) -- * Univ. of Tennessee, Univ. of California Berkeley and NAG Ltd.. * November 2006 * * .. Scalar Arguments .. CHARACTER DIAG, TRANS, UPLO INTEGER INFO, LDB, N, NRHS * .. * .. Array Arguments .. REAL AP( * ), B( LDB, * ) * .. * * Purpose * ======= * * STPTRS solves a triangular system of the form * * A * X = B or A**T * X = B, * * where A is a triangular matrix of order N stored in packed format, * and B is an N-by-NRHS matrix. A check is made to verify that A is * nonsingular. * * Arguments * ========= * * UPLO (input) CHARACTER*1 * = 'U': A is upper triangular; * = 'L': A is lower triangular. * * TRANS (input) CHARACTER*1 * Specifies the form of the system of equations: * = 'N': A * X = B (No transpose) * = 'T': A**T * X = B (Transpose) * = 'C': A**H * X = B (Conjugate transpose = Transpose) * * DIAG (input) CHARACTER*1 * = 'N': A is non-unit triangular; * = 'U': A is unit triangular. * * N (input) INTEGER * The order of the matrix A. N >= 0. * * NRHS (input) INTEGER * The number of right hand sides, i.e., the number of columns * of the matrix B. NRHS >= 0. * * AP (input) REAL array, dimension (N*(N+1)/2) * The upper or lower triangular matrix A, packed columnwise in * a linear array. The j-th column of A is stored in the array * AP as follows: * if UPLO = 'U', AP(i + (j-1)*j/2) = A(i,j) for 1<=i<=j; * if UPLO = 'L', AP(i + (j-1)*(2*n-j)/2) = A(i,j) for j<=i<=n. * * B (input/output) REAL array, dimension (LDB,NRHS) * On entry, the right hand side matrix B. * On exit, if INFO = 0, the solution matrix X. * * LDB (input) INTEGER * The leading dimension of the array B. LDB >= max(1,N). * * INFO (output) INTEGER * = 0: successful exit * < 0: if INFO = -i, the i-th argument had an illegal value * > 0: if INFO = i, the i-th diagonal element of A is zero, * indicating that the matrix is singular and the * solutions X have not been computed. * * ===================================================================== * * .. Parameters .. REAL ZERO PARAMETER ( ZERO = 0.0E+0 ) * .. * .. Local Scalars .. LOGICAL NOUNIT, UPPER INTEGER J, JC * .. * .. External Functions .. LOGICAL LSAME EXTERNAL LSAME * .. * .. External Subroutines .. EXTERNAL STPSV, XERBLA * .. * .. Intrinsic Functions .. INTRINSIC MAX * .. * .. Executable Statements .. * * Test the input parameters. * INFO = 0 UPPER = LSAME( UPLO, 'U' ) NOUNIT = LSAME( DIAG, 'N' ) IF( .NOT.UPPER .AND. .NOT.LSAME( UPLO, 'L' ) ) THEN INFO = -1 ELSE IF( .NOT.LSAME( TRANS, 'N' ) .AND. .NOT. $ LSAME( TRANS, 'T' ) .AND. .NOT.LSAME( TRANS, 'C' ) ) THEN INFO = -2 ELSE IF( .NOT.NOUNIT .AND. .NOT.LSAME( DIAG, 'U' ) ) THEN INFO = -3 ELSE IF( N.LT.0 ) THEN INFO = -4 ELSE IF( NRHS.LT.0 ) THEN INFO = -5 ELSE IF( LDB.LT.MAX( 1, N ) ) THEN INFO = -8 END IF IF( INFO.NE.0 ) THEN CALL XERBLA( 'STPTRS', -INFO ) RETURN END IF * * Quick return if possible * IF( N.EQ.0 ) $ RETURN * * Check for singularity. * IF( NOUNIT ) THEN IF( UPPER ) THEN JC = 1 DO 10 INFO = 1, N IF( AP( JC+INFO-1 ).EQ.ZERO ) $ RETURN JC = JC + INFO 10 CONTINUE ELSE JC = 1 DO 20 INFO = 1, N IF( AP( JC ).EQ.ZERO ) $ RETURN JC = JC + N - INFO + 1 20 CONTINUE END IF END IF INFO = 0 * * Solve A * x = b or A' * x = b. * DO 30 J = 1, NRHS CALL STPSV( UPLO, TRANS, DIAG, N, AP, B( 1, J ), 1 ) 30 CONTINUE * RETURN * * End of STPTRS * END
Java
<?php /** * SFN Live Report. * * @package SFN Live Report * @author Hampus Persson <hampus@hampuspersson.se> * @license GPL-2.0+ * @link http:// * @copyright 2013 Swedish Football Network */ /** * Plugin class. * * * @package SNF_Live_Report * @author Hampus Persson <hampus@hampuspersson.se> */ class SFN_Live_Report { /** * Plugin version, used for cache-busting of style and script file references. * * @since 1.0.0 * * @var string */ protected $version = '1.1.0'; /** * Unique identifier for your plugin. * * Use this value (not the variable name) as the text domain when internationalizing strings of text. It should * match the Text Domain file header in the main plugin file. * * @since 1.0.0 * * @var string */ protected $plugin_slug = 'sfn-live-report'; /** * Instance of this class. * * @since 1.0.0 * * @var object */ protected static $instance = null; /** * Slug of the plugin screen. * * @since 1.0.0 * * @var string */ protected $plugin_screen_hook_suffix = null; /** * Initialize the plugin by setting localization, filters, and administration functions. * * @since 1.0.0 */ private function __construct() { // Load plugin text domain add_action( 'init', array( $this, 'load_plugin_textdomain' ) ); // At this point no options are needed but if the need arises this is // how to add the options page and menu item. // add_action( 'admin_menu', array( $this, 'add_plugin_admin_menu' ) ); // Load admin style sheet and JavaScript. add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_styles' ) ); add_action( 'admin_enqueue_scripts', array( $this, 'enqueue_admin_scripts' ) ); // Load public-facing style sheet and JavaScript. add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_styles' ) ); add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) ); // Add actions to remove some unwanted scripts and styles that wp_head() forces on us // add_action( 'wp_print_scripts', array( $this, 'sfn_live_report_remove_scripts' ) ); // add_action( 'wp_print_styles', array( $this, 'sfn_live_report_remove_styles' ) ); // Setup callback for AJAX, through WPs admin-ajax add_action('wp_ajax_sfn-submit', array( $this, 'sfn_live_report_callback' )); // Add the shortcode that sets up the whole operation add_shortcode( 'sfn-live-report', array( $this, 'report_games' ) ); } /** * Return an instance of this class. * * @since 1.0.0 * * @return object A single instance of this class. */ public static function get_instance() { // If the single instance hasn't been set, set it now. if ( null == self::$instance ) { self::$instance = new self; } return self::$instance; } /** * Fired when the plugin is activated. * * @since 1.0.0 * * @param boolean $network_wide True if WPMU superadmin uses "Network Activate" action, false if WPMU is disabled or plugin is activated on an individual blog. */ public static function activate( $network_wide ) { // TODO: Define activation functionality here } /** * Fired when the plugin is deactivated. * * @since 1.0.0 * * @param boolean $network_wide True if WPMU superadmin uses "Network Deactivate" action, false if WPMU is disabled or plugin is deactivated on an individual blog. */ public static function deactivate( $network_wide ) { // TODO: Define deactivation functionality here } /** * Load the plugin text domain for translation. * * @since 1.0.0 */ public function load_plugin_textdomain() { $domain = $this->plugin_slug; $locale = apply_filters( 'plugin_locale', get_locale(), $domain ); load_textdomain( $domain, WP_LANG_DIR . '/' . $domain . '/' . $domain . '-' . $locale . '.mo' ); load_plugin_textdomain( $domain, FALSE, dirname( plugin_basename( __FILE__ ) ) . '/lang/' ); } /** * Register and enqueue admin-specific style sheet. * * @since 1.0.0 * * @return null Return early if no settings page is registered. */ public function enqueue_admin_styles() { if ( ! isset( $this->plugin_screen_hook_suffix ) ) { return; } $screen = get_current_screen(); if ( $screen->id == $this->plugin_screen_hook_suffix ) { wp_enqueue_style( $this->plugin_slug .'-admin-styles', plugins_url( 'assets/css/admin.css', __FILE__ ), array(), $this->version ); } } /** * Register and enqueue admin-specific JS. * * @since 1.0.0 * * @return null Return early if no settings page is registered. */ public function enqueue_admin_scripts() { if ( ! isset( $this->plugin_screen_hook_suffix ) ) { return; } $screen = get_current_screen(); if ( $screen->id == $this->plugin_screen_hook_suffix ) { wp_enqueue_script( $this->plugin_slug . '-admin-script', plugins_url( 'assets/javascripts/admin.js', __FILE__ ), array( 'jquery' ), $this->version ); } } /** * Register and enqueue public-facing style sheet. * * @since 1.0.0 */ public function enqueue_styles() { wp_enqueue_style( $this->plugin_slug . '-plugin-styles', plugins_url( 'assets/css/style.css', __FILE__ ), array(), $this->version ); } /** * Register and enqueues public-facing JS files. * * @since 1.0.0 */ public function enqueue_scripts() { wp_enqueue_script( $this->plugin_slug . '-plugin-script', plugins_url( 'assets/javascripts/main.min.js', __FILE__ ), array( 'jquery' ), $this->version ); // Set an object with the ajaxurl for use in main JS wp_localize_script( $this->plugin_slug . '-plugin-script', 'ajax_object', array( 'ajaxurl' => admin_url( 'admin-ajax.php' ) ) ); } /** * Since this plugin doesn't use any other plugins we can remove all scripts that are queued and registered properly * * @since 1.0.0 */ public function sfn_live_report_remove_scripts() { global $wp_scripts; foreach( $wp_scripts->queue as $handle ) : if( 'jquery' != $handle && 'sfn-live-report-plugin-script' != $handle ) { wp_deregister_script( $handle ); wp_dequeue_script( $handle ); } endforeach; } /** * Since this plugin doesn't use any other plugins we can remove all styles that are queued and registered properly * * @since 1.0.0 */ public function sfn_live_report_remove_styles() { global $wp_styles; foreach( $wp_styles->queue as $handle ) : if( 'sfn-live-report-plugin-styles' != $handle ) { wp_deregister_style( $handle ); wp_dequeue_style( $handle ); } endforeach; } /** * Register the administration menu for this plugin into the WordPress Dashboard menu. * * @since 1.0.0 */ public function add_plugin_admin_menu() { $this->plugin_screen_hook_suffix = add_plugins_page( __( 'SFN Live Report', $this->plugin_slug ), __( 'Settings', $this->plugin_slug ), 'read', $this->plugin_slug, array( $this, 'display_plugin_admin_page' ) ); } /** * Render the settings page for this plugin. * * @since 1.0.0 */ public function display_plugin_admin_page() { include_once( 'views/admin.php' ); } /** * Callback for ajax call when the form is submitted * * @since 1.0.0 */ public function sfn_live_report_callback() { // Check that the user has access rights if ( !$this->check_access() ) { echo '<p>Du har inte behörighet att komma åt detta verktyg.</p>'; echo '<h3><a href="' . wp_login_url( site_url( $_SERVER["REQUEST_URI"] ) ) . '">Logga in</a></h3>'; die(); } // If everything checks out and a game is submitted we'll update the meta if( $_POST['game'] ) { update_post_meta($_POST['game'], 'hemmares', $_POST['home']); update_post_meta($_POST['game'], 'bortares', $_POST['away']); update_post_meta($_POST['game'], 'matchtid', $_POST['time']); if( "true" === $_POST['sendToTwitter'] ) { $url = "http://www.swedishfootballnetwork.se/games/" . $_POST['game']; if( "true" === $_POST['finalScore'] ) { $time = ' (Slut)'; } else { $time = empty($_POST['time']) ? '' : ' (' . $_POST['time'] . ')'; } $tweet = $_POST['home-team'] . ' - ' . $_POST['away-team'] . ' ' . $_POST['home'] . '-' . $_POST['away'] . $time . '. Mer info om matchen på: ' . $url; $this->tweetUpdate($tweet); } } } private function tweetUpdate($tweet) { require_once('twitteroauth/twitteroauth.php'); define('CONSUMER_KEY', 'VPWk1tJtrYVoTMTWTLe30A'); define('CONSUMER_SECRET', 'EohfFFQzUSlsQnVjG9aVS1fCdxVv6GCzv6wEkTXYSi8'); define('OAUTH_CALLBACK', 'http://example.com/twitteroauth/callback.php'); /* TOP SECRET STUFF, DO NOT SHARE! */ $access_token = array( "oauth_token" => "1080024924-NpA52OvkNMzzeJivBpHKEEenBzfVdrutsr4qJy4", "oauth_token_secret" => "Xuk19qsgsrlnkTr3VCLnvtwjg1yUnW1u6ykCnbOjkE" ); $connection = new TwitterOAuth(CONSUMER_KEY, CONSUMER_SECRET, $access_token['oauth_token'], $access_token['oauth_token_secret']); $parameters = array('status' => $tweet); $content = $connection->post('statuses/update', $parameters); return $content; } /** * Function to output the form to the user * * @since 1.0.0 */ public function report_games( $atts ) { // Check that the user has access rights if ( !$this->check_access() ) { echo '<p>Du har inte behörighet att komma åt detta verktyg.</p>'; echo '<h3><a href="' . wp_login_url( site_url( $_SERVER["REQUEST_URI"] ) ) . '">Logga in</a></h3>'; die(); } // Store the output we want in a variable $return_page = include('views/public.php'); return $return_page; } private function check_access() { $allowed_users = array( 6, // Hampus Persson, SFN 373 // Carl Klimfors, LG ); $current_user = wp_get_current_user(); if ( in_array($current_user->ID, $allowed_users) ) { return true; } return false; } }
Java
# MSH ## Beta Version ### Created by Ne02ptzero (Louis Solofrizzo), Fusiow (Ryad Kharif) and Ivory9334 (Aurelien Ardjoune) Stable version for **MacOSX** Work on **Linux**, but no manual completion (options & description of command) ## What's MSH ? Msh is a colorful shell to help beginners in learning Linux, but also to confirm that users desire to enjoy a visual comfort. ![alt text](screens/screen1.png) ____ ![alt text](screens/screen2.png) ____ ![alt text](screens/screen3.png) ____ ![alt text](screens/screen5.png) ____ #### Why? - The command is colored in blue if it exists, otherwise red. - When the command is good, all options for this command are posters suggestions. - In addition, there is an auto-completion on the options that allows to know the list of options for a command, and their utilites. - Autocompletion also on files as well as folders. #### Builtins: - Builtins environment (env, setenv and unsetenv) - Alias - Local Variables - Job Control - Configuration file - Advanced prompt ____ ![alt text](screens/screen4.png) For more information see the documentation (docs /). #### Installation: ##### -Compilation: git clone https://github.com/Ne02ptzero/msh.git && cd msh && make ##### -Installation: make install; (For 42 students) make install42; *(Copy the binary to ~/.brew/bin)* Launch with "msh" You don't want the amazing colored read ? Launch with -no-color options.
Java
# encoding: utf-8 # Copyright (c) 2012 Novell, Inc. # # All Rights Reserved. # # 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. # # 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, contact Novell, Inc. # # To contact Novell about this file by physical or electronic mail, you may # find current contact information at www.novell.com. require "yast" module UI # UI layout helpers. # # These started out in the Expert Partitioner in yast2-storage. # The use case is reusing pieces of this legacy code in the new # yast2-partitioner. # That is why the API and the implementation look old. module Greasemonkey include Yast::UIShortcuts extend Yast::UIShortcuts Builtins = Yast::Builtins Convert = Yast::Convert Ops = Yast::Ops Yast.import "Directory" @handlers = [ :VStackFrames, :FrameWithMarginBox, :ComboBoxSelected, :LeftRadioButton, :LeftRadioButtonWithAttachment, :LeftCheckBox, :LeftCheckBoxWithAttachment, :IconAndHeading ] # The compatibility API needs CamelCase method names # rubocop:disable MethodName # Wrap terms in a VBox with small vertical spacings in between. # @param old [Yast::Term] # @return [Yast::Term] # @example # term( # :VStackFrames, # Frame("f1"), # Frame("f2"), # Frame("f3") # ) # -> # VBox( # Frame("f1"), # VSpacing(0.45), # Frame("f2"), # VSpacing(0.45), # Frame("f3") # ) def VStackFrames(old) frames = Convert.convert( Builtins.argsof(old), from: "list", to: "list <term>" ) new = VBox() Builtins.foreach(frames) do |frame| new = Builtins.add(new, VSpacing(0.45)) if Builtins.size(new) != 0 new = Builtins.add(new, frame) end new end module_function :VStackFrames # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:FrameWithMarginBox, "Title", "arg1", "arg2") # -> # Frame("Title", MarginBox(1.45, 0.45, "arg1", "arg2")) def FrameWithMarginBox(old) title = Ops.get_string(old, 0, "error") args = Builtins.sublist(Builtins.argsof(old), 1) Frame( title, Builtins.toterm(:MarginBox, Builtins.union([1.45, 0.45], args)) ) end module_function :FrameWithMarginBox # @param old [Yast::Term] # @return [Yast::Term] # @example # term( # :ComboBoxSelected, # Id(:wish), Opt(:notify), "Wish", # [ # Item(Id(:time), "Time"), # Item(Id(:love), "Love"), # Item(Id(:money), "Money") # ], # Id(:love) # ) # -> # ComboBox( # Id(:wish), Opt(:notify), "Wish", # [ # Item(Id(:time), "Time", false), # Item(Id(:love), "Love", true), # Item(Id(:money), "Money", false) # ] # ) def ComboBoxSelected(old) args = Builtins.argsof(old) tmp = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 2)) items = Ops.get_list(args, Ops.subtract(Builtins.size(args), 2), []) id = Ops.get_term(args, Ops.subtract(Builtins.size(args), 1), Id()) items = Builtins.maplist(items) do |item| Item(Ops.get(item, 0), Ops.get(item, 1), Ops.get(item, 0) == id) end Builtins.toterm(:ComboBox, Builtins.add(tmp, items)) end module_function :ComboBoxSelected # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:LeftRadioButton, Id(...), "args") # -> # Left(RadioButton(Id(...), "args")) def LeftRadioButton(old) Left(Builtins.toterm(:RadioButton, Builtins.argsof(old))) end module_function :LeftRadioButton # NOTE that it does not expand the nested # Greasemonkey term LeftRadioButton! {#transform} does that. # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:LeftRadioButtonWithAttachment, "foo", "bar", "contents") # -> # VBox( # term(:LeftRadioButton, "foo", "bar"), # HBox(HSpacing(4), "contents") # ) def LeftRadioButtonWithAttachment(old) args = Builtins.argsof(old) tmp1 = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 1)) tmp2 = Ops.get(args, Ops.subtract(Builtins.size(args), 1)) if tmp2 == Empty() # rubocop:disable Style/GuardClause return VBox(Builtins.toterm(:LeftRadioButton, tmp1)) else return VBox( Builtins.toterm(:LeftRadioButton, tmp1), HBox(HSpacing(4), tmp2) ) end end module_function :LeftRadioButtonWithAttachment # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:LeftCheckBox, Id(...), "args") # -> # Left(CheckBox(Id(...), "args")) def LeftCheckBox(old) Left(Builtins.toterm(:CheckBox, Builtins.argsof(old))) end module_function :LeftCheckBox # NOTE that it does not expand the nested # Greasemonkey term LeftCheckBox! {#transform} does that. # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:LeftCheckBoxWithAttachment, "foo", "bar", "contents") # -> # VBox( # term(:LeftCheckBox, "foo", "bar"), # HBox(HSpacing(4), "contents") # ) def LeftCheckBoxWithAttachment(old) args = Builtins.argsof(old) tmp1 = Builtins.sublist(args, 0, Ops.subtract(Builtins.size(args), 1)) tmp2 = Ops.get(args, Ops.subtract(Builtins.size(args), 1)) if tmp2 == Empty() # rubocop:disable Style/GuardClause return VBox(Builtins.toterm(:LeftCheckBox, tmp1)) else return VBox( Builtins.toterm(:LeftCheckBox, tmp1), HBox(HSpacing(4), tmp2) ) end end module_function :LeftCheckBoxWithAttachment # @param old [Yast::Term] # @return [Yast::Term] # @example # term(:IconAndHeading, "title", "icon") # -> # Left( # HBox( # Image("/usr/share/YaST2/theme/current/icons/22x22/apps/icon", ""), # Heading("title") # ) # ) def IconAndHeading(old) args = Builtins.argsof(old) title = Ops.get_string(args, 0, "") icon = Ops.get_string(args, 1, "") Left(HBox(Image(icon, ""), Heading(title))) end module_function :IconAndHeading # Recursively apply all Greasemonkey methods on *old* # @param old [Yast::Term] # @return [Yast::Term] def Transform(old) s = Builtins.symbolof(old) handler = Greasemonkey.method(s) if @handlers.include?(s) return Transform(handler.call(old)) if !handler.nil? new = Builtins::List.reduce(Builtins.toterm(s), Builtins.argsof(old)) do |tmp, arg| arg = Transform(Convert.to_term(arg)) if Ops.is_term?(arg) Builtins.add(tmp, arg) end new end module_function :Transform alias_method :transform, :Transform module_function :transform end end
Java
{ int n, dx, dy, sx, pp_inc_1, pp_inc_2; register int a; register PIXEL *pp; #if defined(INTERP_RGB) register unsigned int r, g, b; #endif #ifdef INTERP_RGB register unsigned int rinc, ginc, binc; #endif #ifdef INTERP_Z register unsigned int *pz; int zinc; register unsigned int z; #endif if (p1->y > p2->y || (p1->y == p2->y && p1->x > p2->x)) { ZBufferPoint *tmp; tmp = p1; p1 = p2; p2 = tmp; } sx = zb->xsize; pp = (PIXEL *)((char *) zb->pbuf.getRawBuffer() + zb->linesize * p1->y + p1->x * PSZB); #ifdef INTERP_Z pz = zb->zbuf + (p1->y * sx + p1->x); z = p1->z; #endif dx = p2->x - p1->x; dy = p2->y - p1->y; #ifdef INTERP_RGB r = p2->r << 8; g = p2->g << 8; b = p2->b << 8; #endif #ifdef INTERP_RGB #define RGB(x) x #define RGBPIXEL *pp = RGB_TO_PIXEL(r >> 8,g >> 8,b >> 8) #else // INTERP_RGB #define RGB(x) #define RGBPIXEL *pp = color #endif // INTERP_RGB #ifdef INTERP_Z #define ZZ(x) x #define PUTPIXEL() \ { \ if (ZCMP(z, *pz)) { \ RGBPIXEL; \ *pz = z; \ } \ } #else // INTERP_Z #define ZZ(x) #define PUTPIXEL() RGBPIXEL #endif // INTERP_Z #define DRAWLINE(dx, dy, inc_1, inc_2) \ n = dx; \ ZZ(zinc = (p2->z - p1->z)/n); \ RGB(rinc=((p2->r - p1->r) << 8)/n; \ ginc=((p2->g - p1->g) << 8)/n; \ binc=((p2->b - p1->b) << 8)/n); \ a = 2 * dy - dx; \ dy = 2 * dy; \ dx = 2 * dx - dy; \ pp_inc_1 = (inc_1) * PSZB; \ pp_inc_2 = (inc_2) * PSZB; \ do { \ PUTPIXEL(); \ ZZ(z += zinc); \ RGB(r += rinc; g += ginc; b += binc); \ if (a > 0) { \ pp = (PIXEL *)((char *)pp + pp_inc_1); \ ZZ(pz+=(inc_1)); \ a -= dx; \ } else { \ pp = (PIXEL *)((char *)pp + pp_inc_2); \ ZZ(pz += (inc_2)); \ a += dy; \ } \ } while (--n >= 0); // fin macro if (dx == 0 && dy == 0) { PUTPIXEL(); } else if (dx > 0) { if (dx >= dy) { DRAWLINE(dx, dy, sx + 1, 1); } else { DRAWLINE(dy, dx, sx + 1, sx); } } else { dx = -dx; if (dx >= dy) { DRAWLINE(dx, dy, sx - 1, -1); } else { DRAWLINE(dy, dx, sx - 1, sx); } } } #undef INTERP_Z #undef INTERP_RGB // internal defines #undef DRAWLINE #undef PUTPIXEL #undef ZZ #undef RGB #undef RGBPIXEL
Java
/* utility routines for keeping some statistics */ /* (C) 2009 by Harald Welte <laforge@gnumonks.org> * * 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. * * 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 <sys/types.h> #include <osmocore/linuxlist.h> #include <osmocore/talloc.h> #include <osmocore/statistics.h> static LLIST_HEAD(counters); void *tall_ctr_ctx; struct counter *counter_alloc(const char *name) { struct counter *ctr = talloc_zero(tall_ctr_ctx, struct counter); if (!ctr) return NULL; ctr->name = name; llist_add_tail(&ctr->list, &counters); return ctr; } void counter_free(struct counter *ctr) { llist_del(&ctr->list); talloc_free(ctr); } int counters_for_each(int (*handle_counter)(struct counter *, void *), void *data) { struct counter *ctr; int rc = 0; llist_for_each_entry(ctr, &counters, list) { rc = handle_counter(ctr, data); if (rc < 0) return rc; } return rc; }
Java
using NetworkProbe.Port.Services; using System.Collections.Generic; using System.Net; using NetworkProbe.Port; using NetworkProbe.Model; using System.Threading.Tasks; using System.Linq; namespace NetworkProbe { public static class Probe { /// <summary> /// Initiates a service scan on a single service to a single network device /// </summary> public static ProbeResult Single(ProbeEntity entity) { var result = Task.Run(() => ReturnSingleResult(entity)); return result.Result; } /// <summary> /// Initiates a service scan on multiple services on multiple devices /// </summary> public static IEnumerable<ProbeResult> Multiple(IEnumerable<ProbeEntity> entities) { List<ProbeResult> results = new List<ProbeResult>(); //Run each probe in parallel Parallel.ForEach(entities, x => { var result = Task.Run(() => ReturnSingleResult(x)); results.Add(result.Result); }); //Order results due to some tasks finishing earlier than others ***this adds around 5-7 seconds on 254 address scan :-( *** return results.OrderBy(x => int.Parse(x.IP.ToString().Split('.')[3])); } private async static Task<ProbeResult> ReturnSingleResult(ProbeEntity entity) { var service = ServiceFactory.Create(entity.Type, entity.IP, entity.Port); await service.ReturnPortData(); PortStatus status = service.PortLive ? PortStatus.Live : PortStatus.Dead; bool isData = service.PortResult != null && service.PortResult.Count > 0 ? true : false; Dictionary<string, string> data = isData ? service.PortResult : new Dictionary<string, string>(); return new ProbeResult(entity.Type, entity.Port, entity.IP, status, isData, data); } } }
Java
import urllib2 def sumaDos(): print 10*20 def division(a,b): result=a/b print result def areatriangulo(base,altura): result2=(base*altura)/2 print result2 def cast(): lista=[1,2,3,"hola"] tupla=(1,2,3) diccinario={"key1":"Diego","key2":"Piqui","key3":"Chuy"} for k,v in diccionario: print "%s %s" % (k,v) class Estudiante(object): def __init__(self, nombre, edad): self.nombre=nombre self.edad=edad def hola(self): return self.nombre def esMayor(self): if self.edad>=18: return true else: return false def EXCEPTION(): try: 3/0 except Exception: print "error" def main(): e=Estudiante("Diego",22) print"Hola %s" % e.hola() if e.esMayor(): print"Es mayor de edad" else: print"Es menor de edad" contador = 0 while contador <=10: print contador contador +=1 EXCEPTION(): def getWeb(): try: web=urllib2.urlopen("http://itjiquilpan.edu.mx/") print web.read() web.close() except urllib2.HTTPError, e: print e except urllib2.URLError as e: print e def main(): cast() if __name__=="__main__": main()
Java
/*************************************************************************** qgsmeasure.h ------------------ begin : March 2005 copyright : (C) 2005 by Radim Blazek email : blazek@itc.it ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ #ifndef QGSMEASUREDIALOG_H #define QGSMEASUREDIALOG_H #include "ui_qgsmeasurebase.h" #include "qgspoint.h" #include "qgsdistancearea.h" #include "qgscontexthelp.h" class QCloseEvent; class QgsMeasureTool; class QgsMeasureDialog : public QDialog, private Ui::QgsMeasureBase { Q_OBJECT public: //! Constructor QgsMeasureDialog( QgsMeasureTool* tool, Qt::WFlags f = 0 ); //! Save position void saveWindowLocation( void ); //! Restore last window position/size void restorePosition( void ); //! Add new point void addPoint( QgsPoint &point ); //! Mose move void mouseMove( QgsPoint &point ); //! Mouse press void mousePress( QgsPoint &point ); public slots: //! Reject void on_buttonBox_rejected( void ); //! Reset and start new void restart(); //! Close event void closeEvent( QCloseEvent *e ); //! Show the help for the dialog void on_buttonBox_helpRequested() { QgsContextHelp::run( metaObject()->className() ); } private: //! formats distance to most appropriate units QString formatDistance( double distance, int decimalPlaces ); //! formats area to most appropriate units QString formatArea( double area, int decimalPlaces ); //! shows/hides table, shows correct units void updateUi(); //! Converts the measurement, depending on settings in options and current transformation void convertMeasurement( double &measure, QGis::UnitType &u, bool isArea ); double mTotal; //! indicates whether we're measuring distances or areas bool mMeasureArea; //! pointer to measure tool which owns this dialog QgsMeasureTool* mTool; }; #endif
Java
<!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"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>Overview &mdash; Python 2.7.10rc0 documentation</title> <link rel="stylesheet" href="_static/default.css" type="text/css" /> <link rel="stylesheet" href="_static/pygments.css" type="text/css" /> <script type="text/javascript"> var DOCUMENTATION_OPTIONS = { URL_ROOT: './', VERSION: '2.7.10rc0', COLLAPSE_INDEX: false, FILE_SUFFIX: '.html', HAS_SOURCE: true }; </script> <script type="text/javascript" src="_static/jquery.js"></script> <script type="text/javascript" src="_static/underscore.js"></script> <script type="text/javascript" src="_static/doctools.js"></script> <script type="text/javascript" src="_static/sidebar.js"></script> <link rel="search" type="application/opensearchdescription+xml" title="Search within Python 2.7.10rc0 documentation" href="_static/opensearch.xml"/> <link rel="author" title="About these documents" href="about.html" /> <link rel="copyright" title="Copyright" href="copyright.html" /> <link rel="top" title="Python 2.7.10rc0 documentation" href="#" /> <link rel="shortcut icon" type="image/png" href="_static/py.png" /> <script type="text/javascript" src="_static/copybutton.js"></script> <script type="text/javascript" src="_static/version_switch.js"></script> </head> <body> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" accesskey="I">index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><img src="_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> &raquo;</li> <li> <span class="version_switcher_placeholder">2.7.10rc0</span> <a href="#">Documentation</a> &raquo; </li> </ul> </div> <div class="document"> <div class="documentwrapper"> <div class="bodywrapper"> <div class="body"> <h1>Python 2.7.10rc0 documentation</h1> <p> Welcome! This is the documentation for Python 2.7.10rc0, last updated Apr 13, 2015. </p> <p><strong>Parts of the documentation:</strong></p> <table class="contentstable" align="center"><tr> <td width="50%"> <p class="biglink"><a class="biglink" href="whatsnew/2.7.html">What's new in Python 2.7?</a><br/> <span class="linkdescr">or <a href="whatsnew/index.html">all "What's new" documents</a> since 2.0</span></p> <p class="biglink"><a class="biglink" href="tutorial/index.html">Tutorial</a><br/> <span class="linkdescr">start here</span></p> <p class="biglink"><a class="biglink" href="library/index.html">Library Reference</a><br/> <span class="linkdescr">keep this under your pillow</span></p> <p class="biglink"><a class="biglink" href="reference/index.html">Language Reference</a><br/> <span class="linkdescr">describes syntax and language elements</span></p> <p class="biglink"><a class="biglink" href="using/index.html">Python Setup and Usage</a><br/> <span class="linkdescr">how to use Python on different platforms</span></p> <p class="biglink"><a class="biglink" href="howto/index.html">Python HOWTOs</a><br/> <span class="linkdescr">in-depth documents on specific topics</span></p> </td><td width="50%"> <p class="biglink"><a class="biglink" href="extending/index.html">Extending and Embedding</a><br/> <span class="linkdescr">tutorial for C/C++ programmers</span></p> <p class="biglink"><a class="biglink" href="c-api/index.html">Python/C API</a><br/> <span class="linkdescr">reference for C/C++ programmers</span></p> <p class="biglink"><a class="biglink" href="install/index.html">Installing Python Modules</a><br/> <span class="linkdescr">information for installers &amp; sys-admins</span></p> <p class="biglink"><a class="biglink" href="distutils/index.html">Distributing Python Modules</a><br/> <span class="linkdescr">sharing modules with others</span></p> <p class="biglink"><a class="biglink" href="faq/index.html">FAQs</a><br/> <span class="linkdescr">frequently asked questions (with answers!)</span></p> </td></tr> </table> <p><strong>Indices and tables:</strong></p> <table class="contentstable" align="center"><tr> <td width="50%"> <p class="biglink"><a class="biglink" href="py-modindex.html">Global Module Index</a><br/> <span class="linkdescr">quick access to all modules</span></p> <p class="biglink"><a class="biglink" href="genindex.html">General Index</a><br/> <span class="linkdescr">all functions, classes, terms</span></p> <p class="biglink"><a class="biglink" href="glossary.html">Glossary</a><br/> <span class="linkdescr">the most important terms explained</span></p> </td><td width="50%"> <p class="biglink"><a class="biglink" href="search.html">Search page</a><br/> <span class="linkdescr">search this documentation</span></p> <p class="biglink"><a class="biglink" href="contents.html">Complete Table of Contents</a><br/> <span class="linkdescr">lists all sections and subsections</span></p> </td></tr> </table> <p><strong>Meta information:</strong></p> <table class="contentstable" align="center"><tr> <td width="50%"> <p class="biglink"><a class="biglink" href="bugs.html">Reporting bugs</a></p> <p class="biglink"><a class="biglink" href="about.html">About the documentation</a></p> </td><td width="50%"> <p class="biglink"><a class="biglink" href="license.html">History and License of Python</a></p> <p class="biglink"><a class="biglink" href="copyright.html">Copyright</a></p> </td></tr> </table> </div> </div> </div> <div class="sphinxsidebar"> <div class="sphinxsidebarwrapper"> <h3>Download</h3> <p><a href="download.html">Download these documents</a></p> <h3>Docs for other versions</h3> <ul> <li><a href="https://docs.python.org/3.4/">Python 3.4 (stable)</a></li> <li><a href="https://docs.python.org/3.5/">Python 3.5 (in development)</a></li> <li><a href="https://www.python.org/doc/versions/">Old versions</a></li> </ul> <h3>Other resources</h3> <ul> <li><a href="https://www.python.org/dev/peps/">PEP Index</a></li> <li><a href="https://wiki.python.org/moin/BeginnersGuide">Beginner's Guide</a></li> <li><a href="https://wiki.python.org/moin/PythonBooks">Book List</a></li> <li><a href="https://www.python.org/doc/av/">Audio/Visual Talks</a></li> </ul> <div id="searchbox" style="display: none"> <h3>Quick search</h3> <form class="search" action="search.html" method="get"> <input type="text" name="q" /> <input type="submit" value="Go" /> <input type="hidden" name="check_keywords" value="yes" /> <input type="hidden" name="area" value="default" /> </form> <p class="searchtip" style="font-size: 90%"> Enter search terms or a module, class or function name. </p> </div> <script type="text/javascript">$('#searchbox').show(0);</script> </div> </div> <div class="clearer"></div> </div> <div class="related"> <h3>Navigation</h3> <ul> <li class="right" style="margin-right: 10px"> <a href="genindex.html" title="General Index" >index</a></li> <li class="right" > <a href="py-modindex.html" title="Python Module Index" >modules</a> |</li> <li><img src="_static/py.png" alt="" style="vertical-align: middle; margin-top: -1px"/></li> <li><a href="https://www.python.org/">Python</a> &raquo;</li> <li> <span class="version_switcher_placeholder">2.7.10rc0</span> <a href="#">Documentation</a> &raquo; </li> </ul> </div> <div class="footer"> &copy; <a href="copyright.html">Copyright</a> 1990-2015, Python Software Foundation. <br /> The Python Software Foundation is a non-profit corporation. <a href="https://www.python.org/psf/donations/">Please donate.</a> <br /> Last updated on Apr 13, 2015. <a href="bugs.html">Found a bug</a>? <br /> Created using <a href="http://sphinx.pocoo.org/">Sphinx</a> 1.2.3. </div> </body> </html>
Java
class EmailToken < ActiveRecord::Base belongs_to :user validates_presence_of :token validates_presence_of :user_id validates_presence_of :email before_validation(:on => :create) do self.token = EmailToken.generate_token end after_create do # Expire the previous tokens EmailToken.update_all 'expired = true', ['user_id = ? and id != ?', self.user_id, self.id] end def self.token_length 16 end def self.valid_after 1.week.ago end def self.unconfirmed where(confirmed: false) end def self.active where(expired: false).where('created_at > ?', valid_after) end def self.generate_token SecureRandom.hex(EmailToken.token_length) end def self.confirm(token) return unless token.present? return unless token.length/2 == EmailToken.token_length email_token = EmailToken.where("token = ? AND expired = FALSE and created_at >= ?", token, EmailToken.valid_after).includes(:user).first return if email_token.blank? user = email_token.user User.transaction do row_count = EmailToken.update_all 'confirmed = true', ['id = ? AND confirmed = false', email_token.id] if row_count == 1 # If we are activating the user, send the welcome message user.send_welcome_message = !user.active? user.active = true user.email = email_token.email user.save! end end user rescue ActiveRecord::RecordInvalid # If the user's email is already taken, just return nil (failure) nil end end
Java
/* * fs/f2fs/recovery.c * * Copyright (c) 2012 Samsung Electronics Co., Ltd. * http://www.samsung.com/ * * 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. */ #include <linux/fs.h> #include <linux/f2fs_fs.h> #include "f2fs.h" #include "node.h" #include "segment.h" /* * Roll forward recovery scenarios. * * [Term] F: fsync_mark, D: dentry_mark * * 1. inode(x) | CP | inode(x) | dnode(F) * -> Update the latest inode(x). * * 2. inode(x) | CP | inode(F) | dnode(F) * -> No problem. * * 3. inode(x) | CP | dnode(F) | inode(x) * -> Recover to the latest dnode(F), and drop the last inode(x) * * 4. inode(x) | CP | dnode(F) | inode(F) * -> No problem. * * 5. CP | inode(x) | dnode(F) * -> The inode(DF) was missing. Should drop this dnode(F). * * 6. CP | inode(DF) | dnode(F) * -> No problem. * * 7. CP | dnode(F) | inode(DF) * -> If f2fs_iget fails, then goto next to find inode(DF). * * 8. CP | dnode(F) | inode(x) * -> If f2fs_iget fails, then goto next to find inode(DF). * But it will fail due to no inode(DF). */ static struct kmem_cache *fsync_entry_slab; bool space_for_roll_forward(struct f2fs_sb_info *sbi) { s64 nalloc = percpu_counter_sum_positive(&sbi->alloc_valid_block_count); if (sbi->last_valid_block_count + nalloc > sbi->user_block_count) return false; return true; } static struct fsync_inode_entry *get_fsync_inode(struct list_head *head, nid_t ino) { struct fsync_inode_entry *entry; list_for_each_entry(entry, head, list) if (entry->inode->i_ino == ino) return entry; return NULL; } static struct fsync_inode_entry *add_fsync_inode(struct list_head *head, struct inode *inode) { struct fsync_inode_entry *entry; entry = kmem_cache_alloc(fsync_entry_slab, GFP_F2FS_ZERO); if (!entry) return NULL; entry->inode = inode; list_add_tail(&entry->list, head); return entry; } static void del_fsync_inode(struct fsync_inode_entry *entry) { iput(entry->inode); list_del(&entry->list); kmem_cache_free(fsync_entry_slab, entry); } static int recover_dentry(struct inode *inode, struct page *ipage, struct list_head *dir_list) { struct f2fs_inode *raw_inode = F2FS_INODE(ipage); nid_t pino = le32_to_cpu(raw_inode->i_pino); struct f2fs_dir_entry *de; struct fscrypt_name fname; struct page *page; struct inode *dir, *einode; struct fsync_inode_entry *entry; int err = 0; char *name; entry = get_fsync_inode(dir_list, pino); if (!entry) { dir = f2fs_iget(inode->i_sb, pino); if (IS_ERR(dir)) { err = PTR_ERR(dir); goto out; } entry = add_fsync_inode(dir_list, dir); if (!entry) { err = -ENOMEM; iput(dir); goto out; } } dir = entry->inode; memset(&fname, 0, sizeof(struct fscrypt_name)); fname.disk_name.len = le32_to_cpu(raw_inode->i_namelen); fname.disk_name.name = raw_inode->i_name; if (unlikely(fname.disk_name.len > F2FS_NAME_LEN)) { WARN_ON(1); err = -ENAMETOOLONG; goto out; } retry: de = __f2fs_find_entry(dir, &fname, &page); if (de && inode->i_ino == le32_to_cpu(de->ino)) goto out_unmap_put; if (de) { einode = f2fs_iget(inode->i_sb, le32_to_cpu(de->ino)); if (IS_ERR(einode)) { WARN_ON(1); err = PTR_ERR(einode); if (err == -ENOENT) err = -EEXIST; goto out_unmap_put; } err = acquire_orphan_inode(F2FS_I_SB(inode)); if (err) { iput(einode); goto out_unmap_put; } f2fs_delete_entry(de, page, dir, einode); iput(einode); goto retry; } else if (IS_ERR(page)) { err = PTR_ERR(page); } else { err = __f2fs_do_add_link(dir, &fname, inode, inode->i_ino, inode->i_mode); } goto out; out_unmap_put: f2fs_dentry_kunmap(dir, page); f2fs_put_page(page, 0); out: if (file_enc_name(inode)) name = "<encrypted>"; else name = raw_inode->i_name; f2fs_msg(inode->i_sb, KERN_NOTICE, "%s: ino = %x, name = %s, dir = %lx, err = %d", __func__, ino_of_node(ipage), name, IS_ERR(dir) ? 0 : dir->i_ino, err); return err; } static void recover_inode(struct inode *inode, struct page *page) { struct f2fs_inode *raw = F2FS_INODE(page); char *name; inode->i_mode = le16_to_cpu(raw->i_mode); f2fs_i_size_write(inode, le64_to_cpu(raw->i_size)); inode->i_atime.tv_sec = le64_to_cpu(raw->i_mtime); inode->i_ctime.tv_sec = le64_to_cpu(raw->i_ctime); inode->i_mtime.tv_sec = le64_to_cpu(raw->i_mtime); inode->i_atime.tv_nsec = le32_to_cpu(raw->i_mtime_nsec); inode->i_ctime.tv_nsec = le32_to_cpu(raw->i_ctime_nsec); inode->i_mtime.tv_nsec = le32_to_cpu(raw->i_mtime_nsec); if (file_enc_name(inode)) name = "<encrypted>"; else name = F2FS_INODE(page)->i_name; f2fs_msg(inode->i_sb, KERN_NOTICE, "recover_inode: ino = %x, name = %s", ino_of_node(page), name); } static bool is_same_inode(struct inode *inode, struct page *ipage) { struct f2fs_inode *ri = F2FS_INODE(ipage); struct timespec disk; if (!IS_INODE(ipage)) return true; disk.tv_sec = le64_to_cpu(ri->i_ctime); disk.tv_nsec = le32_to_cpu(ri->i_ctime_nsec); if (timespec_compare(&inode->i_ctime, &disk) > 0) return false; disk.tv_sec = le64_to_cpu(ri->i_atime); disk.tv_nsec = le32_to_cpu(ri->i_atime_nsec); if (timespec_compare(&inode->i_atime, &disk) > 0) return false; disk.tv_sec = le64_to_cpu(ri->i_mtime); disk.tv_nsec = le32_to_cpu(ri->i_mtime_nsec); if (timespec_compare(&inode->i_mtime, &disk) > 0) return false; return true; } static int find_fsync_dnodes(struct f2fs_sb_info *sbi, struct list_head *head) { unsigned long long cp_ver = cur_cp_version(F2FS_CKPT(sbi)); struct curseg_info *curseg; struct inode *inode; struct page *page = NULL; block_t blkaddr; int err = 0; /* get node pages in the current segment */ curseg = CURSEG_I(sbi, CURSEG_WARM_NODE); blkaddr = NEXT_FREE_BLKADDR(sbi, curseg); while (1) { struct fsync_inode_entry *entry; if (!is_valid_blkaddr(sbi, blkaddr, META_POR)) return 0; page = get_tmp_page(sbi, blkaddr); if (cp_ver != cpver_of_node(page)) break; if (!is_fsync_dnode(page)) goto next; entry = get_fsync_inode(head, ino_of_node(page)); if (entry) { if (!is_same_inode(entry->inode, page)) goto next; } else { if (IS_INODE(page) && is_dent_dnode(page)) { err = recover_inode_page(sbi, page); if (err) break; } /* * CP | dnode(F) | inode(DF) * For this case, we should not give up now. */ inode = f2fs_iget(sbi->sb, ino_of_node(page)); if (IS_ERR(inode)) { err = PTR_ERR(inode); if (err == -ENOENT) { err = 0; goto next; } break; } /* add this fsync inode to the list */ entry = add_fsync_inode(head, inode); if (!entry) { err = -ENOMEM; iput(inode); break; } } entry->blkaddr = blkaddr; if (IS_INODE(page) && is_dent_dnode(page)) entry->last_dentry = blkaddr; next: /* check next segment */ blkaddr = next_blkaddr_of_node(page); f2fs_put_page(page, 1); ra_meta_pages_cond(sbi, blkaddr); } f2fs_put_page(page, 1); return err; } static void destroy_fsync_dnodes(struct list_head *head) { struct fsync_inode_entry *entry, *tmp; list_for_each_entry_safe(entry, tmp, head, list) del_fsync_inode(entry); } static int check_index_in_prev_nodes(struct f2fs_sb_info *sbi, block_t blkaddr, struct dnode_of_data *dn) { struct seg_entry *sentry; unsigned int segno = GET_SEGNO(sbi, blkaddr); unsigned short blkoff = GET_BLKOFF_FROM_SEG0(sbi, blkaddr); struct f2fs_summary_block *sum_node; struct f2fs_summary sum; struct page *sum_page, *node_page; struct dnode_of_data tdn = *dn; nid_t ino, nid; struct inode *inode; unsigned int offset; block_t bidx; int i; sentry = get_seg_entry(sbi, segno); if (!f2fs_test_bit(blkoff, sentry->cur_valid_map)) return 0; /* Get the previous summary */ for (i = CURSEG_WARM_DATA; i <= CURSEG_COLD_DATA; i++) { struct curseg_info *curseg = CURSEG_I(sbi, i); if (curseg->segno == segno) { sum = curseg->sum_blk->entries[blkoff]; goto got_it; } } sum_page = get_sum_page(sbi, segno); sum_node = (struct f2fs_summary_block *)page_address(sum_page); sum = sum_node->entries[blkoff]; f2fs_put_page(sum_page, 1); got_it: /* Use the locked dnode page and inode */ nid = le32_to_cpu(sum.nid); if (dn->inode->i_ino == nid) { tdn.nid = nid; if (!dn->inode_page_locked) lock_page(dn->inode_page); tdn.node_page = dn->inode_page; tdn.ofs_in_node = le16_to_cpu(sum.ofs_in_node); goto truncate_out; } else if (dn->nid == nid) { tdn.ofs_in_node = le16_to_cpu(sum.ofs_in_node); goto truncate_out; } /* Get the node page */ node_page = get_node_page(sbi, nid); if (IS_ERR(node_page)) return PTR_ERR(node_page); offset = ofs_of_node(node_page); ino = ino_of_node(node_page); f2fs_put_page(node_page, 1); if (ino != dn->inode->i_ino) { /* Deallocate previous index in the node page */ inode = f2fs_iget(sbi->sb, ino); if (IS_ERR(inode)) return PTR_ERR(inode); } else { inode = dn->inode; } bidx = start_bidx_of_node(offset, inode) + le16_to_cpu(sum.ofs_in_node); /* * if inode page is locked, unlock temporarily, but its reference * count keeps alive. */ if (ino == dn->inode->i_ino && dn->inode_page_locked) unlock_page(dn->inode_page); set_new_dnode(&tdn, inode, NULL, NULL, 0); if (get_dnode_of_data(&tdn, bidx, LOOKUP_NODE)) goto out; if (tdn.data_blkaddr == blkaddr) truncate_data_blocks_range(&tdn, 1); f2fs_put_dnode(&tdn); out: if (ino != dn->inode->i_ino) iput(inode); else if (dn->inode_page_locked) lock_page(dn->inode_page); return 0; truncate_out: if (datablock_addr(tdn.node_page, tdn.ofs_in_node) == blkaddr) truncate_data_blocks_range(&tdn, 1); if (dn->inode->i_ino == nid && !dn->inode_page_locked) unlock_page(dn->inode_page); return 0; } static int do_recover_data(struct f2fs_sb_info *sbi, struct inode *inode, struct page *page, block_t blkaddr) { struct dnode_of_data dn; struct node_info ni; unsigned int start, end; int err = 0, recovered = 0; /* step 1: recover xattr */ if (IS_INODE(page)) { recover_inline_xattr(inode, page); } else if (f2fs_has_xattr_block(ofs_of_node(page))) { /* * Deprecated; xattr blocks should be found from cold log. * But, we should remain this for backward compatibility. */ recover_xattr_data(inode, page, blkaddr); goto out; } /* step 2: recover inline data */ if (recover_inline_data(inode, page)) goto out; /* step 3: recover data indices */ start = start_bidx_of_node(ofs_of_node(page), inode); end = start + ADDRS_PER_PAGE(page, inode); set_new_dnode(&dn, inode, NULL, NULL, 0); err = get_dnode_of_data(&dn, start, ALLOC_NODE); if (err) goto out; f2fs_wait_on_page_writeback(dn.node_page, NODE, true); get_node_info(sbi, dn.nid, &ni); f2fs_bug_on(sbi, ni.ino != ino_of_node(page)); f2fs_bug_on(sbi, ofs_of_node(dn.node_page) != ofs_of_node(page)); for (; start < end; start++, dn.ofs_in_node++) { block_t src, dest; src = datablock_addr(dn.node_page, dn.ofs_in_node); dest = datablock_addr(page, dn.ofs_in_node); /* skip recovering if dest is the same as src */ if (src == dest) continue; /* dest is invalid, just invalidate src block */ if (dest == NULL_ADDR) { truncate_data_blocks_range(&dn, 1); continue; } if ((start + 1) << PAGE_SHIFT > i_size_read(inode)) f2fs_i_size_write(inode, (start + 1) << PAGE_SHIFT); /* * dest is reserved block, invalidate src block * and then reserve one new block in dnode page. */ if (dest == NEW_ADDR) { truncate_data_blocks_range(&dn, 1); reserve_new_block(&dn); continue; } /* dest is valid block, try to recover from src to dest */ if (is_valid_blkaddr(sbi, dest, META_POR)) { if (src == NULL_ADDR) { err = reserve_new_block(&dn); #ifdef CONFIG_F2FS_FAULT_INJECTION while (err) err = reserve_new_block(&dn); #endif /* We should not get -ENOSPC */ f2fs_bug_on(sbi, err); if (err) goto err; } /* Check the previous node page having this index */ err = check_index_in_prev_nodes(sbi, dest, &dn); if (err) goto err; /* write dummy data page */ f2fs_replace_block(sbi, &dn, src, dest, ni.version, false, false); recovered++; } } copy_node_footer(dn.node_page, page); fill_node_footer(dn.node_page, dn.nid, ni.ino, ofs_of_node(page), false); set_page_dirty(dn.node_page); err: f2fs_put_dnode(&dn); out: f2fs_msg(sbi->sb, KERN_NOTICE, "recover_data: ino = %lx, recovered = %d blocks, err = %d", inode->i_ino, recovered, err); return err; } static int recover_data(struct f2fs_sb_info *sbi, struct list_head *inode_list, struct list_head *dir_list) { unsigned long long cp_ver = cur_cp_version(F2FS_CKPT(sbi)); struct curseg_info *curseg; struct page *page = NULL; int err = 0; block_t blkaddr; /* get node pages in the current segment */ curseg = CURSEG_I(sbi, CURSEG_WARM_NODE); blkaddr = NEXT_FREE_BLKADDR(sbi, curseg); while (1) { struct fsync_inode_entry *entry; if (!is_valid_blkaddr(sbi, blkaddr, META_POR)) break; ra_meta_pages_cond(sbi, blkaddr); page = get_tmp_page(sbi, blkaddr); if (cp_ver != cpver_of_node(page)) { f2fs_put_page(page, 1); break; } entry = get_fsync_inode(inode_list, ino_of_node(page)); if (!entry) goto next; /* * inode(x) | CP | inode(x) | dnode(F) * In this case, we can lose the latest inode(x). * So, call recover_inode for the inode update. */ if (IS_INODE(page)) recover_inode(entry->inode, page); if (entry->last_dentry == blkaddr) { err = recover_dentry(entry->inode, page, dir_list); if (err) { f2fs_put_page(page, 1); break; } } err = do_recover_data(sbi, entry->inode, page, blkaddr); if (err) { f2fs_put_page(page, 1); break; } if (entry->blkaddr == blkaddr) del_fsync_inode(entry); next: /* check next segment */ blkaddr = next_blkaddr_of_node(page); f2fs_put_page(page, 1); } if (!err) allocate_new_segments(sbi); return err; } int recover_fsync_data(struct f2fs_sb_info *sbi, bool check_only) { struct curseg_info *curseg = CURSEG_I(sbi, CURSEG_WARM_NODE); struct list_head inode_list; struct list_head dir_list; block_t blkaddr; int err; int ret = 0; bool need_writecp = false; fsync_entry_slab = f2fs_kmem_cache_create("f2fs_fsync_inode_entry", sizeof(struct fsync_inode_entry)); if (!fsync_entry_slab) return -ENOMEM; INIT_LIST_HEAD(&inode_list); INIT_LIST_HEAD(&dir_list); /* prevent checkpoint */ mutex_lock(&sbi->cp_mutex); blkaddr = NEXT_FREE_BLKADDR(sbi, curseg); /* step #1: find fsynced inode numbers */ err = find_fsync_dnodes(sbi, &inode_list); if (err || list_empty(&inode_list)) goto out; if (check_only) { ret = 1; goto out; } need_writecp = true; /* step #2: recover data */ err = recover_data(sbi, &inode_list, &dir_list); if (!err) f2fs_bug_on(sbi, !list_empty(&inode_list)); out: destroy_fsync_dnodes(&inode_list); /* truncate meta pages to be used by the recovery */ truncate_inode_pages_range(META_MAPPING(sbi), (loff_t)MAIN_BLKADDR(sbi) << PAGE_SHIFT, -1); if (err) { truncate_inode_pages_final(NODE_MAPPING(sbi)); truncate_inode_pages_final(META_MAPPING(sbi)); } clear_sbi_flag(sbi, SBI_POR_DOING); if (err) { bool invalidate = false; if (test_opt(sbi, LFS)) { update_meta_page(sbi, NULL, blkaddr); invalidate = true; } else if (discard_next_dnode(sbi, blkaddr)) { invalidate = true; } f2fs_wait_all_discard_bio(sbi); /* Flush all the NAT/SIT pages */ while (get_pages(sbi, F2FS_DIRTY_META)) sync_meta_pages(sbi, META, LONG_MAX); /* invalidate temporary meta page */ if (invalidate) invalidate_mapping_pages(META_MAPPING(sbi), blkaddr, blkaddr); set_ckpt_flags(sbi->ckpt, CP_ERROR_FLAG); mutex_unlock(&sbi->cp_mutex); } else if (need_writecp) { struct cp_control cpc = { .reason = CP_RECOVERY, }; mutex_unlock(&sbi->cp_mutex); err = write_checkpoint(sbi, &cpc); } else { mutex_unlock(&sbi->cp_mutex); } destroy_fsync_dnodes(&dir_list); kmem_cache_destroy(fsync_entry_slab); return ret ? ret: err; }
Java
/* * This file is part of MPlayer. * * MPlayer 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. * * MPlayer 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 MPlayer; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ #include <ctype.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <fcntl.h> #include <string.h> #include "config.h" #include "mp_msg.h" #include "help_mp.h" #ifdef __FreeBSD__ #include <sys/cdrio.h> #endif #include "m_option.h" #include "stream.h" #include "libmpdemux/demuxer.h" /// We keep these 2 for the gui atm, but they will be removed. char* cdrom_device=NULL; int dvd_chapter=1; int dvd_last_chapter=0; char* dvd_device=NULL; char *bluray_device=NULL; // Open a new stream (stdin/file/vcd/url) stream_t* open_stream(const char* filename,char** options, int* file_format){ int dummy = DEMUXER_TYPE_UNKNOWN; if (!file_format) file_format = &dummy; // Check if playlist or unknown if (*file_format != DEMUXER_TYPE_PLAYLIST){ *file_format=DEMUXER_TYPE_UNKNOWN; } if(!filename) { mp_msg(MSGT_OPEN,MSGL_ERR,"NULL filename, report this bug\n"); return NULL; } //============ Open STDIN or plain FILE ============ return open_stream_full(filename,STREAM_READ,options,file_format); }
Java
/** IneoRealTimeFileFormat class implementation. @file IneoRealTimeFileFormat.cpp This file belongs to the SYNTHESE project (public transportation specialized software) Copyright (C) 2002 Hugues Romain - RCSmobility <contact@rcsmobility.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 "IneoRealTimeFileFormat.hpp" #include "Import.hpp" #include "DataSource.h" #include "DataSourceTableSync.h" #include "DBTransaction.hpp" #include "ImportableTableSync.hpp" #include "ScheduledServiceTableSync.h" #include "StopPointTableSync.hpp" #include "CommercialLineTableSync.h" #include "JourneyPatternTableSync.hpp" #include "DesignatedLinePhysicalStop.hpp" #include "LineStopTableSync.h" #include <boost/lexical_cast.hpp> using namespace std; using namespace boost; using namespace boost::posix_time; using namespace gregorian; namespace synthese { using namespace data_exchange; using namespace pt; using namespace server; using namespace util; using namespace impex; using namespace db; using namespace graph; using namespace util; namespace util { template<> const string FactorableTemplate<FileFormat, IneoRealTimeFileFormat>::FACTORY_KEY("ineo_temps_reel"); } namespace data_exchange { const string IneoRealTimeFileFormat::Importer_::PARAMETER_PLANNED_DATASOURCE_ID("ps"); const string IneoRealTimeFileFormat::Importer_::PARAMETER_COURSE_ID("ci"); const string IneoRealTimeFileFormat::Importer_::PARAMETER_DB_CONN_STRING("conn_string"); const string IneoRealTimeFileFormat::Importer_::PARAMETER_STOP_CODE_PREFIX("stop_code_prefix"); bool IneoRealTimeFileFormat::Importer_::_read( ) const { if(_database.empty() || !_plannedDataSource.get()) { return false; } DataSource& dataSource(*_import.get<DataSource>()); boost::shared_ptr<DB> db; if(_dbConnString) { db = DBModule::GetDBForStandaloneUse(*_dbConnString); } else { db = DBModule::GetDBSPtr(); } date today(day_clock::local_day()); string todayStr("'"+ to_iso_extended_string(today) +"'"); // Services linked to the planned source ImportableTableSync::ObjectBySource<StopPointTableSync> stops(*_plannedDataSource, _env); ImportableTableSync::ObjectBySource<CommercialLineTableSync> lines(*_plannedDataSource, _env); if(!_courseId) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::value_type& itLine, lines.getMap()) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::mapped_type::value_type& line, itLine.second) { JourneyPatternTableSync::Search(_env, line->getKey()); ScheduledServiceTableSync::Search(_env, optional<RegistryKeyType>(), line->getKey()); BOOST_FOREACH(const Path* route, line->getPaths()) { LineStopTableSync::Search(_env, route->getKey()); } } } // 1 : clean the old references to the current source ImportableTableSync::ObjectBySource<ScheduledServiceTableSync> sourcedServices(dataSource, _env); BOOST_FOREACH(const ImportableTableSync::ObjectBySource<ScheduledServiceTableSync>::Map::value_type& itService, sourcedServices.getMap()) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<ScheduledServiceTableSync>::Map::mapped_type::value_type& obj, itService.second) { obj->removeSourceLinks(dataSource); } } } else { // 1 : clean the old references to the current source ImportableTableSync::ObjectBySource<ScheduledServiceTableSync> sourcedServices(dataSource, _env); set<ScheduledService*> services(sourcedServices.get(*_courseId)); BOOST_FOREACH(ScheduledService* service, services) { service->removeSourceLinks(dataSource); _services.insert(service); } } // 2 : loop on the services present in the database and link to existing or new services stringstream query; query << "SELECT c.ref, c.chainage, c.ligne, l.mnemo as ligne_ref FROM " << _database << ".COURSE c " << "INNER JOIN " << _database << ".LIGNE l on c.ligne=l.ref AND l.jour=c.jour " << "WHERE c.jour=" << todayStr << " AND c.type='C'"; if(_courseId) { query << " AND c.ref=" << *_courseId; } DBResultSPtr result(db->execQuery(query.str())); while(result->next()) { string serviceRef(result->getText("ref")); string chainage(result->getText("chainage")); string ligneRef(result->getText("ligne_ref")); _logDebug( "Processing serviceRef="+ serviceRef +" chainage="+ chainage +" ligneRef="+ ligneRef ); CommercialLine* line( _getLine( lines, ligneRef, *_plannedDataSource ) ); if(!line) { _logWarning( "Line "+ ligneRef +" was not found for service "+ serviceRef ); continue; } stringstream chainageQuery; chainageQuery << "SELECT a.mnemol AS mnemol, h.htd AS htd, h.hta AS hta, h.type AS type, c.pos AS pos FROM " << _database << ".ARRETCHN c " << "INNER JOIN " << _database << ".ARRET a ON a.ref=c.arret AND a.jour=c.jour " << "INNER JOIN " << _database << ".HORAIRE h ON h.arretchn=c.ref AND h.jour=a.jour " << "INNER JOIN " << _database << ".COURSE o ON o.chainage=c.chainage AND o.ref=h.course AND c.jour=o.jour " << "WHERE h.course='" << serviceRef << "' AND h.jour=" << todayStr << " ORDER BY c.pos"; DBResultSPtr chainageResult(db->execQuery(chainageQuery.str())); JourneyPattern::StopsWithDepartureArrivalAuthorization servedStops; SchedulesBasedService::Schedules departureSchedules; SchedulesBasedService::Schedules arrivalSchedules; while(chainageResult->next()) { string type(chainageResult->getText("type")); string stopCode(chainageResult->getText("mnemol")); time_duration departureTime(duration_from_string(chainageResult->getText("htd"))); time_duration arrivalTime(duration_from_string(chainageResult->getText("hta"))); MetricOffset stopPos(chainageResult->getInt("pos")); bool referenceStop(type != "N"); std::set<StopPoint*> stopsSet( _getStopPoints( stops, _stopCodePrefix + stopCode, boost::optional<const std::string&>() ) ); if(stopsSet.empty()) { _logWarning( "Can't find stops for code "+ _stopCodePrefix + stopCode ); continue; } servedStops.push_back( JourneyPattern::StopWithDepartureArrivalAuthorization( stopsSet, stopPos, (type != "A"), (type != "D"), referenceStop ) ); // Ignoring interpolated times if(referenceStop) { // If the bus leaves after midnight, the hours are stored as 0 instead of 24 if( !departureSchedules.empty() && departureTime < *departureSchedules.rbegin()) { departureTime += hours(24); } if( !arrivalSchedules.empty() && arrivalTime < *arrivalSchedules.rbegin()) { arrivalTime += hours(24); } // round of the seconds departureTime -= seconds(departureTime.seconds()); if(arrivalTime.seconds()) { arrivalTime += seconds(60 - arrivalTime.seconds()); } // storage of the times departureSchedules.push_back(departureTime); arrivalSchedules.push_back(arrivalTime); } } set<JourneyPattern*> routes( _getRoutes( *line, servedStops, *_plannedDataSource ) ); if(routes.empty()) { stringstream routeQuery; routeQuery << "SELECT * FROM " << _database << ".CHAINAGE c " << "WHERE c.ref='" << chainage << "' AND c.jour=" << todayStr; DBResultSPtr routeResult(db->execQuery(routeQuery.str())); if(routeResult->next()) { string routeName(routeResult->getText("nom")); bool wayBack(routeResult->getText("sens") != "A"); _logCreation( "Creation of route "+ routeName ); JourneyPattern* result = new JourneyPattern( JourneyPatternTableSync::getId() ); result->setCommercialLine(line); line->addPath(result); result->setName(routeName); result->setWayBack(wayBack); result->addCodeBySource(*_plannedDataSource, string()); _env.getEditableRegistry<JourneyPattern>().add(boost::shared_ptr<JourneyPattern>(result)); routes.insert(result); size_t rank(0); BOOST_FOREACH(const JourneyPattern::StopWithDepartureArrivalAuthorization stop, servedStops) { boost::shared_ptr<LineStop> ls( new LineStop( LineStopTableSync::getId(), result, rank, rank+1 < servedStops.size() && stop._departure, rank > 0 && stop._arrival, *stop._metricOffset, **stop._stop.begin() ) ); ls->set<ScheduleInput>(stop._withTimes ? *stop._withTimes : true); ls->link(_env, true); _env.getEditableRegistry<LineStop>().add(ls); ++rank; } } } assert(!routes.empty()); ScheduledService* service(NULL); BOOST_FOREACH(JourneyPattern* route, routes) { boost::shared_lock<util::shared_recursive_mutex> sharedServicesLock( *route->sharedServicesMutex ); BOOST_FOREACH(Service* sservice, route->getAllServices()) { service = dynamic_cast<ScheduledService*>(sservice); if(!service) { continue; } if( service->isActive(today) && service->comparePlannedSchedules(departureSchedules, arrivalSchedules) ){ _logLoad( "Use of service "+ lexical_cast<string>(service->getKey()) +" ("+ lexical_cast<string>(departureSchedules[0]) +") on route "+ lexical_cast<string>(route->getKey()) +" ("+ route->getName() +")" ); service->addCodeBySource(dataSource, serviceRef); _services.insert(service); break; } service = NULL; } if(service) { break; } } if(!service) { if (!departureSchedules.empty() && !arrivalSchedules.empty()) { JourneyPattern* route(*routes.begin()); service = new ScheduledService( ScheduledServiceTableSync::getId(), string(), route ); service->setDataSchedules(departureSchedules, arrivalSchedules); service->setPath(route); service->addCodeBySource(dataSource, serviceRef); service->setActive(today); route->addService(*service, false); _env.getEditableRegistry<ScheduledService>().add(boost::shared_ptr<ScheduledService>(service)); _services.insert(service); _logCreation( "Creation of service ("+ lexical_cast<string>(departureSchedules[0]) +") on route "+ lexical_cast<string>(route->getKey()) +" ("+ route->getName() +")" ); } else { _logWarning( "Service (ref="+ serviceRef +") has empty departure or arrival schedules, not creating" ); } } } // 3 : loop on the planned services and remove current day of run if not linked to current source BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::value_type& itLine, lines.getMap()) { BOOST_FOREACH(const ImportableTableSync::ObjectBySource<CommercialLineTableSync>::Map::mapped_type::value_type& obj, itLine.second) { BOOST_FOREACH(Path* route, obj->getPaths()) { // Avoid junctions if(!dynamic_cast<JourneyPattern*>(route)) { continue; } JourneyPattern* jp(static_cast<JourneyPattern*>(route)); if(!jp->hasLinkWithSource(*_plannedDataSource)) { continue; } boost::shared_lock<util::shared_recursive_mutex> sharedServicesLock( *jp->sharedServicesMutex ); BOOST_FOREACH(const Service* service, jp->getAllServices()) { const ScheduledService* sservice(dynamic_cast<const ScheduledService*>(service)); if( sservice && sservice->isActive(today) && !sservice->hasLinkWithSource(dataSource) ){ const_cast<ScheduledService*>(sservice)->setInactive(today); _logInfo( "Deactivating unlinked service "+ lexical_cast<string>(sservice->getKey()) + " on route "+ lexical_cast<string>(sservice->getRoute()->getKey()) +" (" + sservice->getRoute()->getName() +")" ); } } } } } return true; } IneoRealTimeFileFormat::Importer_::Importer_( util::Env& env, const impex::Import& import, impex::ImportLogLevel minLogLevel, const std::string& logPath, boost::optional<std::ostream&> outputStream, util::ParametersMap& pm ): Importer(env, import, minLogLevel, logPath, outputStream, pm), DatabaseReadImporter<IneoRealTimeFileFormat>(env, import, minLogLevel, logPath, outputStream, pm), PTFileFormat(env, import, minLogLevel, logPath, outputStream, pm) {} util::ParametersMap IneoRealTimeFileFormat::Importer_::_getParametersMap() const { ParametersMap map; if(_plannedDataSource.get()) { map.insert(PARAMETER_PLANNED_DATASOURCE_ID, _plannedDataSource->getKey()); } if(_courseId) { map.insert(PARAMETER_COURSE_ID, *_courseId); } if(_dbConnString) { map.insert(PARAMETER_DB_CONN_STRING, *_dbConnString); } if(!_stopCodePrefix.empty()) { map.insert(PARAMETER_STOP_CODE_PREFIX, _stopCodePrefix); } return map; } void IneoRealTimeFileFormat::Importer_::_setFromParametersMap( const util::ParametersMap& map ) { if(map.isDefined(PARAMETER_PLANNED_DATASOURCE_ID)) try { _plannedDataSource = DataSourceTableSync::Get(map.get<RegistryKeyType>(PARAMETER_PLANNED_DATASOURCE_ID), _env); } catch(ObjectNotFoundException<DataSource>&) { throw Exception("No such planned data source"); } _courseId = map.getOptional<string>(PARAMETER_COURSE_ID); _dbConnString = map.getOptional<string>(PARAMETER_DB_CONN_STRING); _stopCodePrefix = map.getDefault<string>(PARAMETER_STOP_CODE_PREFIX, ""); } db::DBTransaction IneoRealTimeFileFormat::Importer_::_save() const { DBTransaction transaction; if(_courseId) { BOOST_FOREACH(ScheduledService* service, _services) { JourneyPatternTableSync::Save(static_cast<JourneyPattern*>(service->getPath()), transaction); BOOST_FOREACH(LineStop* edge, static_cast<JourneyPattern*>(service->getPath())->getLineStops()) { LineStopTableSync::Save(edge, transaction); } ScheduledServiceTableSync::Save(service, transaction); } } else { BOOST_FOREACH(const Registry<JourneyPattern>::value_type& journeyPattern, _env.getRegistry<JourneyPattern>()) { JourneyPatternTableSync::Save(journeyPattern.second.get(), transaction); } BOOST_FOREACH(Registry<LineStop>::value_type lineStop, _env.getRegistry<LineStop>()) { LineStopTableSync::Save(lineStop.second.get(), transaction); } BOOST_FOREACH(const Registry<ScheduledService>::value_type& service, _env.getRegistry<ScheduledService>()) { ScheduledServiceTableSync::Save(service.second.get(), transaction); } } return transaction; } } }
Java
/*************************************************************************** orbitalviewerbase.h - description ------------------- begin : Thu Nov 4 2004 copyright : (C) 2004-2006 by Ben Swerts email : bswerts@users.sourceforge.net ***************************************************************************/ /*************************************************************************** * * * 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. * * * ***************************************************************************/ /// \file /// Contains the declaration of the class OrbitalViewerBase #ifndef ORBITALVIEWERBASE_H #define ORBITALVIEWERBASE_H ///// Forward class declarations & header files /////////////////////////////// ///// Qt forward class declarations class QHBoxLayout; class QTimer; ///// Xbrabo forward class declarations class ColorButton; class GLOrbitalView; class OrbitalOptionsWidget; class OrbitalThread; ///// Base class header file #include <qdialog.h> ///// class OrbitalViewerBase ///////////////////////////////////////////////// class OrbitalViewerBase : public QDialog { Q_OBJECT public: // constructor/destructor OrbitalViewerBase(QWidget* parent = 0, const char* name = 0, bool modal = FALSE, WFlags fl = 0);// constructor ~OrbitalViewerBase(); // destructor protected: void customEvent(QCustomEvent* e); // reimplemented to receive events from calcThread private slots: void update(); // updates the view with the values of the widgets void adjustL(int newN); // adjust the orbital quantum number to the region 1 - n-1 void adjustM(int newL); // adjust the angular momentum quantum number to the region -l - +l void updateColors(); // updates the view with new colors void updateTypeOptions(int type); // updates the options to correspond to the chosen type void cancelCalculation(); // stops calculating a new orbital private: // private member functions void finishCalculation(); // finished up a calculation // private member variables QHBoxLayout* BigLayout; ///< All encompassing horizontal layout. OrbitalOptionsWidget* options; ///< Shows the options. GLOrbitalView* view; ///< Shows the orbital. ColorButton* ColorButtonPositive; ///< The pushbutton for choosing the colour of the positive values. ColorButton* ColorButtonNegative; ///< The pushbutton for choosing the colour of the negative values. OrbitalThread* calcThread; ///< The thread doing the calculation. QTimer* timer; ///< Handles periodic updating of the view during a calculation. }; #endif
Java
// ================================================================================================= // ADOBE SYSTEMS INCORPORATED // Copyright 2011 Adobe Systems Incorporated // All Rights Reserved // // NOTICE: Adobe permits you to use, modify, and distribute this file in accordance with the terms // of the Adobe license agreement accompanying it. // ================================================================================================= #include "Module.h" #include "HostAPI.h" namespace XMP_PLUGIN { static bool CheckAPICompatibility_V1 ( const PluginAPIRef pluginAPIs ) { // these plugin APIs are mandatory to run an XMP file handler if ( pluginAPIs->mTerminatePluginProc && pluginAPIs->mSetHostAPIProc && pluginAPIs->mInitializeSessionProc && pluginAPIs->mTerminateSessionProc && pluginAPIs->mCheckFileFormatProc && pluginAPIs->mCheckFolderFormatProc && pluginAPIs->mGetFileModDateProc && pluginAPIs->mCacheFileDataProc && pluginAPIs->mUpdateFileProc && pluginAPIs->mWriteTempFileProc ) { return true; } return false; } static bool CheckAPICompatibility_V2 ( const PluginAPIRef pluginAPIs ) { if ( CheckAPICompatibility_V1 ( pluginAPIs ) ) { if ( pluginAPIs->mFillMetadataFilesProc && pluginAPIs->mFillAssociatedResourcesProc ) { return true; } } return false; } static bool CheckAPICompatibility_V3 ( const PluginAPIRef pluginAPIs ) { if ( CheckAPICompatibility_V2 ( pluginAPIs ) ) { if ( pluginAPIs->mIsMetadataWritableProc ) { return true; } } return false; } static bool CheckAPICompatibility ( const PluginAPIRef pluginAPIs ) { // Note: This is the place where we can reject old plugins. // For example if we consider all functionality of // plugin API version 2 mandatory we can reject // plugin version 1 by returning false in case 1. switch ( pluginAPIs->mVersion ) { case 1: return CheckAPICompatibility_V1 ( pluginAPIs ); break; case 2: return CheckAPICompatibility_V2 ( pluginAPIs ); break; case 3: return CheckAPICompatibility_V3 ( pluginAPIs ); break; default: // The loaded plugin is newer than the host. // Only basic functionality to run the plugin is required. return CheckAPICompatibility_V1 ( pluginAPIs ); break; } } PluginAPIRef Module::getPluginAPIs() { // // return ref. to Plugin API, load module if not yet loaded // if ( !mPluginAPIs || mLoaded != kModuleLoaded ) { if ( !load() ) { XMP_Throw ( "Plugin API not available.", kXMPErr_Unavailable ); } } return mPluginAPIs; } bool Module::load() { XMP_AutoLock lock ( &mLoadingLock, kXMP_WriteLock ); return loadInternal(); } void Module::unload() { XMP_AutoLock lock (&mLoadingLock, kXMP_WriteLock); unloadInternal(); } void Module::unloadInternal() { WXMP_Error error; // // terminate plugin // if( mPluginAPIs != NULL ) { if( mPluginAPIs->mTerminatePluginProc ) { mPluginAPIs->mTerminatePluginProc( &error ); } delete mPluginAPIs; mPluginAPIs = NULL; } // // unload plugin module // if( mLoaded != kModuleNotLoaded ) { UnloadModule(mHandle, false); mHandle = NULL; if( mLoaded == kModuleLoaded ) { // // Reset mLoaded to kModuleNotLoaded, if the module was loaded successfully. // Otherwise let it remain kModuleErrorOnLoad so that we won't try to load // it again if some other handler ask to do so. // mLoaded = kModuleNotLoaded; } } CheckError( error ); } bool Module::loadInternal() { if( mLoaded == kModuleNotLoaded ) { const char * errorMsg = NULL; // // load module // mLoaded = kModuleErrorOnLoad; mHandle = LoadModule(mPath, false); if( mHandle != NULL ) { // // get entry point function pointer // InitializePluginProc InitializePlugin = reinterpret_cast<InitializePluginProc>( GetFunctionPointerFromModuleImpl(mHandle, "InitializePlugin") ); // legacy entry point InitializePlugin2Proc InitializePlugin2 = reinterpret_cast<InitializePlugin2Proc>( GetFunctionPointerFromModuleImpl(mHandle, "InitializePlugin2") ); if( InitializePlugin2 != NULL || InitializePlugin != NULL ) { std::string moduleID; GetResourceDataFromModule(mHandle, "MODULE_IDENTIFIER", "txt", moduleID); mPluginAPIs = new PluginAPI(); memset( mPluginAPIs, 0, sizeof(PluginAPI) ); mPluginAPIs->mSize = sizeof(PluginAPI); mPluginAPIs->mVersion = XMP_PLUGIN_VERSION; // informational: the latest version that the host knows about WXMP_Error error; // // initialize plugin by calling entry point function // if( InitializePlugin2 != NULL ) { HostAPIRef hostAPI = PluginManager::getHostAPI( XMP_HOST_API_VERSION ); InitializePlugin2( moduleID.c_str(), hostAPI, mPluginAPIs, &error ); if ( error.mErrorID == kXMPErr_NoError ) { // check all function pointers are correct based on version numbers if( CheckAPICompatibility( mPluginAPIs ) ) { mLoaded = kModuleLoaded; } else { errorMsg = "Incompatible plugin API version."; } } else { errorMsg = "Plugin initialization failed."; } } else if( InitializePlugin != NULL ) { // initialize through legacy plugin entry point InitializePlugin( moduleID.c_str(), mPluginAPIs, &error ); if ( error.mErrorID == kXMPErr_NoError ) { // check all function pointers are correct based on version numbers bool compatibleAPIs = CheckAPICompatibility(mPluginAPIs); if ( compatibleAPIs ) { // // set host API at plugin // HostAPIRef hostAPI = PluginManager::getHostAPI( mPluginAPIs->mVersion ); mPluginAPIs->mSetHostAPIProc( hostAPI, &error ); if( error.mErrorID == kXMPErr_NoError ) { mLoaded = kModuleLoaded; } else { errorMsg = "Plugin API incomplete."; } } else { errorMsg = "Incompatible plugin API version."; } } else { errorMsg = "Plugin initialization failed."; } } } if( mLoaded != kModuleLoaded ) { // // plugin wasn't loaded and initialized successfully, // so unload the module // this->unloadInternal(); } } else { errorMsg = "Can't load module"; } if ( mLoaded != kModuleLoaded && errorMsg ) { // // error occurred // throw XMP_Error( kXMPErr_InternalFailure, errorMsg); } } return ( mLoaded == kModuleLoaded ); } } //namespace XMP_PLUGIN
Java
package storm.starter.trident.homework.state; import storm.trident.operation.TridentCollector; import storm.trident.state.BaseStateUpdater; import storm.trident.tuple.TridentTuple; import java.util.ArrayList; import java.util.List; /** * Updater class that updates the state with the new tweets. * Created by Parth Satra on 4/5/15. */ public class TopKStateUpdater extends BaseStateUpdater<TopKState> { @Override public void updateState(TopKState topKState, List<TridentTuple> list, TridentCollector tridentCollector) { for(TridentTuple tuple : list) { // Gets all the space separated hashtags. String hashTags = tuple.getString(0); String[] tag = hashTags.split(" "); // Creates the list to be added to the state List<TopTweet> tweetList = new ArrayList<TopTweet>(); for(String t : tag) { if(t != null && t.trim().length() != 0) { TopTweet tt = new TopTweet(t, 1); tweetList.add(tt); } } // Adds the list to the state. topKState.add(tweetList); } } }
Java
</div> <footer> <p>copyright <a href="mailto:pengmaradi@gmail.com">@Xiaoling Peng</a> <a href="0763363847">call me</a></p> </footer> </body> </html>
Java
@charset "utf-8"; #smenu_srch .iText, #smenu_srch button { background-color: #002a00; } #login_btn svg.active, #login_window .idpwWrap .login, #sider_nav h3 a, #sider_nav ul.smenu_3rdlevel { background-color: #005500; } #sider_nav ul.smenu_3rdlevel li a { border-bottom: 3px solid #005500; } #sider_nav, #login_window .idpw input[type=text], #login_window .idpw input[type=password] { background-color: #007f00; } #sider_nav ul.smenu_2ndlevel li a { border-bottom: 4px solid #007f00; } a:link, a:visited { color: #00aa00; } #topheader, .dialog_tline { background-color: #00aa00; } #header_nav ul li a { border-bottom: 5px solid #00aa00; } a:active, a:hover { /* 흰 바탕에 보이지 않는 #55ff55 색을 다른 색으로 대체 */ color: #55d455; } #header_nav ul li.active a { border-bottom: 5px solid #55ff55; } #sider_nav ul.smenu_2ndlevel li.active a { border-bottom: 4px solid #55ff55; } #sider_nav ul.smenu_3rdlevel li.active a { border-bottom: 3px solid #55ff55; } #topheader a:active, #topheader a:hover, #sider_nav a:active, #sider_nav a:hover, #login_window .idpwWrap .login:active, #login_window .idpwWrap .login:hover { color: #aaffaa; } #smenu_srch button:active svg .stro, #smenu_srch button:hover svg .stro, #login_close:active svg .stro, #login_close:hover svg .stro, #login_btn svg.active .stro { stroke: #aaffaa; } #login_btn svg.active .poly { fill: #aaffaa; }
Java
<!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"> <head> <meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/> <title>ctas: /home/antonmx/work/projects/ctascmake/image/ Directory Reference</title> <link href="tabs.css" rel="stylesheet" type="text/css"/> <link href="doxygen.css" rel="stylesheet" type="text/css"/> </head> <body> <!-- Generated by Doxygen 1.7.3 --> <script type="text/javascript"> function hasClass(ele,cls) { return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')); } function addClass(ele,cls) { if (!this.hasClass(ele,cls)) ele.className += " "+cls; } function removeClass(ele,cls) { if (hasClass(ele,cls)) { var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)'); ele.className=ele.className.replace(reg,' '); } } function toggleVisibility(linkObj) { var base = linkObj.getAttribute('id'); var summary = document.getElementById(base + '-summary'); var content = document.getElementById(base + '-content'); var trigger = document.getElementById(base + '-trigger'); if ( hasClass(linkObj,'closed') ) { summary.style.display = 'none'; content.style.display = 'block'; trigger.src = 'open.png'; removeClass(linkObj,'closed'); addClass(linkObj,'opened'); } else if ( hasClass(linkObj,'opened') ) { summary.style.display = 'block'; content.style.display = 'none'; trigger.src = 'closed.png'; removeClass(linkObj,'opened'); addClass(linkObj,'closed'); } return false; } </script> <div id="top"> <div id="titlearea"> <table cellspacing="0" cellpadding="0"> <tbody> <tr style="height: 56px;"> <td style="padding-left: 0.5em;"> <div id="projectname">ctas&#160;<span id="projectnumber">0.5.2</span></div> </td> </tr> </tbody> </table> </div> <div id="navrow1" class="tabs"> <ul class="tablist"> <li><a href="index.html"><span>Main&#160;Page</span></a></li> <li><a href="pages.html"><span>Related&#160;Pages</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li><a href="files.html"><span>Files</span></a></li> <li><a href="dirs.html"><span>Directories</span></a></li> </ul> </div> <div id="nav-path" class="navpath"> <ul> <li class="navelem"><a class="el" href="dir_ce34702ad4994bea558d8c4eb1fcec0d.html">image</a> </li> </ul> </div> </div> <div class="header"> <div class="headertitle"> <h1>image Directory Reference</h1> </div> </div> <div class="contents"> <table class="memberdecls"> <tr><td colspan="2"><h2><a name="subdirs"></a> Directories</h2></td></tr> <tr><td class="memItemLeft" align="right" valign="top">directory &#160;</td><td class="memItemRight" valign="bottom"><a class="el" href="dir_3ffc36e2e7d775ce6be9331a5d16efc1.html">bin</a></td></tr> </table> </div> <hr class="footer"/><address class="footer"><small>Generated on Fri Apr 8 2011 16:06:01 for ctas by&#160; <a href="http://www.doxygen.org/index.html"> <img class="footer" src="doxygen.png" alt="doxygen"/></a> 1.7.3 </small></address> </body> </html>
Java
<?php /** * @package gantry * @subpackage core.params * @version 3.2.11 September 8, 2011 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2011 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('GANTRY_VERSION') or die(); gantry_import('core.params.gantryparamoverride'); /** * @package gantry * @subpackage core.params */ class GantrySessionParamOverride extends GantryParamOverride { function store(){ global $gantry; foreach($gantry->_setinsession as $session_var){ if ($gantry->_working_params[$session_var]['setby'] != 'menuitem') { if ($gantry->_working_params[$session_var]['value'] != $gantry->_working_params[$session_var]['sitebase'] && $gantry->_working_params[$session_var]['type'] != 'preset'){ $gantry->session->set($gantry->template_prefix.$gantry->_base_params_checksum."-".$session_var,$gantry->_working_params[$session_var]['value']); } else { $gantry->session->set($gantry->template_prefix.$this->_base_params_checksum."-".$session_var,null); } } } } function clean(){ global $gantry; foreach($gantry->_setinsession as $session_var){ $gantry->session->set($gantry->template_prefix.$this->_base_params_checksum."-".$session_var,null); } } function populate(){ global $gantry; // get any session param overrides and set to that // set preset values foreach($gantry->_preset_names as $param_name) { $session_param_name = $gantry->template_prefix.$gantry->_base_params_checksum."-".$param_name; if (in_array($param_name, $gantry->_setbysession) && $gantry->session->get($session_param_name)) { $param =& $gantry->_working_params[$param_name]; $session_value = $gantry->session->get($session_param_name); $session_preset_params = $gantry->presets[$param_name][$session_value]; foreach($session_preset_params as $session_preset_param_name => $session_preset_param_value) { if (array_key_exists($session_preset_param_name, $gantry->_working_params) && !is_null($session_preset_param_value)){ $gantry->_working_params[$session_preset_param_name]['value'] = $session_preset_param_value; $gantry->_working_params[$session_preset_param_name]['setby'] = 'session'; } } } } // set individual values foreach($gantry->_param_names as $param_name) { $session_param_name = $gantry->template_prefix.$gantry->_base_params_checksum."-".$param_name; if (in_array($param_name, $gantry->_setbysession) && $gantry->session->get($session_param_name)) { $param =& $gantry->_working_params[$param_name]; $session_value = $gantry->session->get($session_param_name); if (!is_null($session_value)){ $gantry->_working_params[$param['name']]['value'] = $session_value; $gantry->_working_params[$param['name']]['setby'] = 'session'; } } } } }
Java
<?php /** * Shows basic event infos and countdowns. * * @param array $event_config The event configuration * @return string */ function EventConfig_countdown_page($event_config) { if ($event_config == null) { return div('col-md-12 text-center', [ heading(sprintf(_('Welcome to the %s!'), '<span class="icon-icon_angel"></span> HELFERSYSTEM'), 2) ]); } $elements = []; if ($event_config['event_name'] != null) { $elements[] = div('col-sm-12 text-center', [ heading(sprintf( _('Welcome to the %s!'), $event_config['event_name'] . ' <span class="icon-icon_angel"></span> HELFERSYSTEM' ), 2) ]); } if ($event_config['buildup_start_date'] != null && time() < $event_config['buildup_start_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Buildup starts'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['buildup_start_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['buildup_start_date']) . '</small>' ]); } if ($event_config['event_start_date'] != null && time() < $event_config['event_start_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Event starts'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['event_start_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['event_start_date']) . '</small>' ]); } if ($event_config['event_end_date'] != null && time() < $event_config['event_end_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Event ends'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['event_end_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['event_end_date']) . '</small>' ]); } if ($event_config['teardown_end_date'] != null && time() < $event_config['teardown_end_date']) { $elements[] = div('col-sm-3 text-center hidden-xs', [ heading(_('Teardown ends'), 4), '<span class="moment-countdown text-big" data-timestamp="' . $event_config['teardown_end_date'] . '">%c</span>', '<small>' . date(_('Y-m-d'), $event_config['teardown_end_date']) . '</small>' ]); } return join('', $elements); } /** * Converts event name and start+end date into a line of text. * * @param array $event_config * @return string */ function EventConfig_info($event_config) { if ($event_config == null) { return ''; } // Event name, start+end date are set if ( $event_config['event_name'] != null && $event_config['event_start_date'] != null && $event_config['event_end_date'] != null ) { return sprintf( _('%s, from %s to %s'), $event_config['event_name'], date(_('Y-m-d'), $event_config['event_start_date']), date(_('Y-m-d'), $event_config['event_end_date']) ); } // Event name, start date are set if ($event_config['event_name'] != null && $event_config['event_start_date'] != null) { return sprintf( _('%s, starting %s'), $event_config['event_name'], date(_('Y-m-d'), $event_config['event_start_date']) ); } // Event start+end date are set if ($event_config['event_start_date'] != null && $event_config['event_end_date'] != null) { return sprintf( _('Event from %s to %s'), date(_('Y-m-d'), $event_config['event_start_date']), date(_('Y-m-d'), $event_config['event_end_date']) ); } // Only event name is set if ($event_config['event_name'] != null) { return sprintf($event_config['event_name']); } return ''; } /** * Render edit page for event config. * * @param string $event_name The event name * @param string $event_welcome_msg The welcome message * @param int $buildup_start_date unix time stamp * @param int $event_start_date unix time stamp * @param int $event_end_date unix time stamp * @param int $teardown_end_date unix time stamp * @return string */ function EventConfig_edit_view( $event_name, $event_welcome_msg, $buildup_start_date, $event_start_date, $event_end_date, $teardown_end_date ) { return page_with_title(event_config_title(), [ msg(), form([ div('row', [ div('col-md-6', [ form_text('event_name', _('Event Name'), $event_name), form_info('', _('Event Name is shown on the start page.')), form_textarea('event_welcome_msg', _('Event Welcome Message'), $event_welcome_msg), form_info( '', _('Welcome message is shown after successful registration. You can use markdown.') ) ]), div('col-md-3 col-xs-6', [ form_date('buildup_start_date', _('Buildup date'), $buildup_start_date), form_date('event_start_date', _('Event start date'), $event_start_date) ]), div('col-md-3 col-xs-6', [ form_date('teardown_end_date', _('Teardown end date'), $teardown_end_date), form_date('event_end_date', _('Event end date'), $event_end_date) ]) ]), div('row', [ div('col-md-6', [ form_submit('submit', _('Save')) ]) ]) ]) ]); }
Java
"""Module computes indentation for block It contains implementation of indenters, which are supported by katepart xml files """ import logging logger = logging.getLogger('qutepart') from PyQt4.QtGui import QTextCursor def _getSmartIndenter(indenterName, qpart, indenter): """Get indenter by name. Available indenters are none, normal, cstyle, haskell, lilypond, lisp, python, ruby, xml Indenter name is not case sensitive Raise KeyError if not found indentText is indentation, which shall be used. i.e. '\t' for tabs, ' ' for 4 space symbols """ indenterName = indenterName.lower() if indenterName in ('haskell', 'lilypond'): # not supported yet logger.warning('Smart indentation for %s not supported yet. But you could be a hero who implemented it' % indenterName) from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'none' == indenterName: from qutepart.indenter.base import IndentAlgBase as indenterClass elif 'normal' == indenterName: from qutepart.indenter.base import IndentAlgNormal as indenterClass elif 'cstyle' == indenterName: from qutepart.indenter.cstyle import IndentAlgCStyle as indenterClass elif 'python' == indenterName: from qutepart.indenter.python import IndentAlgPython as indenterClass elif 'ruby' == indenterName: from qutepart.indenter.ruby import IndentAlgRuby as indenterClass elif 'xml' == indenterName: from qutepart.indenter.xmlindent import IndentAlgXml as indenterClass elif 'haskell' == indenterName: from qutepart.indenter.haskell import IndenterHaskell as indenterClass elif 'lilypond' == indenterName: from qutepart.indenter.lilypond import IndenterLilypond as indenterClass elif 'lisp' == indenterName: from qutepart.indenter.lisp import IndentAlgLisp as indenterClass elif 'scheme' == indenterName: from qutepart.indenter.scheme import IndentAlgScheme as indenterClass else: raise KeyError("Indenter %s not found" % indenterName) return indenterClass(qpart, indenter) class Indenter: """Qutepart functionality, related to indentation Public attributes: width Indent width useTabs Indent uses Tabs (instead of spaces) """ _DEFAULT_INDENT_WIDTH = 4 _DEFAULT_INDENT_USE_TABS = False def __init__(self, qpart): self._qpart = qpart self.width = self._DEFAULT_INDENT_WIDTH self.useTabs = self._DEFAULT_INDENT_USE_TABS self._smartIndenter = _getSmartIndenter('normal', self._qpart, self) def setSyntax(self, syntax): """Choose smart indentation algorithm according to syntax""" self._smartIndenter = self._chooseSmartIndenter(syntax) def text(self): """Get indent text as \t or string of spaces """ if self.useTabs: return '\t' else: return ' ' * self.width def triggerCharacters(self): """Trigger characters for smart indentation""" return self._smartIndenter.TRIGGER_CHARACTERS def autoIndentBlock(self, block, char = '\n'): """Indent block after Enter pressed or trigger character typed """ cursor = QTextCursor(block) currentText = block.text() spaceAtStartLen = len(currentText) - len(currentText.lstrip()) currentIndent = currentText[:spaceAtStartLen] indent = self._smartIndenter.computeIndent(block, char) if indent is not None and indent != currentIndent: self._qpart.replaceText(block.position(), spaceAtStartLen, indent) def onChangeSelectedBlocksIndent(self, increase, withSpace=False): """Tab or Space pressed and few blocks are selected, or Shift+Tab pressed Insert or remove text from the beginning of blocks """ def blockIndentation(block): text = block.text() return text[:len(text) - len(text.lstrip())] def cursorAtSpaceEnd(block): cursor = QTextCursor(block) cursor.setPosition(block.position() + len(blockIndentation(block))) return cursor def indentBlock(block): cursor = cursorAtSpaceEnd(block) cursor.insertText(' ' if withSpace else self.text()) def spacesCount(text): return len(text) - len(text.rstrip(' ')) def unIndentBlock(block): currentIndent = blockIndentation(block) if currentIndent.endswith('\t'): charsToRemove = 1 elif withSpace: charsToRemove = 1 if currentIndent else 0 else: if self.useTabs: charsToRemove = min(spacesCount(currentIndent), self.width) else: # spaces if currentIndent.endswith(self.text()): # remove indent level charsToRemove = self.width else: # remove all spaces charsToRemove = min(spacesCount(currentIndent), self.width) if charsToRemove: cursor = cursorAtSpaceEnd(block) cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText() cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) # If end is positioned in the beginning of a block, do not indent this # block, since no text is selected in it (beginning of line) if endBlock.position()==cursor.selectionEnd(): endBlock=endBlock.previous() indentFunc = indentBlock if increase else unIndentBlock if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: indentFunc(block) block = block.next() newCursor = QTextCursor(startBlock) newCursor.setPosition(endBlock.position() + len(endBlock.text()), QTextCursor.KeepAnchor) self._qpart.setTextCursor(newCursor) else: # indent 1 line indentFunc(startBlock) def onShortcutIndentAfterCursor(self): """Tab pressed and no selection. Insert text after cursor """ cursor = self._qpart.textCursor() def insertIndent(): if self.useTabs: cursor.insertText('\t') else: # indent to integer count of indents from line start charsToInsert = self.width - (len(self._qpart.textBeforeCursor()) % self.width) cursor.insertText(' ' * charsToInsert) if cursor.positionInBlock() == 0: # if no any indent - indent smartly block = cursor.block() self.autoIndentBlock(block, '') # if no smart indentation - just insert one indent if self._qpart.textBeforeCursor() == '': insertIndent() else: insertIndent() def onShortcutUnindentWithBackspace(self): """Backspace pressed, unindent """ assert self._qpart.textBeforeCursor().endswith(self.text()) charsToRemove = len(self._qpart.textBeforeCursor()) % len(self.text()) if charsToRemove == 0: charsToRemove = len(self.text()) cursor = self._qpart.textCursor() cursor.setPosition(cursor.position() - charsToRemove, QTextCursor.KeepAnchor) cursor.removeSelectedText() def onAutoIndentTriggered(self): """Indent current line or selected lines """ cursor = self._qpart.textCursor() startBlock = self._qpart.document().findBlock(cursor.selectionStart()) endBlock = self._qpart.document().findBlock(cursor.selectionEnd()) if startBlock != endBlock: # indent multiply lines stopBlock = endBlock.next() block = startBlock with self._qpart: while block != stopBlock: self.autoIndentBlock(block, '') block = block.next() else: # indent 1 line self.autoIndentBlock(startBlock, '') def _chooseSmartIndenter(self, syntax): """Get indenter for syntax """ if syntax.indenter is not None: try: return _getSmartIndenter(syntax.indenter, self._qpart, self) except KeyError: logger.error("Indenter '%s' is not finished yet. But you can do it!" % syntax.indenter) try: return _getSmartIndenter(syntax.name, self._qpart, self) except KeyError: pass return _getSmartIndenter('normal', self._qpart, self)
Java
<?php # Database Configuration define( 'DB_NAME', 'wp_promedia' ); define( 'DB_USER', 'promedia' ); define( 'DB_PASSWORD', 'Hgcjr1nz4UG6M7kD4a2W' ); define( 'DB_HOST', '127.0.0.1' ); define( 'DB_HOST_SLAVE', '127.0.0.1' ); define('DB_CHARSET', 'utf8'); define('DB_COLLATE', 'utf8_unicode_ci'); $table_prefix = 'wp_'; # Security Salts, Keys, Etc define('AUTH_KEY', 'a`F4guyG[^ Y}d c{idj5&MhTD&|JP[[]~@3:[oUZ0C+8}dUu9hqiW9ZJ-5c}6+|'); define('SECURE_AUTH_KEY', 'eU7MN1?7~|AT,pN|!qQ$3BhT%iYHi~}Uf%`R_eH#$I_XJy3utwjOa}-`Z8rP;eZ;'); define('LOGGED_IN_KEY', 'szAvG,^<>/so:#:-(6RKz~caq+*)lRek+o{44r$2?}?Qd.)taRY0+rd+d<6|nb>s'); define('NONCE_KEY', '0Sd#vgoYj|3 _{zHx+O!@bT*l13wu1=N+fNV]P7Cx|JzL_&=_5Kjs$y^P7?IEss+'); define('AUTH_SALT', 'vrQ2560/7/rdC)gXpr+&2;`w-RD%VyZwu+a5sV)!X<5s_Wq,7}S*7Q~vR|K(Lf*B'); define('SECURE_AUTH_SALT', 'wV^Lf;y6[zqv4!Bm8eZuE!u]k||b!mF]vAx|/)5,aQP`,Mav3SFC;2g`gL4*0F{R'); define('LOGGED_IN_SALT', '?|e&TXiXjP$H5#)*!6I+2]^w#?iL? G3H%pG[MvLgr|kT8+0?w&4BTX+nWnp57f`'); define('NONCE_SALT', '4~7piruf+MjyI%%H(U>r|GPuZDtb#EbJ|@ISBwf+V5+nzEzGNv>ihd#?#wpa+~/|'); # Localized Language Stuff define( 'WP_CACHE', TRUE ); define( 'WP_AUTO_UPDATE_CORE', false ); define( 'PWP_NAME', 'promedia' ); define( 'FS_METHOD', 'direct' ); define( 'FS_CHMOD_DIR', 0775 ); define( 'FS_CHMOD_FILE', 0664 ); define( 'PWP_ROOT_DIR', '/nas/wp' ); define( 'WPE_APIKEY', 'dfdfa423dd9708ad4a65f5e571606be13b075046' ); define( 'WPE_FOOTER_HTML', "" ); define( 'WPE_CLUSTER_ID', '1986' ); define( 'WPE_CLUSTER_TYPE', 'pod' ); define( 'WPE_ISP', true ); define( 'WPE_BPOD', false ); define( 'WPE_RO_FILESYSTEM', false ); define( 'WPE_LARGEFS_BUCKET', 'largefs.wpengine' ); define( 'WPE_LBMASTER_IP', '212.71.255.152' ); define( 'WPE_CDN_DISABLE_ALLOWED', true ); define( 'DISALLOW_FILE_EDIT', FALSE ); define( 'DISALLOW_FILE_MODS', FALSE ); define( 'DISABLE_WP_CRON', false ); define( 'WPE_FORCE_SSL_LOGIN', false ); define( 'FORCE_SSL_LOGIN', false ); /*SSLSTART*/ if ( isset($_SERVER['HTTP_X_WPE_SSL']) && $_SERVER['HTTP_X_WPE_SSL'] ) $_SERVER['HTTPS'] = 'on'; /*SSLEND*/ define( 'WPE_EXTERNAL_URL', false ); define( 'WP_POST_REVISIONS', FALSE ); define( 'WPE_WHITELABEL', 'wpengine' ); define( 'WP_TURN_OFF_ADMIN_BAR', false ); define( 'WPE_BETA_TESTER', false ); umask(0002); $wpe_cdn_uris=array ( ); $wpe_no_cdn_uris=array ( ); $wpe_content_regexs=array ( ); $wpe_all_domains=array ( 0 => 'promedia.wpengine.com', ); $wpe_varnish_servers=array ( 0 => 'pod-1986', ); $wpe_special_ips=array ( 0 => '212.71.255.152', ); $wpe_ec_servers=array ( ); $wpe_largefs=array ( ); $wpe_netdna_domains=array ( ); $wpe_netdna_domains_secure=array ( ); $wpe_netdna_push_domains=array ( ); $wpe_domain_mappings=array ( ); $memcached_servers=array ( ); define( 'WPE_SFTP_PORT', 22 ); define('WPLANG',''); # WP Engine ID # WP Engine Settings # That's It. Pencils down if ( !defined('ABSPATH') ) define('ABSPATH', dirname(__FILE__) . '/'); require_once(ABSPATH . 'wp-settings.php'); $_wpe_preamble_path = null; if(false){}
Java
#ifndef _SS_CONSTS_HPP_ #define _SS_CONSTS_HPP_ #include "StrideSearchConfig.h" namespace StrideSearch { /// Meters per second to Kilometers per hour conversion factor static const Real MPS2KPH = 3.6; /// Knots to meters per second conversion factor static const Real KTS2MPS = 0.5144444; /// Nautical miles to kilometers conversion factor static const Real NM2KM = 1.852; /// Pi static constexpr Real PI = 3.1415926535897932384626433832795027975; /// Radians to degrees conversion factor static constexpr Real RAD2DEG = 180.0 / PI; /// Degrees to radians conversion factor static constexpr Real DEG2RAD = PI / 180.0; /// Hours to days conversion factor static constexpr Real HOURS2DAYS = 1.0/24.0; /// Minutes to days conversion factor static constexpr Real MINUTES2DAYS = 1.0/24.0/60.0; /// Gravitational acceleration static constexpr Real G = 9.80616; /// Mean sea level radius of the Earth (meters) static constexpr Real EARTH_RADIUS_KM = 6371.220; static constexpr Real SQ_EARTH_RADIUS_KM = EARTH_RADIUS_KM*EARTH_RADIUS_KM; /// One sidereal day, in units of seconds static constexpr Real SIDEREAL_DAY_SEC = 24.0 * 3600.0; /// Rotational rate of Earth about its z-axis static constexpr Real EARTH_OMEGA_HZ = 2.0 * PI / SIDEREAL_DAY_SEC; /// Floating point zero static constexpr Real ZERO_TOL = 1.0e-11; } #endif
Java
<?php /* $Id$ osCmax e-Commerce http://www.oscmax.com Copyright 2000 - 2011 osCmax Released under the GNU General Public License */ define('NAVBAR_TITLE', 'Cuénteselo a un amigo'); define('HEADING_TITLE', 'Háblele a un amigo sobre \'%s\''); define('FORM_TITLE_CUSTOMER_DETAILS', 'Sus datos'); define('FORM_TITLE_FRIEND_DETAILS', 'Los datos de sus amigo'); define('FORM_TITLE_FRIEND_MESSAGE', 'Su mensaje'); define('FORM_FIELD_CUSTOMER_NAME', 'Su nombre:'); define('FORM_FIELD_CUSTOMER_EMAIL', 'Su dirección e-mail:'); define('FORM_FIELD_FRIEND_NAME', 'Nombre de su amigo:'); define('FORM_FIELD_FRIEND_EMAIL', 'Dirección e-mail de su amigo:'); define('TEXT_EMAIL_SUCCESSFUL_SENT', 'Su e-mail acerca de <b>%s</b> ha sido correctamente enviado a <b>%s</b>.'); define('TEXT_EMAIL_SUBJECT', 'Tu amigo %s te ha recomendado este fantástico producto de %s'); define('TEXT_EMAIL_INTRO', '¡Hola %s!' . "\n\n" . 'Tu amigo, %s, cree que puedes estar interesado en %s de %s.'); define('TEXT_EMAIL_LINK', 'Para ver el producto pulsa en el siguiente enlace o bien copia y pega el enlace en tu navegador:' . "\n\n" . '%s'); // LINE ADDED: MOD - ARTICLE MANAGER define('TEXT_EMAIL_LINK_ARTICLE', 'Para ver la noticia pulsa en el siguiente enlace o bien copia y pega el enlace en tu navegador:' . "\n\n" . '%s'); define('TEXT_EMAIL_SIGNATURE', 'Saludos,' . "\n\n" . '%s'); define('ERROR_TO_NAME', 'Error: Debe rellenar el nombre de tu amigo.'); define('ERROR_TO_ADDRESS', 'Error: La dirección e-mail de su amigo debe ser una dirección válida.'); define('ERROR_FROM_NAME', 'Error: Debes rellenar su nombre.'); define('ERROR_FROM_ADDRESS', 'Error: Su dirección e-mail debe ser una dirección válida.'); ?>
Java
package eu.ttbox.geoping.ui.admob; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import android.view.View; import com.google.android.gms.ads.AdListener; import com.google.android.gms.ads.AdRequest; import com.google.android.gms.ads.AdView; import com.google.android.gms.ads.InterstitialAd; import eu.ttbox.geoping.BuildConfig; import eu.ttbox.geoping.R; import eu.ttbox.geoping.core.AppConstants; public class AdmobHelper { private static final String TAG = "AdmobHelper"; // =========================================================== // AdView : https://developers.google.com/mobile-ads-sdk/docs/admob/fundamentals // https://groups.google.com/forum/#!msg/google-admob-ads-sdk/8MCNsiVAc7A/pkRLcQ9zPtYJ // =========================================================== public static AdView bindAdMobView(Activity context) { // Admob final View admob = context.findViewById(R.id.admob); final AdView adView = (AdView) context.findViewById(R.id.adView); if (isAddBlocked(context)) { Log.d(TAG, "### is Add Blocked adsContainer : " + admob); if (admob != null) { admob.setVisibility(View.GONE); Log.d(TAG, "### is Add Blocked adsContainer ==> GONE"); } } else { // Container Log.d(TAG, "### is Add Not Blocked adsContainer : " + admob); if (admob != null) { admob.setVisibility(View.VISIBLE); Log.d(TAG, "### is Add Not Blocked adsContainer ==> VISIBLE"); } } // Request Ad if (adView != null) { // http://stackoverflow.com/questions/11790376/animated-mopub-admob-native-ads-overlayed-on-a-game-black-out-screen //adView.setLayerType(View.LAYER_TYPE_SOFTWARE, null); // Listener adView.setAdListener(new AdListener() { public void onAdOpened() { Log.d(TAG, "### AdListener onAdOpened AdView"); } public void onAdLoaded() { Log.d(TAG, "### AdListener onAdLoaded AdView"); } public void onAdFailedToLoad(int errorcode) { if (admob!=null) { Log.d(TAG, "### AdListener onAdFailedToLoad ==> HIDE adsContainer : " + admob); admob.setVisibility(View.GONE); } switch (errorcode) { case AdRequest.ERROR_CODE_INTERNAL_ERROR: Log.d(TAG, "### ########################################################################## ###"); Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_INTERNAL_ERROR ###"); Log.d(TAG, "### ########################################################################## ###"); break; case AdRequest.ERROR_CODE_INVALID_REQUEST: Log.d(TAG, "### ########################################################################### ###"); Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_INVALID_REQUEST ###"); Log.d(TAG, "### ########################################################################### ###"); break; case AdRequest.ERROR_CODE_NETWORK_ERROR: Log.d(TAG, "### ######################################################################### ###"); Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_NETWORK_ERROR ###"); Log.d(TAG, "### ######################################################################### ###"); break; case AdRequest.ERROR_CODE_NO_FILL: Log.d(TAG, "### ################################################################### ###"); Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = ERROR_CODE_NO_FILL ###"); Log.d(TAG, "### ################################################################### ###"); break; default: Log.d(TAG, "### ########################################################################### ###"); Log.d(TAG, "### AdListener onAdFailedToLoad AdView : errorcode = " + errorcode + " ###"); Log.d(TAG, "### ########################################################################### ###"); } } }); // adView.setAdUnitId(context.getString(R.string.admob_key)); // adView.setAdSize(AdSize.SMART_BANNER); AdRequest.Builder adRequestBuilder = new AdRequest.Builder(); if (BuildConfig.DEBUG) { adRequestBuilder .addTestDevice(AdRequest.DEVICE_ID_EMULATOR) .addTestDevice("149D6C776DC12F380715698A396A64C4"); } AdRequest adRequest = adRequestBuilder.build(); adView.loadAd(adRequest); Log.d(TAG, "### Load adRequest AdView"); } else { Log.e(TAG, "### Null AdView"); } return adView; } public static boolean isAddBlocked(Context context) { SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(context); boolean isAddBlocked = sharedPreferences != null ? sharedPreferences.getBoolean(AppConstants.PREFS_ADD_BLOCKED, false) : false; return isAddBlocked; } // =========================================================== // InterstitialAd // =========================================================== public static class AppAdListener extends AdListener { InterstitialAd interstitial; public AppAdListener() { } public AppAdListener(InterstitialAd interstitial) { this.interstitial = interstitial; } @Override public void onAdLoaded() { Log.i(TAG, "### AdListener : onAdLoaded"); super.onAdLoaded(); interstitial.show(); } } public static InterstitialAd displayInterstitialAd(Context context) { return displayInterstitialAd(context, new AppAdListener()); } public static InterstitialAd displayInterstitialAd(Context context, AppAdListener adListener) { final InterstitialAd interstitial = new InterstitialAd(context); interstitial.setAdUnitId(context.getString(R.string.admob_key)); // Add Listener adListener.interstitial = interstitial; interstitial.setAdListener(adListener); // Create ad request. AdRequest adRequest = new AdRequest.Builder().build(); // Begin loading your interstitial. interstitial.loadAd(adRequest); return interstitial; } }
Java
/* ** $Id: lgc.h,v 2.58 2012/09/11 12:53:08 roberto Exp $ ** Garbage Collector ** See Copyright Notice in lua.h */ #ifndef lgc_h #define lgc_h #include "lobject.h" #include "lstate.h" /* ** Collectable objects may have one of three colors: white, which ** means the object is not marked; gray, which means the ** object is marked, but its references may be not marked; and ** black, which means that the object and all its references are marked. ** The main invariant of the garbage collector, while marking objects, ** is that a black object can never point to a white one. Moreover, ** any gray object must be in a "gray list" (gray, grayagain, weak, ** allweak, ephemeron) so that it can be visited again before finishing ** the collection cycle. These lists have no meaning when the invariant ** is not being enforced (e.g., sweep phase). */ /* how much to allocate before next GC step */ #if !defined(GCSTEPSIZE) /* ~100 small strings */ #define GCSTEPSIZE (cast_int(100 * sizeof(TString))) #endif /* ** Possible states of the Garbage Collector */ #define GCSpropagate 0 #define GCSatomic 1 #define GCSsweepstring 2 #define GCSsweepudata 3 #define GCSsweep 4 #define GCSpause 5 #define issweepphase(g) \ (GCSsweepstring <= (g)->gcstate && (g)->gcstate <= GCSsweep) #define isgenerational(g) ((g)->gckind == KGC_GEN) /* ** macros to tell when main invariant (white objects cannot point to black ** ones) must be kept. During a non-generational collection, the sweep ** phase may break the invariant, as objects turned white may point to ** still-black objects. The invariant is restored when sweep ends and ** all objects are white again. During a generational collection, the ** invariant must be kept all times. */ #define keepinvariant(g) (isgenerational(g) || g->gcstate <= GCSatomic) /* ** Outside the collector, the state in generational mode is kept in ** 'propagate', so 'keepinvariant' is always true. */ #define keepinvariantout(g) \ check_exp(g->gcstate == GCSpropagate || !isgenerational(g), \ g->gcstate <= GCSatomic) /* ** some useful bit tricks */ #define resetbits(x,m) ((x) &= cast(lu_byte, ~(m))) #define setbits(x,m) ((x) |= (m)) #define testbits(x,m) ((x) & (m)) #define bitmask(b) (1<<(b)) #define bit2mask(b1,b2) (bitmask(b1) | bitmask(b2)) #define l_setbit(x,b) setbits(x, bitmask(b)) #define resetbit(x,b) resetbits(x, bitmask(b)) #define testbit(x,b) testbits(x, bitmask(b)) /* Layout for bit use in `marked' field: */ #define WHITE0BIT 0 /* object is white (type 0) */ #define WHITE1BIT 1 /* object is white (type 1) */ #define BLACKBIT 2 /* object is black */ #define FINALIZEDBIT 3 /* object has been separated for finalization */ #define SEPARATED 4 /* object is in 'finobj' list or in 'tobefnz' */ #define FIXEDBIT 5 /* object is fixed (should not be collected) */ #define OLDBIT 6 /* object is old (only in generational mode) */ /* bit 7 is currently used by tests (luaL_checkmemory) */ #define WHITEBITS bit2mask(WHITE0BIT, WHITE1BIT) #define iswhite(x) testbits((x)->gch.marked, WHITEBITS) #define isblack(x) testbit((x)->gch.marked, BLACKBIT) #define isgray(x) /* neither white nor black */ \ (!testbits((x)->gch.marked, WHITEBITS | bitmask(BLACKBIT))) #define isold(x) testbit((x)->gch.marked, OLDBIT) /* MOVE OLD rule: whenever an object is moved to the beginning of a GC list, its old bit must be cleared */ #define resetoldbit(o) resetbit((o)->gch.marked, OLDBIT) #define otherwhite(g) (g->currentwhite ^ WHITEBITS) #define isdeadm(ow,m) (!(((m) ^ WHITEBITS) & (ow))) #define isdead(g,v) isdeadm(otherwhite(g), (v)->gch.marked) #define changewhite(x) ((x)->gch.marked ^= WHITEBITS) #define gray2black(x) l_setbit((x)->gch.marked, BLACKBIT) #define valiswhite(x) (iscollectable(x) && iswhite(gcvalue(x))) #define luaC_white(g) cast(lu_byte, (g)->currentwhite & WHITEBITS) #define luaC_condGC(L,c) \ {if (G(L)->GCdebt > 0) {c;}; condchangemem(L);} #define luaC_checkGC(L) luaC_condGC(L, luaC_step(L);) #define luaC_barrier(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ luaC_barrier_(L,obj2gco(p),gcvalue(v)); } #define luaC_barrierback(L,p,v) { if (valiswhite(v) && isblack(obj2gco(p))) \ luaC_barrierback_(L,p); } #define luaC_objbarrier(L,p,o) \ { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) \ luaC_barrier_(L,obj2gco(p),obj2gco(o)); } #define luaC_objbarrierback(L,p,o) \ { if (iswhite(obj2gco(o)) && isblack(obj2gco(p))) luaC_barrierback_(L,p); } #define luaC_barrierproto(L,p,c) \ { if (isblack(obj2gco(p))) luaC_barrierproto_(L,p,c); } LUAI_FUNC void luaC_freeallobjects(lua_State *L); LUAI_FUNC void luaC_step(lua_State *L); LUAI_FUNC void luaC_forcestep(lua_State *L); LUAI_FUNC void luaC_runtilstate(lua_State *L, int statesmask); LUAI_FUNC void luaC_fullgc(lua_State *L, int isemergency); LUAI_FUNC GCObject *luaC_newobj(lua_State *L, int tt, size_t sz, GCObject **list, int offset); LUAI_FUNC void luaC_barrier_(lua_State *L, GCObject *o, GCObject *v); LUAI_FUNC void luaC_barrierback_(lua_State *L, GCObject *o); LUAI_FUNC void luaC_barrierproto_(lua_State *L, Proto *p, Closure *c); LUAI_FUNC void luaC_checkfinalizer(lua_State *L, GCObject *o, Table *mt); LUAI_FUNC void luaC_checkupvalcolor(global_State *g, UpVal *uv); LUAI_FUNC void luaC_changemode(lua_State *L, int mode); #endif
Java
package org.cohorte.utilities.security; /** * @author ogattaz * */ public class CXPassphraseBuilder { /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildB64(final IXPassphrase aPassphrase) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseB64(aPassphrase); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildB64(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseB64(aValue); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildB64OBFRDM(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseB64(new CXPassphraseOBF(new CXPassphraseRDM( aValue))); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildOBF(final IXPassphrase aPassphrase) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseOBF(aPassphrase); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildOBF(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseOBF(aValue); } /** * @param aPassphrase * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildRDM(final IXPassphrase aPassphrase) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseRDM(aPassphrase); } /** * @param aValue * @return * @throws InstantiationException * @throws CXPassphraseSchemeException */ public static IXPassphrase buildRDM(final String aValue) throws InstantiationException, CXPassphraseSchemeException { return new CXPassphraseRDM(aValue); } }
Java
'''Manual check (not a discoverable unit test) for the key import, to identify problems with gnupg, gpg, gpg1, gpg2 and so on''' import os import shutil from gnupg import GPG def setup_keyring(keyring_name): '''Setup the keyring''' keyring_path = os.path.join("test", "outputdata", keyring_name) # Delete the entire keyring shutil.rmtree(keyring_path, ignore_errors=True) os.makedirs(keyring_path) gpg = GPG(gnupghome=keyring_path, gpgbinary="gpg") for key_name in ["key1_private", "key1_public"]: with open(os.path.join("test", "inputdata", key_name + ".txt"), "r") as keyfile: key_str = "".join(keyfile.readlines()) import_result = gpg.import_keys(key_str) print("Import result:", type(import_result)) print(import_result.__dict__) if import_result.count == 1 and len(set(import_result.fingerprints)) == 1: print("Got one import result") return gpg CRYPTO = setup_keyring("keyringtest") if CRYPTO: print("Ready", CRYPTO) KEY_LIST = CRYPTO.list_keys(False) NUM_KEYS = len(KEY_LIST) if KEY_LIST else 0 print("Number of public keys:", NUM_KEYS) if NUM_KEYS < 1: print("ERROR: Number of keys should be 1, not", NUM_KEYS) KEY_LIST = CRYPTO.list_keys(True) NUM_KEYS = len(KEY_LIST) if KEY_LIST else 0 print("Number of private keys:", NUM_KEYS) if NUM_KEYS < 1: print("ERROR: Number of keys should be 1, not", NUM_KEYS)
Java
<html> <head> <title>case sensitivity on id</title> <style> #test { background-color: blue; } #TEST { background-color: pink; } </style> <body> <div id="test">Hello</div> <div id="TEST">Goodbye</div> </body> </html>
Java
#!/usr/bin/python """ Since functions are function instances you can wrap them Allow you to - modify arguments - modify function - modify results """ call_count = 0 def count(func): def wrapper(*args, **kw): global call_count call_count += 1 return func(*args, **kw) return wrapper def hello(): print 'Invoked hello' hello = count(hello) ## Now decorating hello to increment call count hello() print call_count hello() print call_count """ ## Syntactic Sugar >>> @count ... def hello(): ... print "Invoked hello" equals hello = count(hello) ## Syntactic Sugar 2 Dont add parens to the decorator >>> @count() ... def hello(): ... print "Invoked hello" ... Traceback (most recent call last): File "<stdin>", line 1, in <module> TypeError: count() takes exactly 1 argument (0 given) >>> ##Decorator Template def decorator(func_to_decorate): def wrapper(*args, **kwargs): # do something before invocation result = func_to_decorate(*args,**kwargs) # do something after invocation return result #update wrapper.__doc__ and .func_name # or functools.wraps return wrapper ##Decorators can also be classes, to have a class that Decorates class decorator(object): def __init__(self, function): self.function = function def __call__(self, *args, **kw): # do something before invocation result = self.function(*args, **kw) # do something after return result ##Decorators can also be classes 2, to have a instance that Decorates class decorator(object): def __init__(self, function): self.function = function def __call__(self, *args, **kw): def wrapper(*args, **kw): # do something before invocation result = self.function(*args, **kw) # do something after return result return wrapper ## The aboves lets you have an instance of a decorator that stores state (rather than using global state) ## Parameterized decorators (need 2 closures) def limit(length): def decorator(function): def wrapper(*args, **kw): result = function(*args, **kw) result = result[:length] return result return wrapper return decorator >>> @limit(5) ## Decorating the simple function echo with limit 5 as parameter ... def echo(foo): ... return foo ... >>> echo ('123456') '12345' >>> Or you can use following as well , to limit the echo function with 3 as parameter >>> echo = limit(3)(echo) >>> echo ('123456') '123' >>> ## Decorator Tidying function attributes get mangled >>> def echo2(input): ... ###return input### I used ### instead of 3 coz that was causing some error ... return input ... >>> echo2.__doc__ 'return input' >>> echo2.func_name 'echo2' >>> >>> echo3 = limit(3)(echo2) >>> echo3.__doc__ >>> echo3.func_name 'wrapper' >>> #Now to fix above define your limit decorator as below def limit(length): def decorator(function): def wrapper(*args, **kw): result = function(*args, **kw) result = result[:length] return result wrapper.__doc__ = function.__doc__ wrapper.func_name = function.func_name return wrapper return decorator >>> echo4 = limit(3)(echo2) >>> echo4.__doc__ 'return input' >>> echo4.func_name 'echo2' >>> #Decorator tidying (3) , using functools , more simple import functools def limit(length): def decorator(function): @functools.wraps(function) def wrapper(*args, **kw): result = function(*args, **kw) result = result[:length] return result #wrapper.__doc__ = function.__doc__ #wrapper.func_name = function.func_name return wrapper return decorator Uses for decorator - caching - monkey patching stdio - memoize - jsonify - logging time in function call - change cwd """ def cwd_decorator(func): """ decorator to change cwd to directory containing rst for this function """ def wrapper(*args, **kw): cur_dir = os.getcwd() found = False for arg in sys.argv: if arg.endswith(".rst"): found = arg break if found: directory = os.path.dirname(arg) if directory: os.chdir(directory) data = func(*args, **kw) os.chdir(cur_dir) return data return wrapper """ ### Properties Call get/set methods via an instance attributes class C(object): def getx(self): return self._x def setx(self, value): self._x = value def delx(self): del self._x x = property(getx, setx, delx, "I'm the 'x' property.") from property.__doc__ """ import os def find_files(base_dir, recurse=True): """ yeild files found in base_dir """ for name in os.listdir(base_dir): filepath = os.path.join(base_dir, name) if os.path.isdir(filepath) and recurse: for child in find_files(filepath, recurse): yield child else: yield filepath
Java
<?php // ini_set('display_errors','1'); function nzshpcrt_getcategoryform($catid) { global $wpdb,$nzshpcrt_imagesize_info; $product = $wpdb->get_row("SELECT * FROM `".WPSC_TABLE_PRODUCT_CATEGORIES."` WHERE `id`=$catid LIMIT 1",ARRAY_A); $output = ''; $output .= "<div class='editing_this_group form_table'>"; $output .= "<p>".str_replace("[categorisation]", htmlentities(stripslashes($product['name'])), TXT_WPSC_EDITING_GROUP)."</p>\n\r"; $output .= "<p><a href='' onclick='return showaddform()' class='add_category_link'><span>".str_replace("&quot;[categorisation]&quot;", "current", TXT_WPSC_ADDNEWCATEGORY)."</span></a></p>"; $output .="<dl>\n\r"; $output .=" <dt>Display Category Shortcode: </dt>\n\r"; $output .=" <dd> [wpsc_products category_url_name='{$product['nice-name']}']</dd>\n\r"; $output .=" <dt>Display Category Template Tag: </dt>\n\r"; $output .=" <dd> &lt;?php echo wpsc_display_products_page(array('category_url_name'=>'{$product['nice-name']}')); ?&gt;</dd>\n\r"; $output .="</dl>\n\r"; //$output .= " [ <a href='#' onclick='return showedit_categorisation_form()'>".TXT_WPSC_EDIT_THIS_GROUP."</a> ]"; $output .= "</div>"; $output .= " <table class='category_forms'>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_NAME.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='text' class='text' name='title' value='".htmlentities(stripslashes($product['name']), ENT_QUOTES, 'UTF-8')."' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_DESCRIPTION.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<textarea name='description' cols='40' rows='8' >".stripslashes($product['description'])."</textarea>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_CATEGORY_PARENT.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= wpsc_parent_category_list($product['group_id'], $product['id'], $product['category_parent']); $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; if ($product['display_type'] == 'grid') { $display_type1="selected='selected'"; } else if ($product['display_type'] == 'default') { $display_type2="selected='selected'"; } switch($product['display_type']) { case "default": $product_view1 = "selected ='selected'"; break; case "grid": if(function_exists('product_display_grid')) { $product_view3 = "selected ='selected'"; break; } case "list": if(function_exists('product_display_list')) { $product_view2 = "selected ='selected'"; break; } default: $product_view0 = "selected ='selected'"; break; } $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_GROUP_IMAGE.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='file' name='image' value='' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; if(function_exists("getimagesize")) { if($product['image'] != '') { $imagepath = WPSC_CATEGORY_DIR . $product['image']; $imagetype = @getimagesize($imagepath); //previously exif_imagetype() $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_HEIGHT.":<input type='text' size='6' name='height' value='".$imagetype[1]."' /> ".TXT_WPSC_WIDTH.":<input type='text' size='6' name='width' value='".$imagetype[0]."' /><br /><span class='wpscsmall description'>$nzshpcrt_imagesize_info</span><br />\n\r"; $output .= "<span class='wpscsmall description'>".TXT_WPSC_GROUP_IMAGE_TEXT."</span>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; } else { $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_HEIGHT.":<input type='text' size='6' name='height' value='".get_option('product_image_height')."' /> ".TXT_WPSC_WIDTH.":<input type='text' size='6' name='width' value='".get_option('product_image_width')."' /><br /><span class='wpscsmall description'>$nzshpcrt_imagesize_info</span><br />\n\r"; $output .= "<span class='wpscsmall description'>".TXT_WPSC_GROUP_IMAGE_TEXT."</span>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; } } $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_DELETEIMAGE.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='checkbox' name='deleteimage' value='1' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; /* START OF TARGET MARKET SELECTION */ $countrylist = $wpdb->get_results("SELECT id,country,visible FROM `".WPSC_TABLE_CURRENCY_LIST."` ORDER BY country ASC ",ARRAY_A); $selectedCountries = $wpdb->get_col("SELECT countryid FROM `".WPSC_TABLE_CATEGORY_TM."` WHERE categoryid=".$product['id']." AND visible= 1"); // exit('<pre>'.print_r($countrylist,true).'</pre><br /><pre>'.print_r($selectedCountries,true).'</pre>'); $output .= " <tr>\n\r"; $output .= " <td colspan='2'><h4>Target Market Restrictions</h4></td></tr><tr><td>&nbsp;</td></tr><tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_TM.":\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; if(@extension_loaded('suhosin')) { $output .= "<em>".__("The Target Markets feature has been disabled because you have the Suhosin PHP extension installed on this server. If you need to use the Target Markets feature then disable the suhosin extension, if you can not do this, you will need to contact your hosting provider. ",'wpsc')."</em>"; } else { $output .= "<span>Select: <a href='' class='wpsc_select_all'>All</a>&nbsp; <a href='' class='wpsc_select_none'>None</a></span><br />"; $output .= " <div id='resizeable' class='ui-widget-content multiple-select'>\n\r"; foreach($countrylist as $country){ if(in_array($country['id'], $selectedCountries)) /* if($country['visible'] == 1) */{ $output .= " <input type='checkbox' name='countrylist2[]' value='".$country['id']."' checked='".$country['visible']."' />".$country['country']."<br />\n\r"; }else{ $output .= " <input type='checkbox' name='countrylist2[]' value='".$country['id']."' />".$country['country']."<br />\n\r"; } } $output .= " </div><br /><br />"; $output .= " <span class='wpscsmall description'>Select the markets you are selling this category to.<span>\n\r"; } $output .= " </td>\n\r"; $output .= " </tr>\n\r"; //////// $output .= " <tr>\n\r"; $output .= " <td colspan='2' class='category_presentation_settings'>\n\r"; $output .= " <h4>".TXT_WPSC_PRESENTATIONSETTINGS."</h4>\n\r"; $output .= " <span class='small'>".TXT_WPSC_GROUP_PRESENTATION_TEXT."</span>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " ". TXT_WPSC_CATALOG_VIEW.":\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <select name='display_type'>\n\r"; $output .= " <option value='' $product_view0 >".TXT_WPSC_PLEASE_SELECT."</option>\n\r"; $output .= " <option value='default' $product_view1 >".TXT_WPSC_DEFAULT."</option>\n\r"; if(function_exists('product_display_list')) { $output .= " <option value='list' ". $product_view2.">". TXT_WPSC_LIST."</option>\n\r"; } else { $output .= " <option value='list' disabled='disabled' ". $product_view2.">". TXT_WPSC_LIST."</option>\n\r"; } if(function_exists('product_display_grid')) { $output .= " <option value='grid' ". $product_view3.">". TXT_WPSC_GRID."</option>\n\r"; } else { $output .= " <option value='grid' disabled='disabled' ". $product_view3.">". TXT_WPSC_GRID."</option>\n\r"; } $output .= " </select>\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; if(function_exists("getimagesize")) { $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_THUMBNAIL_SIZE.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_HEIGHT.": <input type='text' value='".$product['image_height']."' name='product_height' size='6'/> "; $output .= TXT_WPSC_WIDTH.": <input type='text' value='".$product['image_width']."' name='product_width' size='6'/> <br/>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; } $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td class='last_row'>\n\r"; $output .= "<input type='hidden' name='prodid' value='".$product['id']."' />"; $output .= "<input type='hidden' name='submit_action' value='edit' />"; $output .= "<input class='button-primary' style='float:left;' type='submit' name='submit' value='".TXT_WPSC_EDIT_GROUP."' />"; $output .= "<a class='delete_button' href='".add_query_arg('deleteid', $product['id'], 'admin.php?page=wpsc-edit-groups')."' onclick=\"return conf();\" >".TXT_WPSC_DELETE."</a>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </table>\n\r"; return $output; } function nzshpcrt_getvariationform($variation_id) { global $wpdb,$nzshpcrt_imagesize_info; $variation_sql = "SELECT * FROM `".WPSC_TABLE_PRODUCT_VARIATIONS."` WHERE `id`='$variation_id' LIMIT 1"; $variation_data = $wpdb->get_results($variation_sql,ARRAY_A) ; $variation = $variation_data[0]; $output .= " <table class='category_forms' >\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_NAME.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='text' class='text' name='title' value='".htmlentities(stripslashes($variation['name']), ENT_QUOTES, 'UTF-8')."' />"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= TXT_WPSC_VARIATION_VALUES.": "; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $variation_values_sql = "SELECT * FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `variation_id`='$variation_id' ORDER BY `id` ASC"; $variation_values = $wpdb->get_results($variation_values_sql,ARRAY_A); $variation_value_count = count($variation_values); $output .= "<div id='edit_variation_values'>"; $num = 0; foreach($variation_values as $variation_value) { $output .= "<span class='variation_value'>"; $output .= "<input type='text' class='text' name='variation_values[".$variation_value['id']."]' value='".htmlentities(stripslashes($variation_value['name']), ENT_QUOTES, 'UTF-8')."' />"; if($variation_value_count > 1) { $output .= " <a class='image_link' onclick='return remove_variation_value(this,".$variation_value['id'].")' href='#'><img src='".WPSC_URL."/images/trash.gif' alt='".TXT_WPSC_DELETE."' title='".TXT_WPSC_DELETE."' /></a>"; } $output .= "<br />"; $output .= "</span>"; $num++; } $output .= "</div>"; $output .= "<a href='#' onclick='return add_variation_value(\"edit\")'>".TXT_WPSC_ADD."</a>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= "<input type='hidden' name='prodid' value='".$variation['id']."' />"; $output .= "<input type='hidden' name='submit_action' value='edit' />"; $output .= "<input class='button' style='float:left;' type='submit' name='submit' value='".TXT_WPSC_EDIT."' />"; $output .= "<a class='button delete_button' href='admin.php?page=".WPSC_DIR_NAME."/display_variations.php&amp;deleteid=".$variation['id']."' onclick=\"return conf();\" >".TXT_WPSC_DELETE."</a>"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; $output .= " </table>\n\r"; return $output; } function coupon_edit_form($coupon) { $conditions = unserialize($coupon['condition']); $conditions = $conditions[0]; //exit('<pre>'.print_r($conditions, true).'</pre>'); $start_timestamp = strtotime($coupon['start']); $end_timestamp = strtotime($coupon['expiry']); $id = $coupon['id']; $output = ''; $output .= "<form name='edit_coupon' method='post' action='admin.php?page=".WPSC_DIR_NAME."/display-coupons.php'>\n\r"; $output .= " <input type='hidden' value='true' name='is_edit_coupon' />\n\r"; $output .= "<table class='add-coupon'>\n\r"; $output .= " <tr>\n\r"; $output .= " <th>".TXT_WPSC_COUPON_CODE."</th>\n\r"; $output .= " <th>".TXT_WPSC_DISCOUNT."</th>\n\r"; $output .= " <th>".TXT_WPSC_START."</th>\n\r"; $output .= " <th>".TXT_WPSC_EXPIRY."</th>\n\r"; $output .= " <th>".TXT_WPSC_USE_ONCE."</th>\n\r"; $output .= " <th>".TXT_WPSC_ACTIVE."</th>\n\r"; $output .= " <th>".TXT_WPSC_PERTICKED."</th>\n\r"; $output .= " <th></th>\n\r"; $output .= " </tr>\n\r"; $output .= " <tr>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='text' size='8' value='".$coupon['coupon_code']."' name='edit_coupon[".$id."][coupon_code]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='text' style='width:28px;' value='".$coupon['value']."' name=edit_coupon[".$id."][value]' />"; $output .= " <select style='width:20px;' name='edit_coupon[".$id."][is-percentage]'>"; $output .= " <option value='0' ".(($coupon['is-percentage'] == 0) ? "selected='true'" : '')." >$</option>\n\r";// $output .= " <option value='1' ".(($coupon['is-percentage'] == 1) ? "selected='true'" : '')." >%</option>\n\r"; $output .= " </select>\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $coupon_start = explode(" ",$coupon['start']); $output .= "<input type='text' class='pickdate' size='8' name='edit_coupon[".$id."][start]' value='{$coupon_start[0]}'>"; /* $output .= " <select name='edit_coupon[".$id."][start][day]'>\n\r"; for($i = 1; $i <=31; ++$i) { $selected = ''; if($i == date("d", $start_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>$i</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][start][month]'>\n\r"; for($i = 1; $i <=12; ++$i) { $selected = ''; if($i == (int)date("m", $start_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".date("M",mktime(0, 0, 0, $i, 1, date("Y")))."</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][start][year]'>\n\r"; for($i = date("Y"); $i <= (date("Y") +12); ++$i) { $selected = ''; if($i == date("Y", $start_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".$i."</option>"; } $output .= " </select>\n\r";*/ $output .= " </td>\n\r"; $output .= " <td>\n\r"; $coupon_expiry = explode(" ",$coupon['expiry']); $output .= "<input type='text' class='pickdate' size='8' name='edit_coupon[".$id."][expiry]' value='{$coupon_expiry[0]}'>"; /*$output .= " <select name='edit_coupon[".$id."][expiry][day]'>\n\r"; for($i = 1; $i <=31; ++$i) { $selected = ''; if($i == date("d", $end_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>$i</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][expiry][month]'>\n\r"; for($i = 1; $i <=12; ++$i) { $selected = ''; if($i == (int)date("m", $end_timestamp)) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".date("M",mktime(0, 0, 0, $i, 1, date("Y")))."</option>"; } $output .= " </select>\n\r"; $output .= " <select name='edit_coupon[".$id."][expiry][year]'>\n\r"; for($i = date("Y"); $i <= (date("Y") +12); ++$i) { $selected = ''; if($i == (date("Y", $end_timestamp))) { $selected = "selected='true'"; } $output .= " <option $selected value='$i'>".$i."</option>\n\r"; } $output .= " </select>\n\r";*/ $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][use-once]' />\n\r"; $output .= " <input type='checkbox' value='1' ".(($coupon['use-once'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][use-once]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][active]' />\n\r"; $output .= " <input type='checkbox' value='1' ".(($coupon['active'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][active]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='0' name='edit_coupon[".$id."][every_product]' />\n\r"; $output .= " <input type='checkbox' value='1' ".(($coupon['every_product'] == 1) ? "checked='checked'" : '')." name='edit_coupon[".$id."][every_product]' />\n\r"; $output .= " </td>\n\r"; $output .= " <td>\n\r"; $output .= " <input type='hidden' value='".$id."' name='edit_coupon[".$id."][id]' />\n\r"; //$output .= " <input type='hidden' value='false' name='add_coupon' />\n\r"; $output .= " <input type='submit' value='".TXT_WPSC_SUBMIT."' name='edit_coupon[".$id."][submit_coupon]' />\n\r"; $output .= " <input type='submit' value='".TXT_WPSC_DELETE."' name='edit_coupon[".$id."][delete_coupon]' />\n\r"; $output .= " </td>\n\r"; $output .= " </tr>\n\r"; if($conditions != null){ $output .= "<tr>"; $output .= "<th>"; $output .= "Conditions"; $output .= "</th>"; $output .= "</tr>"; $output .= "<th>"; $output .= "Delete"; $output .= "</th>"; $output .= "<th>"; $output .= "Property"; $output .= "</th>"; $output .= "<th>"; $output .= "Logic"; $output .= "</th>"; $output .= "<th>"; $output .= "Value"; $output .= "</th>"; $output .= " </tr>\n\r"; $output .= "<tr>"; $output .= "<td>"; $output .= "<input type='hidden' name='coupon_id' value='".$id."' />"; $output .= "<input type='submit' value='Delete' name='delete_condition' />"; $output .= "</td>"; $output .= "<td>"; $output .= $conditions['property']; $output .= "</td>"; $output .= "<td>"; $output .= $conditions['logic']; $output .= "</td>"; $output .= "<td>"; $output .= $conditions['value']; $output .= "</td>"; $output .= "</tr>"; }elseif($conditions == null){ $output .= wpsc_coupons_conditions( $id); } ?> <!-- <tr><td colspan="8"> <div class="coupon_condition"> <div><img height="16" width="16" class="delete" alt="Delete" src="<?=WPSC_URL?>/images/cross.png"/></button> <select class="ruleprops" name="rules[property][]"> <option value="item_name" rel="order">Item name</option> <option value="item_quantity" rel="order">Item quantity</option> <option value="total_quantity" rel="order">Total quantity</option> <option value="subtotal_amount" rel="order">Subtotal amount</option> </select> <select name="rules[logic][]"> <option value="equal">Is equal to</option> <option value="greater">Is greater than</option> <option value="less">Is less than</option> <option value="contains">Contains</option> <option value="not_contain">Does not contain</option> <option value="begins">Begins with</option> <option value="ends">Ends with</option> </select> <span> <input type="text" name="rules[value][]"/> </span> <span> <button class="add" type="button"> <img height="16" width="16" alt="Add" src="<?=WPSC_URL?>/images/add.png"/> </button> </span> </div> </div> </tr> --> <?php $output .= "</table>\n\r"; $output .= "</form>\n\r"; echo $output; return $output; } function wpsc_coupons_conditions($id){ ?> <?php $output =' <input type="hidden" name="coupon_id" value="'.$id.'" /> <tr><td colspan="3"><b>Conditions</b></td></tr> <tr><td colspan="8"> <div class="coupon_condition"> <div> <select class="ruleprops" name="rules[property][]"> <option value="item_name" rel="order">Item name</option> <option value="item_quantity" rel="order">Item quantity</option> <option value="total_quantity" rel="order">Total quantity</option> <option value="subtotal_amount" rel="order">Subtotal amount</option> </select> <select name="rules[logic][]"> <option value="equal">Is equal to</option> <option value="greater">Is greater than</option> <option value="less">Is less than</option> <option value="contains">Contains</option> <option value="not_contain">Does not contain</option> <option value="begins">Begins with</option> <option value="ends">Ends with</option> </select> <span> <input type="text" name="rules[value][]"/> </span> <span> <input type="submit" value="add" name="submit_condition" /> </span> </div> </div> </tr> '; return $output; } function setting_button(){ $itemsFeedURL = "http://www.google.com/base/feeds/items"; $next_url = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['PHP_SELF']."?page=wpsc-edit-products"; $redirect_url = 'https://www.google.com/accounts/AuthSubRequest?session=1'; $redirect_url .= '&next='; $redirect_url .= urlencode($next_url); $redirect_url .= "&scope="; $redirect_url .= urlencode($itemsFeedURL); // $output.="<div><img src='".get_option('siteurl')."/wp-content/plugins/".WPSC_DIR_NAME."/images/settings_button.jpg' onclick='display_settings_button()'>"; $output.="<div style='float: right; margin-top: 0px; position: relative;'> | <a href='#' onclick='display_settings_button(); return false;' style='text-decoration: underline;'>".TXT_WPSC_SETTINGS." &raquo;</a>"; $output.="<span id='settings_button' style='width:180px;background-color:#f1f1f1;position:absolute; right: 10px; border:1px solid black; display:none;'>"; $output.="<ul class='settings_button'>"; $output.="<li><a href='admin.php?page=wpsc-settings'>".TXT_WPSC_SHOP_SETTINGS."</a></li>"; $output.="<li><a href='admin.php?page=wpsc-settings&amp;tab=gateway'>".TXT_WPSC_MONEY_AND_PAYMENT."</a></li>"; $output.="<li><a href='admin.php?page=wpsc-settings&amp;tab=checkout'>".TXT_WPSC_CHECKOUT_PAGE_SETTINGS."</a></li>"; //$output.="<li><a href='?page=".WPSC_DIR_NAME."/instructions.php'>Help/Upgrade</a></li>"; //$output.="<li><a href='{$redirect_url}'>".TXT_WPSC_LOGIN_TO_GOOGLE_BASE."</a></li>"; $output.="</ul>"; // $output.="<div>Checkout Settings</div>"; $output.="</span>&emsp;&emsp;</div>"; return $output; } function wpsc_right_now() { global $wpdb,$nzshpcrt_imagesize_info; $year = date("Y"); $month = date("m"); $start_timestamp = mktime(0, 0, 0, $month, 1, $year); $end_timestamp = mktime(0, 0, 0, ($month+1), 0, $year); $replace_values[":productcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `active` IN ('1')"); $product_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `active` IN ('1')"); $replace_values[":productcount:"] .= " ".(($replace_values[":productcount:"] == 1) ? TXT_WPSC_PRODUCTCOUNT_SINGULAR : TXT_WPSC_PRODUCTCOUNT_PLURAL); $product_unit = (($replace_values[":productcount:"] == 1) ? TXT_WPSC_PRODUCTCOUNT_SINGULAR : TXT_WPSC_PRODUCTCOUNT_PLURAL); $replace_values[":groupcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_CATEGORIES."` WHERE `active` IN ('1')"); $group_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_CATEGORIES."` WHERE `active` IN ('1')"); $replace_values[":groupcount:"] .= " ".(($replace_values[":groupcount:"] == 1) ? TXT_WPSC_GROUPCOUNT_SINGULAR : TXT_WPSC_GROUPCOUNT_PLURAL); $group_unit = (($replace_values[":groupcount:"] == 1) ? TXT_WPSC_GROUPCOUNT_SINGULAR : TXT_WPSC_GROUPCOUNT_PLURAL); $replace_values[":salecount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `date` BETWEEN '".$start_timestamp."' AND '".$end_timestamp."'"); $sales_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `date` BETWEEN '".$start_timestamp."' AND '".$end_timestamp."'"); $replace_values[":salecount:"] .= " ".(($replace_values[":salecount:"] == 1) ? TXT_WPSC_SALECOUNT_SINGULAR : TXT_WPSC_SALECOUNT_PLURAL); $sales_unit = (($replace_values[":salecount:"] == 1) ? TXT_WPSC_SALECOUNT_SINGULAR : TXT_WPSC_SALECOUNT_PLURAL); $replace_values[":monthtotal:"] = nzshpcrt_currency_display(admin_display_total_price($start_timestamp, $end_timestamp),1); $replace_values[":overaltotal:"] = nzshpcrt_currency_display(admin_display_total_price(),1); $variation_count = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PRODUCT_VARIATIONS."`"); $variation_unit = (($variation_count == 1) ? TXT_WPSC_VARIATION_SINGULAR : TXT_WPSC_VARIATION_PLURAL); $replace_values[":pendingcount:"] = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `processed` IN ('1')"); $pending_sales = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `processed` IN ('1')"); $replace_values[":pendingcount:"] .= " " . (($replace_values[":pendingcount:"] == 1) ? TXT_WPSC_PENDINGCOUNT_SINGULAR : TXT_WPSC_PENDINGCOUNT_PLURAL); $pending_sales_unit = (($replace_values[":pendingcount:"] == 1) ? TXT_WPSC_PENDINGCOUNT_SINGULAR : TXT_WPSC_PENDINGCOUNT_PLURAL); $accept_sales = $wpdb->get_var("SELECT COUNT(*) FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `processed` IN ('2' ,'3', '4')"); $accept_sales_unit = (($accept_sales == 1) ? TXT_WPSC_PENDINGCOUNT_SINGULAR : TXT_WPSC_PENDINGCOUNT_PLURAL); $replace_values[":theme:"] = get_option('wpsc_selected_theme'); $replace_values[":versionnumber:"] = WPSC_PRESENTABLE_VERSION; if (function_exists('add_object_page')) { $output=""; $output.="<div id='dashboard_right_now' class='postbox'>"; $output.=" <h3 class='hndle'>"; $output.=" <span>".TXT_WPSC_CURRENT_MONTH."</span>"; $output.=" <br class='clear'/>"; $output.=" </h3>"; $output .= "<div class='inside'>"; $output .= "<p class='sub'>".TXT_WPSC_AT_A_GLANCE."</p>"; //$output.="<p class='youhave'>".TXT_WPSC_SALES_DASHBOARD."</p>"; $output .= "<div class='table'>"; $output .= "<table>"; $output .= "<tr class='first'>"; $output .= "<td class='first b'>"; $output .= "<a href='?page=wpsc-edit-products'>".$product_count."</a>"; $output .= "</td>"; $output .= "<td class='t'>"; $output .= ucfirst($product_unit); $output .= "</td>"; $output .= "<td class='b'>"; $output .= "<a href='?page=wpsc-sales-logs'>".$sales_count."</a>"; $output .= "</td>"; $output .= "<td class='last'>"; $output .= ucfirst($sales_unit); $output .= "</td>"; $output .= "</tr>"; $output .= "<tr>"; $output .= "<td class='first b'>"; $output .= "<a href='?page=wpsc-edit-groups'>".$group_count."</a>"; $output .= "</td>"; $output .= "<td class='t'>"; $output .= ucfirst($group_unit); $output .= "</td>"; $output .= "<td class='b'>"; $output .= "<a href='?page=wpsc-sales-logs'>".$pending_sales."</a>"; $output .= "</td>"; $output .= "<td class='last t waiting'>".TXT_WPSC_PENDING." "; $output .= ucfirst($pending_sales_unit); $output .= "</td>"; $output .= "</tr>"; $output .= "<tr>"; $output .= "<td class='first b'>"; $output .= "<a href='?page=wpsc-edit-variations'>".$variation_count."</a>"; $output .= "</td>"; $output .= "<td class='t'>"; $output .= ucfirst($variation_unit); $output .= "</td>"; $output .= "<td class='b'>"; $output .= "<a href='?page=wpsc-sales-logs'>".$accept_sales."</a>"; $output .= "</td>"; $output .= "<td class='last t approved'>".TXT_WPSC_CLOSED." "; $output .= ucfirst($accept_sales_unit); $output .= "</td>"; $output .= "</tr>"; $output .= "</table>"; $output .= "</div>"; $output .= "<div class='versions'>"; $output .= "<p><a class='button rbutton' href='admin.php?page=wpsc-edit-products'><strong>".TXT_WPSC_ADD_NEW_PRODUCT."</strong></a>".TXT_WPSC_HERE_YOU_CAN_ADD."</p>"; $output .= "</div>"; $output .= "</div>"; $output.="</div>"; } else { $output=""; $output.="<div id='rightnow'>\n\r"; $output.=" <h3 class='reallynow'>\n\r"; $output.=" <a class='rbutton' href='admin.php?page=wpsc-edit-products'><strong>".TXT_WPSC_ADD_NEW_PRODUCT."</strong></a>\n\r"; $output.=" <span>"._('Right Now')."</span>\n\r"; //$output.=" <br class='clear'/>\n\r"; $output.=" </h3>\n\r"; $output.="<p class='youhave'>".TXT_WPSC_SALES_DASHBOARD."</p>\n\r"; $output.=" <p class='youare'>\n\r"; $output.=" ".TXT_WPSC_YOUAREUSING."\n\r"; //$output.=" <a class='rbutton' href='themes.php'>Change Theme</a>\n\r"; //$output.="<span id='wp-version-message'>This is WordPress version 2.6. <a class='rbutton' href='http://wordpress.org/download/'>Update to 2.6.1</a></span>\n\r"; $output.=" </p>\n\r"; $output.="</div>\n\r"; $output.="<br />\n\r"; $output = str_replace(array_keys($replace_values), array_values($replace_values),$output); } return $output; } function wpsc_packing_slip($purchase_id) { global $wpdb; $purch_sql = "SELECT * FROM `".WPSC_TABLE_PURCHASE_LOGS."` WHERE `id`='".$purchase_id."'"; $purch_data = $wpdb->get_row($purch_sql,ARRAY_A) ; //echo "<p style='padding-left: 5px;'><strong>".TXT_WPSC_DATE."</strong>:".date("jS M Y", $purch_data['date'])."</p>"; $cartsql = "SELECT * FROM `".WPSC_TABLE_CART_CONTENTS."` WHERE `purchaseid`=".$purchase_id.""; $cart_log = $wpdb->get_results($cartsql,ARRAY_A) ; $j = 0; if($cart_log != null) { echo "<div class='packing_slip'>\n\r"; echo "<h2>".TXT_WPSC_PACKING_SLIP."</h2>\n\r"; echo "<strong>".TXT_WPSC_ORDER." #</strong> ".$purchase_id."<br /><br />\n\r"; echo "<table>\n\r"; $form_sql = "SELECT * FROM `".WPSC_TABLE_SUBMITED_FORM_DATA."` WHERE `log_id` = '".(int)$purchase_id."'"; $input_data = $wpdb->get_results($form_sql,ARRAY_A); foreach($input_data as $input_row) { $rekeyed_input[$input_row['form_id']] = $input_row; } if($input_data != null) { $form_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_CHECKOUT_FORMS."` WHERE `active` = '1'",ARRAY_A); foreach($form_data as $form_field) { switch($form_field['type']) { case 'country': $delivery_region_count = $wpdb->get_var("SELECT COUNT(`regions`.`id`) FROM `".WPSC_TABLE_REGION_TAX."` AS `regions` INNER JOIN `".WPSC_TABLE_CURRENCY_LIST."` AS `country` ON `country`.`id` = `regions`.`country_id` WHERE `country`.`isocode` IN('".$wpdb->escape( $purch_data['billing_country'])."')"); if(is_numeric($purch_data['shipping_region']) && ($delivery_region_count > 0)) { echo " <tr><td>".__('State', 'wpsc').":</td><td>".wpsc_get_region($purch_data['shipping_region'])."</td></tr>\n\r"; } echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".wpsc_get_country($purch_data['billing_country'])."</td></tr>\n\r"; break; case 'delivery_country': echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".wpsc_get_country($purch_data['shipping_country'])."</td></tr>\n\r"; break; case 'heading': echo " <tr><td colspan='2'><strong>".wp_kses($form_field['name'], array() ).":</strong></td></tr>\n\r"; break; default: echo " <tr><td>".wp_kses($form_field['name'], array() ).":</td><td>".htmlentities(stripslashes($rekeyed_input[$form_field['id']]['value']), ENT_QUOTES)."</td></tr>\n\r"; break; } } } else { echo " <tr><td>".TXT_WPSC_NAME.":</td><td>".$purch_data['firstname']." ".$purch_data['lastname']."</td></tr>\n\r"; echo " <tr><td>".TXT_WPSC_ADDRESS.":</td><td>".$purch_data['address']."</td></tr>\n\r"; echo " <tr><td>".TXT_WPSC_PHONE.":</td><td>".$purch_data['phone']."</td></tr>\n\r"; echo " <tr><td>".TXT_WPSC_EMAIL.":</td><td>".$purch_data['email']."</td></tr>\n\r"; } if(get_option('payment_method') == 2) { $gateway_name = ''; foreach($GLOBALS['nzshpcrt_gateways'] as $gateway) { if($purch_data['gateway'] != 'testmode') { if($gateway['internalname'] == $purch_data['gateway'] ) { $gateway_name = $gateway['name']; } } else { $gateway_name = "Manual Payment"; } } } // echo " <tr><td colspan='2'></td></tr>\n\r"; // echo " <tr><td>".TXT_WPSC_PAYMENT_METHOD.":</td><td>".$gateway_name."</td></tr>\n\r"; // //echo " <tr><td>".TXT_WPSC_PURCHASE_NUMBER.":</td><td>".$purch_data['id']."</td></tr>\n\r"; // echo " <tr><td>".TXT_WPSC_HOWCUSTOMERFINDUS.":</td><td>".$purch_data['find_us']."</td></tr>\n\r"; // $engrave_line = explode(",",$purch_data['engravetext']); // echo " <tr><td>".TXT_WPSC_ENGRAVE."</td><td></td></tr>\n\r"; // echo " <tr><td>".TXT_WPSC_ENGRAVE_LINE_ONE.":</td><td>".$engrave_line[0]."</td></tr>\n\r"; // echo " <tr><td>".TXT_WPSC_ENGRAVE_LINE_TWO.":</td><td>".$engrave_line[1]."</td></tr>\n\r"; // if($purch_data['transactid'] != '') { // echo " <tr><td>".TXT_WPSC_TXN_ID.":</td><td>".$purch_data['transactid']."</td></tr>\n\r"; // } echo "</table>\n\r"; echo "<table class='packing_slip'>"; echo "<tr>"; echo " <th>".TXT_WPSC_QUANTITY." </th>"; echo " <th>".TXT_WPSC_NAME."</th>"; echo " <th>".TXT_WPSC_PRICE." </th>"; echo " <th>".TXT_WPSC_SHIPPING." </th>"; echo '<th>Tax</th>'; echo '</tr>'; $endtotal = 0; $all_donations = true; $all_no_shipping = true; $file_link_list = array(); foreach($cart_log as $cart_row) { $alternate = ""; $j++; if(($j % 2) != 0) { $alternate = "class='alt'"; } $productsql= "SELECT * FROM `".WPSC_TABLE_PRODUCT_LIST."` WHERE `id`=".$cart_row['prodid'].""; $product_data = $wpdb->get_results($productsql,ARRAY_A); $variation_sql = "SELECT * FROM `".WPSC_TABLE_CART_ITEM_VARIATIONS."` WHERE `cart_id`='".$cart_row['id']."'"; $variation_data = $wpdb->get_results($variation_sql,ARRAY_A); $variation_count = count($variation_data); if($variation_count > 1) { $variation_list = " ("; $i = 0; foreach($variation_data as $variation) { if($i > 0) { $variation_list .= ", "; } $value_id = $variation['value_id']; $value_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `id`='".$value_id."' LIMIT 1",ARRAY_A); $variation_list .= $value_data[0]['name']; $i++; } $variation_list .= ")"; } else if($variation_count == 1) { $value_id = $variation_data[0]['value_id']; $value_data = $wpdb->get_results("SELECT * FROM `".WPSC_TABLE_VARIATION_VALUES."` WHERE `id`='".$value_id."' LIMIT 1",ARRAY_A); $variation_list = " (".$value_data[0]['name'].")"; } else { $variation_list = ''; } if($cart_row['donation'] != 1) { $all_donations = false; } if($cart_row['no_shipping'] != 1) { $shipping = $cart_row['pnp'] * $cart_row['quantity']; $total_shipping += $shipping; $all_no_shipping = false; } else { $shipping = 0; } $price = $cart_row['price'] * $cart_row['quantity']; $gst = $price - ($price / (1+($cart_row['gst'] / 100))); if($gst > 0) { $tax_per_item = $gst / $cart_row['quantity']; } echo "<tr $alternate>"; echo " <td>"; echo $cart_row['quantity']; echo " </td>"; echo " <td>"; echo $product_data[0]['name']; echo stripslashes($variation_list); echo " </td>"; echo " <td>"; echo nzshpcrt_currency_display( $price, 1); echo " </td>"; echo " <td>"; echo nzshpcrt_currency_display($shipping, 1); echo " </td>"; echo '<td>'; echo nzshpcrt_currency_display($cart_row['tax_charged'],1); echo '<td>'; echo '</tr>'; } echo "</table>"; echo "</div>\n\r"; } else { echo "<br />".TXT_WPSC_USERSCARTWASEMPTY; } } function wpsc_product_item_row() { } ?>
Java
////////////////////////////////////////////////////////////////////////////// // oxygensizegrip.cpp // bottom right size grip for borderless windows // ------------------- // // Copyright (c) 2009 Hugo Pereira Da Costa <hugo.pereira@free.fr> // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. ////////////////////////////////////////////////////////////////////////////// #include "oxygensizegrip.h" #include "oxygenbutton.h" #include "oxygenclient.h" #include <cassert> #include <QtGui/QPainter> #include <QtGui/QPolygon> #include <QtCore/QTimer> #include <QtGui/QX11Info> #include <X11/Xlib.h> namespace Oxygen { //_____________________________________________ SizeGrip::SizeGrip( Client* client ): QWidget(0), _client( client ) { setAttribute(Qt::WA_NoSystemBackground ); setAutoFillBackground( false ); // cursor setCursor( Qt::SizeFDiagCursor ); // size setFixedSize( QSize( GRIP_SIZE, GRIP_SIZE ) ); // mask QPolygon p; p << QPoint( 0, GRIP_SIZE ) << QPoint( GRIP_SIZE, 0 ) << QPoint( GRIP_SIZE, GRIP_SIZE ) << QPoint( 0, GRIP_SIZE ); setMask( QRegion( p ) ); // embed embed(); updatePosition(); // event filter client->widget()->installEventFilter( this ); // show show(); } //_____________________________________________ SizeGrip::~SizeGrip( void ) {} //_____________________________________________ void SizeGrip::activeChange( void ) { XMapRaised( QX11Info::display(), winId() ); } //_____________________________________________ void SizeGrip::embed( void ) { WId window_id = client().windowId(); if( client().isPreview() ) { setParent( client().widget() ); } else if( window_id ) { WId current = window_id; while( true ) { WId root, parent = 0; WId *children = 0L; uint child_count = 0; XQueryTree(QX11Info::display(), current, &root, &parent, &children, &child_count); if( parent && parent != root && parent != current ) current = parent; else break; } // reparent XReparentWindow( QX11Info::display(), winId(), current, 0, 0 ); } else { hide(); } } //_____________________________________________ bool SizeGrip::eventFilter( QObject*, QEvent* event ) { if ( event->type() == QEvent::Resize) updatePosition(); return false; } //_____________________________________________ void SizeGrip::paintEvent( QPaintEvent* ) { // get relevant colors QColor base( client().backgroundColor( this, palette(), client().isActive() ) ); QColor light( client().helper().calcDarkColor( base ) ); QColor dark( client().helper().calcDarkColor( base.darker(150) ) ); // create and configure painter QPainter painter(this); painter.setRenderHints(QPainter::Antialiasing ); painter.setPen( Qt::NoPen ); painter.setBrush( base ); // polygon QPolygon p; p << QPoint( 0, GRIP_SIZE ) << QPoint( GRIP_SIZE, 0 ) << QPoint( GRIP_SIZE, GRIP_SIZE ) << QPoint( 0, GRIP_SIZE ); painter.drawPolygon( p ); // diagonal border painter.setBrush( Qt::NoBrush ); painter.setPen( QPen( dark, 3 ) ); painter.drawLine( QPoint( 0, GRIP_SIZE ), QPoint( GRIP_SIZE, 0 ) ); // side borders painter.setPen( QPen( light, 1.5 ) ); painter.drawLine( QPoint( 1, GRIP_SIZE ), QPoint( GRIP_SIZE, GRIP_SIZE ) ); painter.drawLine( QPoint( GRIP_SIZE, 1 ), QPoint( GRIP_SIZE, GRIP_SIZE ) ); painter.end(); } //_____________________________________________ void SizeGrip::mousePressEvent( QMouseEvent* event ) { switch (event->button()) { case Qt::RightButton: { hide(); QTimer::singleShot(5000, this, SLOT(show())); break; } case Qt::MidButton: { hide(); break; } case Qt::LeftButton: if( rect().contains( event->pos() ) ) { // check client window id if( !client().windowId() ) break; client().widget()->setFocus(); if( client().decoration() ) { client().decoration()->performWindowOperation( KDecorationDefines::ResizeOp ); } } break; default: break; } return; } //_______________________________________________________________________________ void SizeGrip::updatePosition( void ) { QPoint position( client().width() - GRIP_SIZE - OFFSET, client().height() - GRIP_SIZE - OFFSET ); if( client().isPreview() ) { position -= QPoint( client().layoutMetric( Client::LM_BorderRight )+ client().layoutMetric( Client::LM_OuterPaddingRight ), client().layoutMetric( Client::LM_OuterPaddingBottom )+ client().layoutMetric( Client::LM_BorderBottom ) ); } else { position -= QPoint( client().layoutMetric( Client::LM_BorderRight ), client().layoutMetric( Client::LM_BorderBottom ) ); } move( position ); } }
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows.Forms; namespace gokiTagDB { public class Settings { public static float[] zoomLevels = new float[7] { .25f, .50f, .75f, 1.0f, 1.25f, 1.5f, 2.0f }; public static int[] updateIntervals = new int[] { 15, 30, 100 }; private string fileFilter; public string FileFilter { get { return fileFilter; } set { fileFilter = value; } } private SortType sortType; public SortType SortType { get { return sortType; } set { sortType = value; } } private SelectionMode selectionMode; public SelectionMode SelectionMode { get { return selectionMode; } set { selectionMode = value; } } private int thumbnailWidth; public int ThumbnailWidth { get { return thumbnailWidth; } set { thumbnailWidth = value; } } private int thumbnailHeight; public int ThumbnailHeight { get { return thumbnailHeight; } set { thumbnailHeight = value; } } private int zoomIndex; public int ZoomIndex { get { return zoomIndex; } set { zoomIndex = value; } } private int updateInterval; public int UpdateInterval { get { return updateInterval; } set { updateInterval = value; } } private Padding panelPadding ; public Padding PanelPadding { get { return panelPadding; } set { panelPadding = value; } } private Padding entryMargin; public Padding EntryMargin { get { return entryMargin; } set { entryMargin = value; } } private Padding entryPadding; public Padding EntryPadding { get { return entryPadding; } set { entryPadding = value; } } private int borderSize; public int BorderSize { get { return borderSize; } set { borderSize = value; if (borderSize < 1) { borderSize = 1; } } } private long approximateMemoryUsage; public long ApproximateMemoryUsage { get { return approximateMemoryUsage; } set { approximateMemoryUsage = value; } } private int maximumSuggestions; public int MaximumSuggestions { get { return maximumSuggestions; } set { maximumSuggestions = value; } } private ThumbnailGenerationMethod thumbnailGenerationMethod; public ThumbnailGenerationMethod ThumbnailGenerationMethod { get { return thumbnailGenerationMethod; } set { thumbnailGenerationMethod = value; } } public Settings() { FileFilter = @".*(\.jpeg|\.jpg|\.png|\.gif|\.bmp|\.webm)"; SortType = SortType.Location; SelectionMode = SelectionMode.Explorer; ThumbnailWidth = 200; ThumbnailHeight = 200; ZoomIndex = 3; UpdateInterval = updateIntervals[0]; PanelPadding = new Padding(2); EntryMargin = new Padding(1); EntryPadding = new Padding(1); BorderSize = 1; ApproximateMemoryUsage = 100000000; MaximumSuggestions = 10; ThumbnailGenerationMethod = gokiTagDB.ThumbnailGenerationMethod.Smart; } } }
Java
using JBB.Model; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace JBB.DAL.EF { public class JBInitializer : System.Data.Entity.DropCreateDatabaseIfModelChanges<JBContext> { protected override void Seed(JBContext context) { //base.Seed(context); var companies = new List<Company> { new Company{Name="Haagi Mettals"}, new Company{Name="Morkels Manufacture Pty Ltd"} }; companies.ForEach(c => context.Companies.Add(c)); context.SaveChanges(); var offers = new List<Offer> { new Offer{Company=companies[0],ShortDescription="Motor Maintenance", LongDescription="A student is required to maintain electric motors for the companies manufacturing division."}, new Offer{Company=companies[0], ShortDescription="Quality Assurance", LongDescription="A student is required to test the diameter of the product. Tcl/Tk and basic electronic skills (soldering) required."}, new Offer{Company=companies[1], ShortDescription="Lathe Operator", LongDescription="Partime work to earn some extras cash by operating a lathe in our furniture workshop in Doornfontein."} }; offers.ForEach(o => context.Offers.Add(o)); context.SaveChanges(); } } }
Java
<link href="./resource/style/emoji.css" rel="stylesheet"> <style> .icon-selection h3{padding-left:1em;padding-bottom:0.2em} .icon-selection a{display:block;float:left;overflow:hidden;margin:3px;padding:5px;border:1px #EEE solid;} .icon-selection a:hover{text-decoration:none; border-color:rgb(66, 139, 202);} .icon-selection a i{display:block;font-size:2em;color:#000;} .icon-selection a span{display:block;width:20px;height:20px;overflow:hidden;word-break:break-all;} .icon-selection a > span{display:none;} </style> <script type="text/javascript"> function insertEmoji(obj) { var subindex = $('#menu-index').attr('data-subindex'); if (subindex == '') { var title = $('.menu').eq($('#menu-index').val()).find('input')[0]; } else { var title = $('.submenu').eq($('#menu-index').val()).find('input').eq(subindex)[0]; } if (title.selectionStart == 0) { title.selectionStart = title.value.length; } title.focus(); var unshift = '::' + obj.find('span').text() + '::'; var newstart = title.selectionStart + unshift.length; var insertval = title.value.substr(0,title.selectionStart) + unshift + title.value.substring(title.selectionEnd); title.value = insertval; title.selectionStart = newstart; title.selectionEnd = newstart; w = selectEmoji(); w.modal('hide'); } </script> <div class="icon-selection"> <div class="clearfix"> <a href='javascript:;' onClick="insertEmoji($(this));" title="black sun with rays"><div><span class="emoji emoji2600"></span></div><span>2600</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cloud"><div><span class="emoji emoji2601"></span></div><span>2601</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="umbrella with rain drops"><div><span class="emoji emoji2614"></span></div><span>2614</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="snowman without snow"><div><span class="emoji emoji26c4"></span></div><span>26C4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="high voltage sign"><div><span class="emoji emoji26a1"></span></div><span>26A1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cyclone"><div><span class="emoji emoji1f300"></span></div><span>1F300</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="foggy"><div><span class="emoji emoji1f301"></span></div><span>1F301</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="closed umbrella"><div><span class="emoji emoji1f302"></span></div><span>1F302</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="night with stars"><div><span class="emoji emoji1f303"></span></div><span>1F303</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sunrise over mountains"><div><span class="emoji emoji1f304"></span></div><span>1F304</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sunrise"><div><span class="emoji emoji1f305"></span></div><span>1F305</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cityscape at dusk"><div><span class="emoji emoji1f306"></span></div><span>1F306</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sunset over buildings"><div><span class="emoji emoji1f307"></span></div><span>1F307</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rainbow"><div><span class="emoji emoji1f308"></span></div><span>1F308</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="snowflake"><div><span class="emoji emoji2744"></span></div><span>2744</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sun behind cloud"><div><span class="emoji emoji26c5"></span></div><span>26C5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bridge at night"><div><span class="emoji emoji1f309"></span></div><span>1F309</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="water wave"><div><span class="emoji emoji1f30a"></span></div><span>1F30A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="volcano"><div><span class="emoji emoji1f30b"></span></div><span>1F30B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="milky way"><div><span class="emoji emoji1f30c"></span></div><span>1F30C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="earth globe asia-australia"><div><span class="emoji emoji1f30f"></span></div><span>1F30F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="new moon symbol"><div><span class="emoji emoji1f311"></span></div><span>1F311</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="waxing gibbous moon symbol"><div><span class="emoji emoji1f314"></span></div><span>1F314</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="first quarter moon symbol"><div><span class="emoji emoji1f313"></span></div><span>1F313</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crescent moon"><div><span class="emoji emoji1f319"></span></div><span>1F319</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="full moon symbol"><div><span class="emoji emoji1f315"></span></div><span>1F315</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="first quarter moon with face"><div><span class="emoji emoji1f31b"></span></div><span>1F31B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="glowing star"><div><span class="emoji emoji1f31f"></span></div><span>1F31F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="shooting star"><div><span class="emoji emoji1f320"></span></div><span>1F320</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face one oclock"><div><span class="emoji emoji1f550"></span></div><span>1F550</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face two oclock"><div><span class="emoji emoji1f551"></span></div><span>1F551</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face three oclock"><div><span class="emoji emoji1f552"></span></div><span>1F552</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face four oclock"><div><span class="emoji emoji1f553"></span></div><span>1F553</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face five oclock"><div><span class="emoji emoji1f554"></span></div><span>1F554</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face six oclock"><div><span class="emoji emoji1f555"></span></div><span>1F555</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face seven oclock"><div><span class="emoji emoji1f556"></span></div><span>1F556</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face eight oclock"><div><span class="emoji emoji1f557"></span></div><span>1F557</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face nine oclock"><div><span class="emoji emoji1f558"></span></div><span>1F558</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face ten oclock"><div><span class="emoji emoji1f559"></span></div><span>1F559</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face eleven oclock"><div><span class="emoji emoji1f55a"></span></div><span>1F55A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clock face twelve oclock"><div><span class="emoji emoji1f55b"></span></div><span>1F55B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="watch"><div><span class="emoji emoji231a"></span></div><span>231A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hourglass"><div><span class="emoji emoji231b"></span></div><span>231B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="alarm clock"><div><span class="emoji emoji23f0"></span></div><span>23F0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hourglass with flowing sand"><div><span class="emoji emoji23f3"></span></div><span>23F3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="aries"><div><span class="emoji emoji2648"></span></div><span>2648</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="taurus"><div><span class="emoji emoji2649"></span></div><span>2649</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="gemini"><div><span class="emoji emoji264a"></span></div><span>264A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cancer"><div><span class="emoji emoji264b"></span></div><span>264B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="leo"><div><span class="emoji emoji264c"></span></div><span>264C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="virgo"><div><span class="emoji emoji264d"></span></div><span>264D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="libra"><div><span class="emoji emoji264e"></span></div><span>264E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="scorpius"><div><span class="emoji emoji264f"></span></div><span>264F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sagittarius"><div><span class="emoji emoji2650"></span></div><span>2650</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="capricorn"><div><span class="emoji emoji2651"></span></div><span>2651</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="aquarius"><div><span class="emoji emoji2652"></span></div><span>2652</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pisces"><div><span class="emoji emoji2653"></span></div><span>2653</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ophiuchus"><div><span class="emoji emoji26ce"></span></div><span>26CE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="four leaf clover"><div><span class="emoji emoji1f340"></span></div><span>1F340</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tulip"><div><span class="emoji emoji1f337"></span></div><span>1F337</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="seedling"><div><span class="emoji emoji1f331"></span></div><span>1F331</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="maple leaf"><div><span class="emoji emoji1f341"></span></div><span>1F341</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cherry blossom"><div><span class="emoji emoji1f338"></span></div><span>1F338</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rose"><div><span class="emoji emoji1f339"></span></div><span>1F339</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fallen leaf"><div><span class="emoji emoji1f342"></span></div><span>1F342</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="leaf fluttering in wind"><div><span class="emoji emoji1f343"></span></div><span>1F343</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hibiscus"><div><span class="emoji emoji1f33a"></span></div><span>1F33A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sunflower"><div><span class="emoji emoji1f33b"></span></div><span>1F33B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="palm tree"><div><span class="emoji emoji1f334"></span></div><span>1F334</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cactus"><div><span class="emoji emoji1f335"></span></div><span>1F335</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ear of rice"><div><span class="emoji emoji1f33e"></span></div><span>1F33E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ear of maize"><div><span class="emoji emoji1f33d"></span></div><span>1F33D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mushroom"><div><span class="emoji emoji1f344"></span></div><span>1F344</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chestnut"><div><span class="emoji emoji1f330"></span></div><span>1F330</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="blossom"><div><span class="emoji emoji1f33c"></span></div><span>1F33C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="herb"><div><span class="emoji emoji1f33f"></span></div><span>1F33F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cherries"><div><span class="emoji emoji1f352"></span></div><span>1F352</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="banana"><div><span class="emoji emoji1f34c"></span></div><span>1F34C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="red apple"><div><span class="emoji emoji1f34e"></span></div><span>1F34E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tangerine"><div><span class="emoji emoji1f34a"></span></div><span>1F34A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="strawberry"><div><span class="emoji emoji1f353"></span></div><span>1F353</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="watermelon"><div><span class="emoji emoji1f349"></span></div><span>1F349</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tomato"><div><span class="emoji emoji1f345"></span></div><span>1F345</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="aubergine"><div><span class="emoji emoji1f346"></span></div><span>1F346</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="melon"><div><span class="emoji emoji1f348"></span></div><span>1F348</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pineapple"><div><span class="emoji emoji1f34d"></span></div><span>1F34D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="grapes"><div><span class="emoji emoji1f347"></span></div><span>1F347</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="peach"><div><span class="emoji emoji1f351"></span></div><span>1F351</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="green apple"><div><span class="emoji emoji1f34f"></span></div><span>1F34F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="eyes"><div><span class="emoji emoji1f440"></span></div><span>1F440</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ear"><div><span class="emoji emoji1f442"></span></div><span>1F442</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="nose"><div><span class="emoji emoji1f443"></span></div><span>1F443</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mouth"><div><span class="emoji emoji1f444"></span></div><span>1F444</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tongue"><div><span class="emoji emoji1f445"></span></div><span>1F445</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="lipstick"><div><span class="emoji emoji1f484"></span></div><span>1F484</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="nail polish"><div><span class="emoji emoji1f485"></span></div><span>1F485</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face massage"><div><span class="emoji emoji1f486"></span></div><span>1F486</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="haircut"><div><span class="emoji emoji1f487"></span></div><span>1F487</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="barber pole"><div><span class="emoji emoji1f488"></span></div><span>1F488</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bust in silhouette"><div><span class="emoji emoji1f464"></span></div><span>1F464</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="boy"><div><span class="emoji emoji1f466"></span></div><span>1F466</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="girl"><div><span class="emoji emoji1f467"></span></div><span>1F467</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="man"><div><span class="emoji emoji1f468"></span></div><span>1F468</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="woman"><div><span class="emoji emoji1f469"></span></div><span>1F469</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="family"><div><span class="emoji emoji1f46a"></span></div><span>1F46A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="man and woman holding hands"><div><span class="emoji emoji1f46b"></span></div><span>1F46B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="police officer"><div><span class="emoji emoji1f46e"></span></div><span>1F46E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="woman with bunny ears"><div><span class="emoji emoji1f46f"></span></div><span>1F46F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bride with veil"><div><span class="emoji emoji1f470"></span></div><span>1F470</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person with blond hair"><div><span class="emoji emoji1f471"></span></div><span>1F471</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="man with gua pi mao"><div><span class="emoji emoji1f472"></span></div><span>1F472</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="man with turban"><div><span class="emoji emoji1f473"></span></div><span>1F473</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="older man"><div><span class="emoji emoji1f474"></span></div><span>1F474</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="older woman"><div><span class="emoji emoji1f475"></span></div><span>1F475</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="baby"><div><span class="emoji emoji1f476"></span></div><span>1F476</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="construction worker"><div><span class="emoji emoji1f477"></span></div><span>1F477</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="princess"><div><span class="emoji emoji1f478"></span></div><span>1F478</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese ogre"><div><span class="emoji emoji1f479"></span></div><span>1F479</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese goblin"><div><span class="emoji emoji1f47a"></span></div><span>1F47A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ghost"><div><span class="emoji emoji1f47b"></span></div><span>1F47B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="baby angel"><div><span class="emoji emoji1f47c"></span></div><span>1F47C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="extraterrestrial alien"><div><span class="emoji emoji1f47d"></span></div><span>1F47D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="alien monster"><div><span class="emoji emoji1f47e"></span></div><span>1F47E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="imp"><div><span class="emoji emoji1f47f"></span></div><span>1F47F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="skull"><div><span class="emoji emoji1f480"></span></div><span>1F480</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="information desk person"><div><span class="emoji emoji1f481"></span></div><span>1F481</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="guardsman"><div><span class="emoji emoji1f482"></span></div><span>1F482</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dancer"><div><span class="emoji emoji1f483"></span></div><span>1F483</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="snail"><div><span class="emoji emoji1f40c"></span></div><span>1F40C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="snake"><div><span class="emoji emoji1f40d"></span></div><span>1F40D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="horse"><div><span class="emoji emoji1f40e"></span></div><span>1F40E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chicken"><div><span class="emoji emoji1f414"></span></div><span>1F414</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="boar"><div><span class="emoji emoji1f417"></span></div><span>1F417</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bactrian camel"><div><span class="emoji emoji1f42b"></span></div><span>1F42B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="elephant"><div><span class="emoji emoji1f418"></span></div><span>1F418</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="koala"><div><span class="emoji emoji1f428"></span></div><span>1F428</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="monkey"><div><span class="emoji emoji1f412"></span></div><span>1F412</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sheep"><div><span class="emoji emoji1f411"></span></div><span>1F411</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="octopus"><div><span class="emoji emoji1f419"></span></div><span>1F419</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="spiral shell"><div><span class="emoji emoji1f41a"></span></div><span>1F41A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bug"><div><span class="emoji emoji1f41b"></span></div><span>1F41B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ant"><div><span class="emoji emoji1f41c"></span></div><span>1F41C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="honeybee"><div><span class="emoji emoji1f41d"></span></div><span>1F41D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="lady beetle"><div><span class="emoji emoji1f41e"></span></div><span>1F41E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tropical fish"><div><span class="emoji emoji1f420"></span></div><span>1F420</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="blowfish"><div><span class="emoji emoji1f421"></span></div><span>1F421</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="turtle"><div><span class="emoji emoji1f422"></span></div><span>1F422</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="baby chick"><div><span class="emoji emoji1f424"></span></div><span>1F424</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="front-facing baby chick"><div><span class="emoji emoji1f425"></span></div><span>1F425</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bird"><div><span class="emoji emoji1f426"></span></div><span>1F426</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hatching chick"><div><span class="emoji emoji1f423"></span></div><span>1F423</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="penguin"><div><span class="emoji emoji1f427"></span></div><span>1F427</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="poodle"><div><span class="emoji emoji1f429"></span></div><span>1F429</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fish"><div><span class="emoji emoji1f41f"></span></div><span>1F41F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dolphin"><div><span class="emoji emoji1f42c"></span></div><span>1F42C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mouse face"><div><span class="emoji emoji1f42d"></span></div><span>1F42D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tiger face"><div><span class="emoji emoji1f42f"></span></div><span>1F42F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cat face"><div><span class="emoji emoji1f431"></span></div><span>1F431</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="spouting whale"><div><span class="emoji emoji1f433"></span></div><span>1F433</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="horse face"><div><span class="emoji emoji1f434"></span></div><span>1F434</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="monkey face"><div><span class="emoji emoji1f435"></span></div><span>1F435</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dog face"><div><span class="emoji emoji1f436"></span></div><span>1F436</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pig face"><div><span class="emoji emoji1f437"></span></div><span>1F437</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bear face"><div><span class="emoji emoji1f43b"></span></div><span>1F43B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hamster face"><div><span class="emoji emoji1f439"></span></div><span>1F439</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wolf face"><div><span class="emoji emoji1f43a"></span></div><span>1F43A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cow face"><div><span class="emoji emoji1f42e"></span></div><span>1F42E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rabbit face"><div><span class="emoji emoji1f430"></span></div><span>1F430</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="frog face"><div><span class="emoji emoji1f438"></span></div><span>1F438</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="paw prints"><div><span class="emoji emoji1f43e"></span></div><span>1F43E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dragon face"><div><span class="emoji emoji1f432"></span></div><span>1F432</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="panda face"><div><span class="emoji emoji1f43c"></span></div><span>1F43C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pig nose"><div><span class="emoji emoji1f43d"></span></div><span>1F43D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="angry face"><div><span class="emoji emoji1f620"></span></div><span>1F620</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="weary face"><div><span class="emoji emoji1f629"></span></div><span>1F629</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="astonished face"><div><span class="emoji emoji1f632"></span></div><span>1F632</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="disappointed face"><div><span class="emoji emoji1f61e"></span></div><span>1F61E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dizzy face"><div><span class="emoji emoji1f635"></span></div><span>1F635</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with open mouth and cold sweat"><div><span class="emoji emoji1f630"></span></div><span>1F630</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="unamused face"><div><span class="emoji emoji1f612"></span></div><span>1F612</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with heart-shaped eyes"><div><span class="emoji emoji1f60d"></span></div><span>1F60D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with look of triumph"><div><span class="emoji emoji1f624"></span></div><span>1F624</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with stuck-out tongue and winking eye"><div><span class="emoji emoji1f61c"></span></div><span>1F61C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with stuck-out tongue and tightly-closed eyes"><div><span class="emoji emoji1f61d"></span></div><span>1F61D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face savouring delicious food"><div><span class="emoji emoji1f60b"></span></div><span>1F60B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face throwing a kiss"><div><span class="emoji emoji1f618"></span></div><span>1F618</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="kissing face with closed eyes"><div><span class="emoji emoji1f61a"></span></div><span>1F61A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with medical mask"><div><span class="emoji emoji1f637"></span></div><span>1F637</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="flushed face"><div><span class="emoji emoji1f633"></span></div><span>1F633</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with open mouth"><div><span class="emoji emoji1f603"></span></div><span>1F603</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with open mouth and cold sweat"><div><span class="emoji emoji1f605"></span></div><span>1F605</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with open mouth and tightly-closed eyes"><div><span class="emoji emoji1f606"></span></div><span>1F606</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="grinning face with smiling eyes"><div><span class="emoji emoji1f601"></span></div><span>1F601</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with tears of joy"><div><span class="emoji emoji1f602"></span></div><span>1F602</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with smiling eyes"><div><span class="emoji emoji1f60a"></span></div><span>1F60A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white smiling face"><div><span class="emoji emoji263a"></span></div><span>263A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling face with open mouth and smiling eyes"><div><span class="emoji emoji1f604"></span></div><span>1F604</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crying face"><div><span class="emoji emoji1f622"></span></div><span>1F622</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="loudly crying face"><div><span class="emoji emoji1f62d"></span></div><span>1F62D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fearful face"><div><span class="emoji emoji1f628"></span></div><span>1F628</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="persevering face"><div><span class="emoji emoji1f623"></span></div><span>1F623</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pouting face"><div><span class="emoji emoji1f621"></span></div><span>1F621</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="relieved face"><div><span class="emoji emoji1f60c"></span></div><span>1F60C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="confounded face"><div><span class="emoji emoji1f616"></span></div><span>1F616</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pensive face"><div><span class="emoji emoji1f614"></span></div><span>1F614</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face screaming in fear"><div><span class="emoji emoji1f631"></span></div><span>1F631</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sleepy face"><div><span class="emoji emoji1f62a"></span></div><span>1F62A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smirking face"><div><span class="emoji emoji1f60f"></span></div><span>1F60F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with cold sweat"><div><span class="emoji emoji1f613"></span></div><span>1F613</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="disappointed but relieved face"><div><span class="emoji emoji1f625"></span></div><span>1F625</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tired face"><div><span class="emoji emoji1f62b"></span></div><span>1F62B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="winking face"><div><span class="emoji emoji1f609"></span></div><span>1F609</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling cat face with open mouth"><div><span class="emoji emoji1f63a"></span></div><span>1F63A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="grinning cat face with smiling eyes"><div><span class="emoji emoji1f638"></span></div><span>1F638</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cat face with tears of joy"><div><span class="emoji emoji1f639"></span></div><span>1F639</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="kissing cat face with closed eyes"><div><span class="emoji emoji1f63d"></span></div><span>1F63D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smiling cat face with heart-shaped eyes"><div><span class="emoji emoji1f63b"></span></div><span>1F63B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crying cat face"><div><span class="emoji emoji1f63f"></span></div><span>1F63F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pouting cat face"><div><span class="emoji emoji1f63e"></span></div><span>1F63E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cat face with wry smile"><div><span class="emoji emoji1f63c"></span></div><span>1F63C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="weary cat face"><div><span class="emoji emoji1f640"></span></div><span>1F640</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with no good gesture"><div><span class="emoji emoji1f645"></span></div><span>1F645</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="face with ok gesture"><div><span class="emoji emoji1f646"></span></div><span>1F646</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person bowing deeply"><div><span class="emoji emoji1f647"></span></div><span>1F647</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="see-no-evil monkey"><div><span class="emoji emoji1f648"></span></div><span>1F648</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="speak-no-evil monkey"><div><span class="emoji emoji1f64a"></span></div><span>1F64A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hear-no-evil monkey"><div><span class="emoji emoji1f649"></span></div><span>1F649</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="happy person raising one hand"><div><span class="emoji emoji1f64b"></span></div><span>1F64B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person raising both hands in celebration"><div><span class="emoji emoji1f64c"></span></div><span>1F64C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person frowning"><div><span class="emoji emoji1f64d"></span></div><span>1F64D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person with pouting face"><div><span class="emoji emoji1f64e"></span></div><span>1F64E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="person with folded hands"><div><span class="emoji emoji1f64f"></span></div><span>1F64F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="house building"><div><span class="emoji emoji1f3e0"></span></div><span>1F3E0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="house with garden"><div><span class="emoji emoji1f3e1"></span></div><span>1F3E1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="office building"><div><span class="emoji emoji1f3e2"></span></div><span>1F3E2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese post office"><div><span class="emoji emoji1f3e3"></span></div><span>1F3E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hospital"><div><span class="emoji emoji1f3e5"></span></div><span>1F3E5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bank"><div><span class="emoji emoji1f3e6"></span></div><span>1F3E6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="automated teller machine"><div><span class="emoji emoji1f3e7"></span></div><span>1F3E7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hotel"><div><span class="emoji emoji1f3e8"></span></div><span>1F3E8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="love hotel"><div><span class="emoji emoji1f3e9"></span></div><span>1F3E9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="convenience store"><div><span class="emoji emoji1f3ea"></span></div><span>1F3EA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="school"><div><span class="emoji emoji1f3eb"></span></div><span>1F3EB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="church"><div><span class="emoji emoji26ea"></span></div><span>26EA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fountain"><div><span class="emoji emoji26f2"></span></div><span>26F2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="department store"><div><span class="emoji emoji1f3ec"></span></div><span>1F3EC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese castle"><div><span class="emoji emoji1f3ef"></span></div><span>1F3EF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="european castle"><div><span class="emoji emoji1f3f0"></span></div><span>1F3F0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="factory"><div><span class="emoji emoji1f3ed"></span></div><span>1F3ED</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="anchor"><div><span class="emoji emoji2693"></span></div><span>2693</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="izakaya lantern"><div><span class="emoji emoji1f3ee"></span></div><span>1F3EE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mount fuji"><div><span class="emoji emoji1f5fb"></span></div><span>1F5FB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tokyo tower"><div><span class="emoji emoji1f5fc"></span></div><span>1F5FC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="statue of liberty"><div><span class="emoji emoji1f5fd"></span></div><span>1F5FD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="silhouette of japan"><div><span class="emoji emoji1f5fe"></span></div><span>1F5FE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="moyai"><div><span class="emoji emoji1f5ff"></span></div><span>1F5FF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mans shoe"><div><span class="emoji emoji1f45e"></span></div><span>1F45E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="athletic shoe"><div><span class="emoji emoji1f45f"></span></div><span>1F45F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="high-heeled shoe"><div><span class="emoji emoji1f460"></span></div><span>1F460</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="womans sandal"><div><span class="emoji emoji1f461"></span></div><span>1F461</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="womans boots"><div><span class="emoji emoji1f462"></span></div><span>1F462</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="footprints"><div><span class="emoji emoji1f463"></span></div><span>1F463</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="eyeglasses"><div><span class="emoji emoji1f453"></span></div><span>1F453</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="t-shirt"><div><span class="emoji emoji1f455"></span></div><span>1F455</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="jeans"><div><span class="emoji emoji1f456"></span></div><span>1F456</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crown"><div><span class="emoji emoji1f451"></span></div><span>1F451</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="necktie"><div><span class="emoji emoji1f454"></span></div><span>1F454</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="womans hat"><div><span class="emoji emoji1f452"></span></div><span>1F452</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dress"><div><span class="emoji emoji1f457"></span></div><span>1F457</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="kimono"><div><span class="emoji emoji1f458"></span></div><span>1F458</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bikini"><div><span class="emoji emoji1f459"></span></div><span>1F459</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="womans clothes"><div><span class="emoji emoji1f45a"></span></div><span>1F45A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="purse"><div><span class="emoji emoji1f45b"></span></div><span>1F45B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="handbag"><div><span class="emoji emoji1f45c"></span></div><span>1F45C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pouch"><div><span class="emoji emoji1f45d"></span></div><span>1F45D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="money bag"><div><span class="emoji emoji1f4b0"></span></div><span>1F4B0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="currency exchange"><div><span class="emoji emoji1f4b1"></span></div><span>1F4B1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chart with upwards trend and yen sign"><div><span class="emoji emoji1f4b9"></span></div><span>1F4B9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy dollar sign"><div><span class="emoji emoji1f4b2"></span></div><span>1F4B2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="credit card"><div><span class="emoji emoji1f4b3"></span></div><span>1F4B3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="banknote with yen sign"><div><span class="emoji emoji1f4b4"></span></div><span>1F4B4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="banknote with dollar sign"><div><span class="emoji emoji1f4b5"></span></div><span>1F4B5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="money with wings"><div><span class="emoji emoji1f4b8"></span></div><span>1F4B8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters cn"><div><span class="emoji emoji1f1e81f1f3"></span></div><span>1F1E8 U+1F1F3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters de"><div><span class="emoji emoji1f1e91f1ea"></span></div><span>1F1E9 U+1F1EA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters es"><div><span class="emoji emoji1f1ea1f1f8"></span></div><span>1F1EA U+1F1F8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters fr"><div><span class="emoji emoji1f1eb1f1f7"></span></div><span>1F1EB U+1F1F7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters gb"><div><span class="emoji emoji1f1ec1f1e7"></span></div><span>1F1EC U+1F1E7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters it"><div><span class="emoji emoji1f1ee1f1f9"></span></div><span>1F1EE U+1F1F9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters jp"><div><span class="emoji emoji1f1ef1f1f5"></span></div><span>1F1EF U+1F1F5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters kr"><div><span class="emoji emoji1f1f01f1f7"></span></div><span>1F1F0 U+1F1F7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters ru"><div><span class="emoji emoji1f1f71f1fa"></span></div><span>1F1F7 U+1F1FA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="regional indicator symbol letters us"><div><span class="emoji emoji1f1fa1f1f8"></span></div><span>1F1FA U+1F1F8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fire"><div><span class="emoji emoji1f525"></span></div><span>1F525</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="electric torch"><div><span class="emoji emoji1f526"></span></div><span>1F526</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wrench"><div><span class="emoji emoji1f527"></span></div><span>1F527</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hammer"><div><span class="emoji emoji1f528"></span></div><span>1F528</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="nut and bolt"><div><span class="emoji emoji1f529"></span></div><span>1F529</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hocho"><div><span class="emoji emoji1f52a"></span></div><span>1F52A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pistol"><div><span class="emoji emoji1f52b"></span></div><span>1F52B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crystal ball"><div><span class="emoji emoji1f52e"></span></div><span>1F52E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="six pointed star with middle dot"><div><span class="emoji emoji1f52f"></span></div><span>1F52F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese symbol for beginner"><div><span class="emoji emoji1f530"></span></div><span>1F530</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="trident emblem"><div><span class="emoji emoji1f531"></span></div><span>1F531</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="syringe"><div><span class="emoji emoji1f489"></span></div><span>1F489</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pill"><div><span class="emoji emoji1f48a"></span></div><span>1F48A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared latin capital letter a"><div><span class="emoji emoji1f170"></span></div><span>1F170</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared latin capital letter b"><div><span class="emoji emoji1f171"></span></div><span>1F171</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared ab"><div><span class="emoji emoji1f18e"></span></div><span>1F18E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared latin capital letter o"><div><span class="emoji emoji1f17e"></span></div><span>1F17E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ribbon"><div><span class="emoji emoji1f380"></span></div><span>1F380</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wrapped present"><div><span class="emoji emoji1f381"></span></div><span>1F381</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="birthday cake"><div><span class="emoji emoji1f382"></span></div><span>1F382</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="christmas tree"><div><span class="emoji emoji1f384"></span></div><span>1F384</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="father christmas"><div><span class="emoji emoji1f385"></span></div><span>1F385</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="crossed flags"><div><span class="emoji emoji1f38c"></span></div><span>1F38C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fireworks"><div><span class="emoji emoji1f386"></span></div><span>1F386</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="balloon"><div><span class="emoji emoji1f388"></span></div><span>1F388</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="party popper"><div><span class="emoji emoji1f389"></span></div><span>1F389</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pine decoration"><div><span class="emoji emoji1f38d"></span></div><span>1F38D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="japanese dolls"><div><span class="emoji emoji1f38e"></span></div><span>1F38E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="graduation cap"><div><span class="emoji emoji1f393"></span></div><span>1F393</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="school satchel"><div><span class="emoji emoji1f392"></span></div><span>1F392</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="carp streamer"><div><span class="emoji emoji1f38f"></span></div><span>1F38F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="firework sparkler"><div><span class="emoji emoji1f387"></span></div><span>1F387</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wind chime"><div><span class="emoji emoji1f390"></span></div><span>1F390</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="jack-o-lantern"><div><span class="emoji emoji1f383"></span></div><span>1F383</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="confetti ball"><div><span class="emoji emoji1f38a"></span></div><span>1F38A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tanabata tree"><div><span class="emoji emoji1f38b"></span></div><span>1F38B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="moon viewing ceremony"><div><span class="emoji emoji1f391"></span></div><span>1F391</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pager"><div><span class="emoji emoji1f4df"></span></div><span>1F4DF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black telephone"><div><span class="emoji emoji260e"></span></div><span>260E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="telephone receiver"><div><span class="emoji emoji1f4de"></span></div><span>1F4DE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mobile phone"><div><span class="emoji emoji1f4f1"></span></div><span>1F4F1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mobile phone with rightwards arrow at left"><div><span class="emoji emoji1f4f2"></span></div><span>1F4F2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="memo"><div><span class="emoji emoji1f4dd"></span></div><span>1F4DD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fax machine"><div><span class="emoji emoji1f4e0"></span></div><span>1F4E0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="envelope"><div><span class="emoji emoji2709"></span></div><span>2709</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="incoming envelope"><div><span class="emoji emoji1f4e8"></span></div><span>1F4E8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="envelope with downwards arrow above"><div><span class="emoji emoji1f4e9"></span></div><span>1F4E9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="closed mailbox with lowered flag"><div><span class="emoji emoji1f4ea"></span></div><span>1F4EA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="closed mailbox with raised flag"><div><span class="emoji emoji1f4eb"></span></div><span>1F4EB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="postbox"><div><span class="emoji emoji1f4ee"></span></div><span>1F4EE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="newspaper"><div><span class="emoji emoji1f4f0"></span></div><span>1F4F0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="public address loudspeaker"><div><span class="emoji emoji1f4e2"></span></div><span>1F4E2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cheering megaphone"><div><span class="emoji emoji1f4e3"></span></div><span>1F4E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="satellite antenna"><div><span class="emoji emoji1f4e1"></span></div><span>1F4E1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="outbox tray"><div><span class="emoji emoji1f4e4"></span></div><span>1F4E4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="inbox tray"><div><span class="emoji emoji1f4e5"></span></div><span>1F4E5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="package"><div><span class="emoji emoji1f4e6"></span></div><span>1F4E6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="e-mail symbol"><div><span class="emoji emoji1f4e7"></span></div><span>1F4E7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="input symbol for latin capital letters"><div><span class="emoji emoji1f520"></span></div><span>1F520</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="input symbol for latin small letters"><div><span class="emoji emoji1f521"></span></div><span>1F521</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="input symbol for numbers"><div><span class="emoji emoji1f522"></span></div><span>1F522</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="input symbol for symbols"><div><span class="emoji emoji1f523"></span></div><span>1F523</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="input symbol for latin letters"><div><span class="emoji emoji1f524"></span></div><span>1F524</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black nib"><div><span class="emoji emoji2712"></span></div><span>2712</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="seat"><div><span class="emoji emoji1f4ba"></span></div><span>1F4BA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="personal computer"><div><span class="emoji emoji1f4bb"></span></div><span>1F4BB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pencil"><div><span class="emoji emoji270f"></span></div><span>270F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="paperclip"><div><span class="emoji emoji1f4ce"></span></div><span>1F4CE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="briefcase"><div><span class="emoji emoji1f4bc"></span></div><span>1F4BC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="minidisc"><div><span class="emoji emoji1f4bd"></span></div><span>1F4BD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="floppy disk"><div><span class="emoji emoji1f4be"></span></div><span>1F4BE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="optical disc"><div><span class="emoji emoji1f4bf"></span></div><span>1F4BF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dvd"><div><span class="emoji emoji1f4c0"></span></div><span>1F4C0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black scissors"><div><span class="emoji emoji2702"></span></div><span>2702</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="round pushpin"><div><span class="emoji emoji1f4cd"></span></div><span>1F4CD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="page with curl"><div><span class="emoji emoji1f4c3"></span></div><span>1F4C3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="page facing up"><div><span class="emoji emoji1f4c4"></span></div><span>1F4C4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="calendar"><div><span class="emoji emoji1f4c5"></span></div><span>1F4C5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="file folder"><div><span class="emoji emoji1f4c1"></span></div><span>1F4C1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="open file folder"><div><span class="emoji emoji1f4c2"></span></div><span>1F4C2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="notebook"><div><span class="emoji emoji1f4d3"></span></div><span>1F4D3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="open book"><div><span class="emoji emoji1f4d6"></span></div><span>1F4D6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="notebook with decorative cover"><div><span class="emoji emoji1f4d4"></span></div><span>1F4D4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="closed book"><div><span class="emoji emoji1f4d5"></span></div><span>1F4D5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="green book"><div><span class="emoji emoji1f4d7"></span></div><span>1F4D7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="blue book"><div><span class="emoji emoji1f4d8"></span></div><span>1F4D8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="orange book"><div><span class="emoji emoji1f4d9"></span></div><span>1F4D9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="books"><div><span class="emoji emoji1f4da"></span></div><span>1F4DA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="name badge"><div><span class="emoji emoji1f4db"></span></div><span>1F4DB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="scroll"><div><span class="emoji emoji1f4dc"></span></div><span>1F4DC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clipboard"><div><span class="emoji emoji1f4cb"></span></div><span>1F4CB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tear-off calendar"><div><span class="emoji emoji1f4c6"></span></div><span>1F4C6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bar chart"><div><span class="emoji emoji1f4ca"></span></div><span>1F4CA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chart with upwards trend"><div><span class="emoji emoji1f4c8"></span></div><span>1F4C8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chart with downwards trend"><div><span class="emoji emoji1f4c9"></span></div><span>1F4C9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="card index"><div><span class="emoji emoji1f4c7"></span></div><span>1F4C7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pushpin"><div><span class="emoji emoji1f4cc"></span></div><span>1F4CC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ledger"><div><span class="emoji emoji1f4d2"></span></div><span>1F4D2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="straight ruler"><div><span class="emoji emoji1f4cf"></span></div><span>1F4CF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="triangular ruler"><div><span class="emoji emoji1f4d0"></span></div><span>1F4D0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bookmark tabs"><div><span class="emoji emoji1f4d1"></span></div><span>1F4D1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="running shirt with sash"><div><span class="emoji emoji1f3bd"></span></div><span>1F3BD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="baseball"><div><span class="emoji emoji26be"></span></div><span>26BE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="flag in hole"><div><span class="emoji emoji26f3"></span></div><span>26F3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tennis racquet and ball"><div><span class="emoji emoji1f3be"></span></div><span>1F3BE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="soccer ball"><div><span class="emoji emoji26bd"></span></div><span>26BD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ski and ski boot"><div><span class="emoji emoji1f3bf"></span></div><span>1F3BF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="basketball and hoop"><div><span class="emoji emoji1f3c0"></span></div><span>1F3C0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chequered flag"><div><span class="emoji emoji1f3c1"></span></div><span>1F3C1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="snowboarder"><div><span class="emoji emoji1f3c2"></span></div><span>1F3C2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="runner"><div><span class="emoji emoji1f3c3"></span></div><span>1F3C3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="surfer"><div><span class="emoji emoji1f3c4"></span></div><span>1F3C4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="trophy"><div><span class="emoji emoji1f3c6"></span></div><span>1F3C6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="american football"><div><span class="emoji emoji1f3c8"></span></div><span>1F3C8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="swimmer"><div><span class="emoji emoji1f3ca"></span></div><span>1F3CA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="railway car"><div><span class="emoji emoji1f683"></span></div><span>1F683</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="metro"><div><span class="emoji emoji1f687"></span></div><span>1F687</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circled latin capital letter m"><div><span class="emoji emoji24c2"></span></div><span>24C2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="high-speed train"><div><span class="emoji emoji1f684"></span></div><span>1F684</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="high-speed train with bullet nose"><div><span class="emoji emoji1f685"></span></div><span>1F685</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="automobile"><div><span class="emoji emoji1f697"></span></div><span>1F697</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="recreational vehicle"><div><span class="emoji emoji1f699"></span></div><span>1F699</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bus"><div><span class="emoji emoji1f68c"></span></div><span>1F68C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bus stop"><div><span class="emoji emoji1f68f"></span></div><span>1F68F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ship"><div><span class="emoji emoji1f6a2"></span></div><span>1F6A2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="airplane"><div><span class="emoji emoji2708"></span></div><span>2708</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sailboat"><div><span class="emoji emoji26f5"></span></div><span>26F5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="station"><div><span class="emoji emoji1f689"></span></div><span>1F689</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rocket"><div><span class="emoji emoji1f680"></span></div><span>1F680</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="speedboat"><div><span class="emoji emoji1f6a4"></span></div><span>1F6A4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="taxi"><div><span class="emoji emoji1f695"></span></div><span>1F695</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="delivery truck"><div><span class="emoji emoji1f69a"></span></div><span>1F69A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fire engine"><div><span class="emoji emoji1f692"></span></div><span>1F692</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ambulance"><div><span class="emoji emoji1f691"></span></div><span>1F691</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="police car"><div><span class="emoji emoji1f693"></span></div><span>1F693</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fuel pump"><div><span class="emoji emoji26fd"></span></div><span>26FD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared latin capital letter p"><div><span class="emoji emoji1f17f"></span></div><span>1F17F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="horizontal traffic light"><div><span class="emoji emoji1f6a5"></span></div><span>1F6A5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="construction sign"><div><span class="emoji emoji1f6a7"></span></div><span>1F6A7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="police cars revolving light"><div><span class="emoji emoji1f6a8"></span></div><span>1F6A8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hot springs"><div><span class="emoji emoji2668"></span></div><span>2668</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tent"><div><span class="emoji emoji26fa"></span></div><span>26FA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="carousel horse"><div><span class="emoji emoji1f3a0"></span></div><span>1F3A0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ferris wheel"><div><span class="emoji emoji1f3a1"></span></div><span>1F3A1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="roller coaster"><div><span class="emoji emoji1f3a2"></span></div><span>1F3A2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fishing pole and fish"><div><span class="emoji emoji1f3a3"></span></div><span>1F3A3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="microphone"><div><span class="emoji emoji1f3a4"></span></div><span>1F3A4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="movie camera"><div><span class="emoji emoji1f3a5"></span></div><span>1F3A5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cinema"><div><span class="emoji emoji1f3a6"></span></div><span>1F3A6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="headphone"><div><span class="emoji emoji1f3a7"></span></div><span>1F3A7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="artist palette"><div><span class="emoji emoji1f3a8"></span></div><span>1F3A8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="top hat"><div><span class="emoji emoji1f3a9"></span></div><span>1F3A9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circus tent"><div><span class="emoji emoji1f3aa"></span></div><span>1F3AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ticket"><div><span class="emoji emoji1f3ab"></span></div><span>1F3AB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clapper board"><div><span class="emoji emoji1f3ac"></span></div><span>1F3AC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="performing arts"><div><span class="emoji emoji1f3ad"></span></div><span>1F3AD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="video game"><div><span class="emoji emoji1f3ae"></span></div><span>1F3AE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mahjong tile red dragon"><div><span class="emoji emoji1f004"></span></div><span>1F004</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="direct hit"><div><span class="emoji emoji1f3af"></span></div><span>1F3AF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="slot machine"><div><span class="emoji emoji1f3b0"></span></div><span>1F3B0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="billiards"><div><span class="emoji emoji1f3b1"></span></div><span>1F3B1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="game die"><div><span class="emoji emoji1f3b2"></span></div><span>1F3B2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bowling"><div><span class="emoji emoji1f3b3"></span></div><span>1F3B3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="flower playing cards"><div><span class="emoji emoji1f3b4"></span></div><span>1F3B4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="playing card black joker"><div><span class="emoji emoji1f0cf"></span></div><span>1F0CF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="musical note"><div><span class="emoji emoji1f3b5"></span></div><span>1F3B5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="multiple musical notes"><div><span class="emoji emoji1f3b6"></span></div><span>1F3B6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="saxophone"><div><span class="emoji emoji1f3b7"></span></div><span>1F3B7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="guitar"><div><span class="emoji emoji1f3b8"></span></div><span>1F3B8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="musical keyboard"><div><span class="emoji emoji1f3b9"></span></div><span>1F3B9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="trumpet"><div><span class="emoji emoji1f3ba"></span></div><span>1F3BA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="violin"><div><span class="emoji emoji1f3bb"></span></div><span>1F3BB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="musical score"><div><span class="emoji emoji1f3bc"></span></div><span>1F3BC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="part alternation mark"><div><span class="emoji emoji303d"></span></div><span>303D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="camera"><div><span class="emoji emoji1f4f7"></span></div><span>1F4F7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="video camera"><div><span class="emoji emoji1f4f9"></span></div><span>1F4F9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="television"><div><span class="emoji emoji1f4fa"></span></div><span>1F4FA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="radio"><div><span class="emoji emoji1f4fb"></span></div><span>1F4FB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="videocassette"><div><span class="emoji emoji1f4fc"></span></div><span>1F4FC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="kiss mark"><div><span class="emoji emoji1f48b"></span></div><span>1F48B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="love letter"><div><span class="emoji emoji1f48c"></span></div><span>1F48C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ring"><div><span class="emoji emoji1f48d"></span></div><span>1F48D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="gem stone"><div><span class="emoji emoji1f48e"></span></div><span>1F48E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="kiss"><div><span class="emoji emoji1f48f"></span></div><span>1F48F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bouquet"><div><span class="emoji emoji1f490"></span></div><span>1F490</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="couple with heart"><div><span class="emoji emoji1f491"></span></div><span>1F491</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wedding"><div><span class="emoji emoji1f492"></span></div><span>1F492</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="no one under eighteen symbol"><div><span class="emoji emoji1f51e"></span></div><span>1F51E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="copyright sign"><div><span class="emoji emojia9"></span></div><span>00A9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="registered sign"><div><span class="emoji emojiae"></span></div><span>00AE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="trade mark sign"><div><span class="emoji emoji2122"></span></div><span>2122</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="information source"><div><span class="emoji emoji2139"></span></div><span>2139</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hash key"><div><span class="emoji emoji2320e3"></span></div><span>0023 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 1"><div><span class="emoji emoji3120e3"></span></div><span>0031 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 2"><div><span class="emoji emoji3220e3"></span></div><span>0032 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 3"><div><span class="emoji emoji3320e3"></span></div><span>0033 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 4"><div><span class="emoji emoji3420e3"></span></div><span>0034 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 5"><div><span class="emoji emoji3520e3"></span></div><span>0035 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 6"><div><span class="emoji emoji3620e3"></span></div><span>0036 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 7"><div><span class="emoji emoji3720e3"></span></div><span>0037 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 8"><div><span class="emoji emoji3820e3"></span></div><span>0038 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 9"><div><span class="emoji emoji3920e3"></span></div><span>0039 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap 0"><div><span class="emoji emoji3020e3"></span></div><span>0030 U+20E3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="keycap ten"><div><span class="emoji emoji1f51f"></span></div><span>1F51F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="antenna with bars"><div><span class="emoji emoji1f4f6"></span></div><span>1F4F6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="vibration mode"><div><span class="emoji emoji1f4f3"></span></div><span>1F4F3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mobile phone off"><div><span class="emoji emoji1f4f4"></span></div><span>1F4F4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hamburger"><div><span class="emoji emoji1f354"></span></div><span>1F354</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rice ball"><div><span class="emoji emoji1f359"></span></div><span>1F359</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="shortcake"><div><span class="emoji emoji1f370"></span></div><span>1F370</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="steaming bowl"><div><span class="emoji emoji1f35c"></span></div><span>1F35C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bread"><div><span class="emoji emoji1f35e"></span></div><span>1F35E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cooking"><div><span class="emoji emoji1f373"></span></div><span>1F373</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="soft ice cream"><div><span class="emoji emoji1f366"></span></div><span>1F366</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="french fries"><div><span class="emoji emoji1f35f"></span></div><span>1F35F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dango"><div><span class="emoji emoji1f361"></span></div><span>1F361</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rice cracker"><div><span class="emoji emoji1f358"></span></div><span>1F358</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cooked rice"><div><span class="emoji emoji1f35a"></span></div><span>1F35A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="spaghetti"><div><span class="emoji emoji1f35d"></span></div><span>1F35D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="curry and rice"><div><span class="emoji emoji1f35b"></span></div><span>1F35B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="oden"><div><span class="emoji emoji1f362"></span></div><span>1F362</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sushi"><div><span class="emoji emoji1f363"></span></div><span>1F363</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bento box"><div><span class="emoji emoji1f371"></span></div><span>1F371</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pot of food"><div><span class="emoji emoji1f372"></span></div><span>1F372</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="shaved ice"><div><span class="emoji emoji1f367"></span></div><span>1F367</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="meat on bone"><div><span class="emoji emoji1f356"></span></div><span>1F356</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fish cake with swirl design"><div><span class="emoji emoji1f365"></span></div><span>1F365</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="roasted sweet potato"><div><span class="emoji emoji1f360"></span></div><span>1F360</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="slice of pizza"><div><span class="emoji emoji1f355"></span></div><span>1F355</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="poultry leg"><div><span class="emoji emoji1f357"></span></div><span>1F357</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ice cream"><div><span class="emoji emoji1f368"></span></div><span>1F368</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="doughnut"><div><span class="emoji emoji1f369"></span></div><span>1F369</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cookie"><div><span class="emoji emoji1f36a"></span></div><span>1F36A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="chocolate bar"><div><span class="emoji emoji1f36b"></span></div><span>1F36B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="candy"><div><span class="emoji emoji1f36c"></span></div><span>1F36C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="lollipop"><div><span class="emoji emoji1f36d"></span></div><span>1F36D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="custard"><div><span class="emoji emoji1f36e"></span></div><span>1F36E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="honey pot"><div><span class="emoji emoji1f36f"></span></div><span>1F36F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fried shrimp"><div><span class="emoji emoji1f364"></span></div><span>1F364</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fork and knife"><div><span class="emoji emoji1f374"></span></div><span>1F374</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hot beverage"><div><span class="emoji emoji2615"></span></div><span>2615</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cocktail glass"><div><span class="emoji emoji1f378"></span></div><span>1F378</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="beer mug"><div><span class="emoji emoji1f37a"></span></div><span>1F37A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="teacup without handle"><div><span class="emoji emoji1f375"></span></div><span>1F375</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sake bottle and cup"><div><span class="emoji emoji1f376"></span></div><span>1F376</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wine glass"><div><span class="emoji emoji1f377"></span></div><span>1F377</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clinking beer mugs"><div><span class="emoji emoji1f37b"></span></div><span>1F37B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="tropical drink"><div><span class="emoji emoji1f379"></span></div><span>1F379</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="north east arrow"><div><span class="emoji emoji2197"></span></div><span>2197</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="south east arrow"><div><span class="emoji emoji2198"></span></div><span>2198</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="north west arrow"><div><span class="emoji emoji2196"></span></div><span>2196</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="south west arrow"><div><span class="emoji emoji2199"></span></div><span>2199</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="arrow pointing rightwards then curving upwards"><div><span class="emoji emoji2934"></span></div><span>2934</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="arrow pointing rightwards then curving downwards"><div><span class="emoji emoji2935"></span></div><span>2935</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="left right arrow"><div><span class="emoji emoji2194"></span></div><span>2194</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="up down arrow"><div><span class="emoji emoji2195"></span></div><span>2195</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="upwards black arrow"><div><span class="emoji emoji2b06"></span></div><span>2B06</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="downwards black arrow"><div><span class="emoji emoji2b07"></span></div><span>2B07</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black rightwards arrow"><div><span class="emoji emoji27a1"></span></div><span>27A1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="leftwards black arrow"><div><span class="emoji emoji2b05"></span></div><span>2B05</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black right-pointing triangle"><div><span class="emoji emoji25b6"></span></div><span>25B6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black left-pointing triangle"><div><span class="emoji emoji25c0"></span></div><span>25C0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black right-pointing double triangle"><div><span class="emoji emoji23e9"></span></div><span>23E9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black left-pointing double triangle"><div><span class="emoji emoji23ea"></span></div><span>23EA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black up-pointing double triangle"><div><span class="emoji emoji23eb"></span></div><span>23EB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black down-pointing double triangle"><div><span class="emoji emoji23ec"></span></div><span>23EC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="up-pointing red triangle"><div><span class="emoji emoji1f53a"></span></div><span>1F53A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="down-pointing red triangle"><div><span class="emoji emoji1f53b"></span></div><span>1F53B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="up-pointing small red triangle"><div><span class="emoji emoji1f53c"></span></div><span>1F53C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="down-pointing small red triangle"><div><span class="emoji emoji1f53d"></span></div><span>1F53D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy large circle"><div><span class="emoji emoji2b55"></span></div><span>2B55</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="cross mark"><div><span class="emoji emoji274c"></span></div><span>274C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="negative squared cross mark"><div><span class="emoji emoji274e"></span></div><span>274E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy exclamation mark symbol"><div><span class="emoji emoji2757"></span></div><span>2757</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="exclamation question mark"><div><span class="emoji emoji2049"></span></div><span>2049</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="double exclamation mark"><div><span class="emoji emoji203c"></span></div><span>203C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black question mark ornament"><div><span class="emoji emoji2753"></span></div><span>2753</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white question mark ornament"><div><span class="emoji emoji2754"></span></div><span>2754</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white exclamation mark ornament"><div><span class="emoji emoji2755"></span></div><span>2755</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wavy dash"><div><span class="emoji emoji3030"></span></div><span>3030</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="curly loop"><div><span class="emoji emoji27b0"></span></div><span>27B0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="double curly loop"><div><span class="emoji emoji27bf"></span></div><span>27BF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy black heart"><div><span class="emoji emoji2764"></span></div><span>2764</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="beating heart"><div><span class="emoji emoji1f493"></span></div><span>1F493</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="broken heart"><div><span class="emoji emoji1f494"></span></div><span>1F494</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="two hearts"><div><span class="emoji emoji1f495"></span></div><span>1F495</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sparkling heart"><div><span class="emoji emoji1f496"></span></div><span>1F496</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="growing heart"><div><span class="emoji emoji1f497"></span></div><span>1F497</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heart with arrow"><div><span class="emoji emoji1f498"></span></div><span>1F498</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="blue heart"><div><span class="emoji emoji1f499"></span></div><span>1F499</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="green heart"><div><span class="emoji emoji1f49a"></span></div><span>1F49A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="yellow heart"><div><span class="emoji emoji1f49b"></span></div><span>1F49B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="purple heart"><div><span class="emoji emoji1f49c"></span></div><span>1F49C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heart with ribbon"><div><span class="emoji emoji1f49d"></span></div><span>1F49D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="revolving hearts"><div><span class="emoji emoji1f49e"></span></div><span>1F49E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heart decoration"><div><span class="emoji emoji1f49f"></span></div><span>1F49F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black heart suit"><div><span class="emoji emoji2665"></span></div><span>2665</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black spade suit"><div><span class="emoji emoji2660"></span></div><span>2660</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black diamond suit"><div><span class="emoji emoji2666"></span></div><span>2666</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black club suit"><div><span class="emoji emoji2663"></span></div><span>2663</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="smoking symbol"><div><span class="emoji emoji1f6ac"></span></div><span>1F6AC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="no smoking symbol"><div><span class="emoji emoji1f6ad"></span></div><span>1F6AD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="wheelchair symbol"><div><span class="emoji emoji267f"></span></div><span>267F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="triangular flag on post"><div><span class="emoji emoji1f6a9"></span></div><span>1F6A9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="warning sign"><div><span class="emoji emoji26a0"></span></div><span>26A0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="no entry"><div><span class="emoji emoji26d4"></span></div><span>26D4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black universal recycling symbol"><div><span class="emoji emoji267b"></span></div><span>267B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bicycle"><div><span class="emoji emoji1f6b2"></span></div><span>1F6B2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pedestrian"><div><span class="emoji emoji1f6b6"></span></div><span>1F6B6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="mens symbol"><div><span class="emoji emoji1f6b9"></span></div><span>1F6B9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="womens symbol"><div><span class="emoji emoji1f6ba"></span></div><span>1F6BA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bath"><div><span class="emoji emoji1f6c0"></span></div><span>1F6C0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="restroom"><div><span class="emoji emoji1f6bb"></span></div><span>1F6BB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="toilet"><div><span class="emoji emoji1f6bd"></span></div><span>1F6BD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="water closet"><div><span class="emoji emoji1f6be"></span></div><span>1F6BE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="baby symbol"><div><span class="emoji emoji1f6bc"></span></div><span>1F6BC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="door"><div><span class="emoji emoji1f6aa"></span></div><span>1F6AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="no entry sign"><div><span class="emoji emoji1f6ab"></span></div><span>1F6AB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy check mark"><div><span class="emoji emoji2714"></span></div><span>2714</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cl"><div><span class="emoji emoji1f191"></span></div><span>1F191</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cool"><div><span class="emoji emoji1f192"></span></div><span>1F192</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared free"><div><span class="emoji emoji1f193"></span></div><span>1F193</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared id"><div><span class="emoji emoji1f194"></span></div><span>1F194</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared new"><div><span class="emoji emoji1f195"></span></div><span>1F195</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared ng"><div><span class="emoji emoji1f196"></span></div><span>1F196</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared ok"><div><span class="emoji emoji1f197"></span></div><span>1F197</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared sos"><div><span class="emoji emoji1f198"></span></div><span>1F198</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared up with exclamation mark"><div><span class="emoji emoji1f199"></span></div><span>1F199</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared vs"><div><span class="emoji emoji1f19a"></span></div><span>1F19A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared katakana koko"><div><span class="emoji emoji1f201"></span></div><span>1F201</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared katakana sa"><div><span class="emoji emoji1f202"></span></div><span>1F202</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-7981"><div><span class="emoji emoji1f232"></span></div><span>1F232</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-7a7a"><div><span class="emoji emoji1f233"></span></div><span>1F233</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-5408"><div><span class="emoji emoji1f234"></span></div><span>1F234</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-6e80"><div><span class="emoji emoji1f235"></span></div><span>1F235</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-6709"><div><span class="emoji emoji1f236"></span></div><span>1F236</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-7121"><div><span class="emoji emoji1f21a"></span></div><span>1F21A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-6708"><div><span class="emoji emoji1f237"></span></div><span>1F237</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-7533"><div><span class="emoji emoji1f238"></span></div><span>1F238</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-5272"><div><span class="emoji emoji1f239"></span></div><span>1F239</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-6307"><div><span class="emoji emoji1f22f"></span></div><span>1F22F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="squared cjk unified ideograph-55b6"><div><span class="emoji emoji1f23a"></span></div><span>1F23A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circled ideograph secret"><div><span class="emoji emoji3299"></span></div><span>3299</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circled ideograph congratulation"><div><span class="emoji emoji3297"></span></div><span>3297</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circled ideograph advantage"><div><span class="emoji emoji1f250"></span></div><span>1F250</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="circled ideograph accept"><div><span class="emoji emoji1f251"></span></div><span>1F251</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy plus sign"><div><span class="emoji emoji2795"></span></div><span>2795</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy minus sign"><div><span class="emoji emoji2796"></span></div><span>2796</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy multiplication x"><div><span class="emoji emoji2716"></span></div><span>2716</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="heavy division sign"><div><span class="emoji emoji2797"></span></div><span>2797</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="diamond shape with a dot inside"><div><span class="emoji emoji1f4a0"></span></div><span>1F4A0</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="electric light bulb"><div><span class="emoji emoji1f4a1"></span></div><span>1F4A1</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="anger symbol"><div><span class="emoji emoji1f4a2"></span></div><span>1F4A2</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bomb"><div><span class="emoji emoji1f4a3"></span></div><span>1F4A3</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sleeping symbol"><div><span class="emoji emoji1f4a4"></span></div><span>1F4A4</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="collision symbol"><div><span class="emoji emoji1f4a5"></span></div><span>1F4A5</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="splashing sweat symbol"><div><span class="emoji emoji1f4a6"></span></div><span>1F4A6</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="droplet"><div><span class="emoji emoji1f4a7"></span></div><span>1F4A7</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dash symbol"><div><span class="emoji emoji1f4a8"></span></div><span>1F4A8</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="pile of poo"><div><span class="emoji emoji1f4a9"></span></div><span>1F4A9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="flexed biceps"><div><span class="emoji emoji1f4aa"></span></div><span>1F4AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="dizzy symbol"><div><span class="emoji emoji1f4ab"></span></div><span>1F4AB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="speech balloon"><div><span class="emoji emoji1f4ac"></span></div><span>1F4AC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sparkles"><div><span class="emoji emoji2728"></span></div><span>2728</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="eight pointed black star"><div><span class="emoji emoji2734"></span></div><span>2734</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="eight spoked asterisk"><div><span class="emoji emoji2733"></span></div><span>2733</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="medium white circle"><div><span class="emoji emoji26aa"></span></div><span>26AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="medium black circle"><div><span class="emoji emoji26ab"></span></div><span>26AB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="large red circle"><div><span class="emoji emoji1f534"></span></div><span>1F534</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="large blue circle"><div><span class="emoji emoji1f535"></span></div><span>1F535</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black square button"><div><span class="emoji emoji1f532"></span></div><span>1F532</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white square button"><div><span class="emoji emoji1f533"></span></div><span>1F533</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white medium star"><div><span class="emoji emoji2b50"></span></div><span>2B50</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white large square"><div><span class="emoji emoji2b1c"></span></div><span>2B1C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black large square"><div><span class="emoji emoji2b1b"></span></div><span>2B1B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white small square"><div><span class="emoji emoji25ab"></span></div><span>25AB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black small square"><div><span class="emoji emoji25aa"></span></div><span>25AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white medium small square"><div><span class="emoji emoji25fd"></span></div><span>25FD</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black medium small square"><div><span class="emoji emoji25fe"></span></div><span>25FE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white medium square"><div><span class="emoji emoji25fb"></span></div><span>25FB</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="black medium square"><div><span class="emoji emoji25fc"></span></div><span>25FC</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="large orange diamond"><div><span class="emoji emoji1f536"></span></div><span>1F536</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="large blue diamond"><div><span class="emoji emoji1f537"></span></div><span>1F537</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="small orange diamond"><div><span class="emoji emoji1f538"></span></div><span>1F538</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="small blue diamond"><div><span class="emoji emoji1f539"></span></div><span>1F539</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="sparkle"><div><span class="emoji emoji2747"></span></div><span>2747</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white flower"><div><span class="emoji emoji1f4ae"></span></div><span>1F4AE</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="hundred points symbol"><div><span class="emoji emoji1f4af"></span></div><span>1F4AF</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="leftwards arrow with hook"><div><span class="emoji emoji21a9"></span></div><span>21A9</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="rightwards arrow with hook"><div><span class="emoji emoji21aa"></span></div><span>21AA</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clockwise downwards and upwards open circle arrows"><div><span class="emoji emoji1f503"></span></div><span>1F503</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="speaker with three sound waves"><div><span class="emoji emoji1f50a"></span></div><span>1F50A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="battery"><div><span class="emoji emoji1f50b"></span></div><span>1F50B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="electric plug"><div><span class="emoji emoji1f50c"></span></div><span>1F50C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="left-pointing magnifying glass"><div><span class="emoji emoji1f50d"></span></div><span>1F50D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="right-pointing magnifying glass"><div><span class="emoji emoji1f50e"></span></div><span>1F50E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="lock"><div><span class="emoji emoji1f512"></span></div><span>1F512</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="open lock"><div><span class="emoji emoji1f513"></span></div><span>1F513</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="lock with ink pen"><div><span class="emoji emoji1f50f"></span></div><span>1F50F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="closed lock with key"><div><span class="emoji emoji1f510"></span></div><span>1F510</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="key"><div><span class="emoji emoji1f511"></span></div><span>1F511</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bell"><div><span class="emoji emoji1f514"></span></div><span>1F514</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ballot box with check"><div><span class="emoji emoji2611"></span></div><span>2611</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="radio button"><div><span class="emoji emoji1f518"></span></div><span>1F518</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="bookmark"><div><span class="emoji emoji1f516"></span></div><span>1F516</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="link symbol"><div><span class="emoji emoji1f517"></span></div><span>1F517</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="back with leftwards arrow above"><div><span class="emoji emoji1f519"></span></div><span>1F519</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="end with leftwards arrow above"><div><span class="emoji emoji1f51a"></span></div><span>1F51A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="on with exclamation mark with left right arrow above"><div><span class="emoji emoji1f51b"></span></div><span>1F51B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="soon with rightwards arrow above"><div><span class="emoji emoji1f51c"></span></div><span>1F51C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="top with upwards arrow above"><div><span class="emoji emoji1f51d"></span></div><span>1F51D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white heavy check mark"><div><span class="emoji emoji2705"></span></div><span>2705</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="raised fist"><div><span class="emoji emoji270a"></span></div><span>270A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="raised hand"><div><span class="emoji emoji270b"></span></div><span>270B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="victory hand"><div><span class="emoji emoji270c"></span></div><span>270C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="fisted hand sign"><div><span class="emoji emoji1f44a"></span></div><span>1F44A</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="thumbs up sign"><div><span class="emoji emoji1f44d"></span></div><span>1F44D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white up pointing index"><div><span class="emoji emoji261d"></span></div><span>261D</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white up pointing backhand index"><div><span class="emoji emoji1f446"></span></div><span>1F446</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white down pointing backhand index"><div><span class="emoji emoji1f447"></span></div><span>1F447</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white left pointing backhand index"><div><span class="emoji emoji1f448"></span></div><span>1F448</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="white right pointing backhand index"><div><span class="emoji emoji1f449"></span></div><span>1F449</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="waving hand sign"><div><span class="emoji emoji1f44b"></span></div><span>1F44B</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="clapping hands sign"><div><span class="emoji emoji1f44f"></span></div><span>1F44F</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="ok hand sign"><div><span class="emoji emoji1f44c"></span></div><span>1F44C</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="thumbs down sign"><div><span class="emoji emoji1f44e"></span></div><span>1F44E</span></a> <a href='javascript:;' onClick="insertEmoji($(this));" title="open hands sign"><div><span class="emoji emoji1f450"></span></div><span>1F450</span></a> </div> </div>
Java
{{#each this}} <dl> <dt>ID: {{this}}</dt> <dd><button data-sincro-id="{{this}}" type="button" class="btn btn-md btn-default sincro-resultados-btn"><span class="glyphicon glyphicon-send" data-sincro-id="{{this}}"></span></button></dd> {{/each}}
Java
/**************************************************************************** Copyright 2011 Jeff Lamarche Copyright 2012 Goffredo Marocchi Copyright 2012 Ricardo Quesada Copyright 2012 cocos2d-x.org Copyright 2013-2014 Chukong Technologies Inc. http://www.cocos2d-x.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ #ifndef __CCGLPROGRAM_H__ #define __CCGLPROGRAM_H__ #include <unordered_map> #include "base/ccMacros.h" #include "base/CCRef.h" #include "base/ccTypes.h" #include "platform/CCGL.h" #include "math/CCMath.h" NS_CC_BEGIN /** * @addtogroup shaders * @{ */ struct _hashUniformEntry; class GLProgram; typedef void (*GLInfoFunction)(GLuint program, GLenum pname, GLint* params); typedef void (*GLLogFunction) (GLuint program, GLsizei bufsize, GLsizei* length, GLchar* infolog); struct VertexAttrib { GLuint index; GLint size; GLenum type; std::string name; }; struct Uniform { GLint location; GLint size; GLenum type; std::string name; }; /** GLProgram Class that implements a glProgram @since v2.0.0 */ class CC_DLL GLProgram : public Ref { friend class GLProgramState; public: enum { VERTEX_ATTRIB_POSITION, VERTEX_ATTRIB_COLOR, VERTEX_ATTRIB_TEX_COORD, VERTEX_ATTRIB_TEX_COORD1, VERTEX_ATTRIB_TEX_COORD2, VERTEX_ATTRIB_TEX_COORD3, VERTEX_ATTRIB_TEX_COORD4, VERTEX_ATTRIB_TEX_COORD5, VERTEX_ATTRIB_TEX_COORD6, VERTEX_ATTRIB_TEX_COORD7, VERTEX_ATTRIB_NORMAL, VERTEX_ATTRIB_BLEND_WEIGHT, VERTEX_ATTRIB_BLEND_INDEX, VERTEX_ATTRIB_MAX, // backward compatibility VERTEX_ATTRIB_TEX_COORDS = VERTEX_ATTRIB_TEX_COORD, }; enum { UNIFORM_P_MATRIX, UNIFORM_MV_MATRIX, UNIFORM_MVP_MATRIX, UNIFORM_TIME, UNIFORM_SIN_TIME, UNIFORM_COS_TIME, UNIFORM_RANDOM01, UNIFORM_SAMPLER0, UNIFORM_SAMPLER1, UNIFORM_SAMPLER2, UNIFORM_SAMPLER3, UNIFORM_MAX, }; static const char* SHADER_NAME_POSITION_TEXTURE_COLOR; static const char* SHADER_NAME_POSITION_TEXTURE_COLOR_NO_MVP; static const char* SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST; static const char* SHADER_NAME_POSITION_TEXTURE_ALPHA_TEST_NO_MV; static const char* SHADER_NAME_POSITION_COLOR; static const char* SHADER_NAME_POSITION_COLOR_NO_MVP; static const char* SHADER_NAME_POSITION_TEXTURE; static const char* SHADER_NAME_POSITION_TEXTURE_U_COLOR; static const char* SHADER_NAME_POSITION_TEXTURE_A8_COLOR; static const char* SHADER_NAME_POSITION_U_COLOR; static const char* SHADER_NAME_POSITION_LENGTH_TEXTURE_COLOR; static const char* SHADER_NAME_LABEL_NORMAL; static const char* SHADER_NAME_LABEL_OUTLINE; static const char* SHADER_NAME_LABEL_DISTANCEFIELD_NORMAL; static const char* SHADER_NAME_LABEL_DISTANCEFIELD_GLOW; //3D static const char* SHADER_3D_POSITION; static const char* SHADER_3D_POSITION_TEXTURE; static const char* SHADER_3D_SKINPOSITION_TEXTURE; // uniform names static const char* UNIFORM_NAME_P_MATRIX; static const char* UNIFORM_NAME_MV_MATRIX; static const char* UNIFORM_NAME_MVP_MATRIX; static const char* UNIFORM_NAME_TIME; static const char* UNIFORM_NAME_SIN_TIME; static const char* UNIFORM_NAME_COS_TIME; static const char* UNIFORM_NAME_RANDOM01; static const char* UNIFORM_NAME_SAMPLER0; static const char* UNIFORM_NAME_SAMPLER1; static const char* UNIFORM_NAME_SAMPLER2; static const char* UNIFORM_NAME_SAMPLER3; static const char* UNIFORM_NAME_ALPHA_TEST_VALUE; // Attribute names static const char* ATTRIBUTE_NAME_COLOR; static const char* ATTRIBUTE_NAME_POSITION; static const char* ATTRIBUTE_NAME_TEX_COORD; static const char* ATTRIBUTE_NAME_TEX_COORD1; static const char* ATTRIBUTE_NAME_TEX_COORD2; static const char* ATTRIBUTE_NAME_TEX_COORD3; static const char* ATTRIBUTE_NAME_TEX_COORD4; static const char* ATTRIBUTE_NAME_TEX_COORD5; static const char* ATTRIBUTE_NAME_TEX_COORD6; static const char* ATTRIBUTE_NAME_TEX_COORD7; static const char* ATTRIBUTE_NAME_NORMAL; static const char* ATTRIBUTE_NAME_BLEND_WEIGHT; static const char* ATTRIBUTE_NAME_BLEND_INDEX; GLProgram(); virtual ~GLProgram(); /** Initializes the GLProgram with a vertex and fragment with bytes array * @js initWithString * @lua initWithString */ #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) /** Initializes the CCGLProgram with precompiled shader program */ static GLProgram* createWithPrecompiledProgramByteArray(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); bool initWithPrecompiledProgramByteArray(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); #endif /** Initializes the GLProgram with a vertex and fragment with bytes array * @js initWithString * @lua initWithString */ static GLProgram* createWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); bool initWithByteArrays(const GLchar* vShaderByteArray, const GLchar* fShaderByteArray); /** Initializes the GLProgram with a vertex and fragment with contents of filenames * @js init * @lua init */ static GLProgram* createWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename); bool initWithFilenames(const std::string& vShaderFilename, const std::string& fShaderFilename); //void bindUniform(std::string uniformName, int value); Uniform* getUniform(const std::string& name); VertexAttrib* getVertexAttrib(const std::string& name); /** It will add a new attribute to the shader by calling glBindAttribLocation */ void bindAttribLocation(const std::string& attributeName, GLuint index) const; /** calls glGetAttribLocation */ GLint getAttribLocation(const std::string& attributeName) const; /** calls glGetUniformLocation() */ GLint getUniformLocation(const std::string& attributeName) const; /** links the glProgram */ bool link(); /** it will call glUseProgram() */ void use(); /** It will create 4 uniforms: - kUniformPMatrix - kUniformMVMatrix - kUniformMVPMatrix - GLProgram::UNIFORM_SAMPLER And it will bind "GLProgram::UNIFORM_SAMPLER" to 0 */ void updateUniforms(); /** calls retrieves the named uniform location for this shader program. */ GLint getUniformLocationForName(const char* name) const; /** calls glUniform1i only if the values are different than the previous call for this same shader program. * @js setUniformLocationI32 * @lua setUniformLocationI32 */ void setUniformLocationWith1i(GLint location, GLint i1); /** calls glUniform2i only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith2i(GLint location, GLint i1, GLint i2); /** calls glUniform3i only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith3i(GLint location, GLint i1, GLint i2, GLint i3); /** calls glUniform4i only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith4i(GLint location, GLint i1, GLint i2, GLint i3, GLint i4); /** calls glUniform2iv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith2iv(GLint location, GLint* ints, unsigned int numberOfArrays); /** calls glUniform3iv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith3iv(GLint location, GLint* ints, unsigned int numberOfArrays); /** calls glUniform4iv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith4iv(GLint location, GLint* ints, unsigned int numberOfArrays); /** calls glUniform1f only if the values are different than the previous call for this same shader program. * In js or lua,please use setUniformLocationF32 * @js NA */ void setUniformLocationWith1f(GLint location, GLfloat f1); /** calls glUniform2f only if the values are different than the previous call for this same shader program. * In js or lua,please use setUniformLocationF32 * @js NA */ void setUniformLocationWith2f(GLint location, GLfloat f1, GLfloat f2); /** calls glUniform3f only if the values are different than the previous call for this same shader program. * In js or lua,please use setUniformLocationF32 * @js NA */ void setUniformLocationWith3f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3); /** calls glUniform4f only if the values are different than the previous call for this same shader program. * In js or lua,please use setUniformLocationF32 * @js NA */ void setUniformLocationWith4f(GLint location, GLfloat f1, GLfloat f2, GLfloat f3, GLfloat f4); /** calls glUniform2fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith2fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniform3fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith3fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniform4fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWith4fv(GLint location, const GLfloat* floats, unsigned int numberOfArrays); /** calls glUniformMatrix2fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWithMatrix2fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** calls glUniformMatrix3fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWithMatrix3fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** calls glUniformMatrix4fv only if the values are different than the previous call for this same shader program. */ void setUniformLocationWithMatrix4fv(GLint location, const GLfloat* matrixArray, unsigned int numberOfMatrices); /** will update the builtin uniforms if they are different than the previous call for this same shader program. */ void setUniformsForBuiltins(); void setUniformsForBuiltins(const Mat4 &modelView); // Attribute /** returns the vertexShader error log */ std::string getVertexShaderLog() const; /** returns the fragmentShader error log */ std::string getFragmentShaderLog() const; /** returns the program error log */ std::string getProgramLog() const; // reload all shaders, this function is designed for android // when opengl context lost, so don't call it. void reset(); inline const GLuint getProgram() const { return _program; } // DEPRECATED CC_DEPRECATED_ATTRIBUTE bool initWithVertexShaderByteArray(const GLchar* vertexByteArray, const GLchar* fragByteArray) { return initWithByteArrays(vertexByteArray, fragByteArray); } CC_DEPRECATED_ATTRIBUTE bool initWithVertexShaderFilename(const std::string &vertexFilename, const std::string& fragFilename) { return initWithFilenames(vertexFilename, fragFilename); } CC_DEPRECATED_ATTRIBUTE void addAttribute(const std::string &attributeName, GLuint index) const { return bindAttribLocation(attributeName, index); } protected: bool updateUniformLocation(GLint location, const GLvoid* data, unsigned int bytes); virtual std::string getDescription() const; void bindPredefinedVertexAttribs(); void parseVertexAttribs(); void parseUniforms(); bool compileShader(GLuint * shader, GLenum type, const GLchar* source); std::string logForOpenGLObject(GLuint object, GLInfoFunction infoFunc, GLLogFunction logFunc) const; GLuint _program; GLuint _vertShader; GLuint _fragShader; GLint _builtInUniforms[UNIFORM_MAX]; struct _hashUniformEntry* _hashForUniforms; bool _hasShaderCompiler; #if (CC_TARGET_PLATFORM == CC_PLATFORM_WINRT) || (CC_TARGET_PLATFORM == CC_PLATFORM_WP8) std::string _shaderId; #endif struct flag_struct { unsigned int usesTime:1; unsigned int usesMVP:1; unsigned int usesMV:1; unsigned int usesP:1; unsigned int usesRandom:1; // handy way to initialize the bitfield flag_struct() { memset(this, 0, sizeof(*this)); } } _flags; std::unordered_map<std::string, Uniform> _userUniforms; std::unordered_map<std::string, VertexAttrib> _vertexAttribs; }; NS_CC_END #endif /* __CCGLPROGRAM_H__ */
Java
package com.tachys.moneyshare.dataaccess.db.contracts; import android.provider.BaseColumns; public class SettlementContract { public SettlementContract() { } public static class SettlementEntry implements BaseColumns { public static final String TABLE_NAME = "settlement"; public static final String COLUMN_NAME_PAYERID = "payer"; public static final String COLUMN_NAME_PAYEEID = "payee"; public static final String COLUMN_NAME_AMOUNT = "amount"; } }
Java
<?php namespace UmnLib\Core\XmlRecord; class NlmCatalog extends Record { // Must be an id type that uniquely identifies the record, // usually the record-creating organization's id. public static function primaryIdType() { return 'nlm'; } // Must return array( 'type' => $type, 'value' => $value ) pairs. public function ids() { if (!isset($this->ids)) { // output $ids = array(); $array = $this->asArray(); // TODO: Not sure this array key lookup will work with Titon... $nlmUniqueId = $array['NlmUniqueID']; $ids[] = array('type' => 'nlm', 'value' => $nlmUniqueId); if (array_key_exists('OtherID', $array)) { $otherIds = $array['OtherID']; if (!array_key_exists(0, $otherIds)) { $otherIds = array($otherIds); } foreach ($otherIds as $otherId) { if ('OCLC' == $otherId['attributes']['Source']) { $oclcId = trim($otherId['value']); // For some goofy reason, some of the OCLC ids are prefixed with 'ocm': $oclcId = preg_replace('/^ocm/', '', $oclcId); $ids[] = array('type' => 'oclc', 'value' => $oclcId); } } } $this->ids = $ids; } return $this->ids; } }
Java
my_inf = float('Inf') print 99999999 > my_inf # False my_neg_inf = float('-Inf') print my_neg_inf < -99999999 # True
Java
cmd_kernel/irq/handle.o := arm-linux-gnueabi-gcc -Wp,-MD,kernel/irq/.handle.o.d -nostdinc -isystem /usr/lib/gcc-cross/arm-linux-gnueabi/4.7/include -Iinclude -I/home/benoit/kernel_android/32/es209ra/arch/arm/include -include include/linux/autoconf.h -D__KERNEL__ -mlittle-endian -Iarch/arm/mach-msm/include -Wall -Wundef -Wstrict-prototypes -Wno-trigraphs -Os -marm -mabi=aapcs-linux -mno-thumb-interwork -funwind-tables -D__LINUX_ARM_ARCH__=7 -march=armv7-a -msoft-float -Uarm -Wframe-larger-than=2048 -fno-stack-protector -fomit-frame-pointer -g -Wdeclaration-after-statement -Wno-pointer-sign -fno-strict-overflow -fno-dwarf2-cfi-asm -fconserve-stack -D"KBUILD_STR(s)=\#s" -D"KBUILD_BASENAME=KBUILD_STR(handle)" -D"KBUILD_MODNAME=KBUILD_STR(handle)" -c -o kernel/irq/handle.o kernel/irq/handle.c deps_kernel/irq/handle.o := \ kernel/irq/handle.c \ $(wildcard include/config/smp.h) \ $(wildcard include/config/generic/hardirqs.h) \ $(wildcard include/config/sparse/irq.h) \ $(wildcard include/config/generic/hardirqs/no//do/irq.h) \ $(wildcard include/config/enable/warn/deprecated.h) \ include/linux/irq.h \ $(wildcard include/config/s390.h) \ $(wildcard include/config/irq/per/cpu.h) \ $(wildcard include/config/irq/release/method.h) \ $(wildcard include/config/intr/remap.h) \ $(wildcard include/config/generic/pending/irq.h) \ $(wildcard include/config/proc/fs.h) \ $(wildcard include/config/numa/irq/desc.h) \ $(wildcard include/config/cpumask/offstack.h) \ $(wildcard include/config/cpumasks/offstack.h) \ include/linux/smp.h \ $(wildcard include/config/use/generic/smp/helpers.h) \ $(wildcard include/config/debug/preempt.h) \ include/linux/errno.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/errno.h \ include/asm-generic/errno.h \ include/asm-generic/errno-base.h \ include/linux/types.h \ $(wildcard include/config/uid16.h) \ $(wildcard include/config/lbdaf.h) \ $(wildcard include/config/phys/addr/t/64bit.h) \ $(wildcard include/config/64bit.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/types.h \ include/asm-generic/int-ll64.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/bitsperlong.h \ include/asm-generic/bitsperlong.h \ include/linux/posix_types.h \ include/linux/stddef.h \ include/linux/compiler.h \ $(wildcard include/config/trace/branch/profiling.h) \ $(wildcard include/config/profile/all/branches.h) \ $(wildcard include/config/enable/must/check.h) \ include/linux/compiler-gcc.h \ $(wildcard include/config/arch/supports/optimized/inlining.h) \ $(wildcard include/config/optimize/inlining.h) \ include/linux/compiler-gcc4.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/posix_types.h \ include/linux/list.h \ $(wildcard include/config/debug/list.h) \ include/linux/poison.h \ include/linux/prefetch.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/processor.h \ $(wildcard include/config/mmu.h) \ $(wildcard include/config/cpu/32v6k.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/ptrace.h \ $(wildcard include/config/cpu/endian/be8.h) \ $(wildcard include/config/arm/thumb.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/hwcap.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/cache.h \ $(wildcard include/config/arm/l1/cache/shift.h) \ $(wildcard include/config/aeabi.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/system.h \ $(wildcard include/config/cpu/xsc3.h) \ $(wildcard include/config/cpu/fa526.h) \ $(wildcard include/config/arch/msm.h) \ $(wildcard include/config/cpu/sa1100.h) \ $(wildcard include/config/cpu/sa110.h) \ include/linux/linkage.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/linkage.h \ include/linux/irqflags.h \ $(wildcard include/config/trace/irqflags.h) \ $(wildcard include/config/irqsoff/tracer.h) \ $(wildcard include/config/preempt/tracer.h) \ $(wildcard include/config/trace/irqflags/support.h) \ $(wildcard include/config/x86.h) \ include/linux/typecheck.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/irqflags.h \ include/asm-generic/cmpxchg-local.h \ include/linux/cpumask.h \ $(wildcard include/config/hotplug/cpu.h) \ $(wildcard include/config/debug/per/cpu/maps.h) \ $(wildcard include/config/disable/obsolete/cpumask/functions.h) \ include/linux/kernel.h \ $(wildcard include/config/preempt/voluntary.h) \ $(wildcard include/config/debug/spinlock/sleep.h) \ $(wildcard include/config/prove/locking.h) \ $(wildcard include/config/printk.h) \ $(wildcard include/config/dynamic/debug.h) \ $(wildcard include/config/ring/buffer.h) \ $(wildcard include/config/tracing.h) \ $(wildcard include/config/numa.h) \ $(wildcard include/config/ftrace/mcount/record.h) \ /usr/lib/gcc-cross/arm-linux-gnueabi/4.7/include/stdarg.h \ include/linux/bitops.h \ $(wildcard include/config/generic/find/first/bit.h) \ $(wildcard include/config/generic/find/last/bit.h) \ $(wildcard include/config/generic/find/next/bit.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/bitops.h \ include/asm-generic/bitops/non-atomic.h \ include/asm-generic/bitops/fls64.h \ include/asm-generic/bitops/sched.h \ include/asm-generic/bitops/hweight.h \ include/asm-generic/bitops/lock.h \ include/linux/log2.h \ $(wildcard include/config/arch/has/ilog2/u32.h) \ $(wildcard include/config/arch/has/ilog2/u64.h) \ include/linux/ratelimit.h \ include/linux/param.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/param.h \ $(wildcard include/config/hz.h) \ include/linux/dynamic_debug.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/byteorder.h \ include/linux/byteorder/little_endian.h \ include/linux/swab.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/swab.h \ include/linux/byteorder/generic.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/bug.h \ $(wildcard include/config/bug.h) \ $(wildcard include/config/debug/bugverbose.h) \ include/asm-generic/bug.h \ $(wildcard include/config/generic/bug.h) \ $(wildcard include/config/generic/bug/relative/pointers.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/div64.h \ include/linux/threads.h \ $(wildcard include/config/nr/cpus.h) \ $(wildcard include/config/base/small.h) \ include/linux/bitmap.h \ include/linux/string.h \ $(wildcard include/config/binary/printf.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/string.h \ include/linux/cache.h \ $(wildcard include/config/arch/has/cache/line/size.h) \ include/linux/spinlock.h \ $(wildcard include/config/debug/spinlock.h) \ $(wildcard include/config/generic/lockbreak.h) \ $(wildcard include/config/preempt.h) \ $(wildcard include/config/debug/lock/alloc.h) \ include/linux/preempt.h \ $(wildcard include/config/preempt/notifiers.h) \ include/linux/thread_info.h \ $(wildcard include/config/compat.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/thread_info.h \ $(wildcard include/config/arm/thumbee.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/fpstate.h \ $(wildcard include/config/vfpv3.h) \ $(wildcard include/config/iwmmxt.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/domain.h \ $(wildcard include/config/verify/permission/fault.h) \ $(wildcard include/config/io/36.h) \ include/linux/stringify.h \ include/linux/bottom_half.h \ include/linux/spinlock_types.h \ include/linux/spinlock_types_up.h \ include/linux/lockdep.h \ $(wildcard include/config/lockdep.h) \ $(wildcard include/config/lock/stat.h) \ include/linux/spinlock_up.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/atomic.h \ include/asm-generic/atomic-long.h \ include/linux/spinlock_api_up.h \ include/linux/gfp.h \ $(wildcard include/config/kmemcheck.h) \ $(wildcard include/config/highmem.h) \ $(wildcard include/config/zone/dma.h) \ $(wildcard include/config/zone/dma32.h) \ $(wildcard include/config/debug/vm.h) \ include/linux/mmzone.h \ $(wildcard include/config/force/max/zoneorder.h) \ $(wildcard include/config/memory/hotplug.h) \ $(wildcard include/config/sparsemem.h) \ $(wildcard include/config/arch/populates/node/map.h) \ $(wildcard include/config/discontigmem.h) \ $(wildcard include/config/flat/node/mem/map.h) \ $(wildcard include/config/cgroup/mem/res/ctlr.h) \ $(wildcard include/config/have/memory/present.h) \ $(wildcard include/config/need/node/memmap/size.h) \ $(wildcard include/config/need/multiple/nodes.h) \ $(wildcard include/config/have/arch/early/pfn/to/nid.h) \ $(wildcard include/config/flatmem.h) \ $(wildcard include/config/sparsemem/extreme.h) \ $(wildcard include/config/nodes/span/other/nodes.h) \ $(wildcard include/config/holes/in/zone.h) \ $(wildcard include/config/arch/has/holes/memorymodel.h) \ include/linux/wait.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/current.h \ include/linux/numa.h \ $(wildcard include/config/nodes/shift.h) \ include/linux/init.h \ $(wildcard include/config/modules.h) \ $(wildcard include/config/hotplug.h) \ include/linux/seqlock.h \ include/linux/nodemask.h \ include/linux/pageblock-flags.h \ $(wildcard include/config/hugetlb/page.h) \ $(wildcard include/config/hugetlb/page/size/variable.h) \ include/linux/bounds.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/page.h \ $(wildcard include/config/cpu/copy/v3.h) \ $(wildcard include/config/cpu/copy/v4wt.h) \ $(wildcard include/config/cpu/copy/v4wb.h) \ $(wildcard include/config/cpu/copy/feroceon.h) \ $(wildcard include/config/cpu/copy/fa.h) \ $(wildcard include/config/cpu/xscale.h) \ $(wildcard include/config/cpu/copy/v6.h) \ $(wildcard include/config/memory/hotplug/sparse.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/glue.h \ $(wildcard include/config/cpu/arm610.h) \ $(wildcard include/config/cpu/arm710.h) \ $(wildcard include/config/cpu/abrt/lv4t.h) \ $(wildcard include/config/cpu/abrt/ev4.h) \ $(wildcard include/config/cpu/abrt/ev4t.h) \ $(wildcard include/config/cpu/abrt/ev5tj.h) \ $(wildcard include/config/cpu/abrt/ev5t.h) \ $(wildcard include/config/cpu/abrt/ev6.h) \ $(wildcard include/config/cpu/abrt/ev7.h) \ $(wildcard include/config/cpu/pabrt/legacy.h) \ $(wildcard include/config/cpu/pabrt/v6.h) \ $(wildcard include/config/cpu/pabrt/v7.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/memory.h \ $(wildcard include/config/page/offset.h) \ $(wildcard include/config/thumb2/kernel.h) \ $(wildcard include/config/dram/size.h) \ $(wildcard include/config/dram/base.h) \ include/linux/const.h \ arch/arm/mach-msm/include/mach/memory.h \ $(wildcard include/config/phys/offset.h) \ $(wildcard include/config/arch/msm7x30.h) \ $(wildcard include/config/vmsplit/3g.h) \ $(wildcard include/config/arch/msm/arm11.h) \ $(wildcard include/config/cache/l2x0.h) \ $(wildcard include/config/arch/msm/scorpion.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/sizes.h \ include/asm-generic/memory_model.h \ $(wildcard include/config/sparsemem/vmemmap.h) \ include/asm-generic/getorder.h \ include/linux/memory_hotplug.h \ $(wildcard include/config/have/arch/nodedata/extension.h) \ $(wildcard include/config/memory/hotremove.h) \ include/linux/notifier.h \ include/linux/mutex.h \ $(wildcard include/config/debug/mutexes.h) \ include/linux/rwsem.h \ $(wildcard include/config/rwsem/generic/spinlock.h) \ include/linux/rwsem-spinlock.h \ include/linux/srcu.h \ include/linux/topology.h \ $(wildcard include/config/sched/smt.h) \ $(wildcard include/config/sched/mc.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/topology.h \ include/asm-generic/topology.h \ include/linux/mmdebug.h \ $(wildcard include/config/debug/virtual.h) \ include/linux/irqreturn.h \ include/linux/irqnr.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/irq.h \ arch/arm/mach-msm/include/mach/irqs.h \ $(wildcard include/config/arch/qsd8x50.h) \ $(wildcard include/config/arch/msm8x60.h) \ arch/arm/mach-msm/include/mach/irqs-8x50.h \ arch/arm/mach-msm/include/mach/sirc.h \ $(wildcard include/config/msm/soc/rev/a.h) \ arch/arm/mach-msm/include/mach/msm_iomap.h \ arch/arm/mach-msm/include/mach/msm_iomap-8x50.h \ $(wildcard include/config/mach/es209ra.h) \ $(wildcard include/config/msm/debug/uart.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/irq_regs.h \ include/asm-generic/irq_regs.h \ include/linux/percpu.h \ $(wildcard include/config/have/legacy/per/cpu/area.h) \ $(wildcard include/config/need/per/cpu/embed/first/chunk.h) \ $(wildcard include/config/need/per/cpu/page/first/chunk.h) \ $(wildcard include/config/debug/kmemleak.h) \ $(wildcard include/config/have/setup/per/cpu/area.h) \ include/linux/slab.h \ $(wildcard include/config/slab/debug.h) \ $(wildcard include/config/debug/objects.h) \ $(wildcard include/config/slub.h) \ $(wildcard include/config/slob.h) \ $(wildcard include/config/debug/slab.h) \ include/linux/slob_def.h \ include/linux/pfn.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/percpu.h \ include/asm-generic/percpu.h \ include/linux/percpu-defs.h \ $(wildcard include/config/debug/force/weak/per/cpu.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/hw_irq.h \ include/linux/sched.h \ $(wildcard include/config/sched/debug.h) \ $(wildcard include/config/no/hz.h) \ $(wildcard include/config/detect/softlockup.h) \ $(wildcard include/config/detect/hung/task.h) \ $(wildcard include/config/core/dump/default/elf/headers.h) \ $(wildcard include/config/bsd/process/acct.h) \ $(wildcard include/config/taskstats.h) \ $(wildcard include/config/audit.h) \ $(wildcard include/config/inotify/user.h) \ $(wildcard include/config/epoll.h) \ $(wildcard include/config/posix/mqueue.h) \ $(wildcard include/config/keys.h) \ $(wildcard include/config/user/sched.h) \ $(wildcard include/config/sysfs.h) \ $(wildcard include/config/perf/events.h) \ $(wildcard include/config/schedstats.h) \ $(wildcard include/config/task/delay/acct.h) \ $(wildcard include/config/fair/group/sched.h) \ $(wildcard include/config/rt/group/sched.h) \ $(wildcard include/config/blk/dev/io/trace.h) \ $(wildcard include/config/tree/preempt/rcu.h) \ $(wildcard include/config/cc/stackprotector.h) \ $(wildcard include/config/sysvipc.h) \ $(wildcard include/config/auditsyscall.h) \ $(wildcard include/config/rt/mutexes.h) \ $(wildcard include/config/task/xacct.h) \ $(wildcard include/config/cpusets.h) \ $(wildcard include/config/cgroups.h) \ $(wildcard include/config/futex.h) \ $(wildcard include/config/fault/injection.h) \ $(wildcard include/config/latencytop.h) \ $(wildcard include/config/function/graph/tracer.h) \ $(wildcard include/config/have/unstable/sched/clock.h) \ $(wildcard include/config/stack/growsup.h) \ $(wildcard include/config/debug/stack/usage.h) \ $(wildcard include/config/group/sched.h) \ $(wildcard include/config/mm/owner.h) \ include/linux/capability.h \ $(wildcard include/config/security/file/capabilities.h) \ include/linux/timex.h \ include/linux/time.h \ $(wildcard include/config/arch/uses/gettimeoffset.h) \ include/linux/math64.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/timex.h \ arch/arm/mach-msm/include/mach/timex.h \ include/linux/jiffies.h \ include/linux/rbtree.h \ include/linux/mm_types.h \ $(wildcard include/config/split/ptlock/cpus.h) \ $(wildcard include/config/want/page/debug/flags.h) \ $(wildcard include/config/aio.h) \ $(wildcard include/config/mmu/notifier.h) \ include/linux/auxvec.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/auxvec.h \ include/linux/prio_tree.h \ include/linux/completion.h \ include/linux/page-debug-flags.h \ $(wildcard include/config/page/poisoning.h) \ $(wildcard include/config/page/debug/something/else.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/mmu.h \ $(wildcard include/config/cpu/has/asid.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/cputime.h \ include/asm-generic/cputime.h \ include/linux/sem.h \ include/linux/ipc.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/ipcbuf.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/sembuf.h \ include/linux/rcupdate.h \ $(wildcard include/config/tree/rcu.h) \ include/linux/rcutree.h \ include/linux/signal.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/signal.h \ include/asm-generic/signal-defs.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/sigcontext.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/siginfo.h \ include/asm-generic/siginfo.h \ include/linux/path.h \ include/linux/pid.h \ include/linux/proportions.h \ include/linux/percpu_counter.h \ include/linux/seccomp.h \ $(wildcard include/config/seccomp.h) \ include/linux/rculist.h \ include/linux/rtmutex.h \ $(wildcard include/config/debug/rt/mutexes.h) \ include/linux/plist.h \ $(wildcard include/config/debug/pi/list.h) \ include/linux/resource.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/resource.h \ include/asm-generic/resource.h \ include/linux/timer.h \ $(wildcard include/config/timer/stats.h) \ $(wildcard include/config/debug/objects/timers.h) \ include/linux/ktime.h \ $(wildcard include/config/ktime/scalar.h) \ include/linux/debugobjects.h \ $(wildcard include/config/debug/objects/free.h) \ include/linux/hrtimer.h \ $(wildcard include/config/high/res/timers.h) \ include/linux/task_io_accounting.h \ $(wildcard include/config/task/io/accounting.h) \ include/linux/kobject.h \ include/linux/sysfs.h \ include/linux/kref.h \ include/linux/latencytop.h \ include/linux/cred.h \ $(wildcard include/config/debug/credentials.h) \ $(wildcard include/config/security.h) \ include/linux/key.h \ $(wildcard include/config/sysctl.h) \ include/linux/sysctl.h \ include/linux/selinux.h \ $(wildcard include/config/security/selinux.h) \ include/linux/aio.h \ include/linux/workqueue.h \ include/linux/aio_abi.h \ include/linux/uio.h \ include/linux/module.h \ $(wildcard include/config/modversions.h) \ $(wildcard include/config/unused/symbols.h) \ $(wildcard include/config/kallsyms.h) \ $(wildcard include/config/tracepoints.h) \ $(wildcard include/config/event/tracing.h) \ $(wildcard include/config/module/unload.h) \ $(wildcard include/config/constructors.h) \ include/linux/stat.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/stat.h \ include/linux/kmod.h \ include/linux/elf.h \ include/linux/elf-em.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/elf.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/user.h \ include/linux/moduleparam.h \ $(wildcard include/config/alpha.h) \ $(wildcard include/config/ia64.h) \ $(wildcard include/config/ppc64.h) \ include/linux/tracepoint.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/local.h \ include/asm-generic/local.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/module.h \ $(wildcard include/config/arm/unwind.h) \ include/trace/events/module.h \ include/trace/define_trace.h \ include/linux/random.h \ include/linux/ioctl.h \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/ioctl.h \ include/asm-generic/ioctl.h \ include/linux/interrupt.h \ $(wildcard include/config/pm/sleep.h) \ $(wildcard include/config/generic/irq/probe.h) \ $(wildcard include/config/debug/shirq.h) \ include/linux/hardirq.h \ $(wildcard include/config/virt/cpu/accounting.h) \ include/linux/smp_lock.h \ $(wildcard include/config/lock/kernel.h) \ include/linux/ftrace_irq.h \ $(wildcard include/config/ftrace/nmi/enter.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/hardirq.h \ include/linux/irq_cpustat.h \ include/linux/kernel_stat.h \ include/linux/hash.h \ include/linux/bootmem.h \ $(wildcard include/config/crash/dump.h) \ $(wildcard include/config/have/arch/bootmem/node.h) \ $(wildcard include/config/have/arch/alloc/remap.h) \ /home/benoit/kernel_android/32/es209ra/arch/arm/include/asm/dma.h \ $(wildcard include/config/isa/dma/api.h) \ $(wildcard include/config/pci.h) \ include/trace/events/irq.h \ kernel/irq/internals.h \ include/linux/kallsyms.h \ kernel/irq/handle.o: $(deps_kernel/irq/handle.o) $(deps_kernel/irq/handle.o):
Java
/* ---------------------------------------------------------------------- LAMMPS - Large-scale Atomic/Molecular Massively Parallel Simulator http://lammps.sandia.gov, Sandia National Laboratories Steve Plimpton, sjplimp@sandia.gov Copyright (2003) Sandia Corporation. Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation, the U.S. Government retains certain rights in this software. This software is distributed under the GNU General Public License. See the README file in the top-level LAMMPS directory. ------------------------------------------------------------------------- */ #include "fix_rigid.h" #include <mpi.h> #include <cmath> #include <cstdlib> #include <cstring> #include "math_extra.h" #include "atom.h" #include "atom_vec_ellipsoid.h" #include "atom_vec_line.h" #include "atom_vec_tri.h" #include "domain.h" #include "update.h" #include "respa.h" #include "modify.h" #include "group.h" #include "comm.h" #include "random_mars.h" #include "force.h" #include "input.h" #include "variable.h" #include "math_const.h" #include "memory.h" #include "error.h" #include "rigid_const.h" using namespace LAMMPS_NS; using namespace FixConst; using namespace MathConst; using namespace RigidConst; /* ---------------------------------------------------------------------- */ FixRigid::FixRigid(LAMMPS *lmp, int narg, char **arg) : Fix(lmp, narg, arg), step_respa(NULL), inpfile(NULL), nrigid(NULL), mol2body(NULL), body2mol(NULL), body(NULL), displace(NULL), masstotal(NULL), xcm(NULL), vcm(NULL), fcm(NULL), inertia(NULL), ex_space(NULL), ey_space(NULL), ez_space(NULL), angmom(NULL), omega(NULL), torque(NULL), quat(NULL), imagebody(NULL), fflag(NULL), tflag(NULL), langextra(NULL), sum(NULL), all(NULL), remapflag(NULL), xcmimage(NULL), eflags(NULL), orient(NULL), dorient(NULL), id_dilate(NULL), id_gravity(NULL), random(NULL), avec_ellipsoid(NULL), avec_line(NULL), avec_tri(NULL) { int i,ibody; scalar_flag = 1; extscalar = 0; time_integrate = 1; rigid_flag = 1; virial_flag = 1; thermo_virial = 1; create_attribute = 1; dof_flag = 1; enforce2d_flag = 1; MPI_Comm_rank(world,&me); MPI_Comm_size(world,&nprocs); // perform initial allocation of atom-based arrays // register with Atom class extended = orientflag = dorientflag = 0; body = NULL; xcmimage = NULL; displace = NULL; eflags = NULL; orient = NULL; dorient = NULL; grow_arrays(atom->nmax); atom->add_callback(0); // parse args for rigid body specification // set nbody and body[i] for each atom if (narg < 4) error->all(FLERR,"Illegal fix rigid command"); int iarg; mol2body = NULL; body2mol = NULL; // single rigid body // nbody = 1 // all atoms in fix group are part of body if (strcmp(arg[3],"single") == 0) { rstyle = SINGLE; iarg = 4; nbody = 1; int *mask = atom->mask; int nlocal = atom->nlocal; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) body[i] = 0; } // each molecule in fix group is a rigid body // maxmol = largest molecule ID // ncount = # of atoms in each molecule (have to sum across procs) // nbody = # of non-zero ncount values // use nall as incremented ptr to set body[] values for each atom } else if (strcmp(arg[3],"molecule") == 0 || strcmp(arg[3],"custom") == 0) { rstyle = MOLECULE; tagint *molecule; int *mask = atom->mask; int nlocal = atom->nlocal; int custom_flag = strcmp(arg[3],"custom") == 0; if (custom_flag) { if (narg < 5) error->all(FLERR,"Illegal fix rigid command"); // determine whether atom-style variable or atom property is used if (strstr(arg[4],"i_") == arg[4]) { int is_double=0; int custom_index = atom->find_custom(arg[4]+2,is_double); if (custom_index == -1) error->all(FLERR,"Fix rigid custom requires " "previously defined property/atom"); else if (is_double) error->all(FLERR,"Fix rigid custom requires " "integer-valued property/atom"); int minval = INT_MAX; int *value = atom->ivector[custom_index]; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) minval = MIN(minval,value[i]); int vmin = minval; MPI_Allreduce(&vmin,&minval,1,MPI_INT,MPI_MIN,world); molecule = new tagint[nlocal]; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) molecule[i] = (tagint)(value[i] - minval + 1); else molecule[i] = 0; } else if (strstr(arg[4],"v_") == arg[4]) { int ivariable = input->variable->find(arg[4]+2); if (ivariable < 0) error->all(FLERR,"Variable name for fix rigid custom does not exist"); if (input->variable->atomstyle(ivariable) == 0) error->all(FLERR,"Fix rigid custom variable is no atom-style variable"); double *value = new double[nlocal]; input->variable->compute_atom(ivariable,0,value,1,0); int minval = INT_MAX; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) minval = MIN(minval,(int)value[i]); int vmin = minval; MPI_Allreduce(&vmin,&minval,1,MPI_INT,MPI_MIN,world); molecule = new tagint[nlocal]; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) molecule[i] = (tagint)((tagint)value[i] - minval + 1); delete[] value; } else error->all(FLERR,"Unsupported fix rigid custom property"); } else { if (atom->molecule_flag == 0) error->all(FLERR,"Fix rigid molecule requires atom attribute molecule"); molecule = atom->molecule; } iarg = 4 + custom_flag; tagint maxmol_tag = -1; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) maxmol_tag = MAX(maxmol_tag,molecule[i]); tagint itmp; MPI_Allreduce(&maxmol_tag,&itmp,1,MPI_LMP_TAGINT,MPI_MAX,world); if (itmp+1 > MAXSMALLINT) error->all(FLERR,"Too many molecules for fix rigid"); maxmol = (int) itmp; int *ncount; memory->create(ncount,maxmol+1,"rigid:ncount"); for (i = 0; i <= maxmol; i++) ncount[i] = 0; for (i = 0; i < nlocal; i++) if (mask[i] & groupbit) ncount[molecule[i]]++; memory->create(mol2body,maxmol+1,"rigid:mol2body"); MPI_Allreduce(ncount,mol2body,maxmol+1,MPI_INT,MPI_SUM,world); nbody = 0; for (i = 0; i <= maxmol; i++) if (mol2body[i]) mol2body[i] = nbody++; else mol2body[i] = -1; memory->create(body2mol,nbody,"rigid:body2mol"); nbody = 0; for (i = 0; i <= maxmol; i++) if (mol2body[i] >= 0) body2mol[nbody++] = i; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) body[i] = mol2body[molecule[i]]; } memory->destroy(ncount); if (custom_flag) delete [] molecule; // each listed group is a rigid body // check if all listed groups exist // an atom must belong to fix group and listed group to be in rigid body // error if atom belongs to more than 1 rigid body } else if (strcmp(arg[3],"group") == 0) { if (narg < 5) error->all(FLERR,"Illegal fix rigid command"); rstyle = GROUP; nbody = force->inumeric(FLERR,arg[4]); if (nbody <= 0) error->all(FLERR,"Illegal fix rigid command"); if (narg < 5+nbody) error->all(FLERR,"Illegal fix rigid command"); iarg = 5+nbody; int *igroups = new int[nbody]; for (ibody = 0; ibody < nbody; ibody++) { igroups[ibody] = group->find(arg[5+ibody]); if (igroups[ibody] == -1) error->all(FLERR,"Could not find fix rigid group ID"); } int *mask = atom->mask; int nlocal = atom->nlocal; int flag = 0; for (i = 0; i < nlocal; i++) { body[i] = -1; if (mask[i] & groupbit) for (ibody = 0; ibody < nbody; ibody++) if (mask[i] & group->bitmask[igroups[ibody]]) { if (body[i] >= 0) flag = 1; body[i] = ibody; } } int flagall; MPI_Allreduce(&flag,&flagall,1,MPI_INT,MPI_SUM,world); if (flagall) error->all(FLERR,"One or more atoms belong to multiple rigid bodies"); delete [] igroups; } else error->all(FLERR,"Illegal fix rigid command"); // error check on nbody if (nbody == 0) error->all(FLERR,"No rigid bodies defined"); // create all nbody-length arrays memory->create(nrigid,nbody,"rigid:nrigid"); memory->create(masstotal,nbody,"rigid:masstotal"); memory->create(xcm,nbody,3,"rigid:xcm"); memory->create(vcm,nbody,3,"rigid:vcm"); memory->create(fcm,nbody,3,"rigid:fcm"); memory->create(inertia,nbody,3,"rigid:inertia"); memory->create(ex_space,nbody,3,"rigid:ex_space"); memory->create(ey_space,nbody,3,"rigid:ey_space"); memory->create(ez_space,nbody,3,"rigid:ez_space"); memory->create(angmom,nbody,3,"rigid:angmom"); memory->create(omega,nbody,3,"rigid:omega"); memory->create(torque,nbody,3,"rigid:torque"); memory->create(quat,nbody,4,"rigid:quat"); memory->create(imagebody,nbody,"rigid:imagebody"); memory->create(fflag,nbody,3,"rigid:fflag"); memory->create(tflag,nbody,3,"rigid:tflag"); memory->create(langextra,nbody,6,"rigid:langextra"); memory->create(sum,nbody,6,"rigid:sum"); memory->create(all,nbody,6,"rigid:all"); memory->create(remapflag,nbody,4,"rigid:remapflag"); // initialize force/torque flags to default = 1.0 // for 2d: fz, tx, ty = 0.0 array_flag = 1; size_array_rows = nbody; size_array_cols = 15; global_freq = 1; extarray = 0; for (i = 0; i < nbody; i++) { fflag[i][0] = fflag[i][1] = fflag[i][2] = 1.0; tflag[i][0] = tflag[i][1] = tflag[i][2] = 1.0; if (domain->dimension == 2) fflag[i][2] = tflag[i][0] = tflag[i][1] = 0.0; } // number of linear rigid bodies is counted later nlinear = 0; // parse optional args int seed; langflag = 0; reinitflag = 1; tstat_flag = 0; pstat_flag = 0; allremap = 1; t_chain = 10; t_iter = 1; t_order = 3; p_chain = 10; inpfile = NULL; id_gravity = NULL; id_dilate = NULL; pcouple = NONE; pstyle = ANISO; dimension = domain->dimension; for (int i = 0; i < 3; i++) { p_start[i] = p_stop[i] = p_period[i] = 0.0; p_flag[i] = 0; } while (iarg < narg) { if (strcmp(arg[iarg],"force") == 0) { if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command"); int mlo,mhi; force->bounds(FLERR,arg[iarg+1],nbody,mlo,mhi); double xflag,yflag,zflag; if (strcmp(arg[iarg+2],"off") == 0) xflag = 0.0; else if (strcmp(arg[iarg+2],"on") == 0) xflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+3],"off") == 0) yflag = 0.0; else if (strcmp(arg[iarg+3],"on") == 0) yflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+4],"off") == 0) zflag = 0.0; else if (strcmp(arg[iarg+4],"on") == 0) zflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (domain->dimension == 2 && zflag == 1.0) error->all(FLERR,"Fix rigid z force cannot be on for 2d simulation"); int count = 0; for (int m = mlo; m <= mhi; m++) { fflag[m-1][0] = xflag; fflag[m-1][1] = yflag; fflag[m-1][2] = zflag; count++; } if (count == 0) error->all(FLERR,"Illegal fix rigid command"); iarg += 5; } else if (strcmp(arg[iarg],"torque") == 0) { if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command"); int mlo,mhi; force->bounds(FLERR,arg[iarg+1],nbody,mlo,mhi); double xflag,yflag,zflag; if (strcmp(arg[iarg+2],"off") == 0) xflag = 0.0; else if (strcmp(arg[iarg+2],"on") == 0) xflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+3],"off") == 0) yflag = 0.0; else if (strcmp(arg[iarg+3],"on") == 0) yflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+4],"off") == 0) zflag = 0.0; else if (strcmp(arg[iarg+4],"on") == 0) zflag = 1.0; else error->all(FLERR,"Illegal fix rigid command"); if (domain->dimension == 2 && (xflag == 1.0 || yflag == 1.0)) error->all(FLERR,"Fix rigid xy torque cannot be on for 2d simulation"); int count = 0; for (int m = mlo; m <= mhi; m++) { tflag[m-1][0] = xflag; tflag[m-1][1] = yflag; tflag[m-1][2] = zflag; count++; } if (count == 0) error->all(FLERR,"Illegal fix rigid command"); iarg += 5; } else if (strcmp(arg[iarg],"langevin") == 0) { if (iarg+5 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid") != 0 && strcmp(style,"rigid/nve") != 0 && strcmp(style,"rigid/omp") != 0 && strcmp(style,"rigid/nve/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); langflag = 1; t_start = force->numeric(FLERR,arg[iarg+1]); t_stop = force->numeric(FLERR,arg[iarg+2]); t_period = force->numeric(FLERR,arg[iarg+3]); seed = force->inumeric(FLERR,arg[iarg+4]); if (t_period <= 0.0) error->all(FLERR,"Fix rigid langevin period must be > 0.0"); if (seed <= 0) error->all(FLERR,"Illegal fix rigid command"); iarg += 5; } else if (strcmp(arg[iarg],"temp") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/nvt") != 0 && strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nvt/omp") != 0 && strcmp(style,"rigid/npt/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); tstat_flag = 1; t_start = force->numeric(FLERR,arg[iarg+1]); t_stop = force->numeric(FLERR,arg[iarg+2]); t_period = force->numeric(FLERR,arg[iarg+3]); iarg += 4; } else if (strcmp(arg[iarg],"iso") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); pcouple = XYZ; p_start[0] = p_start[1] = p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = p_stop[1] = p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = p_period[1] = p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = p_flag[1] = p_flag[2] = 1; if (dimension == 2) { p_start[2] = p_stop[2] = p_period[2] = 0.0; p_flag[2] = 0; } iarg += 4; } else if (strcmp(arg[iarg],"aniso") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[0] = p_start[1] = p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = p_stop[1] = p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = p_period[1] = p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = p_flag[1] = p_flag[2] = 1; if (dimension == 2) { p_start[2] = p_stop[2] = p_period[2] = 0.0; p_flag[2] = 0; } iarg += 4; } else if (strcmp(arg[iarg],"x") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[0] = force->numeric(FLERR,arg[iarg+1]); p_stop[0] = force->numeric(FLERR,arg[iarg+2]); p_period[0] = force->numeric(FLERR,arg[iarg+3]); p_flag[0] = 1; iarg += 4; } else if (strcmp(arg[iarg],"y") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[1] = force->numeric(FLERR,arg[iarg+1]); p_stop[1] = force->numeric(FLERR,arg[iarg+2]); p_period[1] = force->numeric(FLERR,arg[iarg+3]); p_flag[1] = 1; iarg += 4; } else if (strcmp(arg[iarg],"z") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_start[2] = force->numeric(FLERR,arg[iarg+1]); p_stop[2] = force->numeric(FLERR,arg[iarg+2]); p_period[2] = force->numeric(FLERR,arg[iarg+3]); p_flag[2] = 1; iarg += 4; } else if (strcmp(arg[iarg],"couple") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(arg[iarg+1],"xyz") == 0) pcouple = XYZ; else if (strcmp(arg[iarg+1],"xy") == 0) pcouple = XY; else if (strcmp(arg[iarg+1],"yz") == 0) pcouple = YZ; else if (strcmp(arg[iarg+1],"xz") == 0) pcouple = XZ; else if (strcmp(arg[iarg+1],"none") == 0) pcouple = NONE; else error->all(FLERR,"Illegal fix rigid command"); iarg += 2; } else if (strcmp(arg[iarg],"dilate") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid npt/nph command"); if (strcmp(arg[iarg+1],"all") == 0) allremap = 1; else { allremap = 0; delete [] id_dilate; int n = strlen(arg[iarg+1]) + 1; id_dilate = new char[n]; strcpy(id_dilate,arg[iarg+1]); int idilate = group->find(id_dilate); if (idilate == -1) error->all(FLERR, "Fix rigid npt/nph dilate group ID does not exist"); } iarg += 2; } else if (strcmp(arg[iarg],"tparam") == 0) { if (iarg+4 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/nvt") != 0 && strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nvt/omp") != 0 && strcmp(style,"rigid/npt/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); t_chain = force->inumeric(FLERR,arg[iarg+1]); t_iter = force->inumeric(FLERR,arg[iarg+2]); t_order = force->inumeric(FLERR,arg[iarg+3]); iarg += 4; } else if (strcmp(arg[iarg],"pchain") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp(style,"rigid/npt") != 0 && strcmp(style,"rigid/nph") != 0 && strcmp(style,"rigid/npt/omp") != 0 && strcmp(style,"rigid/nph/omp") != 0) error->all(FLERR,"Illegal fix rigid command"); p_chain = force->inumeric(FLERR,arg[iarg+1]); iarg += 2; } else if (strcmp(arg[iarg],"infile") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); delete [] inpfile; int n = strlen(arg[iarg+1]) + 1; inpfile = new char[n]; strcpy(inpfile,arg[iarg+1]); restart_file = 1; reinitflag = 0; iarg += 2; } else if (strcmp(arg[iarg],"reinit") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); if (strcmp("yes",arg[iarg+1]) == 0) reinitflag = 1; else if (strcmp("no",arg[iarg+1]) == 0) reinitflag = 0; else error->all(FLERR,"Illegal fix rigid command"); iarg += 2; } else if (strcmp(arg[iarg],"gravity") == 0) { if (iarg+2 > narg) error->all(FLERR,"Illegal fix rigid command"); delete [] id_gravity; int n = strlen(arg[iarg+1]) + 1; id_gravity = new char[n]; strcpy(id_gravity,arg[iarg+1]); iarg += 2; } else error->all(FLERR,"Illegal fix rigid command"); } // set pstat_flag pstat_flag = 0; for (int i = 0; i < 3; i++) if (p_flag[i]) pstat_flag = 1; if (pcouple == XYZ || (dimension == 2 && pcouple == XY)) pstyle = ISO; else pstyle = ANISO; // initialize Marsaglia RNG with processor-unique seed if (langflag) random = new RanMars(lmp,seed + me); else random = NULL; // initialize vector output quantities in case accessed before run for (i = 0; i < nbody; i++) { xcm[i][0] = xcm[i][1] = xcm[i][2] = 0.0; vcm[i][0] = vcm[i][1] = vcm[i][2] = 0.0; fcm[i][0] = fcm[i][1] = fcm[i][2] = 0.0; torque[i][0] = torque[i][1] = torque[i][2] = 0.0; } // nrigid[n] = # of atoms in Nth rigid body // error if one or zero atoms int *ncount = new int[nbody]; for (ibody = 0; ibody < nbody; ibody++) ncount[ibody] = 0; int nlocal = atom->nlocal; for (i = 0; i < nlocal; i++) if (body[i] >= 0) ncount[body[i]]++; MPI_Allreduce(ncount,nrigid,nbody,MPI_INT,MPI_SUM,world); delete [] ncount; for (ibody = 0; ibody < nbody; ibody++) if (nrigid[ibody] <= 1) error->all(FLERR,"One or zero atoms in rigid body"); // wait to setup bodies until first init() using current atom properties setupflag = 0; // compute per body forces and torques at final_integrate() by default earlyflag = 0; // print statistics int nsum = 0; for (ibody = 0; ibody < nbody; ibody++) nsum += nrigid[ibody]; if (me == 0) { if (screen) fprintf(screen,"%d rigid bodies with %d atoms\n",nbody,nsum); if (logfile) fprintf(logfile,"%d rigid bodies with %d atoms\n",nbody,nsum); } } /* ---------------------------------------------------------------------- */ FixRigid::~FixRigid() { // unregister callbacks to this fix from Atom class atom->delete_callback(id,0); delete random; delete [] inpfile; delete [] id_dilate; delete [] id_gravity; memory->destroy(mol2body); memory->destroy(body2mol); // delete locally stored per-atom arrays memory->destroy(body); memory->destroy(xcmimage); memory->destroy(displace); memory->destroy(eflags); memory->destroy(orient); memory->destroy(dorient); // delete nbody-length arrays memory->destroy(nrigid); memory->destroy(masstotal); memory->destroy(xcm); memory->destroy(vcm); memory->destroy(fcm); memory->destroy(inertia); memory->destroy(ex_space); memory->destroy(ey_space); memory->destroy(ez_space); memory->destroy(angmom); memory->destroy(omega); memory->destroy(torque); memory->destroy(quat); memory->destroy(imagebody); memory->destroy(fflag); memory->destroy(tflag); memory->destroy(langextra); memory->destroy(sum); memory->destroy(all); memory->destroy(remapflag); } /* ---------------------------------------------------------------------- */ int FixRigid::setmask() { int mask = 0; mask |= INITIAL_INTEGRATE; mask |= FINAL_INTEGRATE; if (langflag) mask |= POST_FORCE; mask |= PRE_NEIGHBOR; mask |= INITIAL_INTEGRATE_RESPA; mask |= FINAL_INTEGRATE_RESPA; return mask; } /* ---------------------------------------------------------------------- */ void FixRigid::init() { int i,ibody; triclinic = domain->triclinic; // atom style pointers to particles that store extra info avec_ellipsoid = (AtomVecEllipsoid *) atom->style_match("ellipsoid"); avec_line = (AtomVecLine *) atom->style_match("line"); avec_tri = (AtomVecTri *) atom->style_match("tri"); // warn if more than one rigid fix // if earlyflag, warn if any post-force fixes come after a rigid fix int count = 0; for (i = 0; i < modify->nfix; i++) if (modify->fix[i]->rigid_flag) count++; if (count > 1 && me == 0) error->warning(FLERR,"More than one fix rigid"); if (earlyflag) { int rflag = 0; for (i = 0; i < modify->nfix; i++) { if (modify->fix[i]->rigid_flag) rflag = 1; if (rflag && (modify->fmask[i] & POST_FORCE) && !modify->fix[i]->rigid_flag) { char str[128]; snprintf(str,128,"Fix %s alters forces after fix rigid", modify->fix[i]->id); error->warning(FLERR,str); } } } // warn if body properties are read from inpfile // and the gravity keyword is not set and a gravity fix exists // this could mean body particles are overlapped // and gravity is not applied correctly if (inpfile && !id_gravity) { for (i = 0; i < modify->nfix; i++) { if (strcmp(modify->fix[i]->style,"gravity") == 0) { if (comm->me == 0) error->warning(FLERR,"Gravity may not be correctly applied " "to rigid bodies if they consist of " "overlapped particles"); break; } } } // error if npt,nph fix comes before rigid fix for (i = 0; i < modify->nfix; i++) { if (strcmp(modify->fix[i]->style,"npt") == 0) break; if (strcmp(modify->fix[i]->style,"nph") == 0) break; } if (i < modify->nfix) { for (int j = i; j < modify->nfix; j++) if (strcmp(modify->fix[j]->style,"rigid") == 0) error->all(FLERR,"Rigid fix must come before NPT/NPH fix"); } // add gravity forces based on gravity vector from fix if (id_gravity) { int ifix = modify->find_fix(id_gravity); if (ifix < 0) error->all(FLERR,"Fix rigid cannot find fix gravity ID"); if (strcmp(modify->fix[ifix]->style,"gravity") != 0) error->all(FLERR,"Fix rigid gravity fix is invalid"); int tmp; gvec = (double *) modify->fix[ifix]->extract("gvec",tmp); } // timestep info dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; dtq = 0.5 * update->dt; if (strstr(update->integrate_style,"respa")) step_respa = ((Respa *) update->integrate)->step; // setup rigid bodies, using current atom info. if reinitflag is not set, // do the initialization only once, b/c properties may not be re-computable // especially if overlapping particles. // do not do dynamic init if read body properties from inpfile. // this is b/c the inpfile defines the static and dynamic properties and may // not be computable if contain overlapping particles. // setup_bodies_static() reads inpfile itself if (reinitflag || !setupflag) { setup_bodies_static(); if (!inpfile) setup_bodies_dynamic(); setupflag = 1; } // temperature scale factor double ndof = 0.0; for (ibody = 0; ibody < nbody; ibody++) { ndof += fflag[ibody][0] + fflag[ibody][1] + fflag[ibody][2]; ndof += tflag[ibody][0] + tflag[ibody][1] + tflag[ibody][2]; } ndof -= nlinear; if (ndof > 0.0) tfactor = force->mvv2e / (ndof * force->boltz); else tfactor = 0.0; } /* ---------------------------------------------------------------------- invoke pre_neighbor() to insure body xcmimage flags are reset needed if Verlet::setup::pbc() has remapped/migrated atoms for 2nd run ------------------------------------------------------------------------- */ void FixRigid::setup_pre_neighbor() { pre_neighbor(); } /* ---------------------------------------------------------------------- compute initial fcm and torque on bodies, also initial virial reset all particle velocities to be consistent with vcm and omega ------------------------------------------------------------------------- */ void FixRigid::setup(int vflag) { int i,n,ibody; // fcm = force on center-of-mass of each rigid body double **f = atom->f; int nlocal = atom->nlocal; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; sum[ibody][0] += f[i][0]; sum[ibody][1] += f[i][1]; sum[ibody][2] += f[i][2]; } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { fcm[ibody][0] = all[ibody][0]; fcm[ibody][1] = all[ibody][1]; fcm[ibody][2] = all[ibody][2]; } // torque = torque on each rigid body double **x = atom->x; double dx,dy,dz; double unwrap[3]; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; domain->unmap(x[i],xcmimage[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; sum[ibody][0] += dy * f[i][2] - dz * f[i][1]; sum[ibody][1] += dz * f[i][0] - dx * f[i][2]; sum[ibody][2] += dx * f[i][1] - dy * f[i][0]; } // extended particles add their torque to torque of body if (extended) { double **torque_one = atom->torque; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & TORQUE) { sum[ibody][0] += torque_one[i][0]; sum[ibody][1] += torque_one[i][1]; sum[ibody][2] += torque_one[i][2]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { torque[ibody][0] = all[ibody][0]; torque[ibody][1] = all[ibody][1]; torque[ibody][2] = all[ibody][2]; } // zero langextra in case Langevin thermostat not used // no point to calling post_force() here since langextra // is only added to fcm/torque in final_integrate() for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) langextra[ibody][i] = 0.0; // virial setup before call to set_v if (vflag) v_setup(vflag); else evflag = 0; // set velocities from angmom & omega for (ibody = 0; ibody < nbody; ibody++) MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody], ez_space[ibody],inertia[ibody],omega[ibody]); set_v(); // guesstimate virial as 2x the set_v contribution if (vflag_global) for (n = 0; n < 6; n++) virial[n] *= 2.0; if (vflag_atom) { for (i = 0; i < nlocal; i++) for (n = 0; n < 6; n++) vatom[i][n] *= 2.0; } } /* ---------------------------------------------------------------------- */ void FixRigid::initial_integrate(int vflag) { double dtfm; for (int ibody = 0; ibody < nbody; ibody++) { // update vcm by 1/2 step dtfm = dtf / masstotal[ibody]; vcm[ibody][0] += dtfm * fcm[ibody][0] * fflag[ibody][0]; vcm[ibody][1] += dtfm * fcm[ibody][1] * fflag[ibody][1]; vcm[ibody][2] += dtfm * fcm[ibody][2] * fflag[ibody][2]; // update xcm by full step xcm[ibody][0] += dtv * vcm[ibody][0]; xcm[ibody][1] += dtv * vcm[ibody][1]; xcm[ibody][2] += dtv * vcm[ibody][2]; // update angular momentum by 1/2 step angmom[ibody][0] += dtf * torque[ibody][0] * tflag[ibody][0]; angmom[ibody][1] += dtf * torque[ibody][1] * tflag[ibody][1]; angmom[ibody][2] += dtf * torque[ibody][2] * tflag[ibody][2]; // compute omega at 1/2 step from angmom at 1/2 step and current q // update quaternion a full step via Richardson iteration // returns new normalized quaternion, also updated omega at 1/2 step // update ex,ey,ez to reflect new quaternion MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody], ez_space[ibody],inertia[ibody],omega[ibody]); MathExtra::richardson(quat[ibody],angmom[ibody],omega[ibody], inertia[ibody],dtq); MathExtra::q_to_exyz(quat[ibody], ex_space[ibody],ey_space[ibody],ez_space[ibody]); } // virial setup before call to set_xv if (vflag) v_setup(vflag); else evflag = 0; // set coords/orient and velocity/rotation of atoms in rigid bodies // from quarternion and omega set_xv(); } /* ---------------------------------------------------------------------- apply Langevin thermostat to all 6 DOF of rigid bodies computed by proc 0, broadcast to other procs unlike fix langevin, this stores extra force in extra arrays, which are added in when final_integrate() calculates a new fcm/torque ------------------------------------------------------------------------- */ void FixRigid::apply_langevin_thermostat() { if (me == 0) { double gamma1,gamma2; double delta = update->ntimestep - update->beginstep; if (delta != 0.0) delta /= update->endstep - update->beginstep; t_target = t_start + delta * (t_stop-t_start); double tsqrt = sqrt(t_target); double boltz = force->boltz; double dt = update->dt; double mvv2e = force->mvv2e; double ftm2v = force->ftm2v; for (int i = 0; i < nbody; i++) { gamma1 = -masstotal[i] / t_period / ftm2v; gamma2 = sqrt(masstotal[i]) * tsqrt * sqrt(24.0*boltz/t_period/dt/mvv2e) / ftm2v; langextra[i][0] = gamma1*vcm[i][0] + gamma2*(random->uniform()-0.5); langextra[i][1] = gamma1*vcm[i][1] + gamma2*(random->uniform()-0.5); langextra[i][2] = gamma1*vcm[i][2] + gamma2*(random->uniform()-0.5); gamma1 = -1.0 / t_period / ftm2v; gamma2 = tsqrt * sqrt(24.0*boltz/t_period/dt/mvv2e) / ftm2v; langextra[i][3] = inertia[i][0]*gamma1*omega[i][0] + sqrt(inertia[i][0])*gamma2*(random->uniform()-0.5); langextra[i][4] = inertia[i][1]*gamma1*omega[i][1] + sqrt(inertia[i][1])*gamma2*(random->uniform()-0.5); langextra[i][5] = inertia[i][2]*gamma1*omega[i][2] + sqrt(inertia[i][2])*gamma2*(random->uniform()-0.5); } } MPI_Bcast(&langextra[0][0],6*nbody,MPI_DOUBLE,0,world); } /* ---------------------------------------------------------------------- called from FixEnforce2d post_force() for 2d problems zero all body values that should be zero for 2d model ------------------------------------------------------------------------- */ void FixRigid::enforce2d() { for (int ibody = 0; ibody < nbody; ibody++) { xcm[ibody][2] = 0.0; vcm[ibody][2] = 0.0; fcm[ibody][2] = 0.0; torque[ibody][0] = 0.0; torque[ibody][1] = 0.0; angmom[ibody][0] = 0.0; angmom[ibody][1] = 0.0; omega[ibody][0] = 0.0; omega[ibody][1] = 0.0; if (langflag && langextra) { langextra[ibody][2] = 0.0; langextra[ibody][3] = 0.0; langextra[ibody][4] = 0.0; } } } /* ---------------------------------------------------------------------- */ void FixRigid::compute_forces_and_torques() { int i,ibody; // sum over atoms to get force and torque on rigid body double **x = atom->x; double **f = atom->f; int nlocal = atom->nlocal; double dx,dy,dz; double unwrap[3]; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; sum[ibody][0] += f[i][0]; sum[ibody][1] += f[i][1]; sum[ibody][2] += f[i][2]; domain->unmap(x[i],xcmimage[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; sum[ibody][3] += dy*f[i][2] - dz*f[i][1]; sum[ibody][4] += dz*f[i][0] - dx*f[i][2]; sum[ibody][5] += dx*f[i][1] - dy*f[i][0]; } // extended particles add their torque to torque of body if (extended) { double **torque_one = atom->torque; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & TORQUE) { sum[ibody][3] += torque_one[i][0]; sum[ibody][4] += torque_one[i][1]; sum[ibody][5] += torque_one[i][2]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // include Langevin thermostat forces for (ibody = 0; ibody < nbody; ibody++) { fcm[ibody][0] = all[ibody][0] + langextra[ibody][0]; fcm[ibody][1] = all[ibody][1] + langextra[ibody][1]; fcm[ibody][2] = all[ibody][2] + langextra[ibody][2]; torque[ibody][0] = all[ibody][3] + langextra[ibody][3]; torque[ibody][1] = all[ibody][4] + langextra[ibody][4]; torque[ibody][2] = all[ibody][5] + langextra[ibody][5]; } // add gravity force to COM of each body if (id_gravity) { for (ibody = 0; ibody < nbody; ibody++) { fcm[ibody][0] += gvec[0]*masstotal[ibody]; fcm[ibody][1] += gvec[1]*masstotal[ibody]; fcm[ibody][2] += gvec[2]*masstotal[ibody]; } } } /* ---------------------------------------------------------------------- */ void FixRigid::post_force(int /*vflag*/) { if (langflag) apply_langevin_thermostat(); if (earlyflag) compute_forces_and_torques(); } /* ---------------------------------------------------------------------- */ void FixRigid::final_integrate() { int ibody; double dtfm; if (!earlyflag) compute_forces_and_torques(); // update vcm and angmom // fflag,tflag = 0 for some dimensions in 2d for (ibody = 0; ibody < nbody; ibody++) { // update vcm by 1/2 step dtfm = dtf / masstotal[ibody]; vcm[ibody][0] += dtfm * fcm[ibody][0] * fflag[ibody][0]; vcm[ibody][1] += dtfm * fcm[ibody][1] * fflag[ibody][1]; vcm[ibody][2] += dtfm * fcm[ibody][2] * fflag[ibody][2]; // update angular momentum by 1/2 step angmom[ibody][0] += dtf * torque[ibody][0] * tflag[ibody][0]; angmom[ibody][1] += dtf * torque[ibody][1] * tflag[ibody][1]; angmom[ibody][2] += dtf * torque[ibody][2] * tflag[ibody][2]; MathExtra::angmom_to_omega(angmom[ibody],ex_space[ibody],ey_space[ibody], ez_space[ibody],inertia[ibody],omega[ibody]); } // set velocity/rotation of atoms in rigid bodies // virial is already setup from initial_integrate set_v(); } /* ---------------------------------------------------------------------- */ void FixRigid::initial_integrate_respa(int vflag, int ilevel, int /*iloop*/) { dtv = step_respa[ilevel]; dtf = 0.5 * step_respa[ilevel] * force->ftm2v; dtq = 0.5 * step_respa[ilevel]; if (ilevel == 0) initial_integrate(vflag); else final_integrate(); } /* ---------------------------------------------------------------------- */ void FixRigid::final_integrate_respa(int ilevel, int /*iloop*/) { dtf = 0.5 * step_respa[ilevel] * force->ftm2v; final_integrate(); } /* ---------------------------------------------------------------------- remap xcm of each rigid body back into periodic simulation box done during pre_neighbor so will be after call to pbc() and after fix_deform::pre_exchange() may have flipped box use domain->remap() in case xcm is far away from box due to first-time definition of rigid body in setup_bodies_static() or due to box flip also adjust imagebody = rigid body image flags, due to xcm remap also reset body xcmimage flags of all atoms in bodies xcmimage flags are relative to xcm so that body can be unwrapped if don't do this, would need xcm to move with true image flags then a body could end up very far away from box set_xv() will then compute huge displacements every step to reset coords of all body atoms to be back inside the box, ditto for triclinic box flip, which causes numeric problems ------------------------------------------------------------------------- */ void FixRigid::pre_neighbor() { for (int ibody = 0; ibody < nbody; ibody++) domain->remap(xcm[ibody],imagebody[ibody]); image_shift(); } /* ---------------------------------------------------------------------- reset body xcmimage flags of atoms in bodies xcmimage flags are relative to xcm so that body can be unwrapped xcmimage = true image flag - imagebody flag ------------------------------------------------------------------------- */ void FixRigid::image_shift() { int ibody; imageint tdim,bdim,xdim[3]; imageint *image = atom->image; int nlocal = atom->nlocal; for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; tdim = image[i] & IMGMASK; bdim = imagebody[ibody] & IMGMASK; xdim[0] = IMGMAX + tdim - bdim; tdim = (image[i] >> IMGBITS) & IMGMASK; bdim = (imagebody[ibody] >> IMGBITS) & IMGMASK; xdim[1] = IMGMAX + tdim - bdim; tdim = image[i] >> IMG2BITS; bdim = imagebody[ibody] >> IMG2BITS; xdim[2] = IMGMAX + tdim - bdim; xcmimage[i] = (xdim[2] << IMG2BITS) | (xdim[1] << IMGBITS) | xdim[0]; } } /* ---------------------------------------------------------------------- count # of DOF removed by rigid bodies for atoms in igroup return total count of DOF ------------------------------------------------------------------------- */ int FixRigid::dof(int tgroup) { // cannot count DOF correctly unless setup_bodies_static() has been called if (!setupflag) { if (comm->me == 0) error->warning(FLERR,"Cannot count rigid body degrees-of-freedom " "before bodies are initialized"); return 0; } int tgroupbit = group->bitmask[tgroup]; // nall = # of point particles in each rigid body // mall = # of finite-size particles in each rigid body // particles must also be in temperature group int *mask = atom->mask; int nlocal = atom->nlocal; int *ncount = new int[nbody]; int *mcount = new int[nbody]; for (int ibody = 0; ibody < nbody; ibody++) ncount[ibody] = mcount[ibody] = 0; for (int i = 0; i < nlocal; i++) if (body[i] >= 0 && mask[i] & tgroupbit) { // do not count point particles or point dipoles as extended particles // a spheroid dipole will be counted as extended if (extended && (eflags[i] & ~(POINT | DIPOLE))) mcount[body[i]]++; else ncount[body[i]]++; } int *nall = new int[nbody]; int *mall = new int[nbody]; MPI_Allreduce(ncount,nall,nbody,MPI_INT,MPI_SUM,world); MPI_Allreduce(mcount,mall,nbody,MPI_INT,MPI_SUM,world); // warn if nall+mall != nrigid for any body included in temperature group int flag = 0; for (int ibody = 0; ibody < nbody; ibody++) { if (nall[ibody]+mall[ibody] > 0 && nall[ibody]+mall[ibody] != nrigid[ibody]) flag = 1; } if (flag && me == 0) error->warning(FLERR,"Computing temperature of portions of rigid bodies"); // remove appropriate DOFs for each rigid body wholly in temperature group // N = # of point particles in body // M = # of finite-size particles in body // 3d body has 3N + 6M dof to start with // 2d body has 2N + 3M dof to start with // 3d point-particle body with all non-zero I should have 6 dof, remove 3N-6 // 3d point-particle body (linear) with a 0 I should have 5 dof, remove 3N-5 // 2d point-particle body should have 3 dof, remove 2N-3 // 3d body with any finite-size M should have 6 dof, remove (3N+6M) - 6 // 2d body with any finite-size M should have 3 dof, remove (2N+3M) - 3 int n = 0; nlinear = 0; if (domain->dimension == 3) { for (int ibody = 0; ibody < nbody; ibody++) if (nall[ibody]+mall[ibody] == nrigid[ibody]) { n += 3*nall[ibody] + 6*mall[ibody] - 6; if (inertia[ibody][0] == 0.0 || inertia[ibody][1] == 0.0 || inertia[ibody][2] == 0.0) { n++; nlinear++; } } } else if (domain->dimension == 2) { for (int ibody = 0; ibody < nbody; ibody++) if (nall[ibody]+mall[ibody] == nrigid[ibody]) n += 2*nall[ibody] + 3*mall[ibody] - 3; } delete [] ncount; delete [] mcount; delete [] nall; delete [] mall; return n; } /* ---------------------------------------------------------------------- adjust xcm of each rigid body due to box deformation called by various fixes that change box size/shape flag = 0/1 means map from box to lamda coords or vice versa ------------------------------------------------------------------------- */ void FixRigid::deform(int flag) { if (flag == 0) for (int ibody = 0; ibody < nbody; ibody++) domain->x2lamda(xcm[ibody],xcm[ibody]); else for (int ibody = 0; ibody < nbody; ibody++) domain->lamda2x(xcm[ibody],xcm[ibody]); } /* ---------------------------------------------------------------------- set space-frame coords and velocity of each atom in each rigid body set orientation and rotation of extended particles x = Q displace + Xcm, mapped back to periodic box v = Vcm + (W cross (x - Xcm)) ------------------------------------------------------------------------- */ void FixRigid::set_xv() { int ibody; int xbox,ybox,zbox; double x0,x1,x2,v0,v1,v2,fc0,fc1,fc2,massone; double xy,xz,yz; double ione[3],exone[3],eyone[3],ezone[3],vr[6],p[3][3]; double **x = atom->x; double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; if (triclinic) { xy = domain->xy; xz = domain->xz; yz = domain->yz; } // set x and v of each atom for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; // save old positions and velocities for virial if (evflag) { if (triclinic == 0) { x0 = x[i][0] + xbox*xprd; x1 = x[i][1] + ybox*yprd; x2 = x[i][2] + zbox*zprd; } else { x0 = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; x1 = x[i][1] + ybox*yprd + zbox*yz; x2 = x[i][2] + zbox*zprd; } v0 = v[i][0]; v1 = v[i][1]; v2 = v[i][2]; } // x = displacement from center-of-mass, based on body orientation // v = vcm + omega around center-of-mass MathExtra::matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],displace[i],x[i]); v[i][0] = omega[ibody][1]*x[i][2] - omega[ibody][2]*x[i][1] + vcm[ibody][0]; v[i][1] = omega[ibody][2]*x[i][0] - omega[ibody][0]*x[i][2] + vcm[ibody][1]; v[i][2] = omega[ibody][0]*x[i][1] - omega[ibody][1]*x[i][0] + vcm[ibody][2]; // add center of mass to displacement // map back into periodic box via xbox,ybox,zbox // for triclinic, add in box tilt factors as well if (triclinic == 0) { x[i][0] += xcm[ibody][0] - xbox*xprd; x[i][1] += xcm[ibody][1] - ybox*yprd; x[i][2] += xcm[ibody][2] - zbox*zprd; } else { x[i][0] += xcm[ibody][0] - xbox*xprd - ybox*xy - zbox*xz; x[i][1] += xcm[ibody][1] - ybox*yprd - zbox*yz; x[i][2] += xcm[ibody][2] - zbox*zprd; } // virial = unwrapped coords dotted into body constraint force // body constraint force = implied force due to v change minus f external // assume f does not include forces internal to body // 1/2 factor b/c final_integrate contributes other half // assume per-atom contribution is due to constraint force on that atom if (evflag) { if (rmass) massone = rmass[i]; else massone = mass[type[i]]; fc0 = massone*(v[i][0] - v0)/dtf - f[i][0]; fc1 = massone*(v[i][1] - v1)/dtf - f[i][1]; fc2 = massone*(v[i][2] - v2)/dtf - f[i][2]; vr[0] = 0.5*x0*fc0; vr[1] = 0.5*x1*fc1; vr[2] = 0.5*x2*fc2; vr[3] = 0.5*x0*fc1; vr[4] = 0.5*x0*fc2; vr[5] = 0.5*x1*fc2; v_tally(1,&i,1.0,vr); } } // set orientation, omega, angmom of each extended particle if (extended) { double theta_body,theta; double *shape,*quatatom,*inertiaatom; AtomVecEllipsoid::Bonus *ebonus; if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus; AtomVecLine::Bonus *lbonus; if (avec_line) lbonus = avec_line->bonus; AtomVecTri::Bonus *tbonus; if (avec_tri) tbonus = avec_tri->bonus; double **omega_one = atom->omega; double **angmom_one = atom->angmom; double **mu = atom->mu; int *ellipsoid = atom->ellipsoid; int *line = atom->line; int *tri = atom->tri; for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & SPHERE) { omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; quatatom = ebonus[ellipsoid[i]].quat; MathExtra::quatquat(quat[ibody],orient[i],quatatom); MathExtra::qnormalize(quatatom); ione[0] = EINERTIA*rmass[i] * (shape[1]*shape[1] + shape[2]*shape[2]); ione[1] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[2]*shape[2]); ione[2] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[1]*shape[1]); MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone,ione, angmom_one[i]); } else if (eflags[i] & LINE) { if (quat[ibody][3] >= 0.0) theta_body = 2.0*acos(quat[ibody][0]); else theta_body = -2.0*acos(quat[ibody][0]); theta = orient[i][0] + theta_body; while (theta <= -MY_PI) theta += MY_2PI; while (theta > MY_PI) theta -= MY_2PI; lbonus[line[i]].theta = theta; omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; quatatom = tbonus[tri[i]].quat; MathExtra::quatquat(quat[ibody],orient[i],quatatom); MathExtra::qnormalize(quatatom); MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone, inertiaatom,angmom_one[i]); } if (eflags[i] & DIPOLE) { MathExtra::quat_to_mat(quat[ibody],p); MathExtra::matvec(p,dorient[i],mu[i]); MathExtra::snormalize3(mu[i][3],mu[i],mu[i]); } } } } /* ---------------------------------------------------------------------- set space-frame velocity of each atom in a rigid body set omega and angmom of extended particles v = Vcm + (W cross (x - Xcm)) ------------------------------------------------------------------------- */ void FixRigid::set_v() { int xbox,ybox,zbox; double x0,x1,x2,v0,v1,v2,fc0,fc1,fc2,massone; double xy,xz,yz; double ione[3],exone[3],eyone[3],ezone[3],delta[3],vr[6]; double **x = atom->x; double **v = atom->v; double **f = atom->f; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; if (triclinic) { xy = domain->xy; xz = domain->xz; yz = domain->yz; } // set v of each atom for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; const int ibody = body[i]; MathExtra::matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],displace[i],delta); // save old velocities for virial if (evflag) { v0 = v[i][0]; v1 = v[i][1]; v2 = v[i][2]; } v[i][0] = omega[ibody][1]*delta[2] - omega[ibody][2]*delta[1] + vcm[ibody][0]; v[i][1] = omega[ibody][2]*delta[0] - omega[ibody][0]*delta[2] + vcm[ibody][1]; v[i][2] = omega[ibody][0]*delta[1] - omega[ibody][1]*delta[0] + vcm[ibody][2]; // virial = unwrapped coords dotted into body constraint force // body constraint force = implied force due to v change minus f external // assume f does not include forces internal to body // 1/2 factor b/c initial_integrate contributes other half // assume per-atom contribution is due to constraint force on that atom if (evflag) { if (rmass) massone = rmass[i]; else massone = mass[type[i]]; fc0 = massone*(v[i][0] - v0)/dtf - f[i][0]; fc1 = massone*(v[i][1] - v1)/dtf - f[i][1]; fc2 = massone*(v[i][2] - v2)/dtf - f[i][2]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (triclinic == 0) { x0 = x[i][0] + xbox*xprd; x1 = x[i][1] + ybox*yprd; x2 = x[i][2] + zbox*zprd; } else { x0 = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; x1 = x[i][1] + ybox*yprd + zbox*yz; x2 = x[i][2] + zbox*zprd; } vr[0] = 0.5*x0*fc0; vr[1] = 0.5*x1*fc1; vr[2] = 0.5*x2*fc2; vr[3] = 0.5*x0*fc1; vr[4] = 0.5*x0*fc2; vr[5] = 0.5*x1*fc2; v_tally(1,&i,1.0,vr); } } // set omega, angmom of each extended particle if (extended) { double *shape,*quatatom,*inertiaatom; AtomVecEllipsoid::Bonus *ebonus; if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus; AtomVecTri::Bonus *tbonus; if (avec_tri) tbonus = avec_tri->bonus; double **omega_one = atom->omega; double **angmom_one = atom->angmom; int *ellipsoid = atom->ellipsoid; int *tri = atom->tri; for (int i = 0; i < nlocal; i++) { if (body[i] < 0) continue; const int ibody = body[i]; if (eflags[i] & SPHERE) { omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; quatatom = ebonus[ellipsoid[i]].quat; ione[0] = EINERTIA*rmass[i] * (shape[1]*shape[1] + shape[2]*shape[2]); ione[1] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[2]*shape[2]); ione[2] = EINERTIA*rmass[i] * (shape[0]*shape[0] + shape[1]*shape[1]); MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone,ione, angmom_one[i]); } else if (eflags[i] & LINE) { omega_one[i][0] = omega[ibody][0]; omega_one[i][1] = omega[ibody][1]; omega_one[i][2] = omega[ibody][2]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; quatatom = tbonus[tri[i]].quat; MathExtra::q_to_exyz(quatatom,exone,eyone,ezone); MathExtra::omega_to_angmom(omega[ibody],exone,eyone,ezone, inertiaatom,angmom_one[i]); } } } } /* ---------------------------------------------------------------------- one-time initialization of static rigid body attributes sets extended flags, masstotal, center-of-mass sets Cartesian and diagonalized inertia tensor sets body image flags may read some properties from inpfile ------------------------------------------------------------------------- */ void FixRigid::setup_bodies_static() { int i,ibody; // extended = 1 if any particle in a rigid body is finite size // or has a dipole moment extended = orientflag = dorientflag = 0; AtomVecEllipsoid::Bonus *ebonus; if (avec_ellipsoid) ebonus = avec_ellipsoid->bonus; AtomVecLine::Bonus *lbonus; if (avec_line) lbonus = avec_line->bonus; AtomVecTri::Bonus *tbonus; if (avec_tri) tbonus = avec_tri->bonus; double **mu = atom->mu; double *radius = atom->radius; double *rmass = atom->rmass; double *mass = atom->mass; int *ellipsoid = atom->ellipsoid; int *line = atom->line; int *tri = atom->tri; int *type = atom->type; int nlocal = atom->nlocal; if (atom->radius_flag || atom->ellipsoid_flag || atom->line_flag || atom->tri_flag || atom->mu_flag) { int flag = 0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; if (radius && radius[i] > 0.0) flag = 1; if (ellipsoid && ellipsoid[i] >= 0) flag = 1; if (line && line[i] >= 0) flag = 1; if (tri && tri[i] >= 0) flag = 1; if (mu && mu[i][3] > 0.0) flag = 1; } MPI_Allreduce(&flag,&extended,1,MPI_INT,MPI_MAX,world); } // grow extended arrays and set extended flags for each particle // orientflag = 4 if any particle stores ellipsoid or tri orientation // orientflag = 1 if any particle stores line orientation // dorientflag = 1 if any particle stores dipole orientation if (extended) { if (atom->ellipsoid_flag) orientflag = 4; if (atom->line_flag) orientflag = 1; if (atom->tri_flag) orientflag = 4; if (atom->mu_flag) dorientflag = 1; grow_arrays(atom->nmax); for (i = 0; i < nlocal; i++) { eflags[i] = 0; if (body[i] < 0) continue; // set to POINT or SPHERE or ELLIPSOID or LINE if (radius && radius[i] > 0.0) { eflags[i] |= SPHERE; eflags[i] |= OMEGA; eflags[i] |= TORQUE; } else if (ellipsoid && ellipsoid[i] >= 0) { eflags[i] |= ELLIPSOID; eflags[i] |= ANGMOM; eflags[i] |= TORQUE; } else if (line && line[i] >= 0) { eflags[i] |= LINE; eflags[i] |= OMEGA; eflags[i] |= TORQUE; } else if (tri && tri[i] >= 0) { eflags[i] |= TRIANGLE; eflags[i] |= ANGMOM; eflags[i] |= TORQUE; } else eflags[i] |= POINT; // set DIPOLE if atom->mu and mu[3] > 0.0 if (atom->mu_flag && mu[i][3] > 0.0) eflags[i] |= DIPOLE; } } // set body xcmimage flags = true image flags imageint *image = atom->image; for (i = 0; i < nlocal; i++) if (body[i] >= 0) xcmimage[i] = image[i]; else xcmimage[i] = 0; // compute masstotal & center-of-mass of each rigid body // error if image flag is not 0 in a non-periodic dim double **x = atom->x; int *periodicity = domain->periodicity; double xprd = domain->xprd; double yprd = domain->yprd; double zprd = domain->zprd; double xy = domain->xy; double xz = domain->xz; double yz = domain->yz; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; int xbox,ybox,zbox; double massone,xunwrap,yunwrap,zunwrap; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if ((xbox && !periodicity[0]) || (ybox && !periodicity[1]) || (zbox && !periodicity[2])) error->one(FLERR,"Fix rigid atom has non-zero image flag " "in a non-periodic dimension"); if (triclinic == 0) { xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; } else { xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; yunwrap = x[i][1] + ybox*yprd + zbox*yz; zunwrap = x[i][2] + zbox*zprd; } sum[ibody][0] += xunwrap * massone; sum[ibody][1] += yunwrap * massone; sum[ibody][2] += zunwrap * massone; sum[ibody][3] += massone; } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); for (ibody = 0; ibody < nbody; ibody++) { masstotal[ibody] = all[ibody][3]; xcm[ibody][0] = all[ibody][0]/masstotal[ibody]; xcm[ibody][1] = all[ibody][1]/masstotal[ibody]; xcm[ibody][2] = all[ibody][2]/masstotal[ibody]; } // set vcm, angmom = 0.0 in case inpfile is used // and doesn't overwrite all body's values // since setup_bodies_dynamic() will not be called for (ibody = 0; ibody < nbody; ibody++) { vcm[ibody][0] = vcm[ibody][1] = vcm[ibody][2] = 0.0; angmom[ibody][0] = angmom[ibody][1] = angmom[ibody][2] = 0.0; } // set rigid body image flags to default values for (ibody = 0; ibody < nbody; ibody++) imagebody[ibody] = ((imageint) IMGMAX << IMG2BITS) | ((imageint) IMGMAX << IMGBITS) | IMGMAX; // overwrite masstotal, center-of-mass, image flags with file values // inbody[i] = 0/1 if Ith rigid body is initialized by file int *inbody; if (inpfile) { memory->create(inbody,nbody,"rigid:inbody"); for (ibody = 0; ibody < nbody; ibody++) inbody[ibody] = 0; readfile(0,masstotal,xcm,vcm,angmom,imagebody,inbody); } // remap the xcm of each body back into simulation box // and reset body and atom xcmimage flags via pre_neighbor() pre_neighbor(); // compute 6 moments of inertia of each body in Cartesian reference frame // dx,dy,dz = coords relative to center-of-mass // symmetric 3x3 inertia tensor stored in Voigt notation as 6-vector double dx,dy,dz; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (triclinic == 0) { xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; } else { xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; yunwrap = x[i][1] + ybox*yprd + zbox*yz; zunwrap = x[i][2] + zbox*zprd; } dx = xunwrap - xcm[ibody][0]; dy = yunwrap - xcm[ibody][1]; dz = zunwrap - xcm[ibody][2]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; sum[ibody][0] += massone * (dy*dy + dz*dz); sum[ibody][1] += massone * (dx*dx + dz*dz); sum[ibody][2] += massone * (dx*dx + dy*dy); sum[ibody][3] -= massone * dy*dz; sum[ibody][4] -= massone * dx*dz; sum[ibody][5] -= massone * dx*dy; } // extended particles may contribute extra terms to moments of inertia if (extended) { double ivec[6]; double *shape,*quatatom,*inertiaatom; double length,theta; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if (eflags[i] & SPHERE) { sum[ibody][0] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][1] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][2] += SINERTIA*massone * radius[i]*radius[i]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; quatatom = ebonus[ellipsoid[i]].quat; MathExtra::inertia_ellipsoid(shape,quatatom,massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & LINE) { length = lbonus[line[i]].length; theta = lbonus[line[i]].theta; MathExtra::inertia_line(length,theta,massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; quatatom = tbonus[tri[i]].quat; MathExtra::inertia_triangle(inertiaatom,quatatom,massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // overwrite Cartesian inertia tensor with file values if (inpfile) readfile(1,NULL,all,NULL,NULL,NULL,inbody); // diagonalize inertia tensor for each body via Jacobi rotations // inertia = 3 eigenvalues = principal moments of inertia // evectors and exzy_space = 3 evectors = principal axes of rigid body int ierror; double cross[3]; double tensor[3][3],evectors[3][3]; for (ibody = 0; ibody < nbody; ibody++) { tensor[0][0] = all[ibody][0]; tensor[1][1] = all[ibody][1]; tensor[2][2] = all[ibody][2]; tensor[1][2] = tensor[2][1] = all[ibody][3]; tensor[0][2] = tensor[2][0] = all[ibody][4]; tensor[0][1] = tensor[1][0] = all[ibody][5]; ierror = MathExtra::jacobi(tensor,inertia[ibody],evectors); if (ierror) error->all(FLERR, "Insufficient Jacobi rotations for rigid body"); ex_space[ibody][0] = evectors[0][0]; ex_space[ibody][1] = evectors[1][0]; ex_space[ibody][2] = evectors[2][0]; ey_space[ibody][0] = evectors[0][1]; ey_space[ibody][1] = evectors[1][1]; ey_space[ibody][2] = evectors[2][1]; ez_space[ibody][0] = evectors[0][2]; ez_space[ibody][1] = evectors[1][2]; ez_space[ibody][2] = evectors[2][2]; // if any principal moment < scaled EPSILON, set to 0.0 double max; max = MAX(inertia[ibody][0],inertia[ibody][1]); max = MAX(max,inertia[ibody][2]); if (inertia[ibody][0] < EPSILON*max) inertia[ibody][0] = 0.0; if (inertia[ibody][1] < EPSILON*max) inertia[ibody][1] = 0.0; if (inertia[ibody][2] < EPSILON*max) inertia[ibody][2] = 0.0; // enforce 3 evectors as a right-handed coordinate system // flip 3rd vector if needed MathExtra::cross3(ex_space[ibody],ey_space[ibody],cross); if (MathExtra::dot3(cross,ez_space[ibody]) < 0.0) MathExtra::negate3(ez_space[ibody]); // create initial quaternion MathExtra::exyz_to_q(ex_space[ibody],ey_space[ibody],ez_space[ibody], quat[ibody]); } // displace = initial atom coords in basis of principal axes // set displace = 0.0 for atoms not in any rigid body // for extended particles, set their orientation wrt to rigid body double qc[4],delta[3]; double *quatatom; double theta_body; for (i = 0; i < nlocal; i++) { if (body[i] < 0) { displace[i][0] = displace[i][1] = displace[i][2] = 0.0; continue; } ibody = body[i]; xbox = (xcmimage[i] & IMGMASK) - IMGMAX; ybox = (xcmimage[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (xcmimage[i] >> IMG2BITS) - IMGMAX; if (triclinic == 0) { xunwrap = x[i][0] + xbox*xprd; yunwrap = x[i][1] + ybox*yprd; zunwrap = x[i][2] + zbox*zprd; } else { xunwrap = x[i][0] + xbox*xprd + ybox*xy + zbox*xz; yunwrap = x[i][1] + ybox*yprd + zbox*yz; zunwrap = x[i][2] + zbox*zprd; } delta[0] = xunwrap - xcm[ibody][0]; delta[1] = yunwrap - xcm[ibody][1]; delta[2] = zunwrap - xcm[ibody][2]; MathExtra::transpose_matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],delta,displace[i]); if (extended) { if (eflags[i] & ELLIPSOID) { quatatom = ebonus[ellipsoid[i]].quat; MathExtra::qconjugate(quat[ibody],qc); MathExtra::quatquat(qc,quatatom,orient[i]); MathExtra::qnormalize(orient[i]); } else if (eflags[i] & LINE) { if (quat[ibody][3] >= 0.0) theta_body = 2.0*acos(quat[ibody][0]); else theta_body = -2.0*acos(quat[ibody][0]); orient[i][0] = lbonus[line[i]].theta - theta_body; while (orient[i][0] <= -MY_PI) orient[i][0] += MY_2PI; while (orient[i][0] > MY_PI) orient[i][0] -= MY_2PI; if (orientflag == 4) orient[i][1] = orient[i][2] = orient[i][3] = 0.0; } else if (eflags[i] & TRIANGLE) { quatatom = tbonus[tri[i]].quat; MathExtra::qconjugate(quat[ibody],qc); MathExtra::quatquat(qc,quatatom,orient[i]); MathExtra::qnormalize(orient[i]); } else if (orientflag == 4) { orient[i][0] = orient[i][1] = orient[i][2] = orient[i][3] = 0.0; } else if (orientflag == 1) orient[i][0] = 0.0; if (eflags[i] & DIPOLE) { MathExtra::transpose_matvec(ex_space[ibody],ey_space[ibody], ez_space[ibody],mu[i],dorient[i]); MathExtra::snormalize3(mu[i][3],dorient[i],dorient[i]); } else if (dorientflag) dorient[i][0] = dorient[i][1] = dorient[i][2] = 0.0; } } // test for valid principal moments & axes // recompute moments of inertia around new axes // 3 diagonal moments should equal principal moments // 3 off-diagonal moments should be 0.0 // extended particles may contribute extra terms to moments of inertia for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; sum[ibody][0] += massone * (displace[i][1]*displace[i][1] + displace[i][2]*displace[i][2]); sum[ibody][1] += massone * (displace[i][0]*displace[i][0] + displace[i][2]*displace[i][2]); sum[ibody][2] += massone * (displace[i][0]*displace[i][0] + displace[i][1]*displace[i][1]); sum[ibody][3] -= massone * displace[i][1]*displace[i][2]; sum[ibody][4] -= massone * displace[i][0]*displace[i][2]; sum[ibody][5] -= massone * displace[i][0]*displace[i][1]; } if (extended) { double ivec[6]; double *shape,*inertiaatom; double length; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; if (eflags[i] & SPHERE) { sum[ibody][0] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][1] += SINERTIA*massone * radius[i]*radius[i]; sum[ibody][2] += SINERTIA*massone * radius[i]*radius[i]; } else if (eflags[i] & ELLIPSOID) { shape = ebonus[ellipsoid[i]].shape; MathExtra::inertia_ellipsoid(shape,orient[i],massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & LINE) { length = lbonus[line[i]].length; MathExtra::inertia_line(length,orient[i][0],massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } else if (eflags[i] & TRIANGLE) { inertiaatom = tbonus[tri[i]].inertia; MathExtra::inertia_triangle(inertiaatom,orient[i],massone,ivec); sum[ibody][0] += ivec[0]; sum[ibody][1] += ivec[1]; sum[ibody][2] += ivec[2]; sum[ibody][3] += ivec[3]; sum[ibody][4] += ivec[4]; sum[ibody][5] += ivec[5]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // error check that re-computed moments of inertia match diagonalized ones // do not do test for bodies with params read from inpfile double norm; for (ibody = 0; ibody < nbody; ibody++) { if (inpfile && inbody[ibody]) continue; if (inertia[ibody][0] == 0.0) { if (fabs(all[ibody][0]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } else { if (fabs((all[ibody][0]-inertia[ibody][0])/inertia[ibody][0]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } if (inertia[ibody][1] == 0.0) { if (fabs(all[ibody][1]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } else { if (fabs((all[ibody][1]-inertia[ibody][1])/inertia[ibody][1]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } if (inertia[ibody][2] == 0.0) { if (fabs(all[ibody][2]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } else { if (fabs((all[ibody][2]-inertia[ibody][2])/inertia[ibody][2]) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } norm = (inertia[ibody][0] + inertia[ibody][1] + inertia[ibody][2]) / 3.0; if (fabs(all[ibody][3]/norm) > TOLERANCE || fabs(all[ibody][4]/norm) > TOLERANCE || fabs(all[ibody][5]/norm) > TOLERANCE) error->all(FLERR,"Fix rigid: Bad principal moments"); } if (inpfile) memory->destroy(inbody); } /* ---------------------------------------------------------------------- one-time initialization of dynamic rigid body attributes set vcm and angmom, computed explicitly from constituent particles not done if body properites read from file, e.g. for overlapping particles ------------------------------------------------------------------------- */ void FixRigid::setup_bodies_dynamic() { int i,ibody; double massone,radone; // vcm = velocity of center-of-mass of each rigid body // angmom = angular momentum of each rigid body double **x = atom->x; double **v = atom->v; double *rmass = atom->rmass; double *mass = atom->mass; int *type = atom->type; int nlocal = atom->nlocal; double dx,dy,dz; double unwrap[3]; for (ibody = 0; ibody < nbody; ibody++) for (i = 0; i < 6; i++) sum[ibody][i] = 0.0; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (rmass) massone = rmass[i]; else massone = mass[type[i]]; sum[ibody][0] += v[i][0] * massone; sum[ibody][1] += v[i][1] * massone; sum[ibody][2] += v[i][2] * massone; domain->unmap(x[i],xcmimage[i],unwrap); dx = unwrap[0] - xcm[ibody][0]; dy = unwrap[1] - xcm[ibody][1]; dz = unwrap[2] - xcm[ibody][2]; sum[ibody][3] += dy * massone*v[i][2] - dz * massone*v[i][1]; sum[ibody][4] += dz * massone*v[i][0] - dx * massone*v[i][2]; sum[ibody][5] += dx * massone*v[i][1] - dy * massone*v[i][0]; } // extended particles add their rotation to angmom of body if (extended) { AtomVecLine::Bonus *lbonus; if (avec_line) lbonus = avec_line->bonus; double **omega_one = atom->omega; double **angmom_one = atom->angmom; double *radius = atom->radius; int *line = atom->line; for (i = 0; i < nlocal; i++) { if (body[i] < 0) continue; ibody = body[i]; if (eflags[i] & OMEGA) { if (eflags[i] & SPHERE) { radone = radius[i]; sum[ibody][3] += SINERTIA*rmass[i] * radone*radone * omega_one[i][0]; sum[ibody][4] += SINERTIA*rmass[i] * radone*radone * omega_one[i][1]; sum[ibody][5] += SINERTIA*rmass[i] * radone*radone * omega_one[i][2]; } else if (eflags[i] & LINE) { radone = lbonus[line[i]].length; sum[ibody][5] += LINERTIA*rmass[i] * radone*radone * omega_one[i][2]; } } if (eflags[i] & ANGMOM) { sum[ibody][3] += angmom_one[i][0]; sum[ibody][4] += angmom_one[i][1]; sum[ibody][5] += angmom_one[i][2]; } } } MPI_Allreduce(sum[0],all[0],6*nbody,MPI_DOUBLE,MPI_SUM,world); // normalize velocity of COM for (ibody = 0; ibody < nbody; ibody++) { vcm[ibody][0] = all[ibody][0]/masstotal[ibody]; vcm[ibody][1] = all[ibody][1]/masstotal[ibody]; vcm[ibody][2] = all[ibody][2]/masstotal[ibody]; angmom[ibody][0] = all[ibody][3]; angmom[ibody][1] = all[ibody][4]; angmom[ibody][2] = all[ibody][5]; } } /* ---------------------------------------------------------------------- read per rigid body info from user-provided file which = 0 to read everthing except 6 moments of inertia which = 1 to read 6 moments of inertia flag inbody = 0 for bodies whose info is read from file nlines = # of lines of rigid body info one line = rigid-ID mass xcm ycm zcm ixx iyy izz ixy ixz iyz vxcm vycm vzcm lx ly lz ix iy iz ------------------------------------------------------------------------- */ void FixRigid::readfile(int which, double *vec, double **array1, double **array2, double **array3, imageint *ivec, int *inbody) { int j,nchunk,id,eofflag,xbox,ybox,zbox; int nlines; FILE *fp; char *eof,*start,*next,*buf; char line[MAXLINE]; if (me == 0) { fp = fopen(inpfile,"r"); if (fp == NULL) { char str[128]; snprintf(str,128,"Cannot open fix rigid inpfile %s",inpfile); error->one(FLERR,str); } while (1) { eof = fgets(line,MAXLINE,fp); if (eof == NULL) error->one(FLERR,"Unexpected end of fix rigid file"); start = &line[strspn(line," \t\n\v\f\r")]; if (*start != '\0' && *start != '#') break; } sscanf(line,"%d",&nlines); } MPI_Bcast(&nlines,1,MPI_INT,0,world); if (nlines == 0) error->all(FLERR,"Fix rigid file has no lines"); char *buffer = new char[CHUNK*MAXLINE]; char **values = new char*[ATTRIBUTE_PERBODY]; int nread = 0; while (nread < nlines) { nchunk = MIN(nlines-nread,CHUNK); eofflag = comm->read_lines_from_file(fp,nchunk,MAXLINE,buffer); if (eofflag) error->all(FLERR,"Unexpected end of fix rigid file"); buf = buffer; next = strchr(buf,'\n'); *next = '\0'; int nwords = atom->count_words(buf); *next = '\n'; if (nwords != ATTRIBUTE_PERBODY) error->all(FLERR,"Incorrect rigid body format in fix rigid file"); // loop over lines of rigid body attributes // tokenize the line into values // id = rigid body ID // use ID as-is for SINGLE, as mol-ID for MOLECULE, as-is for GROUP // for which = 0, store all but inertia in vecs and arrays // for which = 1, store inertia tensor array, invert 3,4,5 values to Voigt for (int i = 0; i < nchunk; i++) { next = strchr(buf,'\n'); values[0] = strtok(buf," \t\n\r\f"); for (j = 1; j < nwords; j++) values[j] = strtok(NULL," \t\n\r\f"); id = atoi(values[0]); if (rstyle == MOLECULE) { if (id <= 0 || id > maxmol) error->all(FLERR,"Invalid rigid body ID in fix rigid file"); id = mol2body[id]; } else id--; if (id < 0 || id >= nbody) error->all(FLERR,"Invalid rigid body ID in fix rigid file"); inbody[id] = 1; if (which == 0) { vec[id] = atof(values[1]); array1[id][0] = atof(values[2]); array1[id][1] = atof(values[3]); array1[id][2] = atof(values[4]); array2[id][0] = atof(values[11]); array2[id][1] = atof(values[12]); array2[id][2] = atof(values[13]); array3[id][0] = atof(values[14]); array3[id][1] = atof(values[15]); array3[id][2] = atof(values[16]); xbox = atoi(values[17]); ybox = atoi(values[18]); zbox = atoi(values[19]); ivec[id] = ((imageint) (xbox + IMGMAX) & IMGMASK) | (((imageint) (ybox + IMGMAX) & IMGMASK) << IMGBITS) | (((imageint) (zbox + IMGMAX) & IMGMASK) << IMG2BITS); } else { array1[id][0] = atof(values[5]); array1[id][1] = atof(values[6]); array1[id][2] = atof(values[7]); array1[id][3] = atof(values[10]); array1[id][4] = atof(values[9]); array1[id][5] = atof(values[8]); } buf = next + 1; } nread += nchunk; } if (me == 0) fclose(fp); delete [] buffer; delete [] values; } /* ---------------------------------------------------------------------- write out restart info for mass, COM, inertia tensor, image flags to file identical format to inpfile option, so info can be read in when restarting only proc 0 writes list of global bodies to file ------------------------------------------------------------------------- */ void FixRigid::write_restart_file(char *file) { if (me) return; char outfile[128]; snprintf(outfile,128,"%s.rigid",file); FILE *fp = fopen(outfile,"w"); if (fp == NULL) { char str[192]; snprintf(str,192,"Cannot open fix rigid restart file %s",outfile); error->one(FLERR,str); } fprintf(fp,"# fix rigid mass, COM, inertia tensor info for " "%d bodies on timestep " BIGINT_FORMAT "\n\n", nbody,update->ntimestep); fprintf(fp,"%d\n",nbody); // compute I tensor against xyz axes from diagonalized I and current quat // Ispace = P Idiag P_transpose // P is stored column-wise in exyz_space int xbox,ybox,zbox; double p[3][3],pdiag[3][3],ispace[3][3]; int id; for (int i = 0; i < nbody; i++) { if (rstyle == SINGLE || rstyle == GROUP) id = i; else id = body2mol[i]; MathExtra::col2mat(ex_space[i],ey_space[i],ez_space[i],p); MathExtra::times3_diag(p,inertia[i],pdiag); MathExtra::times3_transpose(pdiag,p,ispace); xbox = (imagebody[i] & IMGMASK) - IMGMAX; ybox = (imagebody[i] >> IMGBITS & IMGMASK) - IMGMAX; zbox = (imagebody[i] >> IMG2BITS) - IMGMAX; fprintf(fp,"%d %-1.16e %-1.16e %-1.16e %-1.16e " "%-1.16e %-1.16e %-1.16e %-1.16e %-1.16e %-1.16e " "%-1.16e %-1.16e %-1.16e %-1.16e %-1.16e %-1.16e " "%d %d %d\n", id,masstotal[i],xcm[i][0],xcm[i][1],xcm[i][2], ispace[0][0],ispace[1][1],ispace[2][2], ispace[0][1],ispace[0][2],ispace[1][2], vcm[i][0],vcm[i][1],vcm[i][2], angmom[i][0],angmom[i][1],angmom[i][2], xbox,ybox,zbox); } fclose(fp); } /* ---------------------------------------------------------------------- memory usage of local atom-based arrays ------------------------------------------------------------------------- */ double FixRigid::memory_usage() { int nmax = atom->nmax; double bytes = nmax * sizeof(int); bytes += nmax * sizeof(imageint); bytes += nmax*3 * sizeof(double); bytes += maxvatom*6 * sizeof(double); // vatom if (extended) { bytes += nmax * sizeof(int); if (orientflag) bytes = nmax*orientflag * sizeof(double); if (dorientflag) bytes = nmax*3 * sizeof(double); } return bytes; } /* ---------------------------------------------------------------------- allocate local atom-based arrays ------------------------------------------------------------------------- */ void FixRigid::grow_arrays(int nmax) { memory->grow(body,nmax,"rigid:body"); memory->grow(xcmimage,nmax,"rigid:xcmimage"); memory->grow(displace,nmax,3,"rigid:displace"); if (extended) { memory->grow(eflags,nmax,"rigid:eflags"); if (orientflag) memory->grow(orient,nmax,orientflag,"rigid:orient"); if (dorientflag) memory->grow(dorient,nmax,3,"rigid:dorient"); } // check for regrow of vatom // must be done whether per-atom virial is accumulated on this step or not // b/c this is only time grow_array() may be called // need to regrow b/c vatom is calculated before and after atom migration if (nmax > maxvatom) { maxvatom = atom->nmax; memory->grow(vatom,maxvatom,6,"fix:vatom"); } } /* ---------------------------------------------------------------------- copy values within local atom-based arrays ------------------------------------------------------------------------- */ void FixRigid::copy_arrays(int i, int j, int /*delflag*/) { body[j] = body[i]; xcmimage[j] = xcmimage[i]; displace[j][0] = displace[i][0]; displace[j][1] = displace[i][1]; displace[j][2] = displace[i][2]; if (extended) { eflags[j] = eflags[i]; for (int k = 0; k < orientflag; k++) orient[j][k] = orient[i][k]; if (dorientflag) { dorient[j][0] = dorient[i][0]; dorient[j][1] = dorient[i][1]; dorient[j][2] = dorient[i][2]; } } // must also copy vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) vatom[j][k] = vatom[i][k]; } /* ---------------------------------------------------------------------- initialize one atom's array values, called when atom is created ------------------------------------------------------------------------- */ void FixRigid::set_arrays(int i) { body[i] = -1; xcmimage[i] = 0; displace[i][0] = 0.0; displace[i][1] = 0.0; displace[i][2] = 0.0; // must also zero vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) vatom[i][k] = 0.0; } /* ---------------------------------------------------------------------- pack values in local atom-based arrays for exchange with another proc ------------------------------------------------------------------------- */ int FixRigid::pack_exchange(int i, double *buf) { buf[0] = ubuf(body[i]).d; buf[1] = ubuf(xcmimage[i]).d; buf[2] = displace[i][0]; buf[3] = displace[i][1]; buf[4] = displace[i][2]; if (!extended) return 5; int m = 5; buf[m++] = eflags[i]; for (int j = 0; j < orientflag; j++) buf[m++] = orient[i][j]; if (dorientflag) { buf[m++] = dorient[i][0]; buf[m++] = dorient[i][1]; buf[m++] = dorient[i][2]; } // must also pack vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) buf[m++] = vatom[i][k]; return m; } /* ---------------------------------------------------------------------- unpack values in local atom-based arrays from exchange with another proc ------------------------------------------------------------------------- */ int FixRigid::unpack_exchange(int nlocal, double *buf) { body[nlocal] = (int) ubuf(buf[0]).i; xcmimage[nlocal] = (imageint) ubuf(buf[1]).i; displace[nlocal][0] = buf[2]; displace[nlocal][1] = buf[3]; displace[nlocal][2] = buf[4]; if (!extended) return 5; int m = 5; eflags[nlocal] = static_cast<int> (buf[m++]); for (int j = 0; j < orientflag; j++) orient[nlocal][j] = buf[m++]; if (dorientflag) { dorient[nlocal][0] = buf[m++]; dorient[nlocal][1] = buf[m++]; dorient[nlocal][2] = buf[m++]; } // must also unpack vatom if per-atom virial calculated on this timestep // since vatom is calculated before and after atom migration if (vflag_atom) for (int k = 0; k < 6; k++) vatom[nlocal][k] = buf[m++]; return m; } /* ---------------------------------------------------------------------- */ void FixRigid::reset_dt() { dtv = update->dt; dtf = 0.5 * update->dt * force->ftm2v; dtq = 0.5 * update->dt; } /* ---------------------------------------------------------------------- zero linear momentum of each rigid body set Vcm to 0.0, then reset velocities of particles via set_v() ------------------------------------------------------------------------- */ void FixRigid::zero_momentum() { for (int ibody = 0; ibody < nbody; ibody++) vcm[ibody][0] = vcm[ibody][1] = vcm[ibody][2] = 0.0; evflag = 0; set_v(); } /* ---------------------------------------------------------------------- zero angular momentum of each rigid body set angmom/omega to 0.0, then reset velocities of particles via set_v() ------------------------------------------------------------------------- */ void FixRigid::zero_rotation() { for (int ibody = 0; ibody < nbody; ibody++) { angmom[ibody][0] = angmom[ibody][1] = angmom[ibody][2] = 0.0; omega[ibody][0] = omega[ibody][1] = omega[ibody][2] = 0.0; } evflag = 0; set_v(); } /* ---------------------------------------------------------------------- */ int FixRigid::modify_param(int narg, char **arg) { if (strcmp(arg[0],"bodyforces") == 0) { if (narg < 2) error->all(FLERR,"Illegal fix_modify command"); if (strcmp(arg[1],"early") == 0) earlyflag = 1; else if (strcmp(arg[1],"late") == 0) earlyflag = 0; else error->all(FLERR,"Illegal fix_modify command"); // reset fix mask // must do here and not in init, // since modify.cpp::init() uses fix masks before calling fix::init() for (int i = 0; i < modify->nfix; i++) if (strcmp(modify->fix[i]->id,id) == 0) { if (earlyflag) modify->fmask[i] |= POST_FORCE; else if (!langflag) modify->fmask[i] &= ~POST_FORCE; break; } return 2; } return 0; } /* ---------------------------------------------------------------------- return temperature of collection of rigid bodies non-active DOF are removed by fflag/tflag and in tfactor ------------------------------------------------------------------------- */ double FixRigid::compute_scalar() { double wbody[3],rot[3][3]; double t = 0.0; for (int i = 0; i < nbody; i++) { t += masstotal[i] * (fflag[i][0]*vcm[i][0]*vcm[i][0] + fflag[i][1]*vcm[i][1]*vcm[i][1] + fflag[i][2]*vcm[i][2]*vcm[i][2]); // wbody = angular velocity in body frame MathExtra::quat_to_mat(quat[i],rot); MathExtra::transpose_matvec(rot,angmom[i],wbody); if (inertia[i][0] == 0.0) wbody[0] = 0.0; else wbody[0] /= inertia[i][0]; if (inertia[i][1] == 0.0) wbody[1] = 0.0; else wbody[1] /= inertia[i][1]; if (inertia[i][2] == 0.0) wbody[2] = 0.0; else wbody[2] /= inertia[i][2]; t += tflag[i][0]*inertia[i][0]*wbody[0]*wbody[0] + tflag[i][1]*inertia[i][1]*wbody[1]*wbody[1] + tflag[i][2]*inertia[i][2]*wbody[2]*wbody[2]; } t *= tfactor; return t; } /* ---------------------------------------------------------------------- */ void *FixRigid::extract(const char *str, int &dim) { if (strcmp(str,"body") == 0) { dim = 1; return body; } if (strcmp(str,"masstotal") == 0) { dim = 1; return masstotal; } if (strcmp(str,"t_target") == 0) { dim = 0; return &t_target; } return NULL; } /* ---------------------------------------------------------------------- return translational KE for all rigid bodies KE = 1/2 M Vcm^2 ------------------------------------------------------------------------- */ double FixRigid::extract_ke() { double ke = 0.0; for (int i = 0; i < nbody; i++) ke += masstotal[i] * (vcm[i][0]*vcm[i][0] + vcm[i][1]*vcm[i][1] + vcm[i][2]*vcm[i][2]); return 0.5*ke; } /* ---------------------------------------------------------------------- return rotational KE for all rigid bodies Erotational = 1/2 I wbody^2 ------------------------------------------------------------------------- */ double FixRigid::extract_erotational() { double wbody[3],rot[3][3]; double erotate = 0.0; for (int i = 0; i < nbody; i++) { // wbody = angular velocity in body frame MathExtra::quat_to_mat(quat[i],rot); MathExtra::transpose_matvec(rot,angmom[i],wbody); if (inertia[i][0] == 0.0) wbody[0] = 0.0; else wbody[0] /= inertia[i][0]; if (inertia[i][1] == 0.0) wbody[1] = 0.0; else wbody[1] /= inertia[i][1]; if (inertia[i][2] == 0.0) wbody[2] = 0.0; else wbody[2] /= inertia[i][2]; erotate += inertia[i][0]*wbody[0]*wbody[0] + inertia[i][1]*wbody[1]*wbody[1] + inertia[i][2]*wbody[2]*wbody[2]; } return 0.5*erotate; } /* ---------------------------------------------------------------------- return attributes of a rigid body 15 values per body xcm = 0,1,2; vcm = 3,4,5; fcm = 6,7,8; torque = 9,10,11; image = 12,13,14 ------------------------------------------------------------------------- */ double FixRigid::compute_array(int i, int j) { if (j < 3) return xcm[i][j]; if (j < 6) return vcm[i][j-3]; if (j < 9) return fcm[i][j-6]; if (j < 12) return torque[i][j-9]; if (j == 12) return (imagebody[i] & IMGMASK) - IMGMAX; if (j == 13) return (imagebody[i] >> IMGBITS & IMGMASK) - IMGMAX; return (imagebody[i] >> IMG2BITS) - IMGMAX; }
Java
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="ResourceList.cs" company="Tygertec"> // Copyright © 2016 Ty Walls. // All rights reserved. // </copyright> // <summary> // Defines the ResourceList type. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace TW.Resfit.Core { using System.Collections.Generic; using System.Linq; using TW.Resfit.Framework; public class ResourceList : ListDecoratorBase<Resource> { public ResourceList() { } public ResourceList(IEnumerable<Resource> resources) : this() { this.Items.AddRange(resources); } /// <summary> /// Gets the underlying Items collection. /// It is just a proxy for the protected Items property. /// Its only purpose is to make the code read easier. /// </summary> public ICollection<Resource> Resources { get { return this.Items; } } public ResourceList Clone(ResourceFilter filter = null) { if (filter == null) { filter = ResourceFilter.NoFilter; } var clonedList = new ResourceList(); foreach (var resource in this.Where(resource => filter.IsMatch(resource))) { clonedList.Add(new Resource(resource)); } return clonedList; } public void Merge(ResourceList resourceListToAbsorb) { foreach (var resource in resourceListToAbsorb) { if (this.All(x => x.Key != resource.Key)) { this.Add(new Resource(resource)); } } } public ResourceList TransformSelfIntoNewList() { var newList = new ResourceList(); foreach (var resource in this) { var newResource = new Resource(resource); foreach (var transform in resource.Transforms) { newResource = transform.Transform(resource); } if (newResource != null) { newList.Add(newResource); } } return newList; } } }
Java
package mnm.mcpackager.gui; import java.io.File; import javax.swing.filechooser.FileFilter; public class JarFilter extends FileFilter { @Override public boolean accept(File f) { if (f.isDirectory()) return true; return getExtension(f).equalsIgnoreCase("jar"); } @Override public String getDescription() { return "Jar Archives"; } private String getExtension(File f) { String ext = null; String s = f.getName(); int i = s.lastIndexOf('.'); if (i > 0 && i < s.length() - 1) ext = s.substring(i + 1).toLowerCase(); return ext; } }
Java
/*************************************************************************** * Copyright (C) 2008-2017 by Andrzej Rybczak * * electricityispower@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 St, Fifth Floor, Boston, MA 02110-1301, USA. * ***************************************************************************/ #ifndef NCMPCPP_MENU_H #define NCMPCPP_MENU_H #include <boost/iterator/transform_iterator.hpp> #include <boost/range/detail/any_iterator.hpp> #include <cassert> #include <functional> #include <iterator> #include <memory> #include <set> #include "curses/formatted_color.h" #include "curses/strbuffer.h" #include "curses/window.h" #include "utility/const.h" namespace NC { struct List { struct Properties { enum Type { None = 0, Selectable = (1 << 0), Selected = (1 << 1), Inactive = (1 << 2), Separator = (1 << 3) }; Properties(Type properties = Selectable) : m_properties(properties) { } void setSelectable(bool is_selectable) { if (is_selectable) m_properties |= Selectable; else m_properties &= ~(Selectable | Selected); } void setSelected(bool is_selected) { if (!isSelectable()) return; if (is_selected) m_properties |= Selected; else m_properties &= ~Selected; } void setInactive(bool is_inactive) { if (is_inactive) m_properties |= Inactive; else m_properties &= ~Inactive; } void setSeparator(bool is_separator) { if (is_separator) m_properties |= Separator; else m_properties &= ~Separator; } bool isSelectable() const { return m_properties & Selectable; } bool isSelected() const { return m_properties & Selected; } bool isInactive() const { return m_properties & Inactive; } bool isSeparator() const { return m_properties & Separator; } private: unsigned m_properties; }; template <typename ValueT> using PropertiesIterator = boost::range_detail::any_iterator< ValueT, boost::random_access_traversal_tag, ValueT &, std::ptrdiff_t >; typedef PropertiesIterator<Properties> Iterator; typedef PropertiesIterator<const Properties> ConstIterator; virtual ~List() { } virtual bool empty() const = 0; virtual size_t size() const = 0; virtual size_t choice() const = 0; virtual void highlight(size_t pos) = 0; virtual Iterator currentP() = 0; virtual ConstIterator currentP() const = 0; virtual Iterator beginP() = 0; virtual ConstIterator beginP() const = 0; virtual Iterator endP() = 0; virtual ConstIterator endP() const = 0; }; inline List::Properties::Type operator|(List::Properties::Type lhs, List::Properties::Type rhs) { return List::Properties::Type(unsigned(lhs) | unsigned(rhs)); } inline List::Properties::Type &operator|=(List::Properties::Type &lhs, List::Properties::Type rhs) { lhs = lhs | rhs; return lhs; } inline List::Properties::Type operator&(List::Properties::Type lhs, List::Properties::Type rhs) { return List::Properties::Type(unsigned(lhs) & unsigned(rhs)); } inline List::Properties::Type &operator&=(List::Properties::Type &lhs, List::Properties::Type rhs) { lhs = lhs & rhs; return lhs; } // for range-based for loop inline List::Iterator begin(List &list) { return list.beginP(); } inline List::ConstIterator begin(const List &list) { return list.beginP(); } inline List::Iterator end(List &list) { return list.endP(); } inline List::ConstIterator end(const List &list) { return list.endP(); } /// Generic menu capable of holding any std::vector compatible values. template <typename ItemT> struct Menu: Window, List { struct Item { friend struct Menu<ItemT>; typedef ItemT Type; Item() : m_impl(std::make_shared<std::tuple<ItemT, Properties>>()) { } template <typename ValueT, typename PropertiesT> Item(ValueT &&value_, PropertiesT properties_) : m_impl( std::make_shared<std::tuple<ItemT, List::Properties>>( std::forward<ValueT>(value_), std::forward<PropertiesT>(properties_))) { } ItemT &value() { return std::get<0>(*m_impl); } const ItemT &value() const { return std::get<0>(*m_impl); } Properties &properties() { return std::get<1>(*m_impl); } const Properties &properties() const { return std::get<1>(*m_impl); } // Forward methods to List::Properties. void setSelectable(bool is_selectable) { properties().setSelectable(is_selectable); } void setSelected (bool is_selected) { properties().setSelected(is_selected); } void setInactive (bool is_inactive) { properties().setInactive(is_inactive); } void setSeparator (bool is_separator) { properties().setSeparator(is_separator); } bool isSelectable() const { return properties().isSelectable(); } bool isSelected() const { return properties().isSelected(); } bool isInactive() const { return properties().isInactive(); } bool isSeparator() const { return properties().isSeparator(); } // Make a deep copy of Item. Item copy() const { return Item(value(), properties()); } private: template <Const const_> struct ExtractProperties { typedef ExtractProperties type; typedef typename std::conditional< const_ == Const::Yes, const Properties, Properties>::type Properties_; typedef typename std::conditional< const_ == Const::Yes, const Item, Item>::type Item_; Properties_ &operator()(Item_ &i) const { return i.properties(); } }; template <Const const_> struct ExtractValue { typedef ExtractValue type; typedef typename std::conditional< const_ == Const::Yes, const ItemT, ItemT>::type Value_; typedef typename std::conditional< const_ == Const::Yes, const Item, Item>::type Item_; Value_ &operator()(Item_ &i) const { return i.value(); } }; static Item mkSeparator() { Item item; item.setSelectable(false); item.setSeparator(true); return item; } std::shared_ptr<std::tuple<ItemT, Properties>> m_impl; }; typedef typename std::vector<Item>::iterator Iterator; typedef typename std::vector<Item>::const_iterator ConstIterator; typedef std::reverse_iterator<Iterator> ReverseIterator; typedef std::reverse_iterator<ConstIterator> ConstReverseIterator; typedef boost::transform_iterator< typename Item::template ExtractValue<Const::No>, Iterator> ValueIterator; typedef boost::transform_iterator< typename Item::template ExtractValue<Const::Yes>, ConstIterator> ConstValueIterator; typedef std::reverse_iterator<ValueIterator> ReverseValueIterator; typedef std::reverse_iterator<ConstValueIterator> ConstReverseValueIterator; typedef boost::transform_iterator< typename Item::template ExtractProperties<Const::No>, Iterator> PropertiesIterator; typedef boost::transform_iterator< typename Item::template ExtractProperties<Const::Yes>, ConstIterator> ConstPropertiesIterator; // For compliance with boost utilities. typedef Iterator iterator; typedef ConstIterator const_iterator; /// Function helper prototype used to display each option on the screen. /// If not set by setItemDisplayer(), menu won't display anything. /// @see setItemDisplayer() typedef std::function<void(Menu<ItemT> &)> ItemDisplayer; typedef std::function<bool(const Item &)> FilterPredicate; Menu(); Menu(size_t startx, size_t starty, size_t width, size_t height, const std::string &title, Color color, Border border); Menu(const Menu &rhs); Menu(Menu &&rhs); Menu &operator=(Menu rhs); /// Sets helper function that is responsible for displaying items /// @param ptr function pointer that matches the ItemDisplayer prototype template <typename ItemDisplayerT> void setItemDisplayer(ItemDisplayerT &&displayer); /// Resizes the list to given size (adequate to std::vector::resize()) /// @param size requested size void resizeList(size_t new_size); /// Adds a new option to list void addItem(ItemT item, Properties::Type properties = Properties::Selectable); /// Adds separator to list void addSeparator(); /// Inserts a new option to the list at given position void insertItem(size_t pos, ItemT item, Properties::Type properties = Properties::Selectable); /// Inserts separator to list at given position /// @param pos initial position of inserted separator void insertSeparator(size_t pos); /// Moves the highlighted position to the given line of window /// @param y Y position of menu window to be highlighted /// @return true if the position is reachable, false otherwise bool Goto(size_t y); /// Checks if list is empty /// @return true if list is empty, false otherwise virtual bool empty() const override { return m_items->empty(); } /// @return size of the list virtual size_t size() const override { return m_items->size(); } /// @return currently highlighted position virtual size_t choice() const override; /// Highlights given position /// @param pos position to be highlighted virtual void highlight(size_t position) override; /// Refreshes the menu window /// @see Window::refresh() virtual void refresh() override; /// Scrolls by given amount of lines /// @param where indicated where exactly one wants to go /// @see Window::scroll() virtual void scroll(Scroll where) override; /// Cleares all options, used filters etc. It doesn't reset highlighted position though. /// @see reset() virtual void clear() override; /// Sets highlighted position to 0 void reset(); /// Apply filter predicate to items in the menu and show the ones for which it /// returned true. template <typename PredicateT> void applyFilter(PredicateT &&pred); /// Reapply previously applied filter. void reapplyFilter(); /// Get current filter predicate. template <typename TargetT> const TargetT *filterPredicate() const; /// Clear results of applyFilter and show all items. void clearFilter(); /// @return true if menu is filtered. bool isFiltered() const { return m_items == &m_filtered_items; } /// Show all items. void showAllItems() { m_items = &m_all_items; } /// Show filtered items. void showFilteredItems() { m_items = &m_filtered_items; } /// Sets prefix, that is put before each selected item to indicate its selection /// Note that the passed variable is not deleted along with menu object. /// @param b pointer to buffer that contains the prefix void setSelectedPrefix(const Buffer &b) { m_selected_prefix = b; } /// Sets suffix, that is put after each selected item to indicate its selection /// Note that the passed variable is not deleted along with menu object. /// @param b pointer to buffer that contains the suffix void setSelectedSuffix(const Buffer &b) { m_selected_suffix = b; } void setHighlightPrefix(const Buffer &b) { m_highlight_prefix = b; } void setHighlightSuffix(const Buffer &b) { m_highlight_suffix = b; } const Buffer &highlightPrefix() const { return m_highlight_prefix; } const Buffer &highlightSuffix() const { return m_highlight_suffix; } /// @return state of highlighting bool isHighlighted() { return m_highlight_enabled; } /// Turns on/off highlighting /// @param state state of hihglighting void setHighlighting(bool state) { m_highlight_enabled = state; } /// Turns on/off cyclic scrolling /// @param state state of cyclic scrolling void cyclicScrolling(bool state) { m_cyclic_scroll_enabled = state; } /// Turns on/off centered cursor /// @param state state of centered cursor void centeredCursor(bool state) { m_autocenter_cursor = state; } /// @return currently drawn item. The result is defined only within /// drawing function that is called by refresh() /// @see refresh() ConstIterator drawn() const { return begin() + m_drawn_position; } /// @param pos requested position /// @return reference to item at given position /// @throw std::out_of_range if given position is out of range Menu<ItemT>::Item &at(size_t pos) { return m_items->at(pos); } /// @param pos requested position /// @return const reference to item at given position /// @throw std::out_of_range if given position is out of range const Menu<ItemT>::Item &at(size_t pos) const { return m_items->at(pos); } /// @param pos requested position /// @return const reference to item at given position const Menu<ItemT>::Item &operator[](size_t pos) const { return (*m_items)[pos]; } /// @param pos requested position /// @return const reference to item at given position Menu<ItemT>::Item &operator[](size_t pos) { return (*m_items)[pos]; } Iterator current() { return Iterator(m_items->begin() + m_highlight); } ConstIterator current() const { return ConstIterator(m_items->begin() + m_highlight); } ReverseIterator rcurrent() { if (empty()) return rend(); else return ReverseIterator(++current()); } ConstReverseIterator rcurrent() const { if (empty()) return rend(); else return ConstReverseIterator(++current()); } ValueIterator currentV() { return ValueIterator(m_items->begin() + m_highlight); } ConstValueIterator currentV() const { return ConstValueIterator(m_items->begin() + m_highlight); } ReverseValueIterator rcurrentV() { if (empty()) return rendV(); else return ReverseValueIterator(++currentV()); } ConstReverseValueIterator rcurrentV() const { if (empty()) return rendV(); else return ConstReverseValueIterator(++currentV()); } Iterator begin() { return Iterator(m_items->begin()); } ConstIterator begin() const { return ConstIterator(m_items->begin()); } Iterator end() { return Iterator(m_items->end()); } ConstIterator end() const { return ConstIterator(m_items->end()); } ReverseIterator rbegin() { return ReverseIterator(end()); } ConstReverseIterator rbegin() const { return ConstReverseIterator(end()); } ReverseIterator rend() { return ReverseIterator(begin()); } ConstReverseIterator rend() const { return ConstReverseIterator(begin()); } ValueIterator beginV() { return ValueIterator(begin()); } ConstValueIterator beginV() const { return ConstValueIterator(begin()); } ValueIterator endV() { return ValueIterator(end()); } ConstValueIterator endV() const { return ConstValueIterator(end()); } ReverseValueIterator rbeginV() { return ReverseValueIterator(endV()); } ConstReverseIterator rbeginV() const { return ConstReverseValueIterator(endV()); } ReverseValueIterator rendV() { return ReverseValueIterator(beginV()); } ConstReverseValueIterator rendV() const { return ConstReverseValueIterator(beginV()); } virtual List::Iterator currentP() override { return List::Iterator(PropertiesIterator(m_items->begin() + m_highlight)); } virtual List::ConstIterator currentP() const override { return List::ConstIterator(ConstPropertiesIterator(m_items->begin() + m_highlight)); } virtual List::Iterator beginP() override { return List::Iterator(PropertiesIterator(m_items->begin())); } virtual List::ConstIterator beginP() const override { return List::ConstIterator(ConstPropertiesIterator(m_items->begin())); } virtual List::Iterator endP() override { return List::Iterator(PropertiesIterator(m_items->end())); } virtual List::ConstIterator endP() const override { return List::ConstIterator(ConstPropertiesIterator(m_items->end())); } private: bool isHighlightable(size_t pos) { return !(*m_items)[pos].isSeparator() && !(*m_items)[pos].isInactive(); } ItemDisplayer m_item_displayer; FilterPredicate m_filter_predicate; std::vector<Item> *m_items; std::vector<Item> m_all_items; std::vector<Item> m_filtered_items; size_t m_beginning; size_t m_highlight; bool m_highlight_enabled; bool m_cyclic_scroll_enabled; bool m_autocenter_cursor; size_t m_drawn_position; Buffer m_highlight_prefix; Buffer m_highlight_suffix; Buffer m_selected_prefix; Buffer m_selected_suffix; }; } #endif // NCMPCPP_MENU_H
Java
<?php /** --------------------------------------------------------------------- * app/lib/core/BaseModel.php : * ---------------------------------------------------------------------- * CollectiveAccess * Open-source collections management software * ---------------------------------------------------------------------- * * Software by Whirl-i-Gig (http://www.whirl-i-gig.com) * Copyright 2000-2012 Whirl-i-Gig * * For more information visit http://www.CollectiveAccess.org * * This program is free software; you may redistribute it and/or modify it under * the terms of the provided license as published by Whirl-i-Gig * * CollectiveAccess is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTIES whatsoever, including any implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * * This source code is free and modifiable under the terms of * GNU General Public License. (http://www.gnu.org/copyleft/gpl.html). See * the "license.txt" file for details, or visit the CollectiveAccess web site at * http://www.CollectiveAccess.org * * @package CollectiveAccess * @subpackage BaseModel * @license http://www.gnu.org/copyleft/gpl.html GNU Public License version 3 * * ---------------------------------------------------------------------- */ /** * */ # ------------------------------------------------------------------------------------ # --- Field type constants # ------------------------------------------------------------------------------------ define("FT_NUMBER",0); define("FT_TEXT", 1); define("FT_TIMESTAMP", 2); define("FT_DATETIME", 3); define("FT_HISTORIC_DATETIME", 4); define("FT_DATERANGE", 5); define("FT_HISTORIC_DATERANGE", 6); define("FT_BIT", 7); define("FT_FILE", 8); define("FT_MEDIA", 9); define("FT_PASSWORD", 10); define("FT_VARS", 11); define("FT_TIMECODE", 12); define("FT_DATE", 13); define("FT_HISTORIC_DATE", 14); define("FT_TIME", 15); define("FT_TIMERANGE", 16); # ------------------------------------------------------------------------------------ # --- Display type constants # ------------------------------------------------------------------------------------ define("DT_SELECT", 0); define("DT_LIST", 1); define("DT_LIST_MULTIPLE", 2); define("DT_CHECKBOXES", 3); define("DT_RADIO_BUTTONS", 4); define("DT_FIELD", 5); define("DT_HIDDEN", 6); define("DT_OMIT", 7); define("DT_TEXT", 8); define("DT_PASSWORD", 9); define("DT_COLORPICKER", 10); define("DT_TIMECODE", 12); define("DT_COUNTRY_LIST", 13); define("DT_STATEPROV_LIST", 14); # ------------------------------------------------------------------------------------ # --- Access mode constants # ------------------------------------------------------------------------------------ define("ACCESS_READ", 0); define("ACCESS_WRITE", 1); # ------------------------------------------------------------------------------------ # --- Text-markup constants # ------------------------------------------------------------------------------------ define("__CA_MT_HTML__", 0); define("__CA_MT_TEXT_ONLY__", 1); # ------------------------------------------------------------------------------------ # --- Hierarchy type constants # ------------------------------------------------------------------------------------ define("__CA_HIER_TYPE_SIMPLE_MONO__", 1); define("__CA_HIER_TYPE_MULTI_MONO__", 2); define("__CA_HIER_TYPE_ADHOC_MONO__", 3); define("__CA_HIER_TYPE_MULTI_POLY__", 4); # ---------------------------------------------------------------------- # --- Import classes # ---------------------------------------------------------------------- require_once(__CA_LIB_DIR__."/core/BaseObject.php"); require_once(__CA_LIB_DIR__."/core/Error.php"); require_once(__CA_LIB_DIR__."/core/Configuration.php"); require_once(__CA_LIB_DIR__."/core/Datamodel.php"); require_once(__CA_LIB_DIR__."/core/ApplicationChangeLog.php"); require_once(__CA_LIB_DIR__."/core/Parsers/TimeExpressionParser.php"); require_once(__CA_LIB_DIR__."/core/Parsers/TimecodeParser.php"); require_once(__CA_LIB_DIR__."/core/Db.php"); require_once(__CA_LIB_DIR__."/core/Media.php"); require_once(__CA_LIB_DIR__."/core/Media/MediaVolumes.php"); require_once(__CA_LIB_DIR__."/core/File.php"); require_once(__CA_LIB_DIR__."/core/File/FileVolumes.php"); require_once(__CA_LIB_DIR__."/core/Utils/Timer.php"); require_once(__CA_LIB_DIR__."/core/Utils/Unicode.php"); require_once(__CA_LIB_DIR__."/core/Search/SearchIndexer.php"); require_once(__CA_LIB_DIR__."/core/Db/Transaction.php"); require_once(__CA_LIB_DIR__."/core/Media/MediaProcessingSettings.php"); require_once(__CA_APP_DIR__."/helpers/utilityHelpers.php"); require_once(__CA_APP_DIR__."/helpers/gisHelpers.php"); require_once(__CA_LIB_DIR__."/ca/ApplicationPluginManager.php"); require_once(__CA_LIB_DIR__."/core/Parsers/htmlpurifier/HTMLPurifier.standalone.php"); /** * Base class for all database table classes. Implements database insert/update/delete * functionality and a whole lot more, including automatic generation of HTML form * widgets, layering of additional field types and data processing functionality * (media upload fields using the Media class; date/time and date range fields * with natural language input using the TimeExpressionParser class; serialized * variable stores using php serialize(), automatic management of hierarchies, etc.) * Each table in your database should have a class that extends BaseModel. */ class BaseModel extends BaseObject { # -------------------------------------------------------------------------------- # --- Properties # -------------------------------------------------------------------------------- /** * representation of the access mode of the current instance. * 0 (ACCESS_READ) means read-only, * 1 (ACCESS_WRITE) characterizes a BaseModel instance that is able to write to the database. * * @access private */ private $ACCESS_MODE; /** * local Db object for database access * * @access private */ private $o_db; /** * debug mode state * * @access private */ var $debug = 0; /** * @access private */ var $_FIELD_VALUES; /** * @access protected */ protected $_FIELD_VALUE_CHANGED; /** * @access private */ var $_FIELD_VALUES_OLD; /** * @access private */ private $_FILES; /** * @access private */ private $_SET_FILES; /** * @access private */ private $_FILES_CLEAR; /** * object-oriented access to media volume information * * @access private */ private $_MEDIA_VOLUMES; /** * object-oriented access to file volume information * * @access private */ private $_FILE_VOLUMES; /** * if true, DATETIME fields take Unix date/times, * not parseable date/time expressions * * @access private */ private $DIRECT_DATETIMES = 0; /** * local Configuration object representation * * @access protected */ protected $_CONFIG; /** * local Datamodel object representation * * @access protected */ protected $_DATAMODEL = null; /** * contains current Transaction object * * @access protected */ protected $_TRANSACTION = null; /** * The current locale. Used to determine which set of localized error messages to use. Default is US English ("en_us") * * @access private */ var $ops_locale = "en_us"; # /** * prepared change log statement (primary log entry) * * @access private */ private $opqs_change_log; /** * prepared change log statement (log subject entries) * * @access private */ private $opqs_change_log_subjects; /** * prepared statement to get change log * * @access private */ private $opqs_get_change_log; /** * prepared statement to get change log * * @access private */ private $opqs_get_change_log_subjects; # /** * array containing parsed version string from * * @access private */ private $opa_php_version; # # -------------------------------------------------------------------------------- # --- Error handling properties # -------------------------------------------------------------------------------- /** * Array of error objects * * @access public */ public $errors; /** * If true, on error error message is printed and execution halted * * @access private */ private $error_output; /** * List of fields that had conflicts with existing data during last update() * (ie. someone else had already saved to this field while the user of this instance was working) * * @access private */ private $field_conflicts; /** * Single instance of search indexer used by all models */ static public $search_indexer; /** * Single instance of HTML Purifier used by all models */ static public $html_purifier; /** * If set, all field values passed through BaseModel::set() are run through HTML Purifier before being stored */ private $opb_purify_input = false; /** * Array of model definitions, keyed on table name */ static $s_ca_models_definitions; /** * Constructor * In general you should not call this constructor directly. Any table in your database * should be represented by an extension of this class. * * @param int $pn_id primary key identifier of the table row represented by this object * if omitted, an empty object is created which can be used to create a new row in the database. * @return BaseModel */ public function __construct($pn_id=null) { $vs_table_name = $this->tableName(); if (!$this->FIELDS =& BaseModel::$s_ca_models_definitions[$vs_table_name]['FIELDS']) { die("Field definitions not found for {$vs_table_name}"); } $this->NAME_SINGULAR =& BaseModel::$s_ca_models_definitions[$vs_table_name]['NAME_SINGULAR']; $this->NAME_PLURAL =& BaseModel::$s_ca_models_definitions[$vs_table_name]['NAME_PLURAL']; $this->errors = array(); $this->error_output = 0; # don't halt on error $this->field_conflicts = array(); $this->_CONFIG = Configuration::load(); $this->_DATAMODEL = Datamodel::load(); $this->_FILES_CLEAR = array(); $this->_SET_FILES = array(); $this->_MEDIA_VOLUMES = MediaVolumes::load(); $this->_FILE_VOLUMES = FileVolumes::load(); $this->_FIELD_VALUE_CHANGED = array(); if ($vs_locale = $this->_CONFIG->get("locale")) { $this->ops_locale = $vs_locale; } $this->opo_app_plugin_manager = new ApplicationPluginManager(); $this->setMode(ACCESS_READ); if ($pn_id) { $this->load($pn_id);} } /** * Get Db object * If a transaction is pending, the Db object representation is taken from the Transaction object, * if not, a new connection is established, stored in a local property and returned. * * @return Db */ public function getDb() { if ($this->inTransaction()) { $this->o_db = $this->getTransaction()->getDb(); } else { if (!$this->o_db) { $this->o_db = new Db(); $this->o_db->dieOnError(false); } } return $this->o_db; } /** * Convenience method to return application configuration object. This is the same object * you'd get if you instantiated a Configuration() object without any parameters * * @return Configuration */ public function getAppConfig() { return $this->_CONFIG; } /** * Convenience method to return application datamodel object. This is the same object * you'd get if you instantiated a Datamodel() object * * @return Configuration */ public function getAppDatamodel() { return $this->_DATAMODEL; } /** * Get character set from configuration file. Defaults to * UTF8 if configuration parameter "character_set" is * not found. * * @return string the character set */ public function getCharacterSet() { if (!($vs_charset = $this->_CONFIG->get("character_set"))) { $vs_charset = "UTF-8"; } return $vs_charset; } # -------------------------------------------------------------------------------- # --- Transactions # -------------------------------------------------------------------------------- /** * Sets up local transaction property and refreshes local db property to * reflect the db connection of that transaction. After setting it, you * can perform common actions. * * @see BaseModel::getTransaction() * @see BaseModel::inTransaction() * @see BaseModel::removeTransaction() * * @param Transaction $transaction * @return bool success state */ public function setTransaction(&$transaction) { if (is_object($transaction)) { $this->_TRANSACTION = $transaction; $this->getDb(); // refresh $o_db property to reflect db connection of transaction return true; } else { return false; } } /** * Get transaction property. * * @see BaseModel::setTransaction() * @see BaseModel::inTransaction() * @see BaseModel::removeTransaction() * * @return Transaction */ public function getTransaction() { return isset($this->_TRANSACTION) ? $this->_TRANSACTION : null; } /** * Is there a pending transaction? * * @return bool */ public function inTransaction() { if (isset($this->_TRANSACTION)) { return ($this->_TRANSACTION) ? true : false; } return false; } /** * Remove transaction property. * * @param bool $ps_commit If true, the transaction is committed, if false, the transaction is rollback. * Defaults to true. * @return bool success state */ public function removeTransaction($ps_commit=true) { if ($this->inTransaction()) { if ($ps_commit) { $this->_TRANSACTION->commit(); } else { $this->_TRANSACTION->rollback(); } unset($this->_TRANSACTION); return true; } else { return false; } } # -------------------------------------------------------------------------------- /** * Sets whether BaseModel::set() input is run through HTML purifier or not * * @param bool $pb_purify If true, all input passed via BaseModel::set() is run through HTML Purifier prior to being stored. If false, input is stored as-is. If null or omitted, no change is made to current setting * @return bool Returns current purification settings. If you simply want to get the current setting call BaseModel::purify without any parameters. */ public function purify($pb_purify=null) { if (!is_null($pb_purify)) { $this->opb_purify_input = (bool)$pb_purify; } return $this->opb_purify_input; } # -------------------------------------------------------------------------------- # Set/get values # -------------------------------------------------------------------------------- /** * Get all field values of the current row that is represented by this BaseModel object. * * @see BaseModel::getChangedFieldValuesArray() * @return array associative array: field name => field value */ public function getFieldValuesArray() { return $this->_FIELD_VALUES; } /** * Set alls field values of the current row that is represented by this BaseModel object * by passing an associative array as follows: field name => field value * * @param array $pa_values associative array: field name => field value * @return void */ public function setFieldValuesArray($pa_values) { $this->_FIELD_VALUES = $pa_values; } /** * Get an associative array of the field values that changed since instantiation of * this BaseModel object. * * @return array associative array: field name => field value */ public function getChangedFieldValuesArray() { $va_fieldnames = array_keys($this->_FIELD_VALUES); $va_changed_field_values_array = array(); foreach($va_fieldnames as $vs_fieldname) { if($this->changed($vs_fieldname)) { $va_changed_field_values_array[$vs_fieldname] = $this->_FIELD_VALUES[$vs_fieldname]; } } return $va_changed_field_values_array; } /** * What was the original value of a field? * * @param string $ps_field field name * @return mixed original field value */ public function getOriginalValue($ps_field) { return $this->_FIELD_VALUES_OLD[$ps_field]; } /** * Check if the content of a field has changed. * * @param string $ps_field field name * @return bool */ public function changed($ps_field) { return isset($this->_FIELD_VALUE_CHANGED[$ps_field]) ? $this->_FIELD_VALUE_CHANGED[$ps_field] : null; } /** * Force field to be considered changed * * @param string $ps_field field name * @return bool Always true */ public function setAsChanged($ps_field) { $this->_FIELD_VALUE_CHANGED[$ps_field] = true; return true; } /** * Returns value of primary key * * @param bool $vb_quoted Set to true if you want the method to return the value in quotes. Default is false. * @return mixed value of primary key */ public function getPrimaryKey ($vb_quoted=false) { if (!isset($this->_FIELD_VALUES[$this->PRIMARY_KEY])) return null; $vm_pk = $this->_FIELD_VALUES[$this->PRIMARY_KEY]; if ($vb_quoted) { $vm_pk = $this->quote($this->PRIMARY_KEY, $vm_pk); } return $vm_pk; } /** * Get a field value of the table row that is represented by this object. * * @param string $ps_field field name * @param array $pa_options options array; can be omitted. * It should be an associative array of boolean (except one of the options) flags. In case that some of the options are not set, they are treated as 'false'. * Possible options (keys) are: * -BINARY: return field value as is * -FILTER_HTML_SPECIAL_CHARS: convert all applicable chars to their html entities * -DONT_PROCESS_GLOSSARY_TAGS: ? * -CONVERT_HTML_BREAKS: similar to nl2br() * -convertLineBreaks: same as CONVERT_HTML_BREAKS * -GET_DIRECT_DATE: return raw date value from database if $ps_field adresses a date field, otherwise the value will be parsed using the TimeExpressionParser::getText() method * -GET_DIRECT_TIME: return raw time value from database if $ps_field adresses a time field, otherwise the value will be parsed using the TimeExpressionParser::getText() method * -TIMECODE_FORMAT: set return format for fields representing time ranges possible (string) values: COLON_DELIMITED, HOURS_MINUTES_SECONDS, RAW; data will be passed through floatval() by default * -QUOTE: set return value into quotes * -URL_ENCODE: value will be passed through urlencode() * -ESCAPE_FOR_XML: convert <, >, &, ' and " characters for XML use * -DONT_STRIP_SLASHES: if set to true, return value will not be passed through stripslashes() * -template: formatting string to use for returned value; ^<fieldname> placeholder is used to represent field value in template * -returnAsArray: if true, fields that can return multiple values [currently only <table_name>.children.<field>] will return values in an indexed array; default is false * -returnAllLocales: * -delimiter: if set, value is used as delimiter when fields that can return multiple fields are returned as strings; default is a single space * -convertCodesToDisplayText: if set, id values refering to foreign keys are returned as preferred label text in the current locale * -returnURL: if set then url is returned for media, otherwise an HTML tag for display is returned * -dateFormat: format to return created or lastModified dates in. Valid values are iso8601 or text */ public function get($ps_field, $pa_options=null) { if (!$ps_field) return null; if (!is_array($pa_options)) { $pa_options = array();} $vb_return_as_array = (isset($pa_options['returnAsArray'])) ? (bool)$pa_options['returnAsArray'] : false; $vb_return_all_locales = (isset($pa_options['returnAllLocales'])) ? (bool)$pa_options['returnAllLocales'] : false; $vs_delimiter = (isset($pa_options['delimiter'])) ? $pa_options['delimiter'] : ' '; if ($vb_return_all_locales && !$vb_return_as_array) { $vb_return_as_array = true; } $vn_row_id = $this->getPrimaryKey(); if ($vb_return_as_array && $vb_return_as_array) { $vn_locale_id = ($this->hasField('locale_id')) ? $this->get('locale_id') : null; } $va_tmp = explode('.', $ps_field); if (sizeof($va_tmp) > 1) { if ($va_tmp[0] === $this->tableName()) { // // Return created on or last modified // if (in_array($va_tmp[1], array('created', 'lastModified'))) { if ($vb_return_as_array) { return ($va_tmp[1] == 'lastModified') ? $this->getLastChangeTimestamp() : $this->getCreationTimestamp(); } else { $va_data = ($va_tmp[1] == 'lastModified') ? $this->getLastChangeTimestamp() : $this->getCreationTimestamp(); $vs_subfield = (isset($va_tmp[2]) && isset($va_data[$va_tmp[2]])) ? $va_tmp[2] : 'timestamp'; $vm_val = $va_data[$vs_subfield]; if ($vs_subfield == 'timestamp') { $o_tep = new TimeExpressionParser(); $o_tep->setUnixTimestamps($vm_val, $vm_val); $vm_val = $o_tep->getText($pa_options); } return $vm_val; } } // // Generalized get // switch(sizeof($va_tmp)) { case 2: // support <table_name>.<field_name> syntax $ps_field = $va_tmp[1]; break; default: // > 2 elements // media field? $va_field_info = $this->getFieldInfo($va_tmp[1]); if (($va_field_info['FIELD_TYPE'] === FT_MEDIA) && (!isset($pa_options['returnAsArray'])) && !$pa_options['returnAsArray']) { $o_media_settings = new MediaProcessingSettings($va_tmp[0], $va_tmp[1]); $va_versions = $o_media_settings->getMediaTypeVersions('*'); $vs_version = $va_tmp[2]; if (!isset($va_versions[$vs_version])) { $vs_version = array_shift(array_keys($va_versions)); } if (isset($pa_options['returnURL']) && $pa_options['returnURL']) { return $this->getMediaUrl($va_tmp[1], $vs_version); } else { return $this->getMediaTag($va_tmp[1], $vs_version); } } if (($va_tmp[1] == 'parent') && ($this->isHierarchical()) && ($vn_parent_id = $this->get($this->getProperty('HIERARCHY_PARENT_ID_FLD')))) { $t_instance = $this->getAppDatamodel()->getInstanceByTableNum($this->tableNum(), true); if (!$t_instance->load($vn_parent_id)) { return ($vb_return_as_array) ? array() : null; } else { unset($va_tmp[1]); $va_tmp = array_values($va_tmp); if ($vb_return_as_array) { if ($vb_return_all_locales) { return array( $vn_row_id => array( // this row_id $vn_locale_id => array( // base model fields aren't translate-able $t_instance->get(join('.', $va_tmp)) ) ) ); } else { return array( $vn_row_id => $t_instance->get(join('.', $va_tmp)) ); } } else { return $t_instance->get(join('.', $va_tmp)); } } } else { if (($va_tmp[1] == 'children') && ($this->isHierarchical())) { unset($va_tmp[1]); // remove 'children' from field path $va_tmp = array_values($va_tmp); $vs_childless_path = join('.', $va_tmp); $va_data = array(); $va_children_ids = $this->getHierarchyChildren(null, array('idsOnly' => true)); $t_instance = $this->getAppDatamodel()->getInstanceByTableNum($this->tableNum()); foreach($va_children_ids as $vn_child_id) { if ($t_instance->load($vn_child_id)) { if ($vb_return_as_array) { $va_data[$vn_child_id] = array_shift($t_instance->get($vs_childless_path, array_merge($pa_options, array('returnAsArray' => $vb_return_as_array, 'returnAllLocales' => $vb_return_all_locales)))); } else { $va_data[$vn_child_id] = $t_instance->get($vs_childless_path, array_merge($pa_options, array('returnAsArray' => false, 'returnAllLocales' => false))); } } } if ($vb_return_as_array) { return $va_data; } else { return join($vs_delimiter, $va_data); } } } break; } } else { // can't pull fields from other tables! return $vb_return_as_array ? array() : null; } } if (isset($pa_options["BINARY"]) && $pa_options["BINARY"]) { return $this->_FIELD_VALUES[$ps_field]; } if (array_key_exists($ps_field,$this->FIELDS)) { $ps_field_type = $this->getFieldInfo($ps_field,"FIELD_TYPE"); if ($this->getFieldInfo($ps_field, 'IS_LIFESPAN')) { $pa_options['isLifespan'] = true; } switch ($ps_field_type) { case (FT_BIT): $vs_prop = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : ""; if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText']) { $vs_prop = (bool)$vs_prop ? _t('yes') : _t('no'); } return $vs_prop; break; case (FT_TEXT): case (FT_NUMBER): case (FT_PASSWORD): $vs_prop = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : null; if (isset($pa_options["FILTER_HTML_SPECIAL_CHARS"]) && ($pa_options["FILTER_HTML_SPECIAL_CHARS"])) { $vs_prop = htmlentities(html_entity_decode($vs_prop)); } // // Convert foreign keys and choice list values to display text is needed // if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && ($vs_list_code = $this->getFieldInfo($ps_field,"LIST_CODE"))) { $t_list = new ca_lists(); $vs_prop = $t_list->getItemFromListForDisplayByItemID($vs_list_code, $vs_prop); } else { if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && ($vs_list_code = $this->getFieldInfo($ps_field,"LIST"))) { $t_list = new ca_lists(); if (!($vs_tmp = $t_list->getItemFromListForDisplayByItemValue($vs_list_code, $vs_prop))) { if ($vs_tmp = $this->getChoiceListValue($ps_field, $vs_prop)) { $vs_prop = $vs_tmp; } } else { $vs_prop = $vs_tmp; } } else { if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && ($ps_field === 'locale_id') && ((int)$vs_prop > 0)) { $t_locale = new ca_locales($vs_prop); $vs_prop = $t_locale->getName(); } else { if (isset($pa_options['convertCodesToDisplayText']) && $pa_options['convertCodesToDisplayText'] && (is_array($va_list = $this->getFieldInfo($ps_field,"BOUNDS_CHOICE_LIST")))) { foreach($va_list as $vs_option => $vs_value) { if ($vs_value == $vs_prop) { $vs_prop = $vs_option; break; } } } } } } if ( (isset($pa_options["CONVERT_HTML_BREAKS"]) && ($pa_options["CONVERT_HTML_BREAKS"])) || (isset($pa_options["convertLineBreaks"]) && ($pa_options["convertLineBreaks"])) ) { $vs_prop = caConvertLineBreaks($vs_prop); } break; case (FT_DATETIME): case (FT_TIMESTAMP): case (FT_HISTORIC_DATETIME): case (FT_HISTORIC_DATE): case (FT_DATE): if (isset($pa_options["GET_DIRECT_DATE"]) && $pa_options["GET_DIRECT_DATE"]) { $vs_prop = $this->_FIELD_VALUES[$ps_field]; } else { $o_tep = new TimeExpressionParser(); $vn_timestamp = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : 0; if (($ps_field_type == FT_HISTORIC_DATETIME) || ($ps_field_type == FT_HISTORIC_DATE)) { $o_tep->setHistoricTimestamps($vn_timestamp, $vn_timestamp); } else { $o_tep->setUnixTimestamps($vn_timestamp, $vn_timestamp); } if (($ps_field_type == FT_DATE) || ($ps_field_type == FT_HISTORIC_DATE)) { $vs_prop = $o_tep->getText(array_merge(array('timeOmit' => true), $pa_options)); } else { $vs_prop = $o_tep->getText($pa_options); } } break; case (FT_TIME): if (isset($pa_options["GET_DIRECT_TIME"]) && $pa_options["GET_DIRECT_TIME"]) { $vs_prop = $this->_FIELD_VALUES[$ps_field]; } else { $o_tep = new TimeExpressionParser(); $vn_timestamp = isset($this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : 0; $o_tep->setTimes($vn_timestamp, $vn_timestamp); $vs_prop = $o_tep->getText($pa_options); } break; case (FT_DATERANGE): case (FT_HISTORIC_DATERANGE): $vs_start_field_name = $this->getFieldInfo($ps_field,"START"); $vs_end_field_name = $this->getFieldInfo($ps_field,"END"); $vn_start_date = isset($this->_FIELD_VALUES[$vs_start_field_name]) ? $this->_FIELD_VALUES[$vs_start_field_name] : null; $vn_end_date = isset($this->_FIELD_VALUES[$vs_end_field_name]) ? $this->_FIELD_VALUES[$vs_end_field_name] : null; if (!isset($pa_options["GET_DIRECT_DATE"]) || !$pa_options["GET_DIRECT_DATE"]) { $o_tep = new TimeExpressionParser(); if ($ps_field_type == FT_HISTORIC_DATERANGE) { $o_tep->setHistoricTimestamps($vn_start_date, $vn_end_date); } else { $o_tep->setUnixTimestamps($vn_start_date, $vn_end_date); } $vs_prop = $o_tep->getText($pa_options); } else { $vs_prop = array($vn_start_date, $vn_end_date); } break; case (FT_TIMERANGE): $vs_start_field_name = $this->getFieldInfo($ps_field,"START"); $vs_end_field_name = $this->getFieldInfo($ps_field,"END"); $vn_start_date = isset($this->_FIELD_VALUES[$vs_start_field_name]) ? $this->_FIELD_VALUES[$vs_start_field_name] : null; $vn_end_date = isset($this->_FIELD_VALUES[$vs_end_field_name]) ? $this->_FIELD_VALUES[$vs_end_field_name] : null; if (!isset($pa_options["GET_DIRECT_TIME"]) || !$pa_options["GET_DIRECT_TIME"]) { $o_tep = new TimeExpressionParser(); $o_tep->setTimes($vn_start_date, $vn_end_date); $vs_prop = $o_tep->getText($pa_options); } else { $vs_prop = array($vn_start_date, $vn_end_date); } break; case (FT_TIMECODE): $o_tp = new TimecodeParser(); $o_tp->setParsedValueInSeconds($this->_FIELD_VALUES[$ps_field]); $vs_prop = $o_tp->getText(isset($pa_options["TIMECODE_FORMAT"]) ? $pa_options["TIMECODE_FORMAT"] : null); break; case (FT_MEDIA): case (FT_FILE): if (isset($pa_options["USE_MEDIA_FIELD_VALUES"]) && $pa_options["USE_MEDIA_FIELD_VALUES"]) { $vs_prop = $this->_FIELD_VALUES[$ps_field]; } else { $vs_prop = (isset($this->_SET_FILES[$ps_field]['tmp_name']) && $this->_SET_FILES[$ps_field]['tmp_name']) ? $this->_SET_FILES[$ps_field]['tmp_name'] : $this->_FIELD_VALUES[$ps_field]; } break; case (FT_VARS): $vs_prop = (isset($this->_FIELD_VALUES[$ps_field]) && $this->_FIELD_VALUES[$ps_field]) ? $this->_FIELD_VALUES[$ps_field] : null; break; } if (isset($pa_options["QUOTE"]) && $pa_options["QUOTE"]) $vs_prop = $this->quote($ps_field, $vs_prop); } else { $this->postError(710,_t("'%1' does not exist in this object", $ps_field),"BaseModel->get()"); return $vb_return_as_array ? array() : null; } if (isset($pa_options["URL_ENCODE"]) && $pa_options["URL_ENCODE"]) { $vs_prop = urlEncode($vs_prop); } if (isset($pa_options["ESCAPE_FOR_XML"]) && $pa_options["ESCAPE_FOR_XML"]) { $vs_prop = escapeForXML($vs_prop); } if (!(isset($pa_options["DONT_STRIP_SLASHES"]) && $pa_options["DONT_STRIP_SLASHES"])) { if (is_string($vs_prop)) { $vs_prop = stripSlashes($vs_prop); } } if ((isset($pa_options["template"]) && $pa_options["template"])) { $vs_template_with_substitution = str_replace("^".$ps_field, $vs_prop, $pa_options["template"]); $vs_prop = str_replace("^".$this->tableName().".".$ps_field, $vs_prop, $vs_template_with_substitution); } if ($vb_return_as_array) { if ($vb_return_all_locales) { return array( $vn_row_id => array( // this row_id $vn_locale_id => array($vs_prop) ) ); } else { return array( $vn_row_id => $vs_prop ); } } else { return $vs_prop; } } /** * Set field value(s) for the table row represented by this object * * @param string|array string $pa_fields representation of a field name * or array of string representations of field names * @param mixed $pm_value value to set the given field(s) to * @param array $pa_options associative array of options * possible options (keys): * when dealing with date/time fields: * - SET_DIRECT_DATE * - SET_DIRECT_TIME * - SET_DIRECT_TIMES * * for media/files fields: * - original_filename : (note that it is lower case) optional parameter which enables you to pass the original filename of a file, in addition to the representation in the temporary, global _FILES array; * * for text fields: * - purify : if set then text input is run through HTML Purifier before being set */ public function set($pa_fields, $pm_value="", $pa_options=null) { $this->errors = array(); if (!is_array($pa_fields)) { $pa_fields = array($pa_fields => $pm_value); } foreach($pa_fields as $vs_field => $vm_value) { if (array_key_exists($vs_field, $this->FIELDS)) { $pa_fields_type = $this->getFieldInfo($vs_field,"FIELD_TYPE"); $pb_need_reload = false; if (!$this->verifyFieldValue($vs_field, $vm_value, $pb_need_reload)) { return false; } if ($pb_need_reload) { return true; } // was set to default if ($vs_field == $this->primaryKey()) { $vm_value = preg_replace("/[\"']/", "", $vm_value); } // what markup is supported for text fields? $vs_markup_type = $this->getFieldInfo($vs_field, "MARKUP_TYPE"); // if markup is non-HTML then strip out HTML special chars for safety if (!($vs_markup_type == __CA_MT_HTML__)) { $vm_value = htmlspecialchars($vm_value, ENT_QUOTES, 'UTF-8'); } $vs_cur_value = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; switch ($pa_fields_type) { case (FT_NUMBER): if ($vs_cur_value != $vm_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } if (($vm_value !== "") || ($this->getFieldInfo($vs_field, "IS_NULL") && ($vm_value == ""))) { if ($vm_value) { $vm_orig_value = $vm_value; $vm_value = preg_replace("/[^\d-.]+/", "", $vm_value); # strip non-numeric characters if (!preg_match("/^[\-]{0,1}[\d.]+$/", $vm_value)) { $this->postError(1100,_t("'%1' for %2 is not numeric", $vm_orig_value, $vs_field),"BaseModel->set()"); return ""; } } $this->_FIELD_VALUES[$vs_field] = $vm_value; } break; case (FT_BIT): if ($vs_cur_value != $vm_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = ($vm_value ? 1 : 0); break; case (FT_DATETIME): case (FT_HISTORIC_DATETIME): case (FT_DATE): case (FT_HISTORIC_DATE): if (($this->DIRECT_DATETIMES) || ($pa_options["SET_DIRECT_DATE"])) { $this->_FIELD_VALUES[$vs_field] = $vm_value; } else { if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) { if ($vs_cur_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = null; } else { $o_tep= new TimeExpressionParser(); if (($pa_fields_type == FT_DATE) || ($pa_fields_type == FT_HISTORIC_DATE)) { $va_timestamps = $o_tep->parseDate($vm_value); } else { $va_timestamps = $o_tep->parseDatetime($vm_value); } if (!$va_timestamps) { $this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } if (($pa_fields_type == FT_HISTORIC_DATETIME) || ($pa_fields_type == FT_HISTORIC_DATE)) { if($vs_cur_value != $va_timestamps["start"]) { $this->_FIELD_VALUES[$vs_field] = $va_timestamps["start"]; $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } } else { $va_timestamps = $o_tep->getUnixTimestamps(); if ($va_timestamps[0] == -1) { $this->postError(1830, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } if ($vs_cur_value != $va_timestamps["start"]) { $this->_FIELD_VALUES[$vs_field] = $va_timestamps["start"]; $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } } } } break; case (FT_TIME): if (($this->DIRECT_TIMES) || ($pa_options["SET_DIRECT_TIME"])) { $this->_FIELD_VALUES[$vs_field] = $vm_value; } else { if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) { if ($vs_cur_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = null; } else { $o_tep= new TimeExpressionParser(); if (!$o_tep->parseTime($vm_value)) { $this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } $va_times = $o_tep->getTimes(); if ($vs_cur_value != $va_times['start']) { $this->_FIELD_VALUES[$vs_field] = $va_times['start']; $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } } } break; case (FT_TIMESTAMP): # can't set timestamp break; case (FT_DATERANGE): case (FT_HISTORIC_DATERANGE): $vs_start_field_name = $this->getFieldInfo($vs_field,"START"); $vs_end_field_name = $this->getFieldInfo($vs_field,"END"); $vn_start_date = isset($this->_FIELD_VALUES[$vs_start_field_name]) ? $this->_FIELD_VALUES[$vs_start_field_name] : null; $vn_end_date = isset($this->_FIELD_VALUES[$vs_end_field_name]) ? $this->_FIELD_VALUES[$vs_end_field_name] : null; if (($this->DIRECT_DATETIMES) || ($pa_options["SET_DIRECT_DATE"])) { if (is_array($vm_value) && (sizeof($vm_value) == 2) && ($vm_value[0] <= $vm_value[1])) { if ($vn_start_date != $vm_value[0]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_start_field_name] = $vm_value[0]; } if ($vn_end_date != $vm_value[1]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_end_field_name] = $vm_value[1]; } } else { $this->postError(1100,_t("Invalid direct date values"),"BaseModel->set()"); } } else { if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) { if ($vn_start_date || $vn_end_date) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_start_field_name] = null; $this->_FIELD_VALUES[$vs_end_field_name] = null; } else { $o_tep = new TimeExpressionParser(); if (!$o_tep->parseDatetime($vm_value)) { $this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } if ($pa_fields_type == FT_HISTORIC_DATERANGE) { $va_timestamps = $o_tep->getHistoricTimestamps(); } else { $va_timestamps = $o_tep->getUnixTimestamps(); if ($va_timestamps[0] == -1) { $this->postError(1830, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } } if ($vn_start_date != $va_timestamps["start"]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_start_field_name] = $va_timestamps["start"]; } if ($vn_end_date != $va_timestamps["end"]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_end_field_name] = $va_timestamps["end"]; } } } break; case (FT_TIMERANGE): $vs_start_field_name = $this->getFieldInfo($vs_field,"START"); $vs_end_field_name = $this->getFieldInfo($vs_field,"END"); if (($this->DIRECT_TIMES) || ($pa_options["SET_DIRECT_TIMES"])) { if (is_array($vm_value) && (sizeof($vm_value) == 2) && ($vm_value[0] <= $vm_value[1])) { if ($this->_FIELD_VALUES[$vs_start_field_name] != $vm_value[0]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_start_field_name] = $vm_value[0]; } if ($this->_FIELD_VALUES[$vs_end_field_name] != $vm_value[1]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_end_field_name] = $vm_value[1]; } } else { $this->postError(1100,_t("Invalid direct time values"),"BaseModel->set()"); } } else { if (!$vm_value && $this->FIELDS[$vs_field]["IS_NULL"]) { if ($this->_FIELD_VALUES[$vs_start_field_name] || $this->_FIELD_VALUES[$vs_end_field_name]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_start_field_name] = null; $this->_FIELD_VALUES[$vs_end_field_name] = null; } else { $o_tep = new TimeExpressionParser(); if (!$o_tep->parseTime($vm_value)) { $this->postError(1805, $o_tep->getParseErrorMessage(), 'BaseModel->set()'); return false; } $va_timestamps = $o_tep->getTimes(); if ($this->_FIELD_VALUES[$vs_start_field_name] != $va_timestamps["start"]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_start_field_name] = $va_timestamps["start"]; } if ($this->_FIELD_VALUES[$vs_end_field_name] != $va_timestamps["end"]) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_end_field_name] = $va_timestamps["end"]; } } } break; case (FT_TIMECODE): $o_tp = new TimecodeParser(); if ($o_tp->parse($vm_value)) { if ($o_tp->getParsedValueInSeconds() != $vs_cur_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; $this->_FIELD_VALUES[$vs_field] = $o_tp->getParsedValueInSeconds(); } } break; case (FT_TEXT): if (is_string($vm_value)) { $vm_value = stripSlashes($vm_value); } if ((isset($pa_options['purify']) && ($pa_options['purify'])) || ((bool)$this->opb_purify_input) || ($this->getFieldInfo($vs_field, "PURIFY")) || ((bool)$this->getAppConfig()->get('useHTMLPurifier'))) { if (!BaseModel::$html_purifier) { BaseModel::$html_purifier = new HTMLPurifier(); } $vm_value = BaseModel::$html_purifier->purify((string)$vm_value); } if ($this->getFieldInfo($vs_field, "DISPLAY_TYPE") == DT_LIST_MULTIPLE) { if (is_array($vm_value)) { if (!($vs_list_multiple_delimiter = $this->getFieldInfo($vs_field, 'LIST_MULTIPLE_DELIMITER'))) { $vs_list_multiple_delimiter = ';'; } $vs_string_value = join($vs_list_multiple_delimiter, $vm_value); $vs_string_value = str_replace("\0", '', $vs_string_value); if ($vs_cur_value != $vs_string_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = $vs_string_value; } } else { $vm_value = str_replace("\0", '', $vm_value); if ($this->getFieldInfo($vs_field, "ENTITY_ENCODE_INPUT")) { $vs_value_entity_encoded = htmlentities(html_entity_decode($vm_value)); if ($vs_cur_value != $vs_value_entity_encoded) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = $vs_value_entity_encoded; } else { if ($this->getFieldInfo($vs_field, "URL_ENCODE_INPUT")) { $vs_value_url_encoded = urlencode($vm_value); if ($vs_cur_value != $vs_value_url_encoded) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = $vs_value_url_encoded; } else { if ($vs_cur_value != $vm_value) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = $vm_value; } } } break; case (FT_PASSWORD): if (!$vm_value) { // store blank passwords as blank, not MD5 of blank $this->_FIELD_VALUES[$vs_field] = $vs_crypt_pw = ""; } else { if ($this->_CONFIG->get("use_old_style_passwords")) { $vs_crypt_pw = crypt($vm_value,substr($vm_value,0,2)); } else { $vs_crypt_pw = md5($vm_value); } if (($vs_cur_value != $vm_value) && ($vs_cur_value != $vs_crypt_pw)) { $this->_FIELD_VALUES[$vs_field] = $vs_crypt_pw; } if ($vs_cur_value != $vs_crypt_pw) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } } break; case (FT_VARS): if (md5(print_r($vs_cur_value, true)) != md5(print_r($vm_value, true))) { $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } $this->_FIELD_VALUES[$vs_field] = $vm_value; break; case (FT_MEDIA): case (FT_FILE): $vb_allow_fetching_of_urls = (bool)$this->_CONFIG->get('allow_fetching_of_media_from_remote_urls'); # if there's a tmp_name is the global _FILES array # then we'll process it in insert()/update()... $this->_SET_FILES[$vs_field]['options'] = $pa_options; if (caGetOSFamily() == OS_WIN32) { // fix for paths using backslashes on Windows failing in processing $vm_value = str_replace('\\', '/', $vm_value); } $va_matches = null; if (is_string($vm_value) && (file_exists($vm_value) || ($vb_allow_fetching_of_urls && isURL($vm_value)))) { $this->_SET_FILES[$vs_field]['original_filename'] = $pa_options["original_filename"]; $this->_SET_FILES[$vs_field]['tmp_name'] = $vm_value; $this->_FIELD_VALUE_CHANGED[$vs_field] = true; } else { # only return error when file name is not 'none' # 'none' is PHP's stupid way of telling you there # isn't a file... if (($vm_value != "none") && ($vm_value)) { //$this->postError(1500,_t("%1 does not exist", $vm_value),"BaseModel->set()"); } return false; } break; default: die("Invalid field type in BaseModel->set()"); break; } } else { $this->postError(710,_t("%1' does not exist in this object", $vs_field),"BaseModel->set()"); return false; } } return true; } # ------------------------------------------------------------------ /** * */ public function getValuesForExport($pa_options=null) { $va_fields = $this->getFields(); $va_data = array(); $t_list = new ca_lists(); // get field values foreach($va_fields as $vs_field) { $vs_value = $this->get($this->tableName().'.'.$vs_field); // Convert list item_id's to idnos for export if ($vs_list_code = $this->getFieldInfo($vs_field, 'LIST_CODE')) { $va_item = $t_list->getItemFromListByItemID($vs_list_code, $vs_value); $vs_value = $va_item['idno']; } $va_data[$vs_field] = $vs_value; } return $va_data; } # -------------------------------------------------------------------------------- # BaseModel info # -------------------------------------------------------------------------------- /** * Returns an array containing the field names of the table. * * @return array field names */ public function getFields() { return array_keys($this->FIELDS); } /** * Returns an array containing the field names of the table as keys and their info as values. * * @return array field names */ public function getFieldsArray() { return $this->FIELDS; } /** * Returns name of primary key * * @return string the primary key of the table */ public function primaryKey() { return $this->PRIMARY_KEY; } /** * Returns name of the table * * @return string the name of the table */ public function tableName() { return $this->TABLE; } /** * Returns number of the table as defined in datamodel.conf configuration file * * @return int table number */ public function tableNum() { return $this->_DATAMODEL->getTableNum($this->TABLE); } /** * Returns number of the given field. Field numbering is defined implicitly by the order. * * @param string $ps_field field name * @return int field number */ public function fieldNum($ps_field) { return $this->_DATAMODEL->getFieldNum($this->TABLE, $ps_field); } /** * Returns name of the given field number. * * @param number $pn_num field number * @return string field name */ public function fieldName($pn_num) { $va_fields = $this->getFields(); return isset($va_fields[$pn_num]) ? $va_fields[$pn_num] : null; } /** * Returns name field used for arbitrary ordering of records (returns "" if none defined) * * @return string field name, "" if none defined */ public function rankField() { return $this->RANK; } /** * Returns table property * * @return mixed the property */ public function getProperty($property) { if (isset($this->{$property})) { return $this->{$property}; } return null; } /** * Returns a string with the values taken from fields which are defined in global property LIST_FIELDS * taking into account the global property LIST_DELIMITER. Each extension of BaseModel can define those properties. * * @return string */ public function getListFieldText() { if (is_array($va_list_fields = $this->getProperty('LIST_FIELDS'))) { $vs_delimiter = $this->getProperty('LIST_DELIMITER'); if ($vs_delimiter == null) { $vs_delimiter = ' '; } $va_tmp = array(); foreach($va_list_fields as $vs_field) { $va_tmp[] = $this->get($vs_field); } return join($vs_delimiter, $va_tmp); } return ''; } # -------------------------------------------------------------------------------- # Access mode # -------------------------------------------------------------------------------- /** * Returns the current access mode. * * @param bool $pb_return_name If set to true, return string representations of the modes * (i.e. 'read' or 'write'). If set to false (it is by default), returns ACCESS_READ or ACCESS_WRITE. * * @return int|string access mode representation */ public function getMode($pb_return_name=false) { if ($pb_return_name) { switch($this->ACCESS_MODE) { case ACCESS_READ: return 'read'; break; case ACCESS_WRITE: return 'write'; break; default: return '???'; break; } } return $this->ACCESS_MODE; } /** * Set current access mode. * * @param int $pn_mode access mode representation, either ACCESS_READ or ACCESS_WRITE * @return bool either returns the access mode or false on error */ public function setMode($pn_mode) { if (in_array($pn_mode, array(ACCESS_READ, ACCESS_WRITE))) { return $this->ACCESS_MODE = $pn_mode; } $this->postError(700,_t("Mode:%1 is not supported by this object", $pn_mode),"BaseModel->setMode()"); return false; } # -------------------------------------------------------------------------------- # --- Content methods (just your standard Create, Return, Update, Delete methods) # -------------------------------------------------------------------------------- /** * Generic method to load content properties of object with database fields. * After dealing with one row in the database using an extension of BaseModel * you can use this method to make the same object represent another row, instead * of destructing the old and constructing a new one. * * @param mixed $pm_id primary key value of the record to load (assuming we have no composed primary key) * @return bool success state */ public function load ($pm_id=null) { $this->clear(); if ($pm_id == null) { //$this->postError(750,_t("Can't load record; key is blank"), "BaseModel->load()"); return false; } $o_db = $this->getDb(); if (!is_array($pm_id)) { if ($this->_getFieldTypeType($this->primaryKey()) == 1) { $pm_id = $this->quote($pm_id); } else { $pm_id = intval($pm_id); } $vs_sql = "SELECT * FROM ".$this->tableName()." WHERE ".$this->primaryKey()." = ".$pm_id; } else { $va_sql_wheres = array(); foreach ($pm_id as $vs_field => $vm_value) { # support case where fieldname is in format table.fieldname if (preg_match("/([\w_]+)\.([\w_]+)/", $vs_field, $va_matches)) { if ($va_matches[1] != $this->tableName()) { if ($this->_DATAMODEL->tableExists($va_matches[1])) { $this->postError(715,_t("BaseModel '%1' cannot be accessed with this class", $matches[1]), "BaseModel->load()"); return false; } else { $this->postError(715, _t("BaseModel '%1' does not exist", $matches[1]), "BaseModel->load()"); return false; } } $vs_field = $matches[2]; # get field name alone } if (!$this->hasField($vs_field)) { $this->postError(716,_t("Field '%1' does not exist", $vs_field), "BaseModel->load()"); return false; } if ($this->_getFieldTypeType($vs_field) == 0) { if (!is_numeric($vm_value) && !is_null($vm_value)) { $vm_value = intval($vm_value); } } else { $vm_value = $this->quote($vs_field, is_null($vm_value) ? '' : $vm_value); } if (is_null($vm_value)) { $va_sql_wheres[] = "($vs_field IS NULL)"; } else { if ($vm_value === '') { continue; } $va_sql_wheres[] = "($vs_field = $vm_value)"; } } $vs_sql = "SELECT * FROM ".$this->tableName()." WHERE ".join(" AND ", $va_sql_wheres); } $qr_res = $o_db->query($vs_sql); if ($o_db->numErrors()) { $this->postError(250, _t('Basemodel::load SQL had an error: %1; SQL was %2', join("; ", $o_db->getErrors()), $vs_sql), 'BaseModel->load'); return false; } if ($qr_res->nextRow()) { foreach($this->FIELDS as $vs_field => $va_attr) { $vs_cur_value = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; $va_row =& $qr_res->getRow(); switch($va_attr["FIELD_TYPE"]) { case FT_DATERANGE: case FT_HISTORIC_DATERANGE: case FT_TIMERANGE: $vs_start_field_name = $va_attr["START"]; $vs_end_field_name = $va_attr["END"]; $this->_FIELD_VALUES[$vs_start_field_name] = $va_row[$vs_start_field_name]; $this->_FIELD_VALUES[$vs_end_field_name] = $va_row[$vs_end_field_name]; break; case FT_TIMESTAMP: $this->_FIELD_VALUES[$vs_field] = $va_row[$vs_field]; break; case FT_VARS: case FT_FILE: case FT_MEDIA: if (!$vs_cur_value) { $this->_FIELD_VALUES[$vs_field] = caUnserializeForDatabase($va_row[$vs_field]); } break; default: $this->_FIELD_VALUES[$vs_field] = $va_row[$vs_field]; break; } } $this->_FIELD_VALUES_OLD = $this->_FIELD_VALUES; $this->_FILES_CLEAR = array(); return true; } else { if (!is_array($pm_id)) { $this->postError(750,_t("Invalid %1 '%2'", $this->primaryKey(), $pm_id), "BaseModel->load()"); } else { $va_field_list = array(); foreach ($pm_id as $vs_field => $vm_value) { $va_field_list[] = "$vs_field => $vm_value"; } $this->postError(750,_t("No record with %1", join(", ", $va_field_list)), "BaseModel->load()"); } return false; } } /** * */ private function _calcHierarchicalIndexing($pa_parent_info) { $vs_hier_left_fld = $this->getProperty('HIERARCHY_LEFT_INDEX_FLD'); $vs_hier_right_fld = $this->getProperty('HIERARCHY_RIGHT_INDEX_FLD'); $vs_hier_id_fld = $this->getProperty('HIERARCHY_ID_FLD'); $vs_parent_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD'); $o_db = $this->getDb(); $qr_up = $o_db->query(" SELECT MAX({$vs_hier_right_fld}) maxChildRight FROM ".$this->tableName()." WHERE ({$vs_hier_left_fld} > ?) AND ({$vs_hier_right_fld} < ?) AND (".$this->primaryKey()." <> ?)". ($vs_hier_id_fld ? " AND ({$vs_hier_id_fld} = ".intval($pa_parent_info[$vs_hier_id_fld]).")" : '')." ", $pa_parent_info[$vs_hier_left_fld], $pa_parent_info[$vs_hier_right_fld], $pa_parent_info[$this->primaryKey()]); if ($qr_up->nextRow()) { if (!($vn_gap_start = $qr_up->get('maxChildRight'))) { $vn_gap_start = $pa_parent_info[$vs_hier_left_fld]; } $vn_gap_end = $pa_parent_info[$vs_hier_right_fld]; $vn_gap_size = ($vn_gap_end - $vn_gap_start); if ($vn_gap_size < 0.00001) { // rebuild hierarchical index if the current gap is not large enough to fit current record $this->rebuildHierarchicalIndex($this->get($vs_hier_id_fld)); $pa_parent_info = $this->_getHierarchyParent($pa_parent_info[$this->primaryKey()]); return $this->_calcHierarchicalIndexing($pa_parent_info); } if (($vn_scale = strlen(floor($vn_gap_size/10000))) < 1) { $vn_scale = 1; } $vn_interval_start = $vn_gap_start + ($vn_gap_size/(pow(10, $vn_scale))); $vn_interval_end = $vn_interval_start + ($vn_gap_size/(pow(10, $vn_scale))); //print "--------------------------\n"; //print "GAP START={$vn_gap_start} END={$vn_gap_end} SIZE={$vn_gap_size} SCALE={$vn_scale} INC=".($vn_gap_size/(pow(10, $vn_scale)))."\n"; //print "INT START={$vn_interval_start} INT END={$vn_interval_end}\n"; //print "--------------------------\n"; return array('left' => $vn_interval_start, 'right' => $vn_interval_end); } return null; } /** * */ private function _getHierarchyParent($pn_parent_id) { $o_db = $this->getDb(); $qr_get_parent = $o_db->query(" SELECT * FROM ".$this->tableName()." WHERE ".$this->primaryKey()." = ? ", intval($pn_parent_id)); if($qr_get_parent->nextRow()) { return $qr_get_parent->getRow(); } return null; } /** * Internal-use-only function for getting child record ids in a hierarchy. Unlike the public getHierarchyChildren() method * which uses nested set hierarchical indexing to fetch all children in a single pass (and also can return more than just the id's * of the children), _getHierarchyChildren() recursively traverses the hierarchy using parent_id field values. This makes it useful for * getting children in situations when the hierarchical indexing may not be valid, such as when moving items between hierarchies. * * @access private * @param array $pa_ids List of ids to get children for * @return array ids of all children of specified ids. List includes the original specified ids. */ private function _getHierarchyChildren($pa_ids) { if(!is_array($pa_ids)) { return null; } if (!sizeof($pa_ids)) { return null; } if (!($vs_parent_id_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD'))) { return null; } foreach($pa_ids as $vn_i => $vn_v) { $pa_ids[$vn_i] = (int)$vn_v; } $o_db = $this->getDb(); $qr_get_children = $o_db->query(" SELECT ".$this->primaryKey()." FROM ".$this->tableName()." WHERE {$vs_parent_id_fld} IN (?) ", array($pa_ids)); $va_child_ids = $qr_get_children->getAllFieldValues($this->primaryKey()); if (($va_child_ids && is_array($va_child_ids) && sizeof($va_child_ids) > 0)) { $va_child_ids = array_merge($va_child_ids, $this->_getHierarchyChildren($va_child_ids)); } if (!is_array($va_child_ids)) { $va_child_ids = array(); } $va_child_ids = array_merge($pa_ids, $va_child_ids); return array_unique($va_child_ids, SORT_STRING); } /** * Use this method to insert new record using supplied values * (assuming that you've constructed your BaseModel object as empty record) * @param $pa_options array optional associative array of options. Supported options include: * dont_do_search_indexing = if set to true then no search indexing on the inserted record is performed * @return int primary key of the new record, false on error */ public function insert ($pa_options=null) { if (!is_array($pa_options)) { $pa_options = array(); } $vb_we_set_transaction = false; $this->clearErrors(); if ($this->getMode() == ACCESS_WRITE) { if (!$this->inTransaction()) { $this->setTransaction(new Transaction($this->getDb())); $vb_we_set_transaction = true; } $o_db = $this->getDb(); $vs_fields = ""; $vs_values = ""; $va_media_fields = array(); $va_file_fields = array(); // // Set any auto-set hierarchical fields (eg. HIERARCHY_LEFT_INDEX_FLD and HIERARCHY_RIGHT_INDEX_FLD indexing for all and HIERARCHY_ID_FLD for ad-hoc hierarchies) here // $vn_hier_left_index_value = $vn_hier_right_index_value = 0; if ($vb_is_hierarchical = $this->isHierarchical()) { $vn_parent_id = $this->get($this->getProperty('HIERARCHY_PARENT_ID_FLD')); $va_parent_info = $this->_getHierarchyParent($vn_parent_id); switch($this->getHierarchyType()) { case __CA_HIER_TYPE_SIMPLE_MONO__: // you only need to set parent_id for this type of hierarchy if (!$vn_parent_id) { if ($vn_parent_id = $this->getHierarchyRootID(null)) { $this->set($this->getProperty('HIERARCHY_PARENT_ID_FLD'), $vn_parent_id); $va_parent_info = $this->_getHierarchyParent($vn_parent_id); } } break; case __CA_HIER_TYPE_MULTI_MONO__: // you need to set parent_id (otherwise it defaults to the hierarchy root); you only need to set hierarchy_id if you're creating a root if (!($vn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD')))) { $this->set($this->getProperty('HIERARCHY_ID_FLD'), $va_parent_info[$this->getProperty('HIERARCHY_ID_FLD')]); } if (!$vn_parent_id) { if ($vn_parent_id = $this->getHierarchyRootID($vn_hierarchy_id)) { $this->set($this->getProperty('HIERARCHY_PARENT_ID_FLD'), $vn_parent_id); $va_parent_info = $this->_getHierarchyParent($vn_parent_id); } } break; case __CA_HIER_TYPE_ADHOC_MONO__: // you need to set parent_id for this hierarchy; you never need to set hierarchy_id if (!($vn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD')))) { if ($va_parent_info) { // set hierarchy to that of parent $this->set($this->getProperty('HIERARCHY_ID_FLD'), $va_parent_info[$this->getProperty('HIERARCHY_ID_FLD')]); } // if there's no parent then this is a root in which case HIERARCHY_ID_FLD should be set to the primary // key of the row, which we'll know once we insert it (so we must set it after insert) } break; case __CA_HIER_TYPE_MULTI_POLY__: // TODO: implement break; default: die("Invalid hierarchy type: ".$this->getHierarchyType()); break; } if ($va_parent_info) { $va_hier_indexing = $this->_calcHierarchicalIndexing($va_parent_info); } else { $va_hier_indexing = array('left' => 1, 'right' => pow(2,32)); } $this->set($this->getProperty('HIERARCHY_LEFT_INDEX_FLD'), $va_hier_indexing['left']); $this->set($this->getProperty('HIERARCHY_RIGHT_INDEX_FLD'), $va_hier_indexing['right']); } $va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName()); foreach($this->FIELDS as $vs_field => $va_attr) { $vs_field_type = $va_attr["FIELD_TYPE"]; # field type $vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW")); if (isset($va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) && (bool)$va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) { continue; } # --- check bounds (value, length and choice lists) $pb_need_reload = false; if (!$this->verifyFieldValue($vs_field, $vs_field_value, $pb_need_reload)) { # verifyFieldValue() posts errors so we don't have to do anything here # No query will be run if there are errors so we don't have to worry about invalid # values being written into the database. By not immediately bailing on an error we # can return a list of *all* input errors to the caller; this is perfect listing all form input errors in # a form-based user interface } if ($pb_need_reload) { $vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW")); // reload value since verifyFieldValue() may force the value to a default } # --- TODO: This is MySQL dependent # --- primary key has no place in an INSERT statement if it is identity if ($vs_field == $this->primaryKey()) { if (isset($va_attr["IDENTITY"]) && $va_attr["IDENTITY"]) { if (!defined('__CA_ALLOW_SETTING_OF_PRIMARY_KEYS__') || !$vs_field_value) { continue; } } } # --- check ->one relations if (isset($va_many_to_one_relations[$vs_field]) && $va_many_to_one_relations[$vs_field]) { # Nothing to verify if key is null if (!( (isset($va_attr["IS_NULL"]) && $va_attr["IS_NULL"]) && ( ($vs_field_value == "") || ($vs_field_value === null) ) )) { if ($t_many_table = $this->_DATAMODEL->getTableInstance($va_many_to_one_relations[$vs_field]["one_table"])) { if ($this->inTransaction()) { $t_many_table->setTransaction($this->getTransaction()); } $t_many_table->load($this->get($va_many_to_one_relations[$vs_field]["many_table_field"])); } if ($t_many_table->numErrors()) { $this->postError(750,_t("%1 record with $vs_field = %2 does not exist", $t_many_table->tableName(), $this->get($vs_field)),"BaseModel->insert()"); } } } if (isset($va_attr["IS_NULL"]) && $va_attr["IS_NULL"] && ($vs_field_value == null)) { $vs_field_value_is_null = true; } else { $vs_field_value_is_null = false; } if ($vs_field_value_is_null) { if (($vs_field_type == FT_DATERANGE) || ($vs_field_type == FT_HISTORIC_DATERANGE) || ($vs_field_type == FT_TIMERANGE)) { $start_field_name = $va_attr["START"]; $end_field_name = $va_attr["END"]; $vs_fields .= "$start_field_name, $end_field_name,"; $vs_values .= "NULL, NULL,"; } else { $vs_fields .= "$vs_field,"; $vs_values .= "NULL,"; } } else { switch($vs_field_type) { # ----------------------------- case (FT_DATETIME): # date/time case (FT_HISTORIC_DATETIME): case (FT_DATE): case (FT_HISTORIC_DATE): $vs_fields .= "$vs_field,"; $v = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if ($v == '') { $this->postError(1805, _t("Date is undefined but field %1 does not support NULL values", $vs_field),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($v)) { $this->postError(1100, _t("Date is invalid for %1", $vs_field),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_values .= $v.","; # output as is break; # ----------------------------- case (FT_TIME): $vs_fields .= $vs_field.","; $v = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if ($v == "") { $this->postError(1805, _t("Time is undefined but field %1 does not support NULL values", $vs_field),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($v)) { $this->postError(1100, _t("Time is invalid for ", $vs_field),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_values .= $v.","; # output as is break; # ----------------------------- case (FT_TIMESTAMP): # insert on stamp $vs_fields .= $vs_field.","; $vs_values .= time().","; break; # ----------------------------- case (FT_DATERANGE): case (FT_HISTORIC_DATERANGE): $start_field_name = $va_attr["START"]; $end_field_name = $va_attr["END"]; if (($this->_FIELD_VALUES[$start_field_name] == "") || ($this->_FIELD_VALUES[$end_field_name] == "")) { $this->postError(1805, _t("Daterange is undefined but field does not support NULL values"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$start_field_name])) { $this->postError(1100, _t("Starting date is invalid"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$end_field_name])) { $this->postError(1100,_t("Ending date is invalid"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_fields .= "$start_field_name, $end_field_name,"; $vs_values .= $this->_FIELD_VALUES[$start_field_name].", ".$this->_FIELD_VALUES[$end_field_name].","; break; # ----------------------------- case (FT_TIMERANGE): $start_field_name = $va_attr["START"]; $end_field_name = $va_attr["END"]; if (($this->_FIELD_VALUES[$start_field_name] == "") || ($this->_FIELD_VALUES[$end_field_name] == "")) { $this->postError(1805,_t("Time range is undefined but field does not support NULL values"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$start_field_name])) { $this->postError(1100,_t("Starting time is invalid"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$end_field_name])) { $this->postError(1100,_t("Ending time is invalid"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_fields .= "$start_field_name, $end_field_name,"; $vs_values .= $this->_FIELD_VALUES[$start_field_name].", ".$this->_FIELD_VALUES[$end_field_name].","; break; # ----------------------------- case (FT_NUMBER): case (FT_BIT): if (!$vb_is_hierarchical) { if ((isset($this->RANK)) && ($vs_field == $this->RANK) && (!$this->get($this->RANK))) { $qr_fmax = $o_db->query("SELECT MAX(".$this->RANK.") m FROM ".$this->TABLE); $qr_fmax->nextRow(); $vs_field_value = $qr_fmax->get("m")+1; $this->set($vs_field, $vs_field_value); } } $vs_fields .= "$vs_field,"; $v = $vs_field_value; if (!trim($v)) { $v = 0; } if (!is_numeric($v)) { $this->postError(1100,_t("Number is invalid for %1 [%2]", $vs_field, $v),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_values .= $v.","; break; # ----------------------------- case (FT_TIMECODE): $vs_fields .= $vs_field.","; $v = $vs_field_value; if (!trim($v)) { $v = 0; } if (!is_numeric($v)) { $this->postError(1100, _t("Timecode is invalid"),"BaseModel->insert()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_values .= $v.","; break; # ----------------------------- case (FT_MEDIA): $vs_fields .= $vs_field.","; $vs_values .= "'',"; $va_media_fields[] = $vs_field; break; # ----------------------------- case (FT_FILE): $vs_fields .= $vs_field.","; $vs_values .= "'',"; $va_file_fields[] = $vs_field; break; # ----------------------------- case (FT_TEXT): case (FT_PASSWORD): $vs_fields .= $vs_field.","; $vs_value = $this->quote($this->get($vs_field)); $vs_values .= $vs_value.","; break; # ----------------------------- case (FT_VARS): $vs_fields .= $vs_field.","; $vs_values .= $this->quote(caSerializeForDatabase($this->get($vs_field), (isset($va_attr['COMPRESS']) && $va_attr['COMPRESS']) ? true : false)).","; break; # ----------------------------- default: # Should never be executed die("$vs_field not caught in insert()"); # ----------------------------- } } } if ($this->numErrors() == 0) { $vs_fields = substr($vs_fields,0,strlen($vs_fields)-1); # remove trailing comma $vs_values = substr($vs_values,0,strlen($vs_values)-1); # remove trailing comma $vs_sql = "INSERT INTO ".$this->TABLE." ($vs_fields) VALUES ($vs_values)"; if ($this->debug) echo $vs_sql; $o_db->query($vs_sql); if ($o_db->numErrors() == 0) { if ($this->getFieldInfo($this->primaryKey(), "IDENTITY")) { $this->_FIELD_VALUES[$this->primaryKey()] = $o_db->getLastInsertID(); } if ((sizeof($va_media_fields) > 0) || (sizeof($va_file_fields) > 0) || ($this->getHierarchyType() == __CA_HIER_TYPE_ADHOC_MONO__)) { $vs_sql = ""; if (sizeof($va_media_fields) > 0) { foreach($va_media_fields as $f) { if($vs_msql = $this->_processMedia($f, array('delete_old_media' => false))) { $vs_sql .= $vs_msql; } } } if (sizeof($va_file_fields) > 0) { foreach($va_file_fields as $f) { if($vs_msql = $this->_processFiles($f)) { $vs_sql .= $vs_msql; } } } if($this->getHierarchyType() == __CA_HIER_TYPE_ADHOC_MONO__) { // Ad-hoc hierarchy if (!$this->get($this->getProperty('HIERARCHY_ID_FLD'))) { $vs_sql .= $this->getProperty('HIERARCHY_ID_FLD').' = '.$this->getPrimaryKey().' '; } } if ($this->numErrors() == 0) { $vs_sql = substr($vs_sql, 0, strlen($vs_sql) - 1); if ($vs_sql) { $o_db->query("UPDATE ".$this->tableName()." SET ".$vs_sql." WHERE ".$this->primaryKey()." = ?", $this->getPrimaryKey(1)); } } else { # media and/or file error $o_db->query("DELETE FROM ".$this->tableName()." WHERE ".$this->primaryKey()." = ?", $this->getPrimaryKey(1)); $this->_FIELD_VALUES[$this->primaryKey()] = ""; if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } $this->_FILES_CLEAR = array(); $this->logChange("I"); # # update search index # $vn_id = $this->getPrimaryKey(); if ((!isset($pa_options['dont_do_search_indexing']) || (!$pa_options['dont_do_search_indexing'])) && !defined('__CA_DONT_DO_SEARCH_INDEXING__')) { $this->doSearchIndexing(); } if ($vb_we_set_transaction) { $this->removeTransaction(true); } $this->_FIELD_VALUE_CHANGED = array(); return $vn_id; } else { foreach($o_db->errors() as $o_e) { $this->postError($o_e->getErrorNumber(), $o_e->getErrorDescription().' ['.$o_e->getErrorNumber().']', "BaseModel->insert()"); } if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } else { foreach($o_db->errors() as $o_e) { switch($vn_err_num = $o_e->getErrorNumber()) { case 251: // violation of unique key (duplicate record) $va_indices = $o_db->getIndices($this->tableName()); // try to get key info if (preg_match("/for key [']{0,1}([\w]+)[']{0,1}$/", $o_e->getErrorDescription(), $va_matches)) { $va_field_labels = array(); foreach($va_indices[$va_matches[1]]['fields'] as $vs_col_name) { $va_tmp = $this->getFieldInfo($vs_col_name); $va_field_labels[] = $va_tmp['LABEL']; } $vs_last_name = array_pop($va_field_labels); if (sizeof($va_field_labels) > 0) { $vs_err_desc = _t("The combination of %1 and %2 must be unique", join(', ', $va_field_labels), $vs_last_name); } else { $vs_err_desc = _t("The value of %1 must be unique", $vs_last_name); } } else { $vs_err_desc = $o_e->getErrorDescription(); } $this->postError($vn_err_num, $vs_err_desc, "BaseModel->insert()"); break; default: $this->postError($vn_err_num, $o_e->getErrorDescription().' ['.$vn_err_num.']', "BaseModel->insert()"); break; } } if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } else { $this->postError(400, _t("Mode was %1; must be write", $this->getMode(true)),"BaseModel->insert()"); return false; } } /** * Generic method to save content properties of object to database fields * Use this, if you've contructed your BaseModel object to represent an existing record * if you've loaded an existing record. * * @param array $pa_options options array * possible options (keys): * dont_check_circular_references = when dealing with strict monohierarchical lists (also known as trees), you can use this option to disable checks for circuits in the graph * update_only_media_versions = when set to an array of valid media version names, media is only processed for the specified versions * force = if set field values are not verified prior to performing the update * @return bool success state */ public function update ($pa_options=null) { if (!is_array($pa_options)) { $pa_options = array(); } $this->field_conflicts = array(); $this->clearErrors(); $va_rebuild_hierarchical_index = null; if (!$this->getPrimaryKey()) { $this->postError(765, _t("Can't do update() on new record; use insert() instead"),"BaseModel->update()"); return false; } if ($this->getMode() == ACCESS_WRITE) { // do form timestamp check if (isset($_REQUEST['form_timestamp']) && ($vn_form_timestamp = $_REQUEST['form_timestamp'])) { $va_possible_conflicts = $this->getChangeLog(null, array('range' => array('start' => $vn_form_timestamp, 'end' => time()), 'excludeUnitID' => $this->getCurrentLoggingUnitID())); if (sizeof($va_possible_conflicts)) { $va_conflict_users = array(); $va_conflict_fields = array(); foreach($va_possible_conflicts as $va_conflict) { $vs_user_desc = trim($va_conflict['fname'].' '.$va_conflict['lname']); if ($vs_user_email = trim($va_conflict['email'])) { $vs_user_desc .= ' ('.$vs_user_email.')'; } if ($vs_user_desc) { $va_conflict_users[$vs_user_desc] = true; } if(isset($va_conflict['snapshot']) && is_array($va_conflict['snapshot'])) { foreach($va_conflict['snapshot'] as $vs_field => $vs_value) { if ($va_conflict_fields[$vs_field]) { continue; } $va_conflict_fields[$vs_field] = true; } } } $this->field_conflicts = array_keys($va_conflict_fields); switch (sizeof($va_conflict_users)) { case 0: $this->postError(795, _t('Changes have been made since you loaded this data. Save again to overwrite the changes or cancel to keep the changes.'), "BaseModel->update()"); break; case 1: $this->postError(795, _t('Changes have been made since you loaded this data by %1. Save again to overwrite the changes or cancel to keep the changes.', join(', ', array_keys($va_conflict_users))), "BaseModel->update()"); break; default: $this->postError(795, _t('Changes have been made since you loaded this data by these users: %1. Save again to overwrite the changes or cancel to keep the changes.', join(', ', array_keys($va_conflict_users))), "BaseModel->update()"); break; } } } $vb_we_set_transaction = false; if (!$this->inTransaction()) { $this->setTransaction(new Transaction($this->getDb())); $vb_we_set_transaction = true; } $o_db = $this->getDb(); if ($vb_is_hierarchical = $this->isHierarchical()) { $vs_parent_id_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD'); $vs_hier_left_fld = $this->getProperty('HIERARCHY_LEFT_INDEX_FLD'); $vs_hier_right_fld = $this->getProperty('HIERARCHY_RIGHT_INDEX_FLD'); $vs_hier_id_fld = $this->getProperty('HIERARCHY_ID_FLD'); // save original left/right index values - we need them later to recalculate // the indexing values for children of this record $vn_orig_hier_left = $this->get($vs_hier_left_fld); $vn_orig_hier_right = $this->get($vs_hier_right_fld); $vn_parent_id = $this->get($vs_parent_id_fld); if ($vb_parent_id_changed = $this->changed($vs_parent_id_fld)) { $va_parent_info = $this->_getHierarchyParent($vn_parent_id); if (!$pa_options['dont_check_circular_references']) { $va_ids = $this->getHierarchyIDs($this->getPrimaryKey()); if (in_array($this->get($vs_parent_id_fld), $va_ids)) { $this->postError(2010,_t("Cannot move %1 under its sub-record", $this->getProperty('NAME_SINGULAR')),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } //if (is_null($this->getOriginalValue($vs_parent_id_fld))) { // don't allow moves of hierarchy roots - just ignore the move and keep on going with the update // $this->set($vs_parent_id_fld, null); // $vb_parent_id_changed = false; //} else { switch($this->getHierarchyType()) { case __CA_HIER_TYPE_SIMPLE_MONO__: // you only need to set parent_id for this type of hierarchy break; case __CA_HIER_TYPE_MULTI_MONO__: // you need to set parent_id; you only need to set hierarchy_id if you're creating a root if (!($vn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD')))) { $this->set($this->getProperty('HIERARCHY_ID_FLD'), $va_parent_info[$this->getProperty('HIERARCHY_ID_FLD')]); } if (!($vn_hierarchy_id = $this->get($vs_hier_id_fld))) { $this->postError(2030, _t("Hierarchy ID must be specified for this update"), "BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } // Moving between hierarchies if ($this->get($vs_hier_id_fld) != $va_parent_info[$vs_hier_id_fld]) { $vn_hierarchy_id = $va_parent_info[$vs_hier_id_fld]; $this->set($this->getProperty('HIERARCHY_ID_FLD'), $vn_hierarchy_id); if (is_array($va_children = $this->_getHierarchyChildren(array($this->getPrimaryKey())))) { $va_rebuild_hierarchical_index = $va_children; } } break; case __CA_HIER_TYPE_ADHOC_MONO__: // you need to set parent_id for this hierarchy; you never need to set hierarchy_id if ($va_parent_info) { // set hierarchy to that of root if (sizeof($va_ancestors = $this->getHierarchyAncestors($vn_parent_id, array('idsOnly' => true, 'includeSelf' => true)))) { $vn_hierarchy_id = array_pop($va_ancestors); } else { $vn_hierarchy_id = $this->getPrimaryKey(); } $this->set($this->getProperty('HIERARCHY_ID_FLD'), $vn_hierarchy_id); if (is_array($va_children = $this->_getHierarchyChildren(array($this->getPrimaryKey())))) { $va_rebuild_hierarchical_index = $va_children; } } // if there's no parent then this is a root in which case HIERARCHY_ID_FLD should be set to the primary // key of the row, which we'll know once we insert it (so we must set it after insert) break; case __CA_HIER_TYPE_MULTI_POLY__: // TODO: implement break; default: die("Invalid hierarchy type: ".$this->getHierarchyType()); break; } if ($va_parent_info) { $va_hier_indexing = $this->_calcHierarchicalIndexing($va_parent_info); } else { $va_hier_indexing = array('left' => 1, 'right' => pow(2,32)); } $this->set($this->getProperty('HIERARCHY_LEFT_INDEX_FLD'), $va_hier_indexing['left']); $this->set($this->getProperty('HIERARCHY_RIGHT_INDEX_FLD'), $va_hier_indexing['right']); //} } } $vs_sql = "UPDATE ".$this->TABLE." SET "; $va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName()); $vn_fields_that_have_been_set = 0; foreach ($this->FIELDS as $vs_field => $va_attr) { if (isset($va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) && (bool)$va_attr['DONT_PROCESS_DURING_INSERT_UPDATE']) { continue; } if (isset($va_attr['IDENTITY']) && $va_attr['IDENTITY']) { continue; } // never update identity fields $vs_field_type = isset($va_attr["FIELD_TYPE"]) ? $va_attr["FIELD_TYPE"] : null; # field type $vn_datatype = $this->_getFieldTypeType($vs_field); # field's underlying datatype $vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW")); # --- check bounds (value, length and choice lists) $pb_need_reload = false; if (!isset($pa_options['force']) || !$pa_options['force']) { if (!$this->verifyFieldValue($vs_field, $vs_field_value, $pb_need_reload)) { # verifyFieldValue() posts errors so we don't have to do anything here # No query will be run if there are errors so we don't have to worry about invalid # values being written into the database. By not immediately bailing on an error we # can return a list of *all* input errors to the caller; this is perfect listing all form input errors in # a form-based user interface } } if ($pb_need_reload) { $vs_field_value = $this->get($vs_field, array("TIMECODE_FORMAT" => "RAW")); // } if (!isset($va_attr["IS_NULL"])) { $va_attr["IS_NULL"] = 0; } if ($va_attr["IS_NULL"] && ($vs_field_value=="")) { $vs_field_value_is_null = 1; } else { $vs_field_value_is_null = 0; } # --- check ->one relations if (isset($va_many_to_one_relations[$vs_field]) && $va_many_to_one_relations[$vs_field]) { # Nothing to verify if key is null if (!(($va_attr["IS_NULL"]) && ($vs_field_value == ""))) { if ($t_many_table = $this->_DATAMODEL->getTableInstance($va_many_to_one_relations[$vs_field]["one_table"])) { if ($this->inTransaction()) { $t_many_table->setTransaction($this->getTransaction()); } $t_many_table->load($this->get($va_many_to_one_relations[$vs_field]["many_table_field"])); } if ($t_many_table->numErrors()) { $this->postError(750,_t("%1 record with $vs_field = %2 does not exist", $t_many_table->tableName(), $this->get($vs_field)),"BaseModel->update()"); } } } if (($vs_field_value_is_null) && (!(isset($va_attr["UPDATE_ON_UPDATE"]) && $va_attr["UPDATE_ON_UPDATE"]))) { if (($vs_field_type == FT_DATERANGE) || ($vs_field_type == FT_HISTORIC_DATERANGE) || ($vs_field_type == FT_TIMERANGE)) { $start_field_name = $va_attr["START"]; $end_field_name = $va_attr["END"]; $vs_sql .= "$start_field_name = NULL, $end_field_name = NULL,"; } else { $vs_sql .= "$vs_field = NULL,"; } $vn_fields_that_have_been_set++; } else { if (($vs_field_type != FT_TIMESTAMP) && !$this->changed($vs_field)) { continue; } // don't try to update fields that haven't changed -- saves time, especially for large fields like FT_VARS and FT_TEXT when text is long switch($vs_field_type) { # ----------------------------- case (FT_NUMBER): case (FT_BIT): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if (!trim($vm_val)) { $vm_val = 0; } if (!is_numeric($vm_val)) { $this->postError(1100,_t("Number is invalid for %1", $vs_field),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vs_field} = {$vm_val},"; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_TEXT): case (FT_PASSWORD): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; $vs_sql .= "{$vs_field} = ".$this->quote($vm_val).","; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_VARS): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; $vs_sql .= "{$vs_field} = ".$this->quote(caSerializeForDatabase($vm_val, ((isset($va_attr['COMPRESS']) && $va_attr['COMPRESS']) ? true : false))).","; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_DATETIME): case (FT_HISTORIC_DATETIME): case (FT_DATE): case (FT_HISTORIC_DATE): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if ($vm_val == "") { $this->postError(1805,_t("Date is undefined but field does not support NULL values"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($vm_val)) { $this->postError(1100,_t("Date is invalid for %1", $vs_field),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vs_field} = {$vm_val},"; # output as is $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_TIME): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if ($vm_val == "") { $this->postError(1805, _t("Time is undefined but field does not support NULL values"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($vm_val)) { $this->postError(1100, _t("Time is invalid for %1", $vs_field),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vs_field} = {$vm_val},"; # output as is $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_TIMESTAMP): if (isset($va_attr["UPDATE_ON_UPDATE"]) && $va_attr["UPDATE_ON_UPDATE"]) { $vs_sql .= "{$vs_field} = ".time().","; $vn_fields_that_have_been_set++; } break; # ----------------------------- case (FT_DATERANGE): case (FT_HISTORIC_DATERANGE): $vn_start_field_name = $va_attr["START"]; $vn_end_field_name = $va_attr["END"]; if (($this->_FIELD_VALUES[$vn_start_field_name] == "") || ($this->_FIELD_VALUES[$vn_end_field_name] == "")) { $this->postError(1805,_t("Daterange is undefined but field does not support NULL values"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$vn_start_field_name])) { $this->postError(1100,_t("Starting date is invalid"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$vn_end_field_name])) { $this->postError(1100,_t("Ending date is invalid"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vn_start_field_name} = ".$this->_FIELD_VALUES[$vn_start_field_name].", {$vn_end_field_name} = ".$this->_FIELD_VALUES[$vn_end_field_name].","; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_TIMERANGE): $vn_start_field_name = $va_attr["START"]; $vn_end_field_name = $va_attr["END"]; if (($this->_FIELD_VALUES[$vn_start_field_name] == "") || ($this->_FIELD_VALUES[$vn_end_field_name] == "")) { $this->postError(1805,_t("Time range is undefined but field does not support NULL values"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$vn_start_field_name])) { $this->postError(1100,_t("Starting time is invalid"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if (!is_numeric($this->_FIELD_VALUES[$vn_end_field_name])) { $this->postError(1100,_t("Ending time is invalid"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vn_start_field_name} = ".$this->_FIELD_VALUES[$vn_start_field_name].", {$vn_end_field_name} = ".$this->_FIELD_VALUES[$vn_end_field_name].","; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_TIMECODE): $vm_val = isset($this->_FIELD_VALUES[$vs_field]) ? $this->_FIELD_VALUES[$vs_field] : null; if (!trim($vm_val)) { $vm_val = 0; } if (!is_numeric($vm_val)) { $this->postError(1100,_t("Timecode is invalid"),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } $vs_sql .= "{$vs_field} = {$vm_val},"; $vn_fields_that_have_been_set++; break; # ----------------------------- case (FT_MEDIA): $va_limit_to_versions = (isset($pa_options['update_only_media_versions']) ? $pa_options['update_only_media_versions'] : null); if ($vs_media_sql = $this->_processMedia($vs_field, array('these_versions_only' => $va_limit_to_versions))) { $vs_sql .= $vs_media_sql; $vn_fields_that_have_been_set++; } else { if ($this->numErrors() > 0) { if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } break; # ----------------------------- case (FT_FILE): if ($vs_file_sql = $this->_processFiles($vs_field)) { $vs_sql .= $vs_file_sql; $vn_fields_that_have_been_set++; } else { if ($this->numErrors() > 0) { if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } break; # ----------------------------- } } } if ($this->numErrors() == 0) { if ($vn_fields_that_have_been_set > 0) { $vs_sql = substr($vs_sql,0,strlen($vs_sql)-1); # remove trailing comma $vs_sql .= " WHERE ".$this->PRIMARY_KEY." = ".$this->getPrimaryKey(1); if ($this->debug) echo $vs_sql; $o_db->query($vs_sql); if ($o_db->numErrors()) { foreach($o_db->errors() as $o_e) { switch($vn_err_num = $o_e->getErrorNumber()) { case 251: // violation of unique key (duplicate record) // try to get key info $va_indices = $o_db->getIndices($this->tableName()); if (preg_match("/for key [']{0,1}([\w]+)[']{0,1}$/", $o_e->getErrorDescription(), $va_matches)) { $va_field_labels = array(); foreach($va_indices[$va_matches[1]]['fields'] as $vs_col_name) { $va_tmp = $this->getFieldInfo($vs_col_name); $va_field_labels[] = $va_tmp['LABEL']; } $vs_last_name = array_pop($va_field_labels); if (sizeof($va_field_labels) > 0) { $vs_err_desc = "The combination of ".join(', ', $va_field_labels).' and '.$vs_last_name." must be unique"; } else { $vs_err_desc = "The value of {$vs_last_name} must be unique"; } } else { $vs_err_desc = $o_e->getErrorDescription(); } $this->postError($vn_err_num, $vs_err_desc, "BaseModel->insert()"); break; default: $this->postError($vn_err_num, $o_e->getErrorDescription().' ['.$vn_err_num.']', "BaseModel->update()"); break; } } if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } else { if (($vb_is_hierarchical) && ($vb_parent_id_changed)) { // recalulate left/right indexing of sub-records $vn_interval_start = $this->get($vs_hier_left_fld); $vn_interval_end = $this->get($vs_hier_right_fld); if (($vn_interval_start > 0) && ($vn_interval_end > 0)) { if ($vs_hier_id_fld) { $vs_hier_sql = ' AND ('.$vs_hier_id_fld.' = '.$this->get($vs_hier_id_fld).')'; } else { $vs_hier_sql = ""; } $vn_ratio = ($vn_interval_end - $vn_interval_start)/($vn_orig_hier_right - $vn_orig_hier_left); $vs_sql = " UPDATE ".$this->tableName()." SET $vs_hier_left_fld = ($vn_interval_start + (($vs_hier_left_fld - $vn_orig_hier_left) * $vn_ratio)), $vs_hier_right_fld = ($vn_interval_end + (($vs_hier_right_fld - $vn_orig_hier_right) * $vn_ratio)) WHERE (".$vs_hier_left_fld." BETWEEN ".$vn_orig_hier_left." AND ".$vn_orig_hier_right.") $vs_hier_sql "; //print "<hr>$vs_sql<hr>"; $o_db->query($vs_sql); if ($vn_err = $o_db->numErrors()) { $this->postError(2030, _t("Could not update sub records in hierarchy: [%1] %2", $vs_sql, join(';', $o_db->getErrors())),"BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } else { $this->postError(2045, _t("Parent record had invalid hierarchical indexing (should not happen!)"), "BaseModel->update()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } } if ((!isset($pa_options['dont_do_search_indexing']) || (!$pa_options['dont_do_search_indexing'])) && !defined('__CA_DONT_DO_SEARCH_INDEXING__')) { # update search index $this->doSearchIndexing(); } if (is_array($va_rebuild_hierarchical_index)) { //$this->rebuildHierarchicalIndex($this->get($vs_hier_id_fld)); $t_instance = $this->_DATAMODEL->getInstanceByTableName($this->tableName()); foreach($va_rebuild_hierarchical_index as $vn_child_id) { if ($t_instance->load($vn_child_id)) { $t_instance->setMode(ACCESS_WRITE); $t_instance->set($this->getProperty('HIERARCHY_ID_FLD'), $vn_hierarchy_id); $t_instance->update(); if ($t_instance->numErrors()) { $this->errors = array_merge($this->errors, $t_instance->errors); } } } } $this->logChange("U"); $this->_FILES_CLEAR = array(); } if ($vb_we_set_transaction) { $this->removeTransaction(true); } $this->_FIELD_VALUE_CHANGED = array(); return true; } else { if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } else { $this->postError(400, _t("Mode was %1; must be write or admin", $this->getMode(true)),"BaseModel->update()"); return false; } } public function doSearchIndexing($pa_changed_field_values_array=null, $pb_reindex_mode=false, $ps_engine=null) { if (defined("__CA_DONT_DO_SEARCH_INDEXING__")) { return; } if (is_null($pa_changed_field_values_array)) { $pa_changed_field_values_array = $this->getChangedFieldValuesArray(); } if (!BaseModel::$search_indexer) { BaseModel::$search_indexer = new SearchIndexer($this->getDb(), $ps_engine); } BaseModel::$search_indexer->indexRow($this->tableNum(), $this->getPrimaryKey(), $this->getFieldValuesArray(), $pb_reindex_mode, null, $pa_changed_field_values_array, $this->_FIELD_VALUES_OLD); } /** * Delete record represented by this object. Uses the Datamodel object * to generate possible dependencies and relationships. * * @param bool $pb_delete_related delete stuff related to the record? pass non-zero value if you want to. * @param array $pa_options Options for delete process. Options are: * hard = if true records which can support "soft" delete are really deleted rather than simply being marked as deleted * @param array $pa_fields instead of deleting the record represented by this object instance you can * pass an array of field => value assignments which is used in a SQL-DELETE-WHERE clause. * @param array $pa_table_list this is your possibility to pass an array of table name => true assignments * to specify which tables to omit when deleting related stuff */ public function delete ($pb_delete_related=false, $pa_options=null, $pa_fields=null, $pa_table_list=null) { if ($this->hasField('deleted') && (!isset($pa_options['hard']) || !$pa_options['hard'])) { $this->setMode(ACCESS_WRITE); $this->set('deleted', 1); return $this->update(array('force' => true)); } $this->clearErrors(); if ((!$this->getPrimaryKey()) && (!is_array($pa_fields))) { # is there a record loaded? $this->postError(770, _t("No record loaded"),"BaseModel->delete()"); return false; } if (!is_array($pa_table_list)) { $pa_table_list = array(); } $pa_table_list[$this->tableName()] = true; if ($this->getMode() == ACCESS_WRITE) { $vb_we_set_transaction = false; if (!$this->inTransaction()) { $o_t = new Transaction($this->getDb()); $this->setTransaction($o_t); $vb_we_set_transaction = true; } $o_db = $this->getDb(); if (is_array($pa_fields)) { $vs_sql = "DELETE FROM ".$this->tableName()." WHERE "; $vs_wheres = ""; while(list($vs_field, $vm_val) = each($pa_fields)) { $vn_datatype = $this->_getFieldTypeType($vs_field); switch($vn_datatype) { # ----------------------------- case (0): # number if ($vm_val == "") { $vm_val = 0; } break; # ----------------------------- case (1): # string $vm_val = $this->quote($vm_val); break; # ----------------------------- } if ($vs_wheres) { $vs_wheres .= " AND "; } $vs_wheres .= "($vs_field = $vm_val)"; } $vs_sql .= $vs_wheres; } else { $vs_sql = "DELETE FROM ".$this->tableName()." WHERE ".$this->primaryKey()." = ".$this->getPrimaryKey(1); } if ($this->isHierarchical()) { // TODO: implement delete of children records $vs_parent_id_fld = $this->getProperty('HIERARCHY_PARENT_ID_FLD'); $qr_res = $o_db->query(" SELECT ".$this->primaryKey()." FROM ".$this->tableName()." WHERE {$vs_parent_id_fld} = ? ", $this->getPrimaryKey()); if ($qr_res->nextRow()) { $this->postError(780, _t("Can't delete item because it has sub-records"),"BaseModel->delete()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } # # --- delete search index entries # $vn_id = $this->getPrimaryKey(); // TODO: FIX THIS ISSUE! // NOTE: we delete the indexing here, before we actually do the // SQL delete because the search indexer relies upon the relevant // relationships to be intact (ie. exist) in order to properly remove the indexing for them. // // In particular, the incremental indexing used by the MySQL Fulltext plugin fails to properly // update if it can't traverse the relationships it is to remove. // // By removing the search indexing here we run the risk of corrupting the search index if the SQL // delete subsequently fails. Specifically, the indexing for rows that still exist in the database // will be removed. Wrapping everything in a MySQL transaction deals with it for MySQL Fulltext, but // other non-SQL engines (Lucene, SOLR, etc.) are still affected. // // At some point we need to come up with something clever to handle this. Most likely it means moving all of the actual // analysis to startRowUnindexing() and only executing commands in commitRowUnIndexing(). For now we blithely assume that // SQL deletes always succeed. If they don't we can always reindex. Only the indexing is affected, not the underlying data. if(!defined('__CA_DONT_DO_SEARCH_INDEXING__')) { if (!BaseModel::$search_indexer) { BaseModel::$search_indexer = new SearchIndexer($this->getDb()); } BaseModel::$search_indexer->startRowUnIndexing($this->tableNum(), $vn_id); BaseModel::$search_indexer->commitRowUnIndexing($this->tableNum(), $vn_id); } # --- Check ->many and many<->many relations $va_one_to_many_relations = $this->_DATAMODEL->getOneToManyRelations($this->tableName()); # # Note: cascading delete code is very slow when used # on a record with a large number of related records as # each record in check individually for cascading deletes... # it is possible to make this *much* faster by crafting clever-er queries # if (is_array($va_one_to_many_relations)) { foreach($va_one_to_many_relations as $vs_many_table => $va_info) { foreach($va_info as $va_relationship) { if (isset($pa_table_list[$vs_many_table.'/'.$va_relationship["many_table_field"]]) && $pa_table_list[$vs_many_table.'/'.$va_relationship["many_table_field"]]) { continue; } # do any records exist? $t_related = $this->_DATAMODEL->getTableInstance($vs_many_table); $t_related->setTransaction($this->getTransaction()); $qr_record_check = $o_db->query(" SELECT ".$t_related->primaryKey()." FROM ".$vs_many_table." WHERE (".$va_relationship["many_table_field"]." = ".$this->getPrimaryKey(1).") "); $pa_table_list[$vs_many_table.'/'.$va_relationship["many_table_field"]] = true; //print "FOR ".$vs_many_table.'/'.$va_relationship["many_table_field"].":".$qr_record_check->numRows()."<br>\n"; if ($qr_record_check->numRows() > 0) { if ($pb_delete_related) { while($qr_record_check->nextRow()) { if ($t_related->load($qr_record_check->get($t_related->primaryKey()))) { $t_related->setMode(ACCESS_WRITE); $t_related->delete($pb_delete_related, $pa_options, null, $pa_table_list); if ($t_related->numErrors()) { $this->postError(790, _t("Can't delete item because items related to it have sub-records (%1)", $vs_many_table),"BaseModel->delete()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } } } else { $this->postError(780, _t("Can't delete item because it is in use (%1)", $vs_many_table),"BaseModel->delete()"); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } } } } } # --- do deletion if ($this->debug) echo $vs_sql; $o_db->query($vs_sql); if ($o_db->numErrors() > 0) { $this->errors = $o_db->errors(); if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } # cancel and pending queued tasks against this record $tq = new TaskQueue(); $tq->cancelPendingTasksForRow(join("/", array($this->tableName(), $vn_id))); $this->_FILES_CLEAR = array(); # --- delete media and file field files foreach($this->FIELDS as $f => $attr) { switch($attr['FIELD_TYPE']) { case FT_MEDIA: $versions = $this->getMediaVersions($f); foreach ($versions as $v) { $this->_removeMedia($f, $v); } break; case FT_FILE: @unlink($this->getFilePath($f)); #--- delete conversions # foreach ($this->getFileConversions($f) as $vs_format => $va_file_conversion) { @unlink($this->getFileConversionPath($f, $vs_format)); } break; } } if ($o_db->numErrors() == 0) { //if ($vb_is_hierarchical = $this->isHierarchical()) { //} # clear object $this->logChange("D"); $this->clear(); } else { if ($vb_we_set_transaction) { $this->removeTransaction(false); } return false; } if ($vb_we_set_transaction) { $this->removeTransaction(true); } return true; } else { $this->postError(400, _t("Mode was %1; must be write", $this->getMode(true)),"BaseModel->delete()"); return false; } } # -------------------------------------------------------------------------------- # --- Uploaded media handling # -------------------------------------------------------------------------------- /** * Check if media content is mirrored (depending on settings in configuration file) * * @return bool */ public function mediaIsMirrored($field, $version) { $media_info = $this->get($field); if (!is_array($media_info)) { return ""; } $vi = $this->_MEDIA_VOLUMES->getVolumeInformation($media_info[$version]["VOLUME"]); if (!is_array($vi)) { return ""; } if (is_array($vi["mirrors"])) { return true; } else { return false; } } /** * Get status of media mirror * * @param string $field field name * @param string $version version of the media file, as defined in media_processing.conf * @param string media mirror name, as defined in media_volumes.conf * @return mixed media mirror status */ public function getMediaMirrorStatus($field, $version, $mirror="") { $media_info = $this->get($field); if (!is_array($media_info)) { return ""; } $vi = $this->_MEDIA_VOLUMES->getVolumeInformation($media_info[$version]["VOLUME"]); if (!is_array($vi)) { return ""; } if ($mirror) { return $media_info["MIRROR_STATUS"][$mirror]; } else { return $media_info["MIRROR_STATUS"][$vi["accessUsingMirror"]]; } } /** * Retry mirroring of given media field. Sets global error properties on failure. * * @param string $ps_field field name * @param string $ps_version version of the media file, as defined in media_processing.conf * @return null */ public function retryMediaMirror($ps_field, $ps_version) { global $AUTH_CURRENT_USER_ID; $va_media_info = $this->get($ps_field); if (!is_array($va_media_info)) { return ""; } $va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($va_media_info[$ps_version]["VOLUME"]); if (!is_array($va_volume_info)) { return ""; } $o_tq = new TaskQueue(); $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey())); $vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $ps_version)); foreach($va_media_info["MIRROR_STATUS"] as $vs_mirror_code => $vs_status) { $va_mirror_info = $va_volume_info["mirrors"][$vs_mirror_code]; $vs_mirror_method = $va_mirror_info["method"]; $vs_queue = $vs_mirror_method."mirror"; switch($vs_status) { case 'FAIL': case 'PARTIAL': if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) { //$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->retryMediaMirror()"); //return false; } if ($o_tq->addTask( $vs_queue, array( "MIRROR" => $vs_mirror_code, "VOLUME" => $va_media_info[$ps_version]["VOLUME"], "FIELD" => $ps_field, "TABLE" => $this->tableName(), "VERSION" => $ps_version, "FILES" => array( array( "FILE_PATH" => $this->getMediaPath($ps_field, $ps_version), "ABS_PATH" => $va_volume_info["absolutePath"], "HASH" => $this->_FIELD_VALUES[$ps_field][$ps_version]["HASH"], "FILENAME" => $this->_FIELD_VALUES[$ps_field][$ps_version]["FILENAME"] ) ), "MIRROR_INFO" => $va_mirror_info, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey() ), array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) { $va_media_info["MIRROR_STATUS"][$vs_mirror_code] = ""; // pending $this->setMediaInfo($ps_field, $va_media_info); $this->setMode(ACCESS_WRITE); $this->update(); continue; } else { $this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $ps_version, $queue),"BaseModel->retryMediaMirror()"); } break; } } } /** * Returns url of media file * * @param string $ps_field field name * @param string $ps_version version of the media file, as defined in media_processing.conf * @param int $pn_page page number, defaults to 1 * @return string the url */ public function getMediaUrl($ps_field, $ps_version, $pn_page=1) { $va_media_info = $this->getMediaInfo($ps_field); if (!is_array($va_media_info)) { return ""; } # # Is this version externally hosted? # if (isset($va_media_info[$ps_version]["EXTERNAL_URL"]) && ($va_media_info[$ps_version]["EXTERNAL_URL"])) { return $va_media_info[$ps_version]["EXTERNAL_URL"]; } # # Is this version queued for processing? # if (isset($va_media_info[$ps_version]["QUEUED"]) && ($va_media_info[$ps_version]["QUEUED"])) { if ($va_media_info[$ps_version]["QUEUED_ICON"]["src"]) { return $va_media_info[$ps_version]["QUEUED_ICON"]["src"]; } else { return ""; } } $va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($va_media_info[$ps_version]["VOLUME"]); if (!is_array($va_volume_info)) { return ""; } # is this mirrored? if ( (isset($va_volume_info["accessUsingMirror"]) && $va_volume_info["accessUsingMirror"]) && ( isset($va_media_info["MIRROR_STATUS"][$va_volume_info["accessUsingMirror"]]) && ($va_media_info["MIRROR_STATUS"][$va_volume_info["accessUsingMirror"]] == "SUCCESS") ) ) { $vs_protocol = $va_volume_info["mirrors"][$va_volume_info["accessUsingMirror"]]["accessProtocol"]; $vs_host = $va_volume_info["mirrors"][$va_volume_info["accessUsingMirror"]]["accessHostname"]; $vs_url_path = $va_volume_info["mirrors"][$va_volume_info["accessUsingMirror"]]["accessUrlPath"]; } else { $vs_protocol = $va_volume_info["protocol"]; $vs_host = $va_volume_info["hostname"]; $vs_url_path = $va_volume_info["urlPath"]; } if ($va_media_info[$ps_version]["FILENAME"]) { $vs_fpath = join("/",array($vs_url_path, $va_media_info[$ps_version]["HASH"], $va_media_info[$ps_version]["MAGIC"]."_".$va_media_info[$ps_version]["FILENAME"])); return $vs_protocol."://$vs_host".$vs_fpath; } else { return ""; } } /** * Returns path of media file * * @param string $ps_field field name * @param string $ps_version version of the media file, as defined in media_processing.conf * @param int $pn_page page number, defaults to 1 * @return string path of the media file */ public function getMediaPath($ps_field, $ps_version, $pn_page=1) { $va_media_info = $this->getMediaInfo($ps_field); if (!is_array($va_media_info)) { return ""; } # # Is this version externally hosted? # if (isset($va_media_info[$ps_version]["EXTERNAL_URL"]) && ($va_media_info[$ps_version]["EXTERNAL_URL"])) { return ''; // no local path for externally hosted media } # # Is this version queued for processing? # if (isset($va_media_info[$ps_version]["QUEUED"]) && $va_media_info[$ps_version]["QUEUED"]) { if ($va_media_info[$ps_version]["QUEUED_ICON"]["filepath"]) { return $va_media_info[$ps_version]["QUEUED_ICON"]["filepath"]; } else { return ""; } } $va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($va_media_info[$ps_version]["VOLUME"]); if (!is_array($va_volume_info)) { return ""; } if ($va_media_info[$ps_version]["FILENAME"]) { return join("/",array($va_volume_info["absolutePath"], $va_media_info[$ps_version]["HASH"], $va_media_info[$ps_version]["MAGIC"]."_".$va_media_info[$ps_version]["FILENAME"])); } else { return ""; } } /** * Returns appropriate representation of that media version in an html tag, including attributes for display * * @param string $field field name * @param string $version version of the media file, as defined in media_processing.conf * @param string $name name attribute of the img tag * @param string $vspace vspace attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict * @param string $hspace hspace attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict * @param string $alt alt attribute of the img tag * @param int $border border attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict * @param string $usemap usemap attribute of the img tag * @param int $align align attribute of the img tag - note: deprecated in HTML 4.01, not supported in XHTML 1.0 Strict * @return string html tag */ public function getMediaTag($field, $version, $pa_options=null) { $media_info = $this->getMediaInfo($field); if (!is_array($media_info[$version])) { return ""; } # # Is this version queued for processing? # if (isset($media_info[$version]["QUEUED"]) && ($media_info[$version]["QUEUED"])) { if ($media_info[$version]["QUEUED_ICON"]["src"]) { return "<img src='".$media_info[$version]["QUEUED_ICON"]["src"]."' width='".$media_info[$version]["QUEUED_ICON"]["width"]."' height='".$media_info[$version]["QUEUED_ICON"]["height"]."' alt='".$media_info[$version]["QUEUED_ICON"]["alt"]."'>"; } else { return $media_info[$version]["QUEUED_MESSAGE"]; } } $url = $this->getMediaUrl($field, $version, isset($options["page"]) ? $options["page"] : null); $m = new Media(); $o_vol = new MediaVolumes(); $va_volume = $o_vol->getVolumeInformation($media_info[$version]['VOLUME']); return $m->htmlTag($media_info[$version]["MIMETYPE"], $url, $media_info[$version]["PROPERTIES"], $pa_options, $va_volume); } /** * Get media information for the given field * * @param string $field field name * @param string $version version of the media file, as defined in media_processing.conf, can be omitted to retrieve information about all versions * @param string $property this is your opportunity to restrict the result to a certain property for the given (field,version) pair. * possible values are: * -VOLUME * -MIMETYPE * -WIDTH * -HEIGHT * -PROPERTIES: returns an array with some media metadata like width, height, mimetype, etc. * -FILENAME * -HASH * -MAGIC * -EXTENSION * -MD5 * @return mixed media information */ public function &getMediaInfo($field, $version="", $property="") { $media_info = $this->get($field, array('USE_MEDIA_FIELD_VALUES' => true)); if (!is_array($media_info)) { return ""; } if ($version) { if (!$property) { return $media_info[$version]; } else { return $media_info[$version][$property]; } } else { return $media_info; } } /** * Fetches media input type for the given field, e.g. "image" * * @param $ps_field field name * @return string media input type */ public function getMediaInputType($ps_field) { if ($va_media_info = $this->getMediaInfo($ps_field)) { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); return $o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"]); } else { return null; } } /** * Fetches media input type for the given field, e.g. "image" and version * * @param string $ps_field field name * @param string $ps_version version * @return string media input type */ public function getMediaInputTypeForVersion($ps_field, $ps_version) { if ($va_media_info = $this->getMediaInfo($ps_field)) { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); if($vs_media_type = $o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"])) { $va_media_type_info = $o_media_proc_settings->getMediaTypeInfo($vs_media_type); if (isset($va_media_type_info['VERSIONS'][$ps_version])) { if ($va_rule = $o_media_proc_settings->getMediaTransformationRule($va_media_type_info['VERSIONS'][$ps_version]['RULE'])) { return $o_media_proc_settings->canAccept($va_rule['SET']['format']); } } } } return null; } /** * Returns default version to display for the given field based upon the currently loaded row * * @param string $ps_field field name */ public function getDefaultMediaVersion($ps_field) { if ($va_media_info = $this->getMediaInfo($ps_field)) { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); $va_type_info = $o_media_proc_settings->getMediaTypeInfo($o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"])); return ($va_type_info['MEDIA_VIEW_DEFAULT_VERSION']) ? $va_type_info['MEDIA_VIEW_DEFAULT_VERSION'] : array_shift($this->getMediaVersions($ps_field)); } else { return null; } } /** * Returns default version to display as a preview for the given field based upon the currently loaded row * * @param string $ps_field field name */ public function getDefaultMediaPreviewVersion($ps_field) { if ($va_media_info = $this->getMediaInfo($ps_field)) { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); $va_type_info = $o_media_proc_settings->getMediaTypeInfo($o_media_proc_settings->canAccept($va_media_info["INPUT"]["MIMETYPE"])); return ($va_type_info['MEDIA_PREVIEW_DEFAULT_VERSION']) ? $va_type_info['MEDIA_PREVIEW_DEFAULT_VERSION'] : array_shift($this->getMediaVersions($ps_field)); } else { return null; } } /** * Fetches available media versions for the given field (and optional mimetype), as defined in media_processing.conf * * @param string $ps_field field name * @param string $ps_mimetype optional mimetype restriction * @return array list of available media versions */ public function getMediaVersions($ps_field, $ps_mimetype="") { if (!$ps_mimetype) { # figure out mimetype from field content $va_media_desc = $this->get($ps_field); if (is_array($va_media_desc)) { unset($va_media_desc["ORIGINAL_FILENAME"]); unset($va_media_desc["INPUT"]); unset($va_media_desc["VOLUME"]); return array_keys($va_media_desc); } } else { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); if ($vs_media_type = $o_media_proc_settings->canAccept($ps_mimetype)) { $va_version_list = $o_media_proc_settings->getMediaTypeVersions($vs_media_type); if (is_array($va_version_list)) { return array_keys($va_version_list); } } } return array(); } /** * Checks if a media version for the given field exists. * * @param string $ps_field field name * @param string $ps_version string representation of the version you are asking for * @return bool */ public function hasMediaVersion($ps_field, $ps_version) { return in_array($ps_version, $this->getMediaVersions($ps_field)); } /** * Fetches processing settings information for the given field with respect to the given mimetype * * @param string $ps_field field name * @param string $ps_mimetype mimetype * @return array containing the information defined in media_processing.conf */ public function &getMediaTypeInfo($ps_field, $ps_mimetype="") { $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); if (!$ps_mimetype) { # figure out mimetype from field content $va_media_desc = $this->get($ps_field); if ($vs_media_type = $o_media_proc_settings->canAccept($media_desc["INPUT"]["MIMETYPE"])) { return $o_media_proc_settings->getMediaTypeInfo($vs_media_type); } } else { if ($vs_media_type = $o_media_proc_settings->canAccept($ps_mimetype)) { return $o_media_proc_settings->getMediaTypeInfo($vs_media_type); } } return null; } /** * Sets media information * * @param $field field name * @param array $info * @return bool success state */ public function setMediaInfo($field, $info) { if(($this->getFieldInfo($field,"FIELD_TYPE")) == FT_MEDIA) { $this->_FIELD_VALUES[$field] = $info; $this->_FIELD_VALUE_CHANGED[$field] = 1; return true; } return false; } /** * Clear media * * @param string $field field name * @return bool always true */ public function clearMedia($field) { $this->_FILES_CLEAR[$field] = 1; $this->_FIELD_VALUE_CHANGED[$field] = 1; return true; } /** * Generate name for media file representation. * Makes the application die if you try to call this on a BaseModel object not representing an actual db row. * * @access private * @param string $field * @return string the media name */ public function _genMediaName($field) { $pk = $this->getPrimaryKey(); if ($pk) { return $this->TABLE."_".$field."_".$pk; } else { die("NO PK TO MAKE media name for $field!"); } } /** * Removes media * * @access private * @param string $ps_field field name * @param string $ps_version string representation of the version (e.g. original) * @param string $ps_dont_delete_path * @param string $ps_dont_delete extension * @return null */ public function _removeMedia($ps_field, $ps_version, $ps_dont_delete_path="", $ps_dont_delete_extension="") { global $AUTH_CURRENT_USER_ID; $va_media_info = $this->getMediaInfo($ps_field,$ps_version); if (!$va_media_info) { return true; } $vs_volume = $va_media_info["VOLUME"]; $va_volume_info = $this->_MEDIA_VOLUMES->getVolumeInformation($vs_volume); # # Get list of media files to delete # $va_files_to_delete = array(); $vs_delete_path = $va_volume_info["absolutePath"]."/".$va_media_info["HASH"]."/".$va_media_info["MAGIC"]."_".$va_media_info["FILENAME"]; if (($va_media_info["FILENAME"]) && ($vs_delete_path != $ps_dont_delete_path.".".$ps_dont_delete_extension)) { $va_files_to_delete[] = $va_media_info["MAGIC"]."_".$va_media_info["FILENAME"]; @unlink($vs_delete_path); } # if media is mirrored, delete file off of mirrored server if (is_array($va_volume_info["mirrors"]) && sizeof($va_volume_info["mirrors"]) > 0) { $o_tq = new TaskQueue(); $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey())); $vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $ps_version)); if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) { $this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_removeMedia()"); return false; } foreach ($va_volume_info["mirrors"] as $vs_mirror_code => $va_mirror_info) { $vs_mirror_method = $va_mirror_info["method"]; $vs_queue = $vs_mirror_method."mirror"; if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) { $this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_removeMedia()"); return false; } $va_tq_filelist = array(); foreach($va_files_to_delete as $vs_filename) { $va_tq_filelist[] = array( "HASH" => $va_media_info["HASH"], "FILENAME" => $vs_filename ); } if ($o_tq->addTask( $vs_queue, array( "MIRROR" => $vs_mirror_code, "VOLUME" => $vs_volume, "FIELD" => $f, "TABLE" => $this->tableName(), "DELETE" => 1, "VERSION" => $ps_version, "FILES" => $va_tq_filelist, "MIRROR_INFO" => $va_mirror_info, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey() ), array("priority" => 50, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) { continue; } else { $this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $queue),"BaseModel->_removeMedia()"); } } } } /** * perform media processing for the given field if sth. has been uploaded * * @access private * @param string $ps_field field name * @param array options * * Supported options: * delete_old_media = set to zero to prevent that old media files are deleted; defaults to 1 * these_versions_only = if set to an array of valid version names, then only the specified versions are updated with the currently updated file; ignored if no media already exists */ public function _processMedia($ps_field, $pa_options=null) { global $AUTH_CURRENT_USER_ID; if(!is_array($pa_options)) { $pa_options = array(); } if(!isset($pa_options['delete_old_media'])) { $pa_options['delete_old_media'] = true; } if(!isset($pa_options['these_versions_only'])) { $pa_options['these_versions_only'] = null; } $vs_sql = ""; $vn_max_execution_time = ini_get('max_execution_time'); set_time_limit(7200); $o_tq = new TaskQueue(); $o_media_proc_settings = new MediaProcessingSettings($this, $ps_field); # only set file if something was uploaded # (ie. don't nuke an existing file because none # was uploaded) $va_field_info = $this->getFieldInfo($ps_field); if ((isset($this->_FILES_CLEAR[$ps_field])) && ($this->_FILES_CLEAR[$ps_field])) { // // Clear files // $va_versions = $this->getMediaVersions($ps_field); #--- delete files foreach ($va_versions as $v) { $this->_removeMedia($ps_field, $v); } $this->_FILES[$ps_field] = null; $this->_FIELD_VALUES[$ps_field] = null; $vs_sql = "{$ps_field} = ".$this->quote(caSerializeForDatabase($this->_FILES[$ps_field], true)).","; } else { // // Process incoming files // $m = new Media(); // is it a URL? $vs_url_fetched_from = null; $vn_url_fetched_on = null; $vb_allow_fetching_of_urls = (bool)$this->_CONFIG->get('allow_fetching_of_media_from_remote_urls'); $vb_is_fetched_file = false; if ($vb_allow_fetching_of_urls && (bool)ini_get('allow_url_fopen') && isURL($this->_SET_FILES[$ps_field]['tmp_name'])) { $vs_tmp_file = tempnam(__CA_APP_DIR__.'/tmp', 'caUrlCopy'); $r_incoming_fp = @fopen($this->_SET_FILES[$ps_field]['tmp_name'], 'r'); if (!$r_incoming_fp) { $this->postError(1600, _t('Cannot open remote URL [%1] to fetch media', $this->_SET_FILES[$ps_field]['tmp_name']),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); return false; } $r_outgoing_fp = fopen($vs_tmp_file, 'w'); if (!$r_outgoing_fp) { $this->postError(1600, _t('Cannot open file for media fetched from URL [%1]', $this->_SET_FILES[$ps_field]['tmp_name']),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); return false; } while(($vs_content = fgets($r_incoming_fp, 4096)) !== false) { fwrite($r_outgoing_fp, $vs_content); } fclose($r_incoming_fp); fclose($r_outgoing_fp); $vs_url_fetched_from = $this->_SET_FILES[$ps_field]['tmp_name']; $vn_url_fetched_on = time(); $this->_SET_FILES[$ps_field]['tmp_name'] = $vs_tmp_file; $vb_is_fetched_file = true; } if (isset($this->_SET_FILES[$ps_field]['tmp_name']) && (file_exists($this->_SET_FILES[$ps_field]['tmp_name']))) { // ImageMagick partly relies on file extensions to properly identify images (RAW images in particular) // therefore we rename the temporary file here (using the extension of the original filename, if any) $va_matches = array(); $vb_renamed_tmpfile = false; preg_match("/[.]*\.([a-zA-Z0-9]+)$/",$this->_SET_FILES[$ps_field]['tmp_name'],$va_matches); if(!isset($va_matches[1])){ // file has no extension, i.e. is probably PHP upload tmp file $va_matches = array(); preg_match("/[.]*\.([a-zA-Z0-9]+)$/",$this->_SET_FILES[$ps_field]['original_filename'],$va_matches); if(strlen($va_matches[1])>0){ $va_parts = explode("/",$this->_SET_FILES[$ps_field]['tmp_name']); $vs_new_filename = sys_get_temp_dir()."/".$va_parts[sizeof($va_parts)-1].".".$va_matches[1]; if (!move_uploaded_file($this->_SET_FILES[$ps_field]['tmp_name'],$vs_new_filename)) { rename($this->_SET_FILES[$ps_field]['tmp_name'],$vs_new_filename); } $this->_SET_FILES[$ps_field]['tmp_name'] = $vs_new_filename; $vb_renamed_tmpfile = true; } } $input_mimetype = $m->divineFileFormat($this->_SET_FILES[$ps_field]['tmp_name']); if (!$input_type = $o_media_proc_settings->canAccept($input_mimetype)) { # error - filetype not accepted by this field $this->postError(1600, ($input_mimetype) ? _t("File type %1 not accepted by %2", $input_mimetype, $ps_field) : _t("Unknown file type not accepted by %1", $ps_field),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } # ok process file... if (!($m->read($this->_SET_FILES[$ps_field]['tmp_name']))) { $this->errors = array_merge($this->errors, $m->errors()); // copy into model plugin errors //$this->postError(1600, _t("File for %1 could not be read", $ps_field),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } $media_desc = array( "ORIGINAL_FILENAME" => $this->_SET_FILES[$ps_field]['original_filename'], "INPUT" => array( "MIMETYPE" => $m->get("mimetype"), "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "MD5" => md5_file($this->_SET_FILES[$ps_field]['tmp_name']), "FILESIZE" => filesize($this->_SET_FILES[$ps_field]['tmp_name']), "FETCHED_FROM" => $vs_url_fetched_from, "FETCHED_ON" => $vn_url_fetched_on ) ); # # Extract metadata from file # $media_metadata = $m->getExtractedMetadata(); # get versions to create $va_versions = $this->getMediaVersions($ps_field, $input_mimetype); $error = 0; # don't process files that are not going to be processed or converted # we don't want to waste time opening file we're not going to do anything with # also, we don't want to recompress JPEGs... $media_type = $o_media_proc_settings->canAccept($input_mimetype); $version_info = $o_media_proc_settings->getMediaTypeVersions($media_type); $va_default_queue_settings = $o_media_proc_settings->getMediaTypeQueueSettings($media_type); if (!($va_media_write_options = $this->_FILES[$ps_field]['options'])) { $va_media_write_options = $this->_SET_FILES[$ps_field]['options']; } $va_process_these_versions_only = array(); if (isset($pa_options['these_versions_only']) && is_array($pa_options['these_versions_only']) && sizeof($pa_options['these_versions_only'])) { $va_tmp = $this->_FIELD_VALUES[$ps_field]; foreach($pa_options['these_versions_only'] as $vs_this_version_only) { if (in_array($vs_this_version_only, $va_versions)) { if (is_array($this->_FIELD_VALUES[$ps_field])) { $va_process_these_versions_only[] = $vs_this_version_only; } } } // Copy metadata for version we're not processing if (sizeof($va_process_these_versions_only)) { foreach (array_keys($va_tmp) as $v) { if (!in_array($v, $va_process_these_versions_only)) { $media_desc[$v] = $va_tmp[$v]; } } } } $va_files_to_delete = array(); $va_queued_versions = array(); $queue_enabled = (!sizeof($va_process_these_versions_only) && $this->getAppConfig()->get('queue_enabled')) ? true : false; $vs_path_to_queue_media = null; foreach ($va_versions as $v) { if (sizeof($va_process_these_versions_only) && (!in_array($v, $va_process_these_versions_only))) { // only processing certain versions... and this one isn't it so skip continue; } $queue = $va_default_queue_settings['QUEUE']; $queue_threshold = isset($version_info[$v]['QUEUE_WHEN_FILE_LARGER_THAN']) ? intval($version_info[$v]['QUEUE_WHEN_FILE_LARGER_THAN']) : (int)$va_default_queue_settings['QUEUE_WHEN_FILE_LARGER_THAN']; $rule = isset($version_info[$v]['RULE']) ? $version_info[$v]['RULE'] : ''; $volume = isset($version_info[$v]['VOLUME']) ? $version_info[$v]['VOLUME'] : ''; # get volume $vi = $this->_MEDIA_VOLUMES->getVolumeInformation($volume); if (!is_array($vi)) { print "Invalid volume '{$volume}'<br>"; exit; } // Send to queue it it's too big to process here if (($queue_enabled) && ($queue) && ($queue_threshold > 0) && ($queue_threshold < (int)$media_desc["INPUT"]["FILESIZE"]) && ($va_default_queue_settings['QUEUE_USING_VERSION'] != $v)) { $va_queued_versions[$v] = array( 'VOLUME' => $volume ); $media_desc[$v]["QUEUED"] = $queue; if ($version_info[$v]["QUEUED_MESSAGE"]) { $media_desc[$v]["QUEUED_MESSAGE"] = $version_info[$v]["QUEUED_MESSAGE"]; } else { $media_desc[$v]["QUEUED_MESSAGE"] = ($va_default_queue_settings['QUEUED_MESSAGE']) ? $va_default_queue_settings['QUEUED_MESSAGE'] : _t("Media is being processed and will be available shortly."); } if ($pa_options['delete_old_media']) { $va_files_to_delete[] = array( 'field' => $ps_field, 'version' => $v ); } continue; } # get transformation rules $rules = $o_media_proc_settings->getMediaTransformationRule($rule); if (sizeof($rules) == 0) { $output_mimetype = $input_mimetype; $m->set("version", $v); # # don't process this media, just copy the file # $ext = $m->mimetype2extension($output_mimetype); if (!$ext) { $this->postError(1600, _t("File could not be copied for %1; can't convert mimetype '%2' to extension", $ps_field, $output_mimetype),"BaseModel->_processMedia()"); $m->cleanup(); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } if (($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey())) === false) { $this->postError(1600, _t("Could not create subdirectory for uploaded file in %1. Please ask your administrator to check the permissions of your media directory.", $vi["absolutePath"]),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } if ((bool)$version_info[$v]["USE_EXTERNAL_URL_WHEN_AVAILABLE"]) { $filepath = $this->_SET_FILES[$ps_field]['tmp_name']; if ($pa_options['delete_old_media']) { $va_files_to_delete[] = array( 'field' => $ps_field, 'version' => $v ); } $media_desc[$v] = array( "VOLUME" => $volume, "MIMETYPE" => $output_mimetype, "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "PROPERTIES" => $m->getProperties(), "EXTERNAL_URL" => $media_desc['INPUT']['FETCHED_FROM'], "FILENAME" => null, "HASH" => null, "MAGIC" => null, "EXTENSION" => $ext, "MD5" => md5_file($filepath) ); } else { $magic = rand(0,99999); $filepath = $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext; if (!copy($this->_SET_FILES[$ps_field]['tmp_name'], $filepath)) { $this->postError(1600, _t("File could not be copied. Ask your administrator to check permissions and file space for %1",$vi["absolutePath"]),"BaseModel->_processMedia()"); $m->cleanup(); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } if ($v === $va_default_queue_settings['QUEUE_USING_VERSION']) { $vs_path_to_queue_media = $filepath; } if ($pa_options['delete_old_media']) { $va_files_to_delete[] = array( 'field' => $ps_field, 'version' => $v, 'dont_delete_path' => $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v, 'dont_delete_extension' => $ext ); } if (is_array($vi["mirrors"]) && sizeof($vi["mirrors"]) > 0) { $vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $v)); $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey())); foreach ($vi["mirrors"] as $vs_mirror_code => $va_mirror_info) { $vs_mirror_method = $va_mirror_info["method"]; $vs_queue = $vs_mirror_method."mirror"; if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) { //$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_processMedia()"); //$m->cleanup(); //return false; } if ($o_tq->addTask( $vs_queue, array( "MIRROR" => $vs_mirror_code, "VOLUME" => $volume, "FIELD" => $ps_field, "TABLE" => $this->tableName(), "VERSION" => $v, "FILES" => array( array( "FILE_PATH" => $filepath, "ABS_PATH" => $vi["absolutePath"], "HASH" => $dirhash, "FILENAME" => $magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext ) ), "MIRROR_INFO" => $va_mirror_info, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey() ), array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) { continue; } else { $this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $queue),"BaseModel->_processMedia()"); } } } $media_desc[$v] = array( "VOLUME" => $volume, "MIMETYPE" => $output_mimetype, "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "PROPERTIES" => $m->getProperties(), "FILENAME" => $this->_genMediaName($ps_field)."_".$v.".".$ext, "HASH" => $dirhash, "MAGIC" => $magic, "EXTENSION" => $ext, "MD5" => md5_file($filepath) ); } } else { $m->set("version", $v); while(list($operation, $parameters) = each($rules)) { if ($operation === 'SET') { foreach($parameters as $pp => $pv) { if ($pp == 'format') { $output_mimetype = $pv; } else { $m->set($pp, $pv); } } } else { if (!($m->transform($operation, $parameters))) { $error = 1; $error_msg = "Couldn't do transformation '$operation'"; break(2); } } } if (!$output_mimetype) { $output_mimetype = $input_mimetype; } if (!($ext = $m->mimetype2extension($output_mimetype))) { $this->postError(1600, _t("File could not be processed for %1; can't convert mimetype '%2' to extension", $ps_field, $output_mimetype),"BaseModel->_processMedia()"); $m->cleanup(); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } if (($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey())) === false) { $this->postError(1600, _t("Could not create subdirectory for uploaded file in %1. Please ask your administrator to check the permissions of your media directory.", $vi["absolutePath"]),"BaseModel->_processMedia()"); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; } $magic = rand(0,99999); $filepath = $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v; $va_output_files = array(); if (!($vs_output_file = $m->write($filepath, $output_mimetype, $va_media_write_options))) { $this->postError(1600,_t("Couldn't write file: %1", join("; ", $m->getErrors())),"BaseModel->_processMedia()"); $m->cleanup(); set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return false; break; } else { $va_output_files[] = $vs_output_file; } if ($v === $va_default_queue_settings['QUEUE_USING_VERSION']) { $vs_path_to_queue_media = $vs_output_file; } if (($pa_options['delete_old_media']) && (!$error)) { if($vs_old_media_path = $this->getMediaPath($ps_field, $v)) { $va_files_to_delete[] = array( 'field' => $ps_field, 'version' => $v, 'dont_delete_path' => $filepath, 'dont_delete_extension' => $ext ); } } if (is_array($vi["mirrors"]) && sizeof($vi["mirrors"]) > 0) { $vs_entity_key = join("/", array($this->tableName(), $ps_field, $this->getPrimaryKey(), $v)); $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey())); foreach ($vi["mirrors"] as $vs_mirror_code => $va_mirror_info) { $vs_mirror_method = $va_mirror_info["method"]; $vs_queue = $vs_mirror_method."mirror"; if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key))) { //$this->postError(560, _t("Could not cancel pending tasks: %1", $this->error),"BaseModel->_processMedia()"); //$m->cleanup(); //return false; } if ($o_tq->addTask( $vs_queue, array( "MIRROR" => $vs_mirror_code, "VOLUME" => $volume, "FIELD" => $ps_field, "TABLE" => $this->tableName(), "VERSION" => $v, "FILES" => array( array( "FILE_PATH" => $filepath.".".$ext, "ABS_PATH" => $vi["absolutePath"], "HASH" => $dirhash, "FILENAME" => $magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext ) ), "MIRROR_INFO" => $va_mirror_info, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey() ), array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) { continue; } else { $this->postError(100, _t("Couldn't queue mirror using '%1' for version '%2' (handler '%3')", $vs_mirror_method, $v, $queue),"BaseModel->_processMedia()"); } } } $media_desc[$v] = array( "VOLUME" => $volume, "MIMETYPE" => $output_mimetype, "WIDTH" => $m->get("width"), "HEIGHT" => $m->get("height"), "PROPERTIES" => $m->getProperties(), "FILENAME" => $this->_genMediaName($ps_field)."_".$v.".".$ext, "HASH" => $dirhash, "MAGIC" => $magic, "EXTENSION" => $ext, "MD5" => md5_file($vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($ps_field)."_".$v.".".$ext) ); $m->reset(); } } if (sizeof($va_queued_versions)) { $vs_entity_key = md5(join("/", array_merge(array($this->tableName(), $ps_field, $this->getPrimaryKey()), array_keys($va_queued_versions)))); $vs_row_key = join("/", array($this->tableName(), $this->getPrimaryKey())); if (!($o_tq->cancelPendingTasksForEntity($vs_entity_key, $queue))) { // TODO: log this } if (!($filename = $vs_path_to_queue_media)) { // if we're not using a designated not-queued representation to generate the queued ones // then copy the uploaded file to the tmp dir and use that $filename = $o_tq->copyFileToQueueTmp($va_default_queue_settings['QUEUE'], $this->_SET_FILES[$ps_field]['tmp_name']); } if ($filename) { if ($o_tq->addTask( $va_default_queue_settings['QUEUE'], array( "TABLE" => $this->tableName(), "FIELD" => $ps_field, "PK" => $this->primaryKey(), "PK_VAL" => $this->getPrimaryKey(), "INPUT_MIMETYPE" => $input_mimetype, "FILENAME" => $filename, "VERSIONS" => $va_queued_versions, "OPTIONS" => $va_media_write_options, "DONT_DELETE_OLD_MEDIA" => ($filename == $vs_path_to_queue_media) ? true : false ), array("priority" => 100, "entity_key" => $vs_entity_key, "row_key" => $vs_row_key, 'user_id' => $AUTH_CURRENT_USER_ID))) { if ($pa_options['delete_old_media']) { foreach($va_queued_versions as $vs_version => $va_version_info) { $va_files_to_delete[] = array( 'field' => $ps_field, 'version' => $vs_version ); } } } else { $this->postError(100, _t("Couldn't queue processing for version '%1' using handler '%2'", !$v, $queue),"BaseModel->_processMedia()"); } } else { $this->errors = $o_tq->errors; } } else { // Generate preview frames for media that support that (Eg. video) // and add them as "multifiles" assuming the current model supports that (ca_object_representations does) if (!sizeof($va_process_these_versions_only) && ((bool)$this->_CONFIG->get('video_preview_generate_frames') || (bool)$this->_CONFIG->get('document_preview_generate_pages')) && method_exists($this, 'addFile')) { $va_preview_frame_list = $m->writePreviews( array( 'width' => $m->get("width"), 'height' => $m->get("height"), 'minNumberOfFrames' => $this->_CONFIG->get('video_preview_min_number_of_frames'), 'maxNumberOfFrames' => $this->_CONFIG->get('video_preview_max_number_of_frames'), 'numberOfPages' => $this->_CONFIG->get('document_preview_max_number_of_pages'), 'frameInterval' => $this->_CONFIG->get('video_preview_interval_between_frames'), 'pageInterval' => $this->_CONFIG->get('document_preview_interval_between_pages'), 'startAtTime' => $this->_CONFIG->get('video_preview_start_at'), 'endAtTime' => $this->_CONFIG->get('video_preview_end_at'), 'startAtPage' => $this->_CONFIG->get('document_preview_start_page'), 'outputDirectory' => __CA_APP_DIR__.'/tmp' ) ); $this->removeAllFiles(); // get rid of any previously existing frames (they might be hanging around if we're editing an existing record) if (is_array($va_preview_frame_list)) { foreach($va_preview_frame_list as $vn_time => $vs_frame) { $this->addFile($vs_frame, $vn_time, true); // the resource path for each frame is it's time, in seconds (may be fractional) for video, or page number for documents @unlink($vs_frame); // clean up tmp preview frame file } } } } if (!$error) { # # --- Clean up old media from versions that are not supported in the new media # if ($pa_options['delete_old_media']) { foreach ($this->getMediaVersions($ps_field) as $old_version) { if (!is_array($media_desc[$old_version])) { $this->_removeMedia($ps_field, $old_version); } } } foreach($va_files_to_delete as $va_file_to_delete) { $this->_removeMedia($va_file_to_delete['field'], $va_file_to_delete['version'], $va_file_to_delete['dont_delete_path'], $va_file_to_delete['dont_delete_extension']); } $this->_FILES[$ps_field] = $media_desc; $this->_FIELD_VALUES[$ps_field] = $media_desc; $vs_serialized_data = caSerializeForDatabase($this->_FILES[$ps_field], true); $vs_sql = "$ps_field = ".$this->quote($vs_serialized_data).","; if (($vs_metadata_field_name = $o_media_proc_settings->getMetadataFieldName()) && $this->hasField($vs_metadata_field_name)) { $this->set($vs_metadata_field_name, $media_metadata); $vs_sql .= " ".$vs_metadata_field_name." = ".$this->quote(caSerializeForDatabase($media_metadata, true)).","; } if (($vs_content_field_name = $o_media_proc_settings->getMetadataContentName()) && $this->hasField($vs_content_field_name)) { $this->_FIELD_VALUES[$vs_content_field_name] = $this->quote($m->getExtractedText()); $vs_sql .= " ".$vs_content_field_name." = ".$this->_FIELD_VALUES[$vs_content_field_name].","; } } else { # error - invalid media $this->postError(1600, _t("File could not be processed for %1: %2", $ps_field, $error_msg),"BaseModel->_processMedia()"); # return false; } $m->cleanup(); if($vb_renamed_tmpfile){ @unlink($this->_SET_FILES[$ps_field]['tmp_name']); } } else { if(is_array($this->_FIELD_VALUES[$ps_field])) { $this->_FILES[$ps_field] = $this->_FIELD_VALUES[$ps_field]; $vs_sql = "$ps_field = ".$this->quote(caSerializeForDatabase($this->_FILES[$ps_field], true)).","; } } $this->_SET_FILES[$ps_field] = null; } set_time_limit($vn_max_execution_time); if ($vb_is_fetched_file) { @unlink($vs_tmp_file); } return $vs_sql; } # -------------------------------------------------------------------------------- /** * Fetches hash directory * * @access private * @param string $basepath path * @param int $id identifier * @return string directory */ public function _getDirectoryHash ($basepath, $id) { $n = intval($id / 100); $dirs = array(); $l = strlen($n); for($i=0;$i<$l; $i++) { $dirs[] = substr($n,$i,1); if (!file_exists($basepath."/".join("/", $dirs))) { if (!@mkdir($basepath."/".join("/", $dirs))) { return false; } } } return join("/", $dirs); } # -------------------------------------------------------------------------------- # --- Uploaded file handling # -------------------------------------------------------------------------------- /** * Returns url of file * * @access public * @param $field field name * @return string file url */ public function getFileUrl($ps_field) { $va_file_info = $this->get($ps_field); if (!is_array($va_file_info)) { return null; } $va_volume_info = $this->_FILE_VOLUMES->getVolumeInformation($va_file_info["VOLUME"]); if (!is_array($va_volume_info)) { return null; } $vs_protocol = $va_volume_info["protocol"]; $vs_host = $va_volume_info["hostname"]; $vs_path = join("/",array($va_volume_info["urlPath"], $va_file_info["HASH"], $va_file_info["MAGIC"]."_".$va_file_info["FILENAME"])); return $va_file_info["FILENAME"] ? "{$vs_protocol}://{$vs_host}.{$vs_path}" : ""; } # -------------------------------------------------------------------------------- /** * Returns path of file * * @access public * @param string $field field name * @return string path in local filesystem */ public function getFilePath($ps_field) { $va_file_info = $this->get($ps_field); if (!is_array($va_file_info)) { return null; } $va_volume_info = $this->_FILE_VOLUMES->getVolumeInformation($va_file_info["VOLUME"]); if (!is_array($va_volume_info)) { return null; } return join("/",array($va_volume_info["absolutePath"], $va_file_info["HASH"], $va_file_info["MAGIC"]."_".$va_file_info["FILENAME"])); } # -------------------------------------------------------------------------------- /** * Wrapper around BaseModel::get(), used to fetch information about files * * @access public * @param string $field field name * @return array file information */ public function &getFileInfo($ps_field) { $va_file_info = $this->get($ps_field); if (!is_array($va_file_info)) { return null; } return $va_file_info; } # -------------------------------------------------------------------------------- /** * Clear file * * @access public * @param string $field field name * @return bool always true */ public function clearFile($ps_field) { $this->_FILES_CLEAR[$ps_field] = 1; $this->_FIELD_VALUE_CHANGED[$ps_field] = 1; return true; } # -------------------------------------------------------------------------------- /** * Returns list of mimetypes of available conversions of files * * @access public * @param string $ps_field field name * @return array */ public function getFileConversions($ps_field) { $va_info = $this->getFileInfo($ps_field); if (!is_array($va_info["CONVERSIONS"])) { return array(); } return $va_info["CONVERSIONS"]; } # -------------------------------------------------------------------------------- /** * Returns file path to converted version of file * * @access public * @param string $ps_field field name * @param string $ps_format format of the converted version * @return string file path */ public function getFileConversionPath($ps_field, $ps_format) { $va_info = $this->getFileInfo($ps_field); if (!is_array($va_info)) { return ""; } $vi = $this->_FILE_VOLUMES->getVolumeInformation($va_info["VOLUME"]); if (!is_array($vi)) { return ""; } $va_conversions = $this->getFileConversions($ps_field); if ($va_conversions[$ps_format]) { return join("/",array($vi["absolutePath"], $va_info["HASH"], $va_info["MAGIC"]."_".$va_conversions[$ps_format]["FILENAME"])); } else { return ""; } } # -------------------------------------------------------------------------------- /** * Returns url to converted version of file * * @access public * @param string $ps_field field name * @param string $ps_format format of the converted version * @return string url */ public function getFileConversionUrl($ps_field, $ps_format) { $va_info = $this->getFileInfo($ps_field); if (!is_array($va_info)) { return ""; } $vi = $this->_FILE_VOLUMES->getVolumeInformation($va_info["VOLUME"]); if (!is_array($vi)) { return ""; } $va_conversions = $this->getFileConversions($ps_field); if ($va_conversions[$ps_format]) { return $vi["protocol"]."://".join("/", array($vi["hostname"], $vi["urlPath"], $va_info["HASH"], $va_info["MAGIC"]."_".$va_conversions[$ps_format]["FILENAME"])); } else { return ""; } } # ------------------------------------------------------------------------------- /** * Generates filenames as follows: <table>_<field>_<primary_key> * Makes the application die if no record is loaded * * @access private * @param string $field field name * @return string file name */ public function _genFileName($field) { $pk = $this->getPrimaryKey(); if ($pk) { return $this->TABLE."_".$field."_".$pk; } else { die("NO PK TO MAKE file name for $field!"); } } # -------------------------------------------------------------------------------- /** * Processes uploaded files (only if something was uploaded) * * @access private * @param string $field field name * @return string */ public function _processFiles($field) { $vs_sql = ""; # only set file if something was uploaded # (ie. don't nuke an existing file because none # was uploaded) if ((isset($this->_FILES_CLEAR[$field])) && ($this->_FILES_CLEAR[$field])) { #--- delete file @unlink($this->getFilePath($field)); #--- delete conversions # # TODO: wvWWare MSWord conversion to HTML generates untracked graphics files for embedded images... they are currently # *not* deleted when the file and associated conversions are deleted. We will need to parse the HTML to derive the names # of these files... # foreach ($this->getFileConversions($field) as $vs_format => $va_file_conversion) { @unlink($this->getFileConversionPath($field, $vs_format)); } $this->_FILES[$field] = ""; $this->_FIELD_VALUES[$field] = ""; $vs_sql = "$field = ".$this->quote(caSerializeForDatabase($this->_FILES[$field], true)).","; } else { $va_field_info = $this->getFieldInfo($field); if ((file_exists($this->_SET_FILES[$field]['tmp_name']))) { $ff = new File(); $mimetype = $ff->divineFileFormat($this->_SET_FILES[$field]['tmp_name'], $this->_SET_FILES[$field]['original_filename']); if (is_array($va_field_info["FILE_FORMATS"]) && sizeof($va_field_info["FILE_FORMATS"]) > 0) { if (!in_array($mimetype, $va_field_info["FILE_FORMATS"])) { $this->postError(1605, _t("File is not a valid format"),"BaseModel->_processFiles()"); return false; } } $vn_dangerous = 0; if (!$mimetype) { $mimetype = "application/octet-stream"; $vn_dangerous = 1; } # get volume $vi = $this->_FILE_VOLUMES->getVolumeInformation($va_field_info["FILE_VOLUME"]); if (!is_array($vi)) { print "Invalid volume ".$va_field_info["FILE_VOLUME"]."<br>"; exit; } $properties = $ff->getProperties(); if ($properties['dangerous'] > 0) { $vn_dangerous = 1; } if (($dirhash = $this->_getDirectoryHash($vi["absolutePath"], $this->getPrimaryKey())) === false) { $this->postError(1600, _t("Could not create subdirectory for uploaded file in %1. Please ask your administrator to check the permissions of your media directory.", $vi["absolutePath"]),"BaseModel->_processFiles()"); return false; } $magic = rand(0,99999); $va_pieces = explode("/", $this->_SET_FILES[$field]['original_filename']); $ext = array_pop($va_tmp = explode(".", array_pop($va_pieces))); if ($properties["dangerous"]) { $ext .= ".bin"; } if (!$ext) $ext = "bin"; $filestem = $vi["absolutePath"]."/".$dirhash."/".$magic."_".$this->_genMediaName($field); $filepath = $filestem.".".$ext; $filesize = isset($properties["filesize"]) ? $properties["filesize"] : 0; if (!$filesize) { $properties["filesize"] = filesize($this->_SET_FILES[$field]['tmp_name']); } $file_desc = array( "FILE" => 1, # signifies is file "VOLUME" => $va_field_info["FILE_VOLUME"], "ORIGINAL_FILENAME" => $this->_SET_FILES[$field]['original_filename'], "MIMETYPE" => $mimetype, "FILENAME" => $this->_genMediaName($field).".".$ext, "HASH" => $dirhash, "MAGIC" => $magic, "PROPERTIES" => $properties, "DANGEROUS" => $vn_dangerous, "CONVERSIONS" => array(), "MD5" => md5_file($this->_SET_FILES[$field]['tmp_name']) ); if (!copy($this->_SET_FILES[$field]['tmp_name'], $filepath)) { $this->postError(1600, _t("File could not be copied. Ask your administrator to check permissions and file space for %1",$vi["absolutePath"]),"BaseModel->_processFiles()"); return false; } # -- delete old file if its name is different from the one we just wrote (otherwise, we overwrote it) if ($filepath != $this->getFilePath($field)) { @unlink($this->getFilePath($field)); } # # -- Attempt to do file conversions # if (isset($va_field_info["FILE_CONVERSIONS"]) && is_array($va_field_info["FILE_CONVERSIONS"]) && (sizeof($va_field_info["FILE_CONVERSIONS"]) > 0)) { foreach($va_field_info["FILE_CONVERSIONS"] as $vs_output_format) { if ($va_tmp = $ff->convert($vs_output_format, $filepath,$filestem)) { # new extension is added to end of stem by conversion $vs_file_ext = $va_tmp["extension"]; $vs_format_name = $va_tmp["format_name"]; $vs_long_format_name = $va_tmp["long_format_name"]; $file_desc["CONVERSIONS"][$vs_output_format] = array( "MIMETYPE" => $vs_output_format, "FILENAME" => $this->_genMediaName($field)."_conv.".$vs_file_ext, "PROPERTIES" => array( "filesize" => filesize($filestem."_conv.".$vs_file_ext), "extension" => $vs_file_ext, "format_name" => $vs_format_name, "long_format_name" => $vs_long_format_name ) ); } } } $this->_FILES[$field] = $file_desc; $vs_sql = "$field = ".$this->quote(caSerializeForDatabase($this->_FILES[$field], true)).","; $this->_FIELD_VALUES[$field]= $this->_SET_FILES[$field] = $file_desc; } } return $vs_sql; } # -------------------------------------------------------------------------------- # --- Utilities # -------------------------------------------------------------------------------- /** * Can be called in two ways: * 1. Called with two arguments: returns $val quoted and escaped for use with $field. * That is, it will only quote $val if the field type requires it. * 2. Called with one argument: simply returns $val quoted and escaped. * * @access public * @param string $field field name * @param string $val optional field value */ public function &quote ($field, $val=null) { if (is_null($val)) { # just quote it! $field = "'".$this->escapeForDatabase($field)."'"; return $field;# quote only if field needs it } else { if ($this->_getFieldTypeType($field) == 1) { $val = "'".$this->escapeForDatabase($val)."'"; } return $val; } } # -------------------------------------------------------------------------------- /** * Escapes a string for SQL use * * @access public * @param string $ps_value * @return string */ public function escapeForDatabase ($ps_value) { $o_db = $this->getDb(); return $o_db->escape($ps_value); } # -------------------------------------------------------------------------------- /** * Make copy of BaseModel object with all fields information intact *EXCEPT* for the * primary key value and all media and file fields, all of which are empty. * * @access public * @return BaseModel the copy */ public function &cloneRecord() { $o_clone = $this; $o_clone->set($o_clone->getPrimaryKey(), null); foreach($o_clone->getFields() as $vs_f) { switch($o_clone->getFieldInfo($vs_f, "FIELD_TYPE")) { case FT_MEDIA: $o_clone->_FIELD_VALUES[$vs_f] = ""; break; case FT_FILE: $o_clone->_FIELD_VALUES[$vs_f] = ""; break; } } return $o_clone; } # -------------------------------------------------------------------------------- /** * Clears all fields in object * * @access public */ public function clear () { $this->clearErrors(); foreach($this->FIELDS as $field => $attr) { if (isset($this->FIELDS[$field]['START']) && ($vs_start_fld = $this->FIELDS[$field]['START'])) { unset($this->_FIELD_VALUES[$vs_start_fld]); unset($this->_FIELD_VALUES[$this->FIELDS[$field]['END']]); } unset($this->_FIELD_VALUES[$field]); } } # -------------------------------------------------------------------------------- /** * Prints contents of all fields in object * * @access public */ public function dump () { $this->clearErrors(); reset($this->FIELDS); while (list($field, $attr) = each($this->FIELDS)) { echo "$field = ".$this->_FIELD_VALUES[$field]."<BR>\n"; } } # -------------------------------------------------------------------------------- /** * Returns true if field exists in this object * * @access public * @param string $field field name * @return bool */ public function hasField ($field) { return (isset($this->FIELDS[$field]) && $this->FIELDS[$field]) ? 1 : 0; } # -------------------------------------------------------------------------------- /** * Returns underlying datatype for given field type * 0 = numeric, 1 = string * * @access private * @param string $fieldname * @return int */ public function _getFieldTypeType ($fieldname) { switch($this->FIELDS[$fieldname]["FIELD_TYPE"]) { case (FT_TEXT): case (FT_MEDIA): case (FT_FILE): case (FT_PASSWORD): case (FT_VARS): return 1; break; case (FT_NUMBER): case (FT_TIMESTAMP): case (FT_DATETIME): case (FT_TIME): case (FT_TIMERANGE): case (FT_HISTORIC_DATETIME): case (FT_DATE): case (FT_HISTORIC_DATE): case (FT_DATERANGE): case (FT_TIMECODE): case (FT_HISTORIC_DATERANGE): case (FT_BIT): return 0; break; default: print "Invalid field type in _getFieldTypeType: ". $this->FIELDS[$fieldname]["FIELD_TYPE"]; exit; } } # -------------------------------------------------------------------------------- /** * Fetches the choice list value for a given field * * @access public * @param string $field field name * @param string $value choice list name * @return string */ public function getChoiceListValue($field, $value) { $va_attr = $this->getFieldInfo($field); $va_list = $va_attr["BOUNDS_CHOICE_LIST"]; if (isset($va_attr['LIST']) && $va_attr['LIST']) { $t_list = new ca_lists(); if ($t_list->load(array('list_code' => $va_attr['LIST']))) { $va_items = caExtractValuesByUserLocale($t_list->getItemsForList($va_attr['LIST'])); $va_list = array(); foreach($va_items as $vn_item_id => $va_item_info) { $va_list[$va_item_info['name_singular']] = $va_item_info['item_value']; } } } if ($va_list) { foreach ($va_list as $k => $v) { if ($v == $value) { return $k; } } } else { return; } } # -------------------------------------------------------------------------------- # --- Field input verification # -------------------------------------------------------------------------------- /** * Does bounds checks specified for field $field on value $value. * Returns 0 and throws an exception is it fails, returns 1 on success. * * @access public * @param string $field field name * @param string $value value */ public function verifyFieldValue ($field, $value, &$pb_need_reload) { $pb_need_reload = false; $va_attr = $this->FIELDS[$field]; if (!$va_attr) { $this->postError(716,_t("%1 does not exist", $field),"BaseModel->verifyFieldValue()"); return false; } $data_type = $this->_getFieldTypeType($field); $field_type = $this->getFieldInfo($field,"FIELD_TYPE"); if ((isset($va_attr["FILTER"]) && ($filter = $va_attr["FILTER"]))) { if (!preg_match($filter, $value)) { $this->postError(1102,_t("%1 is invalid", $va_attr["LABEL"]),"BaseModel->verifyFieldValue()"); return false; } } if ($data_type == 0) { # number; check value if (isset($va_attr["BOUNDS_VALUE"][0])) { $min_value = $va_attr["BOUNDS_VALUE"][0]; } if (isset($va_attr["BOUNDS_VALUE"][1])) { $max_value = $va_attr["BOUNDS_VALUE"][1]; } if (!($va_attr["IS_NULL"] && (!$value))) { if ((isset($min_value)) && ($value < $min_value)) { $this->postError(1101,_t("%1 must not be less than %2", $va_attr["LABEL"], $min_value),"BaseModel->verifyFieldValue()"); return false; } if ((isset($max_value)) && ($value > $max_value)) { $this->postError(1101,_t("%1 must not be greater than %2", $va_attr["LABEL"], $max_value),"BaseModel->verifyFieldValue()"); return false; } } } if (!isset($va_attr["IS_NULL"])) { $va_attr["IS_NULL"] = 0; } if (!($va_attr["IS_NULL"] && (!$value))) { # check length if (isset($va_attr["BOUNDS_LENGTH"]) && is_array($va_attr["BOUNDS_LENGTH"])) { $min_length = $va_attr["BOUNDS_LENGTH"][0]; $max_length = $va_attr["BOUNDS_LENGTH"][1]; } if ((isset($min_length)) && (strlen($value) < $min_length)) { $this->postError(1102, _t("%1 must be at least %2 characters", $va_attr["LABEL"], $min_length),"BaseModel->verifyFieldValue()"); return false; } if ((isset($max_length)) && (strlen($value) > $max_length)) { $this->postError(1102,_t("%1 must not be more than %2 characters long", $va_attr["LABEL"], $max_length),"BaseModel->verifyFieldValue()"); return false; } $va_list = isset($va_attr["BOUNDS_CHOICE_LIST"]) ? $va_attr["BOUNDS_CHOICE_LIST"] : null; if (isset($va_attr['LIST']) && $va_attr['LIST']) { $t_list = new ca_lists(); if ($t_list->load(array('list_code' => $va_attr['LIST']))) { $va_items = caExtractValuesByUserLocale($t_list->getItemsForList($va_attr['LIST'])); $va_list = array(); $vs_list_default = null; foreach($va_items as $vn_item_id => $va_item_info) { if(is_null($vs_list_default) || (isset($va_item_info['is_default']) && $va_item_info['is_default'])) { $vs_list_default = $va_item_info['item_value']; } $va_list[$va_item_info['name_singular']] = $va_item_info['item_value']; } $va_attr['DEFAULT'] = $vs_list_default; } } if ((in_array($data_type, array(FT_NUMBER, FT_TEXT))) && (isset($va_list)) && (is_array($va_list)) && (count($va_list) > 0)) { # string; check choice list if (isset($va_attr['DEFAULT']) && !strlen($value)) { $value = $va_attr['DEFAULT']; if (strlen($value)) { $this->set($field, $value); $pb_need_reload = true; } } // force default value if nothing is set if (!is_array($value)) { $value = explode(":",$value); } if (!isset($va_attr['LIST_MULTIPLE_DELIMITER']) || !($vs_list_multiple_delimiter = $va_attr['LIST_MULTIPLE_DELIMITER'])) { $vs_list_multiple_delimiter = ';'; } foreach($value as $v) { if ((sizeof($value) > 1) && (!$v)) continue; if ($va_attr['DISPLAY_TYPE'] == DT_LIST_MULTIPLE) { $va_tmp = explode($vs_list_multiple_delimiter, $v); foreach($va_tmp as $vs_mult_item) { if (!in_array($vs_mult_item,$va_list)) { $this->postError(1103,_t("'%1' is not valid choice for %2", $v, $va_attr["LABEL"]),"BaseModel->verifyFieldValue()"); return false; } } } else { if (!in_array($v,$va_list)) { $this->postError(1103, _t("'%1' is not valid choice for %2", $v, $va_attr["LABEL"]),"BaseModel->verifyFieldValue()"); return false; } } } } } return true; } # -------------------------------------------------------------------------------------------- /** * Verifies values of each field and returns a hash keyed on field name with values set to * and array of error messages for each field. Returns false (0) if no errors. * * @access public * @return array|bool */ public function verifyForm() { $this->clearErrors(); $errors = array(); $errors_found = 0; $fields = $this->getFormFields(); $err_halt = $this->error->getHaltOnError(); $err_report = $this->error->getReportOnError(); $this->error->setErrorOutput(0); while(list($field,$attr) = each($fields)) { $pb_need_reload = false; $this->verifyFieldValue ($field, $this->get($field), $pb_need_reload); if ($errnum = $this->error->getErrorNumber()) { $errors[$field][$errnum] = $this->error->getErrorDescription(); $errors_found++; } } $this->error->setHaltOnError($err_halt); $this->error->setReportOnError($err_report); if ($errors_found) { return $errors; } else { return false; } } # -------------------------------------------------------------------------------------------- # --- Field info # -------------------------------------------------------------------------------------------- /** * Returns a hash with field names as keys and attributes hashes as values * If $names_only is set, only the field names are returned in an indexed array (NOT a hash) * Only returns fields that belong in public forms - it omits those fields with a display type of 7 ("PRIVATE") * * @param bool $return_all * @param bool $names_only * @return array */ public function getFormFields ($return_all = 0, $names_only = 0) { if (($return_all) && (!$names_only)) { return $this->FIELDS; } $form_fields = array(); if (!$names_only) { foreach($this->FIELDS as $field => $attr) { if ($return_all || ($attr["DISPLAY_TYPE"] != DT_OMIT)) { $form_fields[$field] = $attr; } } } else { foreach($this->FIELDS as $field => $attr) { if ($return_all || ($attr["DISPLAY_TYPE"] != DT_OMIT)) { $form_fields[] = $field; } } } return $form_fields; } # -------------------------------------------------------------------------------------------- /** * Returns (array) snapshot of the record represented by this BaseModel object * * @access public * @param bool $pb_changes_only optional, just return changed fields * @return array */ public function &getSnapshot($pb_changes_only=false) { $va_field_list = $this->getFormFields(true, true); $va_snapshot = array(); foreach($va_field_list as $vs_field) { if (!$pb_changes_only || ($pb_changes_only && $this->changed($vs_field))) { $va_snapshot[$vs_field] = $this->get($vs_field); } } // We need to include the element_id when storing snapshots of ca_attributes and ca_attribute_values // whether is has changed or not (actually, it shouldn't really be changing after insert in normal use) // We need it available to assist in proper display of attributes in the change log if (in_array($this->tableName(), array('ca_attributes', 'ca_attribute_values'))) { $va_snapshot['element_id'] = $this->get('element_id'); $va_snapshot['attribute_id'] = $this->get('attribute_id'); } return $va_snapshot; } # -------------------------------------------------------------------------------------------- /** * Returns attributes hash for specified field * * @access public * @param string $field field name * @param string $attribute optional restriction to a single attribute */ public function getFieldInfo($field, $attribute = "") { if (isset($this->FIELDS[$field])) { $fieldinfo = $this->FIELDS[$field]; if ($attribute) { return (isset($fieldinfo[$attribute])) ? $fieldinfo[$attribute] : ""; } else { return $fieldinfo; } } else { $this->postError(710,_t("'%1' does not exist in this object", $field),"BaseModel->getFieldInfo()"); return false; } } # -------------------------------------------------------------------------------------------- /** * Returns display label for element specified by standard "get" bundle code (eg. <table_name>.<field_name> format) */ public function getDisplayLabel($ps_field) { $va_tmp = explode('.', $ps_field); if ($va_tmp[0] == 'created') { return _t('Creation date/time'); } if ($va_tmp[0] == 'modified') { return _t('Modification date/time'); } if ($va_tmp[0] != $this->tableName()) { return null; } if ($this->hasField($va_tmp[1])) { return $this->getFieldInfo($va_tmp[1], 'LABEL'); } if ($va_tmp[1] == 'created') { return _t('Creation date/time'); } if ($va_tmp[1] == 'lastModified') { return _t('Last modification date/time'); } return null; } # -------------------------------------------------------------------------------------------- /** * Returns display description for element specified by standard "get" bundle code (eg. <table_name>.<bundle_name> format) */ public function getDisplayDescription($ps_field) { $va_tmp = explode('.', $ps_field); if ($va_tmp[0] == 'created') { return _t('Date and time %1 was created', $this->getProperty('NAME_SINGULAR')); } if ($va_tmp[0] == 'modified') { return _t('Date and time %1 was modified', $this->getProperty('NAME_SINGULAR')); } if ($va_tmp[0] != $this->tableName()) { return null; } if ($this->hasField($va_tmp[1])) { return $this->getFieldInfo($va_tmp[1], 'DESCRIPTION'); } if ($va_tmp[1] == 'created') { return _t('Date and time %1 was created', $this->getProperty('NAME_SINGULAR')); } if ($va_tmp[1] == 'lastModified') { return _t('Date and time %1 was last modified', $this->getProperty('NAME_SINGULAR')); } return null; } # -------------------------------------------------------------------------------------------- /** * Returns HTML search form input widget for bundle specified by standard "get" bundle code (eg. <table_name>.<bundle_name> format) * This method handles generation of search form widgets for intrinsic fields in the primary table. If this method can't handle * the bundle (because it is not an intrinsic field in the primary table...) it will return null. * * @param $po_request HTTPRequest * @param $ps_field string * @param $pa_options array * @return string HTML text of form element. Will return null if it is not possible to generate an HTML form widget for the bundle. * */ public function htmlFormElementForSearch($po_request, $ps_field, $pa_options=null) { if (!is_array($pa_options)) { $pa_options = array(); } if (isset($pa_options['width'])) { if ($va_dim = caParseFormElementDimension($pa_options['width'])) { if ($va_dim['type'] == 'pixels') { unset($pa_options['width']); $pa_options['maxPixelWidth'] = $va_dim['dimension']; } } } $va_tmp = explode('.', $ps_field); if (in_array($va_tmp[0], array('created', 'modified'))) { return caHTMLTextInput($ps_field, array( 'id' => str_replace(".", "_", $ps_field), 'width' => (isset($pa_options['width']) && ($pa_options['width'] > 0)) ? $pa_options['width'] : 30, 'height' => (isset($pa_options['height']) && ($pa_options['height'] > 0)) ? $pa_options['height'] : 1, 'value' => (isset($pa_options['values'][$ps_field]) ? $pa_options['values'][$ps_field] : '')) ); } if ($va_tmp[0] != $this->tableName()) { return null; } if ($this->hasField($va_tmp[1])) { return $this->htmlFormElement($va_tmp[1], '^ELEMENT', array_merge($pa_options, array( 'name' => $ps_field, 'id' => str_replace(".", "_", $ps_field), 'nullOption' => '-', 'value' => (isset($pa_options['values'][$ps_field]) ? $pa_options['values'][$ps_field] : ''), 'width' => (isset($pa_options['width']) && ($pa_options['width'] > 0)) ? $pa_options['width'] : 30, 'height' => (isset($pa_options['height']) && ($pa_options['height'] > 0)) ? $pa_options['height'] : 1, 'no_tooltips' => true ))); } return null; } # -------------------------------------------------------------------------------------------- /** * Return list of fields that had conflicts with existing data during last update() * (ie. someone else had already saved to this field while the user of this instance was working) * * @access public */ public function getFieldConflicts() { return $this->field_conflicts; } # -------------------------------------------------------------------------------------------- # --- Change log # -------------------------------------------------------------------------------------------- /** * Log a change * * @access private * @param string $ps_change_type 'I', 'U' or 'D', meaning INSERT, UPDATE or DELETE * @param int $pn_user_id user identifier, defaults to null */ private function logChange($ps_change_type, $pn_user_id=null) { $vb_is_metadata = $vb_is_metadata_value = false; if ($this->tableName() == 'ca_attributes') { $vb_log_changes_to_self = false; $va_subject_config = null; $vb_is_metadata = true; } elseif($this->tableName() == 'ca_attribute_values') { $vb_log_changes_to_self = false; $va_subject_config = null; $vb_is_metadata_value = true; } else { $vb_log_changes_to_self = $this->getProperty('LOG_CHANGES_TO_SELF'); $va_subject_config = $this->getProperty('LOG_CHANGES_USING_AS_SUBJECT'); } global $AUTH_CURRENT_USER_ID; if (!$pn_user_id) { $pn_user_id = $AUTH_CURRENT_USER_ID; } if (!$pn_user_id) { $pn_user_id = null; } if (!in_array($ps_change_type, array('I', 'U', 'D'))) { return false; }; // invalid change type (shouldn't happen) if (!($vn_row_id = $this->getPrimaryKey())) { return false; } // no logging without primary key value // get unit id (if set) global $g_change_log_unit_id; $vn_unit_id = $g_change_log_unit_id; if (!$vn_unit_id) { $vn_unit_id = null; } // get subject ids $va_subjects = array(); if ($vb_is_metadata) { // special case for logging attribute changes if (($vn_id = $this->get('row_id')) > 0) { $va_subjects[$this->get('table_num')][] = $vn_id; } } elseif ($vb_is_metadata_value) { // special case for logging metadata changes $t_attr = new ca_attributes($this->get('attribute_id')); if (($vn_id = $t_attr->get('row_id')) > 0) { $va_subjects[$t_attr->get('table_num')][] = $vn_id; } } else { if (is_array($va_subject_config)) { if(is_array($va_subject_config['FOREIGN_KEYS'])) { foreach($va_subject_config['FOREIGN_KEYS'] as $vs_field) { $va_relationships = $this->_DATAMODEL->getManyToOneRelations($this->tableName(), $vs_field); if ($va_relationships['one_table']) { $vn_table_num = $this->_DATAMODEL->getTableNum($va_relationships['one_table']); if (!isset($va_subjects[$vn_table_num]) || !is_array($va_subjects[$vn_table_num])) { $va_subjects[$vn_table_num] = array(); } if (($vn_id = $this->get($vs_field)) > 0) { $va_subjects[$vn_table_num][] = $vn_id; } } } } if(is_array($va_subject_config['RELATED_TABLES'])) { if (!isset($o_db) || !$o_db) { $o_db = new Db(); $o_db->dieOnError(false); } foreach($va_subject_config['RELATED_TABLES'] as $vs_dest_table => $va_path_to_dest) { $t_dest = $this->_DATAMODEL->getTableInstance($vs_dest_table); if (!$t_dest) { continue; } $vn_dest_table_num = $t_dest->tableNum(); $vs_dest_primary_key = $t_dest->primaryKey(); $va_path_to_dest[] = $vs_dest_table; $vs_cur_table = $this->tableName(); $vs_sql = "SELECT ".$vs_dest_table.".".$vs_dest_primary_key." FROM ".$this->tableName()."\n"; foreach($va_path_to_dest as $vs_ltable) { $va_relations = $this->_DATAMODEL->getRelationships($vs_cur_table, $vs_ltable); $vs_sql .= "INNER JOIN $vs_ltable ON $vs_cur_table.".$va_relations[$vs_cur_table][$vs_ltable][0][0]." = $vs_ltable.".$va_relations[$vs_cur_table][$vs_ltable][0][1]."\n"; $vs_cur_table = $vs_ltable; } $vs_sql .= "WHERE ".$this->tableName().".".$this->primaryKey()." = ".$this->getPrimaryKey(); if ($qr_subjects = $o_db->query($vs_sql)) { if (!isset($va_subjects[$vn_dest_table_num]) || !is_array($va_subjects[$vn_dest_table_num])) { $va_subjects[$vn_dest_table_num] = array(); } while($qr_subjects->nextRow()) { if (($vn_id = $qr_subjects->get($vs_dest_primary_key)) > 0) { $va_subjects[$vn_dest_table_num][] = $vn_id; } } } else { print "<hr>Error in subject logging: "; print "<br>$vs_sql<hr>\n"; } } } } } if (!sizeof($va_subjects) && !$vb_log_changes_to_self) { return true; } if (!$this->opqs_change_log) { $o_db = $this->getDb(); $o_db->dieOnError(false); $vs_change_log_database = ''; if ($vs_change_log_database = $this->_CONFIG->get("change_log_database")) { $vs_change_log_database .= "."; } if (!($this->opqs_change_log = $o_db->prepare(" INSERT INTO ".$vs_change_log_database."ca_change_log ( log_datetime, user_id, unit_id, changetype, logged_table_num, logged_row_id ) VALUES (?, ?, ?, ?, ?, ?) "))) { // prepare failed - shouldn't happen return false; } if (!($this->opqs_change_log_snapshot = $o_db->prepare(" INSERT INTO ".$vs_change_log_database."ca_change_log_snapshots ( log_id, snapshot ) VALUES (?, ?) "))) { // prepare failed - shouldn't happen return false; } if (!($this->opqs_change_log_subjects = $o_db->prepare(" INSERT INTO ".$vs_change_log_database."ca_change_log_subjects ( log_id, subject_table_num, subject_row_id ) VALUES (?, ?, ?) "))) { // prepare failed - shouldn't happen return false; } } // get snapshot of changes made to record $va_snapshot = $this->getSnapshot(($ps_change_type === 'U') ? true : false); $vs_snapshot = caSerializeForDatabase($va_snapshot, true); if (!(($ps_change_type == 'U') && (!sizeof($va_snapshot)))) { // Create primary log entry $this->opqs_change_log->execute( time(), $pn_user_id, $vn_unit_id, $ps_change_type, $this->tableNum(), $vn_row_id ); $vn_log_id = $this->opqs_change_log->getLastInsertID(); $this->opqs_change_log_snapshot->execute( $vn_log_id, $vs_snapshot ); foreach($va_subjects as $vn_subject_table_num => $va_subject_ids) { foreach($va_subject_ids as $vn_subject_row_id) { $this->opqs_change_log_subjects->execute($vn_log_id, $vn_subject_table_num, $vn_subject_row_id); } } } } # -------------------------------------------------------------------------------------------- /** * Get change log for the current record represented by this BaseModel object, or for another specified row. * * @access public * @param int $pn_row_id Return change log for row with specified primary key id. If omitted currently loaded record is used. * @param array $pa_options Array of options. Valid options are: * range = optional range to restrict returned entries to. Should be array with 0th key set to start and 1st key set to end of range. Both values should be Unix timestamps. You can also use 'start' and 'end' as keys if desired. * limit = maximum number of entries returned. Omit or set to zero for no limit. [default=all] * forTable = if true only return changes made directly to the current table (ie. omit changes to related records that impact this record [default=false] * excludeUnitID = if set, log records with the specific unit_id are not returned [default=not set] * changeType = if set to I, U or D, will limit change log to inserts, updates or deletes respectively. If not set all types are returned. * @return array Change log data */ public function getChangeLog($pn_row_id=null, $pa_options=null) { $pa_datetime_range = (isset($pa_options['range']) && is_array($pa_options['range'])) ? $pa_options['range'] : null; $pn_max_num_entries_returned = (isset($pa_options['limit']) && (int)$pa_options['limit']) ? (int)$pa_options['limit'] : 0; $pb_for_table = (isset($pa_options['forTable'])) ? (bool)$pa_options['forTable'] : false; $ps_exclude_unit_id = (isset($pa_options['excludeUnitID']) && $pa_options['excludeUnitID']) ? $pa_options['excludeUnitID'] : null; $ps_change_type = (isset($pa_options['changeType']) && in_array($pa_options['changeType'], array('I', 'U', 'D'))) ? $pa_options['changeType'] : null; $vs_daterange_sql = ''; if ($pa_datetime_range) { $vn_start = $vn_end = null; if (isset($pa_datetime_range[0])) { $vn_start = (int)$pa_datetime_range[0]; } else { if (isset($pa_datetime_range['start'])) { $vn_start = (int)$pa_datetime_range['start']; } } if (isset($pa_datetime_range[1])) { $vn_end = (int)$pa_datetime_range[1]; } else { if (isset($pa_datetime_range['end'])) { $vn_end = (int)$pa_datetime_range['end']; } } if ($vn_start <= 0) { $vn_start = time() - 3600; } if (!$vn_end <= 0) { $vn_end = time(); } if ($vn_end < $vn_start) { $vn_end = $vn_start; } if (!$pn_row_id) { if (!($pn_row_id = $this->getPrimaryKey())) { return array(); } } $vs_daterange_sql = " AND (wcl.log_datetime > ? AND wcl.log_datetime < ?)"; } if (!$this->opqs_get_change_log) { $vs_change_log_database = ''; if ($vs_change_log_database = $this->_CONFIG->get("change_log_database")) { $vs_change_log_database .= "."; } $o_db = $this->getDb(); if ($pb_for_table) { if (!($this->opqs_get_change_log = $o_db->prepare(" SELECT DISTINCT wcl.log_id, wcl.log_datetime log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id, wclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname FROM ca_change_log wcl INNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id WHERE ( (wcl.logged_table_num = ".((int)$this->tableNum()).") AND ".(($ps_change_type) ? "(wcl.changetype = '".$ps_change_type."') AND " : "")." (wcl.logged_row_id = ?) ) {$vs_daterange_sql} ORDER BY log_datetime "))) { # should not happen return false; } } else { if (!($this->opqs_get_change_log = $o_db->prepare(" SELECT DISTINCT wcl.log_id, wcl.log_datetime log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id, wclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname FROM ca_change_log wcl INNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id WHERE ( (wcl.logged_table_num = ".((int)$this->tableNum()).") AND ".(($ps_change_type) ? "(wcl.changetype = '".$ps_change_type."') AND " : "")." (wcl.logged_row_id = ?) ) {$vs_daterange_sql} UNION SELECT DISTINCT wcl.log_id, wcl.log_datetime, wcl.user_id, wcl.changetype, wcl.logged_table_num, wcl.logged_row_id, wclsnap.snapshot, wcl.unit_id, wu.email, wu.fname, wu.lname FROM ca_change_log wcl INNER JOIN ca_change_log_snapshots AS wclsnap ON wclsnap.log_id = wcl.log_id LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id WHERE ( (wcls.subject_table_num = ".((int)$this->tableNum()).") AND ".(($ps_change_type) ? "(wcl.changetype = '".$ps_change_type."') AND " : "")." (wcls.subject_row_id = ?) ) {$vs_daterange_sql} ORDER BY log_datetime "))) { # should not happen return false; } } if ($pn_max_num_entries_returned > 0) { $this->opqs_get_change_log->setLimit($pn_max_num_entries_returned); } } // get directly logged records $va_log = array(); if ($pb_for_table) { $qr_log = $this->opqs_get_change_log->execute($vs_daterange_sql ? array((int)$pn_row_id, (int)$vn_start, (int)$vn_end) : array((int)$pn_row_id)); } else { $qr_log = $this->opqs_get_change_log->execute($vs_daterange_sql ? array((int)$pn_row_id, (int)$vn_start, (int)$vn_end, (int)$pn_row_id, (int)$vn_start, (int)$vn_end) : array((int)$pn_row_id, (int)$pn_row_id)); } while($qr_log->nextRow()) { if ($ps_exclude_unit_id && ($ps_exclude_unit_id == $qr_log->get('unit_id'))) { continue; } $va_log[] = $qr_log->getRow(); $va_log[sizeof($va_log)-1]['snapshot'] = caUnserializeForDatabase($va_log[sizeof($va_log)-1]['snapshot']); } return $va_log; } # -------------------------------------------------------------------------------------------- /** * Get list of users (containing username, user id, forename, last name and email adress) who changed something * in a) this record (if the parameter is omitted) or b) the whole table (if the parameter is set). * * @access public * @param bool $pb_for_table * @return array */ public function getChangeLogUsers($pb_for_table=false) { $o_db = $this->getDb(); if ($pb_for_table) { $qr_users = $o_db->query(" SELECT DISTINCT wu.user_id, wu.user_name, wu.fname, wu.lname, wu.email FROM ca_users wu INNER JOIN ca_change_log AS wcl ON wcl.user_id = wu.user_id LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id WHERE ((wcls.subject_table_num = ?) OR (wcl.logged_table_num = ?)) ORDER BY wu.lname, wu.fname ", $this->tableNum(), $this->tableNum()); } else { $qr_users = $o_db->query(" SELECT DISTINCT wu.user_id, wu.user_name, wu.fname, wu.lname, wu.email FROM ca_users wu INNER JOIN ca_change_log AS wcl ON wcl.user_id = wu.user_id LEFT JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id WHERE ((wcls.subject_table_num = ?) OR (wcl.logged_table_num = ?)) AND ((wcl.logged_row_id = ?) OR (wcls.subject_row_id = ?)) ORDER BY wu.lname, wu.fname ", $this->tableNum(), $this->tableNum(), $this->getPrimaryKey(), $this->getPrimaryKey()); } $va_users = array(); while($qr_users->nextRow()) { $vs_user_name = $qr_users->get('user_name'); $va_users[$vs_user_name] = array( 'user_name' => $vs_user_name, 'user_id' => $qr_users->get('user_id'), 'fname' => $qr_users->get('fname'), 'lname' => $qr_users->get('lname'), 'email' => $qr_users->get('email') ); } return $va_users; } # -------------------------------------------------------------------------------------------- /** * Returns information about the creation currently loaded row * * @param int $pn_row_id If set information is returned about the specified row instead of the currently loaded one. * @param array $pa_options Array of options. Supported options are: * timestampOnly = if set to true an integer Unix timestamp for the date/time of creation is returned. If false (default) then an array is returned with timestamp and user information about the creation. * @return mixed An array detailing the date/time and creator of the row. Array includes the user_id, fname, lname and email of the user who executed the change as well as an integer Unix-style timestamp. If the timestampOnly option is set then only the timestamp is returned. */ public function getCreationTimestamp($pn_row_id=null, $pa_options=null) { if (!($vn_row_id = $pn_row_id)) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } } $o_db = $this->getDb(); $qr_res = $o_db->query(" SELECT wcl.log_datetime, wu.user_id, wu.fname, wu.lname, wu.email FROM ca_change_log wcl LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id WHERE (wcl.logged_table_num = ?) AND (wcl.logged_row_id = ?) AND(wcl.changetype = 'I')", $this->tableNum(), $vn_row_id); if ($qr_res->nextRow()) { if (isset($pa_options['timestampOnly']) && $pa_options['timestampOnly']) { return $qr_res->get('log_datetime'); } return array( 'user_id' => $qr_res->get('user_id'), 'fname' => $qr_res->get('fname'), 'lname' => $qr_res->get('lname'), 'email' => $qr_res->get('email'), 'timestamp' => $qr_res->get('log_datetime') ); } return null; } # -------------------------------------------------------------------------------------------- /** * Returns information about the last change made to the currently loaded row * * @param int $pn_row_id If set information is returned about the specified row instead of the currently loaded one. * @param array $pa_options Array of options. Supported options are: * timestampOnly = if set to true an integer Unix timestamp for the last change is returned. If false (default) then an array is returned with timestamp and user information about the change. * @return mixed An array detailing the date/time and initiator of the last change. Array includes the user_id, fname, lname and email of the user who executed the change as well as an integer Unix-style timestamp. If the timestampOnly option is set then only the timestamp is returned. */ public function getLastChangeTimestamp($pn_row_id=null, $pa_options=null) { if (!($vn_row_id = $pn_row_id)) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } } $o_db = $this->getDb(); $qr_res = $o_db->query(" SELECT wcl.log_datetime, wu.user_id, wu.fname, wu.lname, wu.email FROM ca_change_log wcl LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id INNER JOIN ca_change_log_subjects AS wcls ON wcl.log_id = wcls.log_id WHERE (wcls.subject_table_num = ?) AND (wcls.subject_row_id = ?) AND (wcl.changetype IN ('I', 'U')) ORDER BY wcl.log_datetime DESC LIMIT 1", $this->tableNum(), $vn_row_id); $vn_last_change_timestamp = 0; $va_last_change_info = null; if ($qr_res->nextRow()) { $vn_last_change_timestamp = $qr_res->get('log_datetime'); $va_last_change_info = array( 'user_id' => $qr_res->get('user_id'), 'fname' => $qr_res->get('fname'), 'lname' => $qr_res->get('lname'), 'email' => $qr_res->get('email'), 'timestamp' => $qr_res->get('log_datetime') ); } $qr_res = $o_db->query(" SELECT wcl.log_datetime, wu.user_id, wu.fname, wu.lname, wu.email FROM ca_change_log wcl LEFT JOIN ca_users AS wu ON wcl.user_id = wu.user_id WHERE (wcl.logged_table_num = ?) AND (wcl.logged_row_id = ?) AND (wcl.changetype IN ('I', 'U')) ORDER BY wcl.log_datetime DESC LIMIT 1", $this->tableNum(), $vn_row_id); if ($qr_res->nextRow()) { if ($qr_res->get('log_datetime') > $vn_last_change_timestamp) { $vn_last_change_timestamp = $qr_res->get('log_datetime'); $va_last_change_info = array( 'user_id' => $qr_res->get('user_id'), 'fname' => $qr_res->get('fname'), 'lname' => $qr_res->get('lname'), 'email' => $qr_res->get('email'), 'timestamp' => $qr_res->get('log_datetime') ); } } if ($vn_last_change_timestamp > 0) { if (isset($pa_options['timestampOnly']) && $pa_options['timestampOnly']) { return $vn_last_change_timestamp; } return $va_last_change_info; } return null; } # -------------------------------------------------------------------------------------------- # --- Hierarchical functions # -------------------------------------------------------------------------------------------- /** * Are we dealing with a hierarchical structure in this table? * * @access public * @return bool */ public function isHierarchical() { return (!is_null($this->getProperty("HIERARCHY_TYPE"))) ? true : false; } # -------------------------------------------------------------------------------------------- /** * What type of hierarchical structure is used by this table? * * @access public * @return int (__CA_HIER_*__ constant) */ public function getHierarchyType() { return $this->getProperty("HIERARCHY_TYPE"); } # -------------------------------------------------------------------------------------------- /** * Fetches primary key of the hierarchy root. * DOES NOT CREATE ROOT - YOU HAVE TO DO THAT YOURSELF (this differs from previous versions of these libraries). * * @param int $pn_hierarchy_id optional, points to record in related table containing hierarchy description * @return int root id */ public function getHierarchyRootID($pn_hierarchy_id=null) { $vn_root_id = null; $o_db = $this->getDb(); switch($this->getHierarchyType()) { # ------------------------------------------------------------------ case __CA_HIER_TYPE_SIMPLE_MONO__: // For simple "table is one big hierarchy" setups all you need // to do is look for the row where parent_id is NULL $qr_res = $o_db->query(" SELECT ".$this->primaryKey()." FROM ".$this->tableName()." WHERE (".$this->getProperty('HIERARCHY_PARENT_ID_FLD')." IS NULL) "); if ($qr_res->nextRow()) { $vn_root_id = $qr_res->get($this->primaryKey()); } break; # ------------------------------------------------------------------ case __CA_HIER_TYPE_MULTI_MONO__: // For tables that house multiple hierarchies defined in a second table // you need to look for the row where parent_id IS NULL and hierarchy_id = the value // passed in $pn_hierarchy_id if (!$pn_hierarchy_id) { // if hierarchy_id is not explicitly set use the value in the currently loaded row $pn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_PARENT_ID_FLD')); } $qr_res = $o_db->query(" SELECT ".$this->primaryKey()." FROM ".$this->tableName()." WHERE (".$this->getProperty('HIERARCHY_PARENT_ID_FLD')." IS NULL) AND (".$this->getProperty('HIERARCHY_ID_FLD')." = ?) ", (int)$pn_hierarchy_id); if ($qr_res->nextRow()) { $vn_root_id = $qr_res->get($this->primaryKey()); } break; # ------------------------------------------------------------------ case __CA_HIER_TYPE_ADHOC_MONO__: // For ad-hoc hierarchies you just return the hierarchy_id value if (!$pn_hierarchy_id) { // if hierarchy_id is not explicitly set use the value in the currently loaded row $pn_hierarchy_id = $this->get($this->getProperty('HIERARCHY_ID_FLD')); } $vn_root_id = $pn_hierarchy_id; break; # ------------------------------------------------------------------ case __CA_HIER_TYPE_MULTI_POLY__: // TODO: implement this break; # ------------------------------------------------------------------ default: die("Invalid hierarchy type: ".$this->getHierarchyType()); break; # ------------------------------------------------------------------ } return $vn_root_id; } # -------------------------------------------------------------------------------------------- /** * Fetch a DbResult representation of the whole hierarchy * * @access public * @param int $pn_id optional, id of record to be treated as root * @param array $pa_options * returnDeleted = return deleted records in list (def. false) * additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported * * @return DbResult */ public function &getHierarchy($pn_id=null, $pa_options=null) { if (!is_array($pa_options)) { $pa_options = array(); } $vs_table_name = $this->tableName(); if ($this->isHierarchical()) { $vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD"); $vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD"); $vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD"); $vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD"); $vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE"); if (!$pn_id) { if (!($pn_id = $this->getHierarchyRootID($this->get($vs_hier_id_fld)))) { return null; } } $vn_hierarchy_id = $this->get($vs_hier_id_fld); $vs_hier_id_sql = ""; if ($vn_hierarchy_id) { // TODO: verify hierarchy_id exists $vs_hier_id_sql = " AND (".$vs_hier_id_fld." = ".$vn_hierarchy_id.")"; } $o_db = $this->getDb(); $qr_root = $o_db->query(" SELECT $vs_hier_left_fld, $vs_hier_right_fld ".(($this->hasField($vs_hier_id_fld)) ? ", $vs_hier_id_fld" : "")." FROM ".$this->tableName()." WHERE (".$this->primaryKey()." = ?) ", intval($pn_id)); if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { if ($qr_root->nextRow()) { $va_count = array(); if (($this->hasField($vs_hier_id_fld)) && (!($vn_hierarchy_id = $this->get($vs_hier_id_fld))) && (!($vn_hierarchy_id = $qr_root->get($vs_hier_id_fld)))) { $this->postError(2030, _t("Hierarchy ID must be specified"), "Table->getHierarchy()"); return false; } $vs_table_name = $this->tableName(); $vs_hier_id_sql = ""; if ($vn_hierarchy_id) { $vs_hier_id_sql = " AND ({$vs_table_name}.{$vs_hier_id_fld} = {$vn_hierarchy_id})"; } $va_sql_joins = array(); if (isset($pa_options['additionalTableToJoin']) && ($pa_options['additionalTableToJoin'])){ $ps_additional_table_to_join = $pa_options['additionalTableToJoin']; // what kind of join are we doing for the additional table? LEFT or INNER? (default=INNER) $ps_additional_table_join_type = 'INNER'; if (isset($pa_options['additionalTableJoinType']) && ($pa_options['additionalTableJoinType'] === 'LEFT')) { $ps_additional_table_join_type = 'LEFT'; } if (is_array($va_rel = $this->getAppDatamodel()->getOneToManyRelations($this->tableName(), $ps_additional_table_to_join))) { // one-many rel $va_sql_joins[] = "{$ps_additional_table_join_type} JOIN {$ps_additional_table_to_join} ON ".$this->tableName().'.'.$va_rel['one_table_field']." = {$ps_additional_table_to_join}.".$va_rel['many_table_field']; } else { // TODO: handle many-many cases } // are there any SQL WHERE criteria for the additional table? $va_additional_table_wheres = null; if (isset($pa_options['additionalTableWheres']) && is_array($pa_options['additionalTableWheres'])) { $va_additional_table_wheres = $pa_options['additionalTableWheres']; } $vs_additional_wheres = ''; if (is_array($va_additional_table_wheres) && (sizeof($va_additional_table_wheres) > 0)) { $vs_additional_wheres = ' AND ('.join(' AND ', $va_additional_table_wheres).') '; } } $vs_deleted_sql = ''; if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) { $vs_deleted_sql = " AND ({$vs_table_name}.deleted = 0)"; } $vs_sql_joins = join("\n", $va_sql_joins); $vs_sql = " SELECT * FROM {$vs_table_name} {$vs_sql_joins} WHERE ({$vs_table_name}.{$vs_hier_left_fld} BETWEEN ".$qr_root->get($vs_hier_left_fld)." AND ".$qr_root->get($vs_hier_right_fld).") {$vs_hier_id_sql} {$vs_deleted_sql} {$vs_additional_wheres} ORDER BY {$vs_table_name}.{$vs_hier_left_fld} "; //print $vs_sql; $qr_hier = $o_db->query($vs_sql); if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { return $qr_hier; } } else { return null; } } } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Get the hierarchy in list form * * @param int $pn_id * @param array $pa_options * * additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported * idsOnly: if true, only the primary key id values of the chidlren records are returned * returnDeleted = return deleted records in list (def. false) * maxLevels = * dontIncludeRoot = * * @return array */ public function &getHierarchyAsList($pn_id=null, $pa_options=null) { $pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false; $pn_max_levels = isset($pa_options['maxLevels']) ? intval($pa_options['maxLevels']) : null; $ps_additional_table_to_join = isset($pa_options['additionalTableToJoin']) ? $pa_options['additionalTableToJoin'] : null; $pb_dont_include_root = (isset($pa_options['dontIncludeRoot']) && $pa_options['dontIncludeRoot']) ? true : false; if ($qr_hier = $this->getHierarchy($pn_id, $pa_options)) { $vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD"); $va_indent_stack = array(); $va_hier = array(); $vn_cur_level = -1; $va_omit_stack = array(); $vn_root_id = $pn_id; while($qr_hier->nextRow()) { $vn_row_id = $qr_hier->get($this->primaryKey()); if (is_null($vn_root_id)) { $vn_root_id = $vn_row_id; } if ($pb_dont_include_root && ($vn_row_id == $vn_root_id)) { continue; } // skip root if desired $vn_r = $qr_hier->get($vs_hier_right_fld); $vn_c = sizeof($va_indent_stack); if($vn_c > 0) { while (($vn_c) && ($va_indent_stack[$vn_c - 1] <= $vn_r)){ array_pop($va_indent_stack); $vn_c = sizeof($va_indent_stack); } } if($vn_cur_level != sizeof($va_indent_stack)) { if ($vn_cur_level > sizeof($va_indent_stack)) { $va_omit_stack = array(); } $vn_cur_level = intval(sizeof($va_indent_stack)); } if (is_null($pn_max_levels) || ($vn_cur_level < $pn_max_levels)) { $va_field_values = $qr_hier->getRow(); foreach($va_field_values as $vs_key => $vs_val) { $va_field_values[$vs_key] = stripSlashes($vs_val); } if ($pb_ids_only) { $va_hier[] = $vn_row_id; } else { $va_node = array( "NODE" => $va_field_values, "LEVEL" => $vn_cur_level ); $va_hier[] = $va_node; } } $va_indent_stack[] = $vn_r; } return $va_hier; } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Returns a list of primary keys comprising all child rows * * @param int $pn_id node to start from - default is the hierarchy root * @return array id list */ public function &getHierarchyIDs($pn_id=null, $pa_options=null) { if ($qr_hier = $this->getHierarchy($pn_id, $pa_options)) { $va_ids = array(); $vs_pk = $this->primaryKey(); while($qr_hier->nextRow()) { $va_ids[] = $qr_hier->get($vs_pk); } return $va_ids; } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Get *direct* child records for currently loaded record or one specified by $pn_id * Note that this only returns direct children, *NOT* children of children and further descendents * If you need to get a chunk of the hierarchy use getHierarchy() * * @access public * @param int optional, primary key value of a record. * Use this if you want to know the children of a record different than $this * @param array, optional associative array of options. Valid keys for the array are: * additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported * returnChildCounts: if true, the number of children under each returned child is calculated and returned in the result set under the column name 'child_count'. Note that this count is always at least 1, even if there are no children. The 'has_children' column will be null if the row has, in fact no children, or non-null if it does have children. You should check 'has_children' before using 'child_count' and disregard 'child_count' if 'has_children' is null. * returnDeleted = return deleted records in list (def. false) * @return DbResult */ public function &getHierarchyChildrenAsQuery($pn_id=null, $pa_options=null) { $o_db = $this->getDb(); $vs_table_name = $this->tableName(); // return counts of child records for each child found? $pb_return_child_counts = isset($pa_options['returnChildCounts']) ? true : false; $va_additional_table_wheres = array(); $va_additional_table_select_fields = array(); // additional table to join into query? $ps_additional_table_to_join = isset($pa_options['additionalTableToJoin']) ? $pa_options['additionalTableToJoin'] : null; if ($ps_additional_table_to_join) { // what kind of join are we doing for the additional table? LEFT or INNER? (default=INNER) $ps_additional_table_join_type = 'INNER'; if (isset($pa_options['additionalTableJoinType']) && ($pa_options['additionalTableJoinType'] === 'LEFT')) { $ps_additional_table_join_type = 'LEFT'; } // what fields from the additional table are we going to return? if (isset($pa_options['additionalTableSelectFields']) && is_array($pa_options['additionalTableSelectFields'])) { foreach($pa_options['additionalTableSelectFields'] as $vs_fld) { $va_additional_table_select_fields[] = "{$ps_additional_table_to_join}.{$vs_fld}"; } } // are there any SQL WHERE criteria for the additional table? if (isset($pa_options['additionalTableWheres']) && is_array($pa_options['additionalTableWheres'])) { $va_additional_table_wheres = $pa_options['additionalTableWheres']; } } if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) { $va_additional_table_wheres[] = "({$vs_table_name}.deleted = 0)"; } if ($this->isHierarchical()) { if (!$pn_id) { if (!($pn_id = $this->getPrimaryKey())) { return null; } } $va_sql_joins = array(); $vs_additional_table_to_join_group_by = ''; if ($ps_additional_table_to_join){ if (is_array($va_rel = $this->getAppDatamodel()->getOneToManyRelations($this->tableName(), $ps_additional_table_to_join))) { // one-many rel $va_sql_joins[] = $ps_additional_table_join_type." JOIN {$ps_additional_table_to_join} ON ".$this->tableName().'.'.$va_rel['one_table_field']." = {$ps_additional_table_to_join}.".$va_rel['many_table_field']; } else { // TODO: handle many-many cases } $t_additional_table_to_join = $this->_DATAMODEL->getTableInstance($ps_additional_table_to_join); $vs_additional_table_to_join_group_by = ', '.$ps_additional_table_to_join.'.'.$t_additional_table_to_join->primaryKey(); } $vs_sql_joins = join("\n", $va_sql_joins); $vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD"); if ($vs_rank_fld = $this->getProperty('RANK')) { $vs_order_by = $this->tableName().'.'.$vs_rank_fld; } else { $vs_order_by = $this->tableName().".".$this->primaryKey(); } if ($pb_return_child_counts) { $qr_hier = $o_db->query(" SELECT ".$this->tableName().".* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '').", count(*) child_count, p2.".$this->primaryKey()." has_children FROM ".$this->tableName()." {$vs_sql_joins} LEFT JOIN ".$this->tableName()." AS p2 ON p2.".$vs_hier_parent_id_fld." = ".$this->tableName().".".$this->primaryKey()." WHERE (".$this->tableName().".{$vs_hier_parent_id_fld} = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')." GROUP BY ".$this->tableName().".".$this->primaryKey()." {$vs_additional_table_to_join_group_by} ORDER BY ".$vs_order_by." ", $pn_id); } else { $qr_hier = $o_db->query(" SELECT ".$this->tableName().".* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '')." FROM ".$this->tableName()." {$vs_sql_joins} WHERE (".$this->tableName().".{$vs_hier_parent_id_fld} = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')." ORDER BY ".$vs_order_by." ", $pn_id); } if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { return $qr_hier; } } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Get *direct* child records for currently loaded record or one specified by $pn_id * Note that this only returns direct children, *NOT* children of children and further descendents * If you need to get a chunk of the hierarchy use getHierarchy(). * * Results are returned as an array with either associative array values for each child record, or if the * idsOnly option is set, then the primary key values. * * @access public * @param int optional, primary key value of a record. * Use this if you want to know the children of a record different than $this * @param array, optional associative array of options. Valid keys for the array are: * additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported * returnChildCounts: if true, the number of children under each returned child is calculated and returned in the result set under the column name 'child_count'. Note that this count is always at least 1, even if there are no children. The 'has_children' column will be null if the row has, in fact no children, or non-null if it does have children. You should check 'has_children' before using 'child_count' and disregard 'child_count' if 'has_children' is null. * idsOnly: if true, only the primary key id values of the chidlren records are returned * returnDeleted = return deleted records in list (def. false) * @return array */ public function getHierarchyChildren($pn_id=null, $pa_options=null) { $pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false; if (!$pn_id) { $pn_id = $this->getPrimaryKey(); } if (!$pn_id) { return null; } $qr_children = $this->getHierarchyChildrenAsQuery($pn_id, $pa_options); $va_children = array(); $vs_pk = $this->primaryKey(); while($qr_children->nextRow()) { if ($pb_ids_only) { $va_row = $qr_children->getRow(); $va_children[] = $va_row[$vs_pk]; } else { $va_children[] = $qr_children->getRow(); } } return $va_children; } # -------------------------------------------------------------------------------------------- /** * Get "siblings" records - records with the same parent - as the currently loaded record * or the record with its primary key = $pn_id * * Results are returned as an array with either associative array values for each sibling record, or if the * idsOnly option is set, then the primary key values. * * @access public * @param int optional, primary key value of a record. * Use this if you want to know the siblings of a record different than $this * @param array, optional associative array of options. Valid keys for the array are: * additionalTableToJoin: name of table to join to hierarchical table (and return fields from); only fields related many-to-one are currently supported * returnChildCounts: if true, the number of children under each returned sibling is calculated and returned in the result set under the column name 'sibling_count'.d * idsOnly: if true, only the primary key id values of the chidlren records are returned * returnDeleted = return deleted records in list (def. false) * @return array */ public function &getHierarchySiblings($pn_id=null, $pa_options=null) { $pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false; if (!$pn_id) { $pn_id = $this->getPrimaryKey(); } if (!$pn_id) { return null; } $vs_table_name = $this->tableName(); $va_additional_table_wheres = array($this->primaryKey()." = ?"); if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) { $va_additional_table_wheres[] = "({$vs_table_name}.deleted = 0)"; } // convert id into parent_id - get the children of the parent is equivalent to getting the siblings for the id if ($qr_parent = $this->getDb()->query(" SELECT ".$this->getProperty('HIERARCHY_PARENT_ID_FLD')." FROM ".$this->tableName()." WHERE ".join(' AND ', $va_additional_table_wheres), (int)$pn_id)) { if ($qr_parent->nextRow()) { $pn_id = $qr_parent->get($this->getProperty('HIERARCHY_PARENT_ID_FLD')); } else { $this->postError(250, _t('Could not get parent_id to load siblings by: %1', join(';', $this->getDb()->getErrors())), 'BaseModel->getHierarchySiblings'); return false; } } else { $this->postError(250, _t('Could not get hierarchy siblings: %1', join(';', $this->getDb()->getErrors())), 'BaseModel->getHierarchySiblings'); return false; } if (!$pn_id) { return array(); } $qr_children = $this->getHierarchyChildrenAsQuery($pn_id, $pa_options); $va_siblings = array(); $vs_pk = $this->primaryKey(); while($qr_children->nextRow()) { if ($pb_ids_only) { $va_row = $qr_children->getRow(); $va_siblings[] = $va_row[$vs_pk]; } else { $va_siblings[] = $qr_children->getRow(); } } return $va_siblings; } # -------------------------------------------------------------------------------------------- /** * Get hierarchy ancestors * * @access public * @param int optional, primary key value of a record. * Use this if you want to know the ancestors of a record different than $this * @param array optional, options * idsOnly = just return the ids of the ancestors (def. false) * includeSelf = include this record (def. false) * additionalTableToJoin = name of additonal table data to return * returnDeleted = return deleted records in list (def. false) * @return array */ public function &getHierarchyAncestors($pn_id=null, $pa_options=null) { $pb_include_self = (isset($pa_options['includeSelf']) && $pa_options['includeSelf']) ? true : false; $pb_ids_only = (isset($pa_options['idsOnly']) && $pa_options['idsOnly']) ? true : false; $vs_table_name = $this->tableName(); $va_additional_table_select_fields = array(); $va_additional_table_wheres = array(); // additional table to join into query? $ps_additional_table_to_join = isset($pa_options['additionalTableToJoin']) ? $pa_options['additionalTableToJoin'] : null; if ($ps_additional_table_to_join) { // what kind of join are we doing for the additional table? LEFT or INNER? (default=INNER) $ps_additional_table_join_type = 'INNER'; if (isset($pa_options['additionalTableJoinType']) && ($pa_options['additionalTableJoinType'] === 'LEFT')) { $ps_additional_table_join_type = 'LEFT'; } // what fields from the additional table are we going to return? if (isset($pa_options['additionalTableSelectFields']) && is_array($pa_options['additionalTableSelectFields'])) { foreach($pa_options['additionalTableSelectFields'] as $vs_fld) { $va_additional_table_select_fields[] = "{$ps_additional_table_to_join}.{$vs_fld}"; } } // are there any SQL WHERE criteria for the additional table? if (isset($pa_options['additionalTableWheres']) && is_array($pa_options['additionalTableWheres'])) { $va_additional_table_wheres = $pa_options['additionalTableWheres']; } } if ($this->hasField('deleted') && (!isset($pa_options['returnDeleted']) || (!$pa_options['returnDeleted']))) { $va_additional_table_wheres[] = "({$vs_table_name}.deleted = 0)"; } if ($this->isHierarchical()) { if (!$pn_id) { if (!($pn_id = $this->getPrimaryKey())) { return null; } } $vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD"); $vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD"); $vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD"); $vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE"); $vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD"); $va_sql_joins = array(); if ($ps_additional_table_to_join){ $va_path = $this->getAppDatamodel()->getPath($vs_table_name, $ps_additional_table_to_join); switch(sizeof($va_path)) { case 2: $va_rels = $this->getAppDatamodel()->getRelationships($vs_table_name, $ps_additional_table_to_join); $va_sql_joins[] = $ps_additional_table_join_type." JOIN {$ps_additional_table_to_join} ON ".$vs_table_name.'.'.$va_rels[$ps_additional_table_to_join][$vs_table_name][0][1]." = {$ps_additional_table_to_join}.".$va_rels[$ps_additional_table_to_join][$vs_table_name][0][0]; break; case 3: // TODO: handle many-many cases break; } } $vs_sql_joins = join("\n", $va_sql_joins); $o_db = $this->getDb(); $qr_root = $o_db->query(" SELECT {$vs_table_name}.* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '')." FROM {$vs_table_name} {$vs_sql_joins} WHERE ({$vs_table_name}.".$this->primaryKey()." = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')." ", intval($pn_id)); if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { if ($qr_root->numRows()) { $va_ancestors = array(); $vn_parent_id = null; $vn_level = 0; if ($pb_include_self) { while ($qr_root->nextRow()) { if (!$vn_parent_id) { $vn_parent_id = $qr_root->get($vs_hier_parent_id_fld); } if ($pb_ids_only) { $va_ancestors[] = $qr_root->get($this->primaryKey()); } else { $va_ancestors[] = array( "NODE" => $qr_root->getRow(), "LEVEL" => $vn_level ); } $vn_level++; } } else { $qr_root->nextRow(); $vn_parent_id = $qr_root->get($vs_hier_parent_id_fld); } if($vn_parent_id) { do { $vs_sql = " SELECT {$vs_table_name}.* ".(sizeof($va_additional_table_select_fields) ? ', '.join(', ', $va_additional_table_select_fields) : '')." FROM {$vs_table_name} {$vs_sql_joins} WHERE ({$vs_table_name}.".$this->primaryKey()." = ?) ".((sizeof($va_additional_table_wheres) > 0) ? ' AND '.join(' AND ', $va_additional_table_wheres) : '')." "; $qr_hier = $o_db->query($vs_sql, $vn_parent_id); $vn_parent_id = null; while ($qr_hier->nextRow()) { if (!$vn_parent_id) { $vn_parent_id = $qr_hier->get($vs_hier_parent_id_fld); } if ($pb_ids_only) { $va_ancestors[] = $qr_hier->get($this->primaryKey()); } else { $va_ancestors[] = array( "NODE" => $qr_hier->getRow(), "LEVEL" => $vn_level ); } } $vn_level++; } while($vn_parent_id); return $va_ancestors; } else { return $va_ancestors; } } else { return null; } } } else { return null; } } # -------------------------------------------------------------------------------------------- public function rebuildAllHierarchicalIndexes() { $vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD"); $vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD"); $vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD"); $vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE"); $vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD"); if (!$vs_hier_id_fld) { return false; } $o_db = $this->getDb(); $qr_hier_ids = $o_db->query(" SELECT DISTINCT ".$vs_hier_id_fld." FROM ".$this->tableName()." "); while($qr_hier_ids->nextRow()) { $this->rebuildHierarchicalIndex($qr_hier_ids->get($vs_hier_id_fld)); } return true; } # -------------------------------------------------------------------------------------------- public function rebuildHierarchicalIndex($pn_hierarchy_id=null) { if ($this->isHierarchical()) { $vb_we_set_transaction = false; if (!$this->inTransaction()) { $this->setTransaction(new Transaction($this->getDb())); $vb_we_set_transaction = true; } if ($vn_root_id = $this->getHierarchyRootID($pn_hierarchy_id)) { $this->_rebuildHierarchicalIndex($vn_root_id, 1); if ($vb_we_set_transaction) { $this->removeTransaction(true);} return true; } else { if ($vb_we_set_transaction) { $this->removeTransaction(false);} return null; } } else { return null; } } # -------------------------------------------------------------------------------------------- private function _rebuildHierarchicalIndex($pn_parent_id, $pn_hier_left) { $vs_hier_parent_id_fld = $this->getProperty("HIERARCHY_PARENT_ID_FLD"); $vs_hier_left_fld = $this->getProperty("HIERARCHY_LEFT_INDEX_FLD"); $vs_hier_right_fld = $this->getProperty("HIERARCHY_RIGHT_INDEX_FLD"); $vs_hier_id_fld = $this->getProperty("HIERARCHY_ID_FLD"); $vs_hier_id_table = $this->getProperty("HIERARCHY_DEFINITION_TABLE"); $vn_hier_right = $pn_hier_left + 100; $vs_pk = $this->primaryKey(); $o_db = $this->getDb(); if (is_null($pn_parent_id)) { $vs_sql = " SELECT * FROM ".$this->tableName()." WHERE (".$vs_hier_parent_id_fld." IS NULL) "; } else { $vs_sql = " SELECT * FROM ".$this->tableName()." WHERE (".$vs_hier_parent_id_fld." = ".intval($pn_parent_id).") "; } $qr_level = $o_db->query($vs_sql); if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { while($qr_level->nextRow()) { $vn_hier_right = $this->_rebuildHierarchicalIndex($qr_level->get($vs_pk), $vn_hier_right); } $qr_up = $o_db->query(" UPDATE ".$this->tableName()." SET ".$vs_hier_left_fld." = ".intval($pn_hier_left).", ".$vs_hier_right_fld." = ".intval($vn_hier_right)." WHERE (".$vs_pk." = ?) ", intval($pn_parent_id)); if ($o_db->numErrors()) { $this->errors = array_merge($this->errors, $o_db->errors()); return null; } else { return $vn_hier_right + 100; } } } # -------------------------------------------------------------------------------------------- /** * HTML Form element generation * Optional name parameter allows you to generate a form element for a field but give it a * name different from the field name * * @param string $ps_field field name * @param string $ps_format field format * @param array $pa_options additional options * TODO: document them. */ public function htmlFormElement($ps_field, $ps_format=null, $pa_options=null) { $o_db = $this->getDb(); // init options if (!is_array($pa_options)) { $pa_options = array(); } foreach (array( 'display_form_field_tips', 'classname', 'maxOptionLength', 'textAreaTagName', 'display_use_count', 'display_omit_items__with_zero_count', 'display_use_count_filters', 'display_use_count_filters', 'selection', 'name', 'value', 'dont_show_null_value', 'size', 'multiple', 'show_text_field_for_vars', 'nullOption', 'empty_message', 'displayMessageForFieldValues', 'DISPLAY_FIELD', 'WHERE', 'select_item_text', 'hide_select_if_only_one_option', 'field_errors', 'display_form_field_tips', 'form_name', 'no_tooltips', 'tooltip_namespace', 'extraLabelText', 'width', 'height', 'label', 'list_code', 'hide_select_if_no_options', 'id', 'lookup_url', 'progress_indicator', 'error_icon', 'maxPixelWidth', 'displayMediaVersion', 'FIELD_TYPE', 'DISPLAY_TYPE', 'choiceList', 'readonly' ) as $vs_key) { if(!isset($pa_options[$vs_key])) { $pa_options[$vs_key] = null; } } $va_attr = $this->getFieldInfo($ps_field); foreach (array( 'DISPLAY_WIDTH', 'DISPLAY_USE_COUNT', 'DISPLAY_SHOW_COUNT', 'DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT', 'DISPLAY_TYPE', 'IS_NULL', 'DEFAULT_ON_NULL', 'DEFAULT', 'LIST_MULTIPLE_DELIMITER', 'FIELD_TYPE', 'LIST_CODE', 'DISPLAY_FIELD', 'WHERE', 'DISPLAY_WHERE', 'DISPLAY_ORDERBY', 'LIST', 'BOUNDS_CHOICE_LIST', 'BOUNDS_LENGTH', 'DISPLAY_DESCRIPTION', 'LABEL', 'DESCRIPTION', 'SUB_LABEL', 'SUB_DESCRIPTION', 'MAX_PIXEL_WIDTH' ) as $vs_key) { if(!isset($va_attr[$vs_key])) { $va_attr[$vs_key] = null; } } if (isset($pa_options['FIELD_TYPE'])) { $va_attr['FIELD_TYPE'] = $pa_options['FIELD_TYPE']; } if (isset($pa_options['DISPLAY_TYPE'])) { $va_attr['DISPLAY_TYPE'] = $pa_options['DISPLAY_TYPE']; } $vn_display_width = (isset($pa_options['width']) && ($pa_options['width'] > 0)) ? $pa_options['width'] : $va_attr["DISPLAY_WIDTH"]; $vn_display_height = (isset($pa_options['height']) && ($pa_options['height'] > 0)) ? $pa_options['height'] : $va_attr["DISPLAY_HEIGHT"]; $va_parsed_width = caParseFormElementDimension($vn_display_width); $va_parsed_height = caParseFormElementDimension($vn_display_height); $va_dim_styles = array(); if ($va_parsed_width['type'] == 'pixels') { $va_dim_styles[] = "width: ".$va_parsed_width['dimension']."px;"; } if ($va_parsed_height['type'] == 'pixels') { $va_dim_styles[] = "height: ".$va_parsed_height['dimension']."px;"; } if ($vn_max_pixel_width) { $va_dim_styles[] = "max-width: {$vn_max_pixel_width}px;"; } $vs_dim_style = trim(join(" ", $va_dim_styles)); $vs_field_label = (isset($pa_options['label']) && (strlen($pa_options['label']) > 0)) ? $pa_options['label'] : $va_attr["LABEL"]; $vs_errors = ''; // TODO: PULL THIS FROM A CONFIG FILE $pa_options["display_form_field_tips"] = true; if (isset($pa_options['classname'])) { $vs_css_class_attr = ' class="'.$pa_options['classname'].'" '; } else { $vs_css_class_attr = ''; } if (!isset($pa_options['id'])) { $pa_options['id'] = $pa_options['name']; } if (!isset($pa_options['id'])) { $pa_options['id'] = $ps_field; } if (!isset($pa_options['maxPixelWidth']) || ((int)$pa_options['maxPixelWidth'] <= 0)) { $vn_max_pixel_width = $va_attr['MAX_PIXEL_WIDTH']; } else { $vn_max_pixel_width = (int)$pa_options['maxPixelWidth']; } if ($vn_max_pixel_width <= 0) { $vn_max_pixel_width = null; } if (!isset($pa_options["maxOptionLength"]) && isset($vn_display_width)) { $pa_options["maxOptionLength"] = isset($vn_display_width) ? $vn_display_width : null; } $vs_text_area_tag_name = 'textarea'; if (isset($pa_options["textAreaTagName"]) && $pa_options['textAreaTagName']) { $vs_text_area_tag_name = isset($pa_options['textAreaTagName']) ? $pa_options['textAreaTagName'] : null; } if (!isset($va_attr["DISPLAY_USE_COUNT"]) || !($vs_display_use_count = $va_attr["DISPLAY_USE_COUNT"])) { $vs_display_use_count = isset($pa_options["display_use_count"]) ? $pa_options["display_use_count"] : null; } if (!isset($va_attr["DISPLAY_SHOW_COUNT"]) || !($vb_display_show_count = (boolean)$va_attr["DISPLAY_SHOW_COUNT"])) { $vb_display_show_count = isset($pa_options["display_show_count"]) ? (boolean)$pa_options["display_show_count"] : null; } if (!isset($va_attr["DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT"]) || !($vb_display_omit_items__with_zero_count = (boolean)$va_attr["DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT"])) { $vb_display_omit_items__with_zero_count = isset($pa_options["display_omit_items__with_zero_count"]) ? (boolean)$pa_options["display_omit_items__with_zero_count"] : null; } if (!isset($va_attr["DISPLAY_OMIT_ITEMS_WITH_ZERO_COUNT"]) || !($va_display_use_count_filters = $va_attr["DISPLAY_USE_COUNT_FILTERS"])) { $va_display_use_count_filters = isset($pa_options["display_use_count_filters"]) ? $pa_options["display_use_count_filters"] : null; } if (!isset($va_display_use_count_filters) || !is_array($va_display_use_count_filters)) { $va_display_use_count_filters = null; } if (isset($pa_options["selection"]) && is_array($pa_options["selection"])) { $va_selection = isset($pa_options["selection"]) ? $pa_options["selection"] : null; } else { $va_selection = array(); } if (isset($pa_options["choiceList"]) && is_array($pa_options["choiceList"])) { $va_attr["BOUNDS_CHOICE_LIST"] = $pa_options["choiceList"]; } $vs_element = $vs_subelement = ""; if ($va_attr) { # --- Skip omitted fields completely if ($va_attr["DISPLAY_TYPE"] == DT_OMIT) { return ""; } if (!isset($pa_options["name"]) || !$pa_options["name"]) { $pa_options["name"] = htmlspecialchars($ps_field, ENT_QUOTES, 'UTF-8'); } $va_js = array(); $va_handlers = array("onclick", "onchange", "onkeypress", "onkeydown", "onkeyup"); foreach($va_handlers as $vs_handler) { if (isset($pa_options[$vs_handler]) && $pa_options[$vs_handler]) { $va_js[] = "$vs_handler='".($pa_options[$vs_handler])."'"; } } $vs_js = join(" ", $va_js); if (!isset($pa_options["value"])) { // allow field value to be overriden with value from options array $vm_field_value = $this->get($ps_field, $pa_options); } else { $vm_field_value = $pa_options["value"]; } $vm_raw_field_value = $vm_field_value; $vb_is_null = isset($va_attr["IS_NULL"]) ? $va_attr["IS_NULL"] : false; if (isset($pa_options['dont_show_null_value']) && $pa_options['dont_show_null_value']) { $vb_is_null = false; } if ( (!is_array($vm_field_value) && (strlen($vm_field_value) == 0)) && ( (!isset($vb_is_null) || (!$vb_is_null)) || ((isset($va_attr["DEFAULT_ON_NULL"]) ? $va_attr["DEFAULT_ON_NULL"] : 0)) ) ) { $vm_field_value = isset($va_attr["DEFAULT"]) ? $va_attr["DEFAULT"] : ""; } # --- Return hidden fields if ($va_attr["DISPLAY_TYPE"] == DT_HIDDEN) { return '<input type="hidden" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value).'"/>'; } if (isset($pa_options["size"]) && ($pa_options["size"] > 0)) { $ps_size = " size='".$pa_options["size"]."'"; } else{ if ((($va_attr["DISPLAY_TYPE"] == DT_LIST_MULTIPLE) || ($va_attr["DISPLAY_TYPE"] == DT_LIST)) && ($vn_display_height > 1)) { $ps_size = " size='".$vn_display_height."'"; } else { $ps_size = ''; } } $vs_multiple_name_extension = ''; if ($vs_is_multiple = ((isset($pa_options["multiple"]) && $pa_options["multiple"]) || ($va_attr["DISPLAY_TYPE"] == DT_LIST_MULTIPLE) ? "multiple='1'" : "")) { $vs_multiple_name_extension = '[]'; if (!($vs_list_multiple_delimiter = $va_attr['LIST_MULTIPLE_DELIMITER'])) { $vs_list_multiple_delimiter = ';'; } $va_selection = array_merge($va_selection, explode($vs_list_multiple_delimiter, $vm_field_value)); } # --- Return form element switch($va_attr["FIELD_TYPE"]) { # ---------------------------- case(FT_NUMBER): case(FT_TEXT): case(FT_VARS): if ($va_attr["FIELD_TYPE"] == FT_VARS) { if (!$pa_options['show_text_field_for_vars']) { break; } if (!is_string($vm_field_value) && !is_numeric($vm_field_value)) { $vm_value = ''; } } if ($va_attr['DISPLAY_TYPE'] == DT_COUNTRY_LIST) { $vs_element = caHTMLSelect($ps_field, caGetCountryList(), array('id' => $ps_field), array('value' => $vm_field_value)); if ($va_attr['STATEPROV_FIELD']) { $vs_element .="<script type='text/javascript'>\n"; $vs_element .= "var caStatesByCountryList = ".json_encode(caGetStateList()).";\n"; $vs_element .= " jQuery('#{$ps_field}').click({countryID: '{$ps_field}', stateProvID: '".$va_attr['STATEPROV_FIELD']."', value: '".addslashes($this->get($va_attr['STATEPROV_FIELD']))."', statesByCountryList: caStatesByCountryList}, caUI.utils.updateStateProvinceForCountry); jQuery(document).ready(function() { caUI.utils.updateStateProvinceForCountry({data: {countryID: '{$ps_field}', stateProvID: '".$va_attr['STATEPROV_FIELD']."', value: '".addslashes($this->get($va_attr['STATEPROV_FIELD']))."', statesByCountryList: caStatesByCountryList}}); }); "; $vs_element .="</script>\n"; } break; } if ($va_attr['DISPLAY_TYPE'] == DT_STATEPROV_LIST) { $vs_element = caHTMLSelect($ps_field.'_select', array(), array('id' => $ps_field.'_select'), array('value' => $vm_field_value)); $vs_element .= caHTMLTextInput($ps_field.'_name', array('id' => $ps_field.'_text', 'value' => $vm_field_value)); break; } if (($vn_display_width > 0) && (in_array($va_attr["DISPLAY_TYPE"], array(DT_SELECT, DT_LIST, DT_LIST_MULTIPLE)))) { # # Generate auto generated <select> (from foreign key, from ca_lists or from field-defined choice list) # # TODO: CLEAN UP THIS CODE, RUNNING VARIOUS STAGES THROUGH HELPER FUNCTIONS; ALSO FORMALIZE AND DOCUMENT VARIOUS OPTIONS // ----- // from ca_lists // ----- if(!($vs_list_code = $pa_options['list_code'])) { if(isset($va_attr['LIST_CODE']) && $va_attr['LIST_CODE']) { $vs_list_code = $va_attr['LIST_CODE']; } } if ($vs_list_code) { $va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName()); if ($va_many_to_one_relations[$ps_field]) { $vs_key = 'item_id'; } else { $vs_key = 'item_value'; } $vs_null_option = null; if (!$pa_options["nullOption"] && $vb_is_null) { $vs_null_option = "- NONE -"; } else { if ($pa_options["nullOption"]) { $vs_null_option = $pa_options["nullOption"]; } } $t_list = new ca_lists(); $va_list_attrs = array( 'id' => $pa_options['id']); if ($vn_max_pixel_width) { $va_list_attrs['style'] = $vs_width_style; } // NOTE: "raw" field value (value passed into method, before the model default value is applied) is used so as to allow the list default to be used if needed $vs_element = $t_list->getListAsHTMLFormElement($vs_list_code, $pa_options["name"].$vs_multiple_name_extension, $va_list_attrs, array('value' => $vm_raw_field_value, 'key' => $vs_key, 'nullOption' => $vs_null_option, 'readonly' => $pa_options['readonly'])); if (isset($pa_options['hide_select_if_no_options']) && $pa_options['hide_select_if_no_options'] && (!$vs_element)) { $vs_element = ""; $ps_format = '^ERRORS^ELEMENT'; } } else { // ----- // from related table // ----- $va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName()); if (isset($va_many_to_one_relations[$ps_field]) && $va_many_to_one_relations[$ps_field]) { # # Use foreign key to populate <select> # $o_one_table = $this->_DATAMODEL->getTableInstance($va_many_to_one_relations[$ps_field]["one_table"]); $vs_one_table_primary_key = $o_one_table->primaryKey(); if ($o_one_table->isHierarchical()) { # # Hierarchical <select> # $va_hier = $o_one_table->getHierarchyAsList(0, $vs_display_use_count, $va_display_use_count_filters, $vb_display_omit_items__with_zero_count); $va_display_fields = $va_attr["DISPLAY_FIELD"]; if (!in_array($vs_one_table_primary_key, $va_display_fields)) { $va_display_fields[] = $o_one_table->tableName().".".$vs_one_table_primary_key; } if (!is_array($va_display_fields) || sizeof($va_display_fields) < 1) { $va_display_fields = array("*"); } $vs_hier_parent_id_fld = $o_one_table->getProperty("HIER_PARENT_ID_FLD"); $va_options = array(); if ($pa_options["nullOption"]) { $va_options[""] = array($pa_options["nullOption"]); } $va_suboptions = array(); $va_suboption_values = array(); $vn_selected = 0; $vm_cur_top_level_val = null; $vm_selected_top_level_val = null; foreach($va_hier as $va_option) { if (!$va_option["NODE"][$vs_hier_parent_id_fld]) { continue; } $vn_val = $va_option["NODE"][$o_one_table->primaryKey()]; $vs_selected = ($vn_val == $vm_field_value) ? 'selected="1"' : ""; $vn_indent = $va_option["LEVEL"] - 1; $va_display_data = array(); foreach ($va_display_fields as $vs_fld) { $va_bits = explode(".", $vs_fld); if ($va_bits[1] != $vs_one_table_primary_key) { $va_display_data[] = $va_option["NODE"][$va_bits[1]]; } } $vs_option_label = join(" ", $va_display_data); $va_options[$vn_val] = array($vs_option_label, $vn_indent, $va_option["HITS"], $va_option['NODE']); } if (sizeof($va_options) == 0) { $vs_element = isset($pa_options['empty_message']) ? $pa_options['empty_message'] : 'No options available'; } else { $vs_element = "<select name='".$pa_options["name"].$vs_multiple_name_extension."' ".$vs_js." ".$vs_is_multiple." ".$ps_size." id='".$pa_options["id"].$vs_multiple_name_extension."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n"; if (!$pa_options["nullOption"] && $vb_is_null) { $vs_element .= "<option value=''>- NONE -</option>\n"; } else { if ($pa_options["nullOption"]) { $vs_element .= "<option value=''>".$pa_options["nullOption"]."</option>\n"; } } foreach($va_options as $vn_val => $va_option_info) { $vs_selected = (($vn_val == $vm_field_value) || in_array($vn_val, $va_selection)) ? "selected='selected'" : ""; $vs_element .= "<option value='".$vn_val."' $vs_selected>"; $vn_indent = ($va_option_info[1]) * 2; $vs_indent = ""; if ($vn_indent > 0) { $vs_indent = str_repeat("&nbsp;", ($vn_indent - 1) * 2)." "; $vn_indent++; } $vs_option_text = $va_option_info[0]; $vs_use_count = ""; if($vs_display_use_count && $vb_display_show_count&& ($vn_val != "")) { $vs_use_count = " (".intval($va_option_info[2]).")"; } $vs_display_message = ''; if (is_array($pa_options['displayMessageForFieldValues'])) { foreach($pa_options['displayMessageForFieldValues'] as $vs_df => $va_df_vals) { if ((isset($va_option_info[3][$vs_df])) && is_array($va_df_vals)) { $vs_tmp = $va_option_info[3][$vs_df]; if (isset($va_df_vals[$vs_tmp])) { $vs_display_message = ' '.$va_df_vals[$vs_tmp]; } } } } if ( ($pa_options["maxOptionLength"]) && (strlen($vs_option_text) + strlen($vs_use_count) + $vn_indent > $pa_options["maxOptionLength"]) ) { if (($vn_strlen = $pa_options["maxOptionLength"] - strlen($vs_indent) - strlen($vs_use_count) - 3) < $pa_options["maxOptionLength"]) { $vn_strlen = $pa_options["maxOptionLength"]; } $vs_option_text = unicode_substr($vs_option_text, 0, $vn_strlen)."..."; } $vs_element .= $vs_indent.$vs_option_text.$vs_use_count.$vs_display_message."</option>\n"; } $vs_element .= "</select>\n"; } } else { # # "Flat" <select> # if (!is_array($va_display_fields = $pa_options["DISPLAY_FIELD"])) { $va_display_fields = $va_attr["DISPLAY_FIELD"]; } if (!is_array($va_display_fields)) { return "Configuration error: DISPLAY_FIELD directive for field '$ps_field' must be an array of field names in the format tablename.fieldname"; } if (!in_array($vs_one_table_primary_key, $va_display_fields)) { $va_display_fields[] = $o_one_table->tableName().".".$vs_one_table_primary_key; } if (!is_array($va_display_fields) || sizeof($va_display_fields) < 1) { $va_display_fields = array("*"); } $vs_sql = " SELECT * FROM ".$va_many_to_one_relations[$ps_field]["one_table"]." "; if (isset($pa_options["WHERE"]) && (is_array($pa_options["WHERE"]) && ($vs_where = join(" AND ",$pa_options["WHERE"]))) || ((is_array($va_attr["DISPLAY_WHERE"])) && ($vs_where = join(" AND ",$va_attr["DISPLAY_WHERE"])))) { $vs_sql .= " WHERE $vs_where "; } if ((isset($va_attr["DISPLAY_ORDERBY"])) && ($va_attr["DISPLAY_ORDERBY"]) && ($vs_orderby = join(",",$va_attr["DISPLAY_ORDERBY"]))) { $vs_sql .= " ORDER BY $vs_orderby "; } $qr_res = $o_db->query($vs_sql); if ($o_db->numErrors()) { $vs_element = "Error creating menu: ".join(';', $o_db->getErrors()); break; } $va_opts = array(); if (isset($pa_options["nullOption"]) && $pa_options["nullOption"]) { $va_opts[$pa_options["nullOption"]] = array($pa_options["nullOption"], null); } else { if ($vb_is_null) { $va_opts["- NONE -"] = array("- NONE -", null); } } if ($pa_options["select_item_text"]) { $va_opts[$pa_options["select_item_text"]] = array($pa_options["select_item_text"], null); } $va_fields = array(); foreach($va_display_fields as $vs_field) { $va_tmp = explode(".", $vs_field); $va_fields[] = $va_tmp[1]; } while ($qr_res->nextRow()) { $vs_display = ""; foreach($va_fields as $vs_field) { if ($vs_field != $vs_one_table_primary_key) { $vs_display .= $qr_res->get($vs_field). " "; } } $va_opts[] = array($vs_display, $qr_res->get($vs_one_table_primary_key), $qr_res->getRow()); } if (sizeof($va_opts) == 0) { $vs_element = isset($pa_options['empty_message']) ? $pa_options['empty_message'] : 'No options available'; } else { if (isset($pa_options['hide_select_if_only_one_option']) && $pa_options['hide_select_if_only_one_option'] && (sizeof($va_opts) == 1)) { $vs_element = "<input type='hidden' name='".$pa_options["name"]."' ".$vs_js." ".$ps_size." id='".$pa_options["id"]."' value='".($vm_field_value ? $vm_field_value : $va_opts[0][1])."' {$vs_css_class_attr}/>"; $ps_format = '^ERRORS^ELEMENT'; } else { $vs_element = "<select name='".$pa_options["name"].$vs_multiple_name_extension."' ".$vs_js." ".$vs_is_multiple." ".$ps_size." id='".$pa_options["id"].$vs_multiple_name_extension."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n"; foreach ($va_opts as $va_opt) { $vs_option_text = $va_opt[0]; $vs_value = $va_opt[1]; $vs_selected = (($vs_value == $vm_field_value) || in_array($vs_value, $va_selection)) ? "selected='selected'" : ""; $vs_use_count = ""; if ($vs_display_use_count && $vb_display_show_count && ($vs_value != "")) { $vs_use_count = "(".intval($va_option_info[2]).")"; } if ( ($pa_options["maxOptionLength"]) && (strlen($vs_option_text) + strlen($vs_use_count) > $pa_options["maxOptionLength"]) ) { $vs_option_text = unicode_substr($vs_option_text,0, $pa_options["maxOptionLength"] - 3 - strlen($vs_use_count))."..."; } $vs_display_message = ''; if (is_array($pa_options['displayMessageForFieldValues'])) { foreach($pa_options['displayMessageForFieldValues'] as $vs_df => $va_df_vals) { if ((isset($va_opt[2][$vs_df])) && is_array($va_df_vals)) { $vs_tmp = $va_opt[2][$vs_df]; if (isset($va_df_vals[$vs_tmp])) { $vs_display_message = ' '.$va_df_vals[$vs_tmp]; } } } } $vs_element.= "<option value='$vs_value' $vs_selected>"; $vs_element .= $vs_option_text.$vs_use_count.$vs_display_message; $vs_element .= "</option>\n"; } $vs_element .= "</select>\n"; } } } } else { # # choice list # $vs_element = ''; // if 'LIST' is set try to stock over choice list with the contents of the list if (isset($va_attr['LIST']) && $va_attr['LIST']) { // NOTE: "raw" field value (value passed into method, before the model default value is applied) is used so as to allow the list default to be used if needed $vs_element = ca_lists::getListAsHTMLFormElement($va_attr['LIST'], $pa_options["name"].$vs_multiple_name_extension, array('class' => $pa_options['classname'], 'id' => $pa_options['id']), array('key' => 'item_value', 'value' => $vm_raw_field_value, 'nullOption' => $pa_options['nullOption'], 'readonly' => $pa_options['readonly'])); } if (!$vs_element && (isset($va_attr["BOUNDS_CHOICE_LIST"]) && is_array($va_attr["BOUNDS_CHOICE_LIST"]))) { if (sizeof($va_attr["BOUNDS_CHOICE_LIST"]) == 0) { $vs_element = isset($pa_options['empty_message']) ? $pa_options['empty_message'] : 'No options available'; } else { $vs_element = "<select name='".$pa_options["name"].$vs_multiple_name_extension."' ".$vs_js." ".$vs_is_multiple." ".$ps_size." id='".$pa_options['id'].$vs_multiple_name_extension."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n"; if ($pa_options["select_item_text"]) { $vs_element.= "<option value=''>".$this->escapeHTML($pa_options["select_item_text"])."</option>\n"; } if (!$pa_options["nullOption"] && $vb_is_null) { $vs_element .= "<option value=''>- NONE -</option>\n"; } else { if ($pa_options["nullOption"]) { $vs_element .= "<option value=''>".$pa_options["nullOption"]."</option>\n"; } } foreach($va_attr["BOUNDS_CHOICE_LIST"] as $vs_option => $vs_value) { $vs_selected = ((strval($vs_value) === strval($vm_field_value)) || in_array($vs_value, $va_selection)) ? "selected='selected'" : ""; if (($pa_options["maxOptionLength"]) && (strlen($vs_option) > $pa_options["maxOptionLength"])) { $vs_option = unicode_substr($vs_option, 0, $pa_options["maxOptionLength"] - 3)."..."; } $vs_element.= "<option value='$vs_value' $vs_selected>".$this->escapeHTML($vs_option)."</option>\n"; } $vs_element .= "</select>\n"; } } } } } else { if ($va_attr["DISPLAY_TYPE"] === DT_COLORPICKER) { // COLORPICKER $vs_element = '<input name="'.$pa_options["name"].'" type="hidden" size="'.($pa_options['size'] ? $pa_options['size'] : $vn_display_width).'" value="'.$this->escapeHTML($vm_field_value).'" '.$vs_js.' id=\''.$pa_options["id"]."' style='{$vs_dim_style}'/>\n"; $vs_element .= '<div id="'.$pa_options["id"].'_colorchip" class="colorpicker_chip" style="background-color: #'.$vm_field_value.'"><!-- empty --></div>'; $vs_element .= "<script type='text/javascript'>jQuery(document).ready(function() { jQuery('#".$pa_options["name"]."_colorchip').ColorPicker({ onShow: function (colpkr) { jQuery(colpkr).fadeIn(500); return false; }, onHide: function (colpkr) { jQuery(colpkr).fadeOut(500); return false; }, onChange: function (hsb, hex, rgb) { jQuery('#".$pa_options["name"]."').val(hex); jQuery('#".$pa_options["name"]."_colorchip').css('backgroundColor', '#' + hex); }, color: jQuery('#".$pa_options["name"]."').val() })}); </script>\n"; if (method_exists('JavascriptLoadManager', 'register')) { JavascriptLoadManager::register('jquery', 'colorpicker'); } } else { # normal controls: all non-DT_SELECT display types are returned as DT_FIELD's. We could generate # radio-button controls for foreign key and choice lists, but we don't bother because it's never # really necessary. if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'"'.($pa_options['readonly'] ? ' readonly="readonly" ' : '').' wrap="soft" '.$vs_js.' id=\''.$pa_options["id"]."' style='{$vs_dim_style}' ".$vs_css_class_attr.">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>'."\n"; } else { $vs_element = '<input name="'.$pa_options["name"].'" type="text" size="'.($pa_options['size'] ? $pa_options['size'] : $vn_display_width).'"'.($pa_options['readonly'] ? ' readonly="readonly" ' : '').' value="'.$this->escapeHTML($vm_field_value).'" '.$vs_js.' id=\''.$pa_options["id"]."' {$vs_css_class_attr} style='{$vs_dim_style}'/>\n"; } if (isset($va_attr['UNIQUE_WITHIN']) && is_array($va_attr['UNIQUE_WITHIN'])) { $va_within_fields = array(); foreach($va_attr['UNIQUE_WITHIN'] as $vs_within_field) { $va_within_fields[$vs_within_field] = $this->get($vs_within_field); } $vs_element .= "<span id='".$pa_options["id"].'_uniqueness_status'."'></span>"; $vs_element .= "<script type='text/javascript'> caUI.initUniquenessChecker({ errorIcon: '".$pa_options['error_icon']."', processIndicator: '".$pa_options['progress_indicator']."', statusID: '".$pa_options["id"]."_uniqueness_status', lookupUrl: '".$pa_options['lookup_url']."', formElementID: '".$pa_options["id"]."', row_id: ".intval($this->getPrimaryKey()).", table_num: ".$this->tableNum().", field: '".$ps_field."', withinFields: ".json_encode($va_within_fields).", alreadyInUseMessage: '".addslashes(_t('Value must be unique. Please try another.'))."' }); </script>"; } } } break; # ---------------------------- case (FT_TIMESTAMP): if ($this->get($ps_field)) { # is timestamp set? $vs_element = $this->escapeHTML($vm_field_value); # return printed date } else { $vs_element = "[Not set]"; # return text instead of 1969 date } break; # ---------------------------- case (FT_DATETIME): case (FT_HISTORIC_DATETIME): case (FT_DATE): case (FT_HISTORIC_DATE): if (!$vm_field_value) { $vm_field_value = $pa_options['value']; } switch($va_attr["DISPLAY_TYPE"]) { case DT_TEXT: $vs_element = $vm_field_value ? $vm_field_value : "[Not set]"; break; default: $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>'; } else { $vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; } break; } break; # ---------------------------- case(FT_TIME): if (!$this->get($ps_field)) { $vm_field_value = ""; } switch($va_attr["DISPLAY_TYPE"]) { case DT_TEXT: $vs_element = $vm_field_value ? $vm_field_value : "[Not set]"; break; default: $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>'; } else { $vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr}' style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; } break; } break; # ---------------------------- case(FT_DATERANGE): case(FT_HISTORIC_DATERANGE): switch($va_attr["DISPLAY_TYPE"]) { case DT_TEXT: $vs_element = $vm_field_value ? $vm_field_value : "[Not set]"; break; default: $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>'; } else { $vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vn_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; } break; } break; # ---------------------------- case (FT_TIMERANGE): switch($va_attr["DISPLAY_TYPE"]) { case DT_TEXT: $vs_element = $vm_field_value ? $vm_field_value : "[Not set]"; break; default: $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vm_field_value).'</'.$vs_text_area_tag_name.'>'; } else { $vs_element = '<input type="text" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; } break; } break; # ---------------------------- case(FT_TIMECODE): $o_tp = new TimecodeParser(); $o_tp->setParsedValueInSeconds($vm_field_value); $vs_timecode = $o_tp->getText("COLON_DELIMITED", array("BLANK_ON_ZERO" => true)); $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; if ($vn_display_height > 1) { $vs_element = '<'.$vs_text_area_tag_name.' name="'.$pa_options["name"].'" rows="'.$vn_display_height.'" cols="'.$vn_display_width.'" wrap="soft" '.$vs_js.' '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '').">".$this->escapeHTML($vs_timecode).'</'.$vs_text_area_tag_name.'>'; } else { $vs_element = '<input type="text" NAME="'.$pa_options["name"].'" value="'.$this->escapeHTML($vs_timecode)."\" size='{$vn_display_width}' {$vs_max_length} {$vs_js} {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; } break; # ---------------------------- case(FT_MEDIA): case(FT_FILE): $vs_element = '<input type="file" name="'.$pa_options["name"].'" '.$vs_js.'/>'; // show current media icon if ($vs_version = (array_key_exists('displayMediaVersion', $pa_options)) ? $pa_options['displayMediaVersion'] : 'icon') { $va_valid_versions = $this->getMediaVersions($ps_field); if (!in_array($vs_version, $va_valid_versions)) { $vs_version = $va_valid_versions[0]; } if ($vs_tag = $this->getMediaTag($ps_field, $vs_version)) { $vs_element .= $vs_tag; } } break; # ---------------------------- case(FT_PASSWORD): $vn_max_length = $va_attr["BOUNDS_LENGTH"][1]; $vs_max_length = ''; if ($vn_max_length > 0) $vs_max_length = 'maxlength="'.$vn_max_length.'"'; $vs_element = '<input type="password" name="'.$pa_options["name"].'" value="'.$this->escapeHTML($vm_field_value).'" size="'.$vn_display_width.'" '.$vs_max_length.' '.$vs_js.' autocomplete="off" '.$vs_css_class_attr." style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; break; # ---------------------------- case(FT_BIT): switch($va_attr["DISPLAY_TYPE"]) { case (DT_FIELD): $vs_element = '<input type="text" name="'.$pa_options["name"]."\" value='{$vm_field_value}' maxlength='1' size='2' {$vs_js} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' readonly="readonly" ' : '')."/>"; break; case (DT_SELECT): $vs_element = "<select name='".$pa_options["name"]."' ".$vs_js." id='".$pa_options["id"]."' {$vs_css_class_attr} style='{$vs_dim_style}'".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">\n"; foreach(array("Yes" => 1, "No" => 0) as $vs_option => $vs_value) { $vs_selected = ($vs_value == $vm_field_value) ? "selected='selected'" : ""; $vs_element.= "<option value='$vs_value' {$vs_selected}".($pa_options['readonly'] ? ' disabled="disabled" ' : '').">$vs_option</option>\n"; } $vs_element .= "</select>\n"; break; case (DT_CHECKBOXES): $vs_element = '<input type="checkbox" name="'.$pa_options["name"].'" value="1" '.($vm_field_value ? 'checked="1"' : '').' '.$vs_js.($pa_options['readonly'] ? ' disabled="disabled" ' : '').' id="'.$pa_options["id"].'"/>'; break; case (DT_RADIO_BUTTONS): $vs_element = 'Radio buttons not supported for bit-type fields'; break; } break; # ---------------------------- } # Apply format $vs_formatting = ""; if (isset($pa_options['field_errors']) && is_array($pa_options['field_errors']) && sizeof($pa_options['field_errors'])) { $va_field_errors = array(); foreach($pa_options['field_errors'] as $o_e) { $va_field_errors[] = $o_e->getErrorDescription(); } $vs_errors = join('; ', $va_field_errors); } else { $vs_errors = ''; } if (is_null($ps_format)) { if (isset($pa_options['field_errors']) && is_array($pa_options['field_errors']) && sizeof($pa_options['field_errors'])) { $ps_format = $this->_CONFIG->get('form_element_error_display_format'); } else { $ps_format = $this->_CONFIG->get('form_element_display_format'); } } if ($ps_format != '') { $ps_formatted_element = $ps_format; $ps_formatted_element = str_replace("^ELEMENT", $vs_element, $ps_formatted_element); if ($vs_subelement) { $ps_formatted_element = str_replace("^SUB_ELEMENT", $vs_subelement, $ps_formatted_element); } $vb_fl_display_form_field_tips = false; if ( $pa_options["display_form_field_tips"] || (!isset($pa_options["display_form_field_tips"]) && $va_attr["DISPLAY_DESCRIPTION"]) || (!isset($pa_options["display_form_field_tips"]) && !isset($va_attr["DISPLAY_DESCRIPTION"]) && $vb_fl_display_form_field_tips) ) { if (preg_match("/\^DESCRIPTION/", $ps_formatted_element)) { $ps_formatted_element = str_replace("^LABEL",$vs_field_label, $ps_formatted_element); $ps_formatted_element = str_replace("^DESCRIPTION",$va_attr["DESCRIPTION"], $ps_formatted_element); } else { // no explicit placement of description text, so... $vs_field_id = '_'.$this->tableName().'_'.$this->getPrimaryKey().'_'.$pa_options["name"].'_'.$pa_options['form_name']; $ps_formatted_element = str_replace("^LABEL",'<span id="'.$vs_field_id.'">'.$vs_field_label.'</span>', $ps_formatted_element); if (!isset($pa_options['no_tooltips']) || !$pa_options['no_tooltips']) { TooltipManager::add('#'.$vs_field_id, "<h3>{$vs_field_label}</h3>".$va_attr["DESCRIPTION"], $pa_options['tooltip_namespace']); } } if (!isset($va_attr["SUB_LABEL"])) { $va_attr["SUB_LABEL"] = ''; } if (!isset($va_attr["SUB_DESCRIPTION"])) { $va_attr["SUB_DESCRIPTION"] = ''; } if (preg_match("/\^SUB_DESCRIPTION/", $ps_formatted_element)) { $ps_formatted_element = str_replace("^SUB_LABEL",$va_attr["SUB_LABEL"], $ps_formatted_element); $ps_formatted_element = str_replace("^SUB_DESCRIPTION", $va_attr["SUB_DESCRIPTION"], $ps_formatted_element); } else { // no explicit placement of description text, so... // ... make label text itself rollover for description text because no icon was specified $ps_formatted_element = str_replace("^SUB_LABEL",$va_attr["SUB_LABEL"], $ps_formatted_element); } } else { $ps_formatted_element = str_replace("^LABEL", $vs_field_label, $ps_formatted_element); $ps_formatted_element = str_replace("^DESCRIPTION", "", $ps_formatted_element); if ($vs_subelement) { $ps_formatted_element = str_replace("^SUB_LABEL", $va_attr["SUB_LABEL"], $ps_formatted_element); $ps_formatted_element = str_replace("^SUB_DESCRIPTION", "", $ps_formatted_element); } } $ps_formatted_element = str_replace("^ERRORS", $vs_errors, $ps_formatted_element); $ps_formatted_element = str_replace("^EXTRA", isset($pa_options['extraLabelText']) ? $pa_options['extraLabelText'] : '', $ps_formatted_element); $vs_element = $ps_formatted_element; } else { $vs_element .= "<br/>".$vs_subelement; } return $vs_element; } else { $this->postError(716,_t("'%1' does not exist in this object", $ps_field),"BaseModel->formElement()"); return ""; } return ""; } # -------------------------------------------------------------------------------------------- /** * Get list name * * @access public * @return string */ public function getListName() { if (is_array($va_display_fields = $this->getProperty('LIST_FIELDS'))) { $va_tmp = array(); $vs_delimiter = $this->getProperty('LIST_DELIMITER'); foreach($va_display_fields as $vs_display_field) { $va_tmp[] = $this->get($vs_display_field); } return join($vs_delimiter, $va_tmp); } return null; } # -------------------------------------------------------------------------------------------- /** * Modifies text for HTML use (i.e. passing it through stripslashes and htmlspecialchars) * * @param string $ps_text * @return string */ public function escapeHTML($ps_text) { $opa_php_version = caGetPHPVersion(); if ($opa_php_version['versionInt'] >= 50203) { $ps_text = htmlspecialchars(stripslashes($ps_text), ENT_QUOTES, $this->getCharacterSet(), false); } else { $ps_text = htmlspecialchars(stripslashes($ps_text), ENT_QUOTES, $this->getCharacterSet()); } return str_replace("&amp;#", "&#", $ps_text); } # -------------------------------------------------------------------------------------------- /** * Returns list of names of fields that must be defined */ public function getMandatoryFields() { $va_fields = $this->getFormFields(true); $va_many_to_one_relations = $this->_DATAMODEL->getManyToOneRelations($this->tableName()); $va_mandatory_fields = array(); foreach($va_fields as $vs_field => $va_info) { if (isset($va_info['IDENTITY']) && $va_info['IDENTITY']) { continue;} if ((isset($va_many_to_one_relations[$vs_field]) && $va_many_to_one_relations[$vs_field]) && (!isset($va_info['IS_NULL']) || !$va_info['IS_NULL'])) { $va_mandatory_fields[] = $vs_field; continue; } if (isset($va_info['BOUNDS_LENGTH']) && is_array($va_info['BOUNDS_LENGTH'])) { if ($va_info['BOUNDS_LENGTH'][0] > 0) { $va_mandatory_fields[] = $vs_field; continue; } } } return $va_mandatory_fields; } # -------------------------------------------------------------------------------------------- /** * Returns a list_code for a list in the ca_lists table that is used for the specified field * Return null if the field has no list associated with it */ public function getFieldListCode($ps_field) { $va_field_info = $this->getFieldInfo($ps_field); return ($vs_list_code = $va_field_info['LIST_CODE']) ? $vs_list_code : null; } # -------------------------------------------------------------------------------------------- /** * Return list of items specified for the given field. * * @param string $ps_field The name of the field * @param string $ps_list_code Optional list code or list_id to force return of, overriding the list configured in the model * @return array A list of items, filtered on the current user locale; the format is the same as that returned by ca_lists::getItemsForList() */ public function getFieldList($ps_field, $ps_list_code=null) { $t_list = new ca_lists(); return caExtractValuesByUserLocale($t_list->getItemsForList($ps_list_code ? $ps_list_code : $this->getFieldListCode($ps_field))); } # -------------------------------------------------------------------------------------------- /** * Creates a relationship between the currently loaded row and the specified row. * * @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to creation relationship to. * @param int $pn_rel_id primary key value of row to creation relationship to. * @param mixed $pm_type_id Relationship type type_code or type_id, as defined in the ca_relationship_types table. This is required for all relationships that use relationship types. This includes all of the most common types of relationships. * @param string $ps_effective_date Optional date expression to qualify relation with. Any expression that the TimeExpressionParser can handle is supported here. * @param string $ps_source_info Text field for storing information about source of relationship. Not currently used. * @param string $ps_direction Optional direction specification for self-relationships (relationships linking two rows in the same table). Valid values are 'ltor' (left-to-right) and 'rtol' (right-to-left); the direction determines which "side" of the relationship the currently loaded row is on: 'ltor' puts the current row on the left side. For many self-relations the direction determines the nature and display text for the relationship. * @return boolean True on success, false on error. */ public function addRelationship($pm_rel_table_name_or_num, $pn_rel_id, $pm_type_id=null, $ps_effective_date=null, $ps_source_info=null, $ps_direction=null, $pn_rank=null) { if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { $this->postError(1240, _t('Related table specification "%1" is not valid', $pm_rel_table_name_or_num), 'BaseModel->addRelationship()'); return false; } $t_item_rel = $va_rel_info['t_item_rel']; if ($pm_type_id && !is_numeric($pm_type_id)) { $t_rel_type = new ca_relationship_types(); if ($vs_linking_table = $t_rel_type->getRelationshipTypeTable($this->tableName(), $t_item_rel->tableName())) { $pn_type_id = $t_rel_type->getRelationshipTypeID($vs_linking_table, $pm_type_id); } } else { $pn_type_id = $pm_type_id; } if ($va_rel_info['related_table_name'] == $this->tableName()) { // is self relation $t_item_rel->setMode(ACCESS_WRITE); // is self relationship if ($ps_direction == 'rtol') { $t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id); } else { // default is left-to-right $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id); } $t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); } if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); } $t_item_rel->insert(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } else { switch(sizeof($va_rel_info['path'])) { case 3: // many-to-many relationship $t_rel = $this->getAppDatamodel()->getTableInstance($va_rel_info['related_table_name']); $t_item_rel->setMode(ACCESS_WRITE); $vs_left_table = $t_item_rel->getLeftTableName(); $vs_right_table = $t_item_rel->getRightTableName(); if ($this->tableName() == $vs_left_table) { // is lefty $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id); } else { // is righty $t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id); } $t_item_rel->set('rank', $pn_rank); $t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); } if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); } $t_item_rel->insert(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } case 2: // many-to-one relationship if ($this->tableName() == $va_rel_info['rel_keys']['one_table']) { if ($t_item_rel->load($pn_rel_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], $this->getPrimaryKey()); $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } else { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id); $t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); $t_item_rel->insert(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } } else { $this->setMode(ACCESS_WRITE); $this->set($va_rel_info['rel_keys']['many_table_field'], $pn_rel_id); $this->update(); if ($this->numErrors()) { return false; } } break; default: return false; break; } } return true; } # -------------------------------------------------------------------------------------------- /** * Edits the data in an existing relationship between the currently loaded row and the specified row. * * @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to create relationships to. * @param int $pn_relation_id primary key value of the relation to edit. * @param int $pn_rel_id primary key value of row to creation relationship to. * @param mixed $pm_type_id Relationship type type_code or type_id, as defined in the ca_relationship_types table. This is required for all relationships that use relationship types. This includes all of the most common types of relationships. * @param string $ps_effective_date Optional date expression to qualify relation with. Any expression that the TimeExpressionParser can handle is supported here. * @param string $ps_source_info Text field for storing information about source of relationship. Not currently used. * @param string $ps_direction Optional direction specification for self-relationships (relationships linking two rows in the same table). Valid values are 'ltor' (left-to-right) and 'rtol' (right-to-left); the direction determines which "side" of the relationship the currently loaded row is on: 'ltor' puts the current row on the left side. For many self-relations the direction determines the nature and display text for the relationship. * @return boolean True on success, false on error. */ public function editRelationship($pm_rel_table_name_or_num, $pn_relation_id, $pn_rel_id, $pm_type_id=null, $ps_effective_date=null, $pa_source_info=null, $ps_direction=null, $pn_rank=null) { if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { $this->postError(1240, _t('Related table specification "%1" is not valid', $pm_rel_table_name_or_num), 'BaseModel->editRelationship()'); return false; } $t_item_rel = $va_rel_info['t_item_rel']; if ($pm_type_id && !is_numeric($pm_type_id)) { $t_rel_type = new ca_relationship_types(); if ($vs_linking_table = $t_rel_type->getRelationshipTypeTable($this->tableName(), $t_item_rel->tableName())) { $pn_type_id = $t_rel_type->getRelationshipTypeID($vs_linking_table, $pm_type_id); } } else { $pn_type_id = $pm_type_id; } if ($va_rel_info['related_table_name'] == $this->tableName()) { // is self relation if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); if ($ps_direction == 'rtol') { $t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id); } else { // default is left-to-right $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id); } $t_item_rel->set('rank', $pn_rank); $t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); } if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); } $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } } else { switch(sizeof($va_rel_info['path'])) { case 3: // many-to-many relationship if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); $vs_left_table = $t_item_rel->getLeftTableName(); $vs_right_table = $t_item_rel->getRightTableName(); if ($this->tableName() == $vs_left_table) { // is lefty $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getRightTableFieldName(), $pn_rel_id); } else { // is righty $t_item_rel->set($t_item_rel->getRightTableFieldName(), $this->getPrimaryKey()); $t_item_rel->set($t_item_rel->getLeftTableFieldName(), $pn_rel_id); } $t_item_rel->set('rank', $pn_rank); $t_item_rel->set($t_item_rel->getTypeFieldName(), $pn_type_id); // TODO: verify type_id based upon type_id's of each end of the relationship if(!is_null($ps_effective_date)){ $t_item_rel->set('effective_date', $ps_effective_date); } if(!is_null($ps_source_info)){ $t_item_rel->set("source_info",$ps_source_info); } $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } return true; } case 2: // many-to-one relations if ($this->tableName() == $va_rel_info['rel_keys']['one_table']) { if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], null); $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } if ($t_item_rel->load($pn_rel_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], $this->getPrimaryKey()); $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } } else { $this->setMode(ACCESS_WRITE); $this->set($va_rel_info['rel_keys']['many_table_field'], $pn_rel_id); $this->update(); if ($this->numErrors()) { return false; } } break; default: return false; break; } } return false; } # -------------------------------------------------------------------------------------------- /** * Removes the specified relationship * * @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to edit relationships to. * @param int $pn_relation_id primary key value of the relation to remove. * @return boolean True on success, false on error. */ public function removeRelationship($pm_rel_table_name_or_num, $pn_relation_id) { if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { $this->postError(1240, _t('Related table specification "%1" is not valid', $pm_rel_table_name_or_num), 'BaseModel->removeRelationship()'); return false; } $t_item_rel = $va_rel_info['t_item_rel']; if ($va_rel_info['related_table_name'] == $this->tableName()) { if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->delete(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } return true; } } else { switch(sizeof($va_rel_info['path'])) { case 3: // many-to-one relationship if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->delete(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } return true; } case 2: if ($this->tableName() == $va_rel_info['rel_keys']['one_table']) { if ($t_item_rel->load($pn_relation_id)) { $t_item_rel->setMode(ACCESS_WRITE); $t_item_rel->set($va_rel_info['rel_keys']['many_table_field'], null); $t_item_rel->update(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return false; } } } else { $this->setMode(ACCESS_WRITE); $this->set($va_rel_info['rel_keys']['many_table_field'], null); $this->update(); if ($this->numErrors()) { return false; } } break; default: return false; break; } } return false; } # -------------------------------------------------------------------------------------------- /** * Remove all relations with the specified table from the currently loaded row * * @param mixed $pm_rel_table_name_or_num Table name (eg. "ca_entities") or number as defined in datamodel.conf of table containing row to removes relationships to. * @return boolean True on success, false on error */ public function removeRelationships($pm_rel_table_name_or_num) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { return null; } $t_item_rel = $va_rel_info['t_item_rel']; $o_db = $this->getDb(); if ($t_item_rel->tableName() == $this->getSelfRelationTableName()) { $qr_res = $o_db->query(" SELECT relation_id FROM ".$t_item_rel->tableName()." WHERE ".$t_item_rel->getLeftTableFieldName()." = ? OR ".$t_item_rel->getRightTableFieldName()." = ? ", (int)$vn_row_id, (int)$vn_row_id); while($qr_res->nextRow()) { if (!$this->removeRelationship($pm_rel_table_name_or_num, $qr_res->get('relation_id'))) { return false; } } } else { $qr_res = $o_db->query(" SELECT relation_id FROM ".$t_item_rel->tableName()." WHERE ".$this->primaryKey()." = ? ", (int)$vn_row_id); while($qr_res->nextRow()) { if (!$this->removeRelationship($pm_rel_table_name_or_num, $qr_res->get('relation_id'))) { return false; } } } return true; } # -------------------------------------------------------------------------------------------- /** * */ public function getRelationshipInstance($pm_rel_table_name_or_num) { if ($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num)) { return $va_rel_info['t_item_rel']; } return null; } # -------------------------------------------------------------------------------------------- /** * Moves relationships from currently loaded row to another row specified by $pn_row_id. The existing relationship * rows are simply re-pointed to the new row, so this is a relatively fast operation. Note that this method does not copy * relationships, it moves them. After the operation completes no relationships to the specified related table will exist for the current row. * * @param mixed $pm_rel_table_name_or_num The table name or number of the related table. Only relationships pointing to this table will be moved. * @param int $pn_to_id The primary key value of the row to move the relationships to. * @param array $pa_options Array of options. No options are currently supported. * * @return int Number of relationships moved, or null on error. Note that you should carefully test the return value for null-ness rather than false-ness, since zero is a valid return value in cases where no relationships need to be moved. */ public function moveRelationships($pm_rel_table_name_or_num, $pn_to_id, $pa_options=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { return null; } $t_item_rel = $va_rel_info['t_item_rel']; // linking table $o_db = $this->getDb(); $vs_item_pk = $this->primaryKey(); if (!($t_rel_item = $this->getAppDatamodel()->getTableInstance($va_rel_info['related_table_name']))) { // related item return null; } $va_to_reindex_relations = array(); if ($t_item_rel->tableName() == $this->getSelfRelationTableName()) { $qr_res = $o_db->query(" SELECT * FROM ".$t_item_rel->tableName()." WHERE ".$t_item_rel->getLeftTableFieldName()." = ? OR ".$t_item_rel->getRightTableFieldName()." = ? ", (int)$vn_row_id, (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } while($qr_res->nextRow()) { $va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow(); } if (!sizeof($va_to_reindex_relations)) { return 0; } $o_db->query(" UPDATE ".$t_item_rel->tableName()." SET ".$t_item_rel->getLeftTableFieldName()." = ? WHERE ".$t_item_rel->getLeftTableFieldName()." = ? ", (int)$pn_to_id, (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } $o_db->query(" UPDATE ".$t_item_rel->tableName()." SET ".$t_item_rel->getRightTableFieldName()." = ? WHERE ".$t_item_rel->getRightTableFieldName()." = ? ", (int)$pn_to_id, (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } } else { $qr_res = $o_db->query(" SELECT * FROM ".$t_item_rel->tableName()." WHERE {$vs_item_pk} = ? ", (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } while($qr_res->nextRow()) { $va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow(); } if (!sizeof($va_to_reindex_relations)) { return 0; } $o_db->query(" UPDATE ".$t_item_rel->tableName()." SET {$vs_item_pk} = ? WHERE {$vs_item_pk} = ? ", (int)$pn_to_id, (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } } $vn_rel_table_num = $t_item_rel->tableNum(); // Reindex modified relationships if (!BaseModel::$search_indexer) { BaseModel::$search_indexer = new SearchIndexer($this->getDb()); } foreach($va_to_reindex_relations as $vn_relation_id => $va_row) { BaseModel::$search_indexer->indexRow($vn_rel_table_num, $vn_relation_id, $va_row, false, null, array($vs_item_pk => true)); } return sizeof($va_to_reindex_relations); } # -------------------------------------------------------------------------------------------- /** * Copies relationships from currently loaded row to another row specified by $pn_row_id. If you want to transfer relationships * from one row to another use moveRelationships() which is much faster than copying and then deleting relationships. * * @see moveRelationships() * * @param mixed $pm_rel_table_name_or_num The table name or number of the related table. Only relationships pointing to this table will be moved. * @param int $pn_to_id The primary key value of the row to move the relationships to. * @param array $pa_options Array of options. No options are currently supported. * * @return int Number of relationships copied, or null on error. Note that you should carefully test the return value for null-ness rather than false-ness, since zero is a valid return value in cases where no relationships were available to be copied. */ public function copyRelationships($pm_rel_table_name_or_num, $pn_to_id, $pa_options=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if(!($va_rel_info = $this->_getRelationshipInfo($pm_rel_table_name_or_num))) { return null; } $t_item_rel = $va_rel_info['t_item_rel']; // linking table if ($this->inTransaction()) { $t_item_rel->setTransaction($this->getTransaction()); } $o_db = $this->getDb(); $vs_item_pk = $this->primaryKey(); if (!($t_rel_item = $this->getAppDatamodel()->getTableInstance($va_rel_info['related_table_name']))) { // related item return null; } $va_to_reindex_relations = array(); if ($t_item_rel->tableName() == $this->getSelfRelationTableName()) { $vs_left_field_name = $t_item_rel->getLeftTableFieldName(); $vs_right_field_name = $t_item_rel->getRightTableFieldName(); $qr_res = $o_db->query(" SELECT * FROM ".$t_item_rel->tableName()." WHERE {$vs_left_field_name} = ? OR {$vs_right_field_name} = ? ", (int)$vn_row_id, (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } while($qr_res->nextRow()) { $va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow(); } if (!sizeof($va_to_reindex_relations)) { return 0; } $va_new_relations = array(); foreach($va_to_reindex_relations as $vn_relation_id => $va_row) { $t_item_rel->setMode(ACCESS_WRITE); unset($va_row[$vs_rel_pk]); if ($va_row[$vs_left_field_name] == $vn_row_id) { $va_row[$vs_left_field_name] = $pn_to_id; } else { $va_row[$vs_right_field_name] = $pn_to_id; } $t_item_rel->set($va_row); $t_item_rel->insert(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return null; } $va_new_relations[$t_item_rel->getPrimaryKey()] = $va_row; } } else { $qr_res = $o_db->query(" SELECT * FROM ".$t_item_rel->tableName()." WHERE {$vs_item_pk} = ? ", (int)$vn_row_id); if ($o_db->numErrors()) { $this->errors = $o_db->errors; return null; } while($qr_res->nextRow()) { $va_to_reindex_relations[(int)$qr_res->get('relation_id')] = $qr_res->getRow(); } if (!sizeof($va_to_reindex_relations)) { return 0; } $vs_pk = $this->primaryKey(); $vs_rel_pk = $t_item_rel->primaryKey(); $va_new_relations = array(); foreach($va_to_reindex_relations as $vn_relation_id => $va_row) { $t_item_rel->setMode(ACCESS_WRITE); unset($va_row[$vs_rel_pk]); $va_row[$vs_item_pk] = $pn_to_id; $t_item_rel->set($va_row); $t_item_rel->insert(); if ($t_item_rel->numErrors()) { $this->errors = $t_item_rel->errors; return null; } $va_new_relations[$t_item_rel->getPrimaryKey()] = $va_row; } } $vn_rel_table_num = $t_item_rel->tableNum(); // Reindex modified relationships if (!BaseModel::$search_indexer) { BaseModel::$search_indexer = new SearchIndexer($this->getDb()); } foreach($va_new_relations as $vn_relation_id => $va_row) { BaseModel::$search_indexer->indexRow($vn_rel_table_num, $vn_relation_id, $va_row, false, null, array($vs_item_pk => true)); } return sizeof($va_new_relations); } # -------------------------------------------------------------------------------------------- /** * */ private function _getRelationshipInfo($pm_rel_table_name_or_num) { if (is_numeric($pm_rel_table_name_or_num)) { $vs_related_table_name = $this->getAppDataModel()->getTableName($pm_rel_table_name_or_num); } else { $vs_related_table_name = $pm_rel_table_name_or_num; } $va_rel_keys = array(); if ($this->tableName() == $vs_related_table_name) { // self relations if ($vs_self_relation_table = $this->getSelfRelationTableName()) { $t_item_rel = $this->getAppDatamodel()->getTableInstance($vs_self_relation_table); } else { return null; } } else { $va_path = array_keys($this->getAppDatamodel()->getPath($this->tableName(), $vs_related_table_name)); switch(sizeof($va_path)) { case 3: $t_item_rel = $this->getAppDatamodel()->getTableInstance($va_path[1]); break; case 2: $t_item_rel = $this->getAppDatamodel()->getTableInstance($va_path[1]); if (!sizeof($va_rel_keys = $this->_DATAMODEL->getOneToManyRelations($this->tableName(), $va_path[1]))) { $va_rel_keys = $this->_DATAMODEL->getOneToManyRelations($va_path[1], $this->tableName()); } break; default: // bad related table return null; break; } } return array( 'related_table_name' => $vs_related_table_name, 'path' => $va_path, 'rel_keys' => $va_rel_keys, 't_item_rel' => $t_item_rel ); } # -------------------------------------------------------------------------------------------- /** * */ public function getDefaultLocaleList() { global $g_ui_locale_id; $va_locale_dedup = array(); if ($g_ui_locale_id) { $va_locale_dedup[$g_ui_locale_id] = true; } $t_locale = new ca_locales(); $va_locales = $t_locale->getLocaleList(); if (is_array($va_locale_defaults = $this->getAppConfig()->getList('locale_defaults'))) { foreach($va_locale_defaults as $vs_locale_default) { $va_locale_dedup[$va_locales[$vs_locale_default]] = true; } } foreach($va_locales as $vn_locale_id => $vs_locale_code) { $va_locale_dedup[$vn_locale_id] = true; } return array_keys($va_locale_dedup); } # -------------------------------------------------------------------------------------------- /** * Returns name of self relation table (table that links two rows in this table) or NULL if no table exists * * @return string Name of table or null if no table is defined. */ public function getSelfRelationTableName() { if (isset($this->SELF_RELATION_TABLE_NAME)) { return $this->SELF_RELATION_TABLE_NAME; } return null; } # -------------------------------------------------------------------------------------------- # User tagging # -------------------------------------------------------------------------------------------- /** * Adds a tag to currently loaded row. Returns null if no row is loaded. Otherwise returns true * if tag was successfully added, false if an error occurred in which case the errors will be available * via the model's standard error methods (getErrors() and friends. * * Most of the parameters are optional with the exception of $ps_tag - the text of the tag. Note that * tag text is monolingual; if you want to do multilingual tags then you must add multiple tags. * * The parameters are: * * @param $ps_tag [string] Text of the tag (mandatory) * @param $pn_user_id [integer] A valid ca_users.user_id indicating the user who added the tag; is null for tags from non-logged-in users (optional - default is null) * @param $pn_locale_id [integer] A valid ca_locales.locale_id indicating the language of the comment. If omitted or left null then the value in the global $g_ui_locale_id variable is used. If $g_ui_locale_id is not set and $pn_locale_id is not set then an error will occur (optional - default is to use $g_ui_locale_id) * @param $pn_access [integer] Determines public visibility of tag; if set to 0 then tag is not visible to public; if set to 1 tag is visible (optional - default is 0) * @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the tag; if omitted or set to null then moderation status will not be set unless app.conf setting dont_moderate_comments = 1 (optional - default is null) * @param array $pa_options Array of options. Supported options are: * purify = if true, comment, name and email are run through HTMLPurifier before being stored in the database. Default is true. */ public function addTag($ps_tag, $pn_user_id=null, $pn_locale_id=null, $pn_access=0, $pn_moderator=null, $pa_options=null) { global $g_ui_locale_id; if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; } if (!$pn_locale_id) { $this->postErrors(2830, _t('No locale was set for tag'), 'BaseModel->addTag()'); return false; } if(!isset($pa_options['purify'])) { $pa_options['purify'] = true; } if ((bool)$pa_options['purify']) { $o_purifier = new HTMLPurifier(); $ps_tag = $o_purifier->purify($ps_tag); } $t_tag = new ca_item_tags(); if (!$t_tag->load(array('tag' => $ps_tag, 'locale_id' => $pn_locale_id))) { // create new new $t_tag->setMode(ACCESS_WRITE); $t_tag->set('tag', $ps_tag); $t_tag->set('locale_id', $pn_locale_id); $vn_tag_id = $t_tag->insert(); if ($t_tag->numErrors()) { $this->errors = $t_tag->errors; return false; } } else { $vn_tag_id = $t_tag->getPrimaryKey(); } $t_ixt = new ca_items_x_tags(); $t_ixt->setMode(ACCESS_WRITE); $t_ixt->set('table_num', $this->tableNum()); $t_ixt->set('row_id', $this->getPrimaryKey()); $t_ixt->set('user_id', $pn_user_id); $t_ixt->set('tag_id', $vn_tag_id); $t_ixt->set('access', $pn_access); if (!is_null($pn_moderator)) { $t_ixt->set('moderated_by_user_id', $pn_moderator); $t_ixt->set('moderated_on', 'now'); }elseif($this->_CONFIG->get("dont_moderate_comments")){ $t_ixt->set('moderated_on', 'now'); } $t_ixt->insert(); if ($t_ixt->numErrors()) { $this->errors = $t_ixt->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Changed the access value for an existing tag. Returns null if no row is loaded. Otherwise returns true * if tag access setting was successfully changed, false if an error occurred in which case the errors will be available * via the model's standard error methods (getErrors() and friends. * * If $pn_user_id is set then only tag relations created by the specified user can be modified. Attempts to modify * tags created by users other than the one specified in $pn_user_id will return false and post an error. * * Most of the parameters are optional with the exception of $ps_tag - the text of the tag. Note that * tag text is monolingual; if you want to do multilingual tags then you must add multiple tags. * * The parameters are: * * @param $pn_relation_id [integer] A valid ca_items_x_tags.relation_id value specifying the tag relation to modify (mandatory) * @param $pn_access [integer] Determines public visibility of tag; if set to 0 then tag is not visible to public; if set to 1 tag is visible (optional - default is 0) * @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the tag; if omitted or set to null then moderation status will not be set (optional - default is null) * @param $pn_user_id [integer] A valid ca_users.user_id valid; if set only tag relations created by the specified user will be modifed (optional - default is null) */ public function changeTagAccess($pn_relation_id, $pn_access=0, $pn_moderator=null, $pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $t_ixt = new ca_items_x_tags($pn_relation_id); if (!$t_ixt->getPrimaryKey()) { $this->postError(2800, _t('Tag relation id is invalid'), 'BaseModel->changeTagAccess()'); return false; } if ( ($t_ixt->get('table_num') != $this->tableNum()) || ($t_ixt->get('row_id') != $vn_row_id) ) { $this->postError(2810, _t('Tag is not part of the current row'), 'BaseModel->changeTagAccess()'); return false; } if ($pn_user_id) { if ($t_ixt->get('user_id') != $pn_user_id) { $this->postError(2820, _t('Tag was not created by specified user'), 'BaseModel->changeTagAccess()'); return false; } } $t_ixt->setMode(ACCESS_WRITE); $t_ixt->set('access', $pn_access); if (!is_null($pn_moderator)) { $t_ixt->set('moderated_by_user_id', $pn_moderator); $t_ixt->set('moderated_on', 'now'); } $t_ixt->update(); if ($t_ixt->numErrors()) { $this->errors = $t_ixt->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Deletes the tag relation specified by $pn_relation_id (a ca_items_x_tags.relation_id value) from the currently loaded row. Will only delete * tags attached to the currently loaded row. If you attempt to delete a ca_items_x_tags.relation_id not attached to the current row * removeTag() will return false and post an error. If you attempt to call removeTag() with no row loaded null will be returned. * If $pn_user_id is specified then only tags created by the specified user will be deleted; if the tag being * deleted is not created by the user then false is returned and an error posted. * * @param $pn_relation_id [integer] a valid ca_items_x_tags.relation_id to be removed; must be related to the currently loaded row (mandatory) * @param $pn_user_id [integer] a valid ca_users.user_id value; if specified then only tag relations added by the specified user will be deleted (optional - default is null) */ public function removeTag($pn_relation_id, $pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $t_ixt = new ca_items_x_tags($pn_relation_id); if (!$t_ixt->getPrimaryKey()) { $this->postError(2800, _t('Tag relation id is invalid'), 'BaseModel->removeTag()'); return false; } if ( ($t_ixt->get('table_num') != $this->tableNum()) || ($t_ixt->get('row_id') != $vn_row_id) ) { $this->postError(2810, _t('Tag is not part of the current row'), 'BaseModel->removeTag()'); return false; } if ($pn_user_id) { if ($t_ixt->get('user_id') != $pn_user_id) { $this->postError(2820, _t('Tag was not created by specified user'), 'BaseModel->removeTag()'); return false; } } $t_ixt->setMode(ACCESS_WRITE); $t_ixt->delete(); if ($t_ixt->numErrors()) { $this->errors = $t_ixt->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Removes all tags associated with the currently loaded row. Will return null if no row is currently loaded. * If the optional $ps_user_id parameter is passed then only tags added by the specified user will be removed. * * @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only tags added by the specified user will be removed. (optional - default is null) */ public function removeAllTags($pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $va_tags = $this->getTags($pn_user_id); foreach($va_tags as $va_tag) { if (!$this->removeTag($va_tag['tag_id'], $pn_user_id)) { return false; } } return true; } # -------------------------------------------------------------------------------------------- /** * Returns all tags associated with the currently loaded row. Will return null if not row is currently loaded. * If the optional $ps_user_id parameter is passed then only tags created by the specified user will be returned. * If the optional $pb_moderation_status parameter is passed then only tags matching the criteria will be returned: * Passing $pb_moderation_status = TRUE will cause only moderated tags to be returned * Passing $pb_moderation_status = FALSE will cause only unmoderated tags to be returned * If you want both moderated and unmoderated tags to be returned then omit the parameter or pass a null value * * @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only tags added by the specified user will be returned. (optional - default is null) * @param $pn_moderation_status [boolean] To return only unmoderated tags set to FALSE; to return only moderated tags set to TRUE; to return all tags set to null or omit */ public function getTags($pn_user_id=null, $pb_moderation_status=null, $pn_row_id=null) { if (!($vn_row_id = $pn_row_id)) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } } $o_db = $this->getDb(); $vs_user_sql = ($pn_user_id) ? ' AND (cixt.user_id = '.intval($pn_user_id).')' : ''; $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (cixt.moderated_on IS NOT NULL)' : ' AND (cixt.moderated_on IS NULL)'; } $qr_comments = $o_db->query(" SELECT * FROM ca_item_tags cit INNER JOIN ca_items_x_tags AS cixt ON cit.tag_id = cixt.tag_id WHERE (cixt.table_num = ?) AND (cixt.row_id = ?) {$vs_user_sql} {$vs_moderation_sql} ", $this->tableNum(), $vn_row_id); return $qr_comments->getAllRows(); } # -------------------------------------------------------------------------------------------- # User commenting # -------------------------------------------------------------------------------------------- /** * Adds a comment to currently loaded row. Returns null if no row is loaded. Otherwise returns true * if comment was successfully added, false if an error occurred in which case the errors will be available * via the model's standard error methods (getErrors() and friends. * * Most of the parameters are optional with the exception of $ps_comment - the text of the comment. Note that * comment text is monolingual; if you want to do multilingual comments (which aren't really comments then, are they?) then * you should add multiple comments. * * @param $ps_comment [string] Text of the comment (mandatory) * @param $pn_rating [integer] A number between 1 and 5 indicating the user's rating of the row; larger is better (optional - default is null) * @param $pn_user_id [integer] A valid ca_users.user_id indicating the user who posted the comment; is null for comments from non-logged-in users (optional - default is null) * @param $pn_locale_id [integer] A valid ca_locales.locale_id indicating the language of the comment. If omitted or left null then the value in the global $g_ui_locale_id variable is used. If $g_ui_locale_id is not set and $pn_locale_id is not set then an error will occur (optional - default is to use $g_ui_locale_id) * @param $ps_name [string] Name of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null) * @param $ps_email [string] E-mail address of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null) * @param $pn_access [integer] Determines public visibility of comments; if set to 0 then comment is not visible to public; if set to 1 comment is visible (optional - default is 0) * @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the comment; if omitted or set to null then moderation status will not be set unless app.conf setting dont_moderate_comments = 1 (optional - default is null) * @param array $pa_options Array of options. Supported options are: * purify = if true, comment, name and email are run through HTMLPurifier before being stored in the database. Default is true. * media1_original_filename = original file name to set for comment "media1" * media2_original_filename = original file name to set for comment "media2" * media3_original_filename = original file name to set for comment "media3" * media4_original_filename = original file name to set for comment "media4" */ public function addComment($ps_comment, $pn_rating=null, $pn_user_id=null, $pn_locale_id=null, $ps_name=null, $ps_email=null, $pn_access=0, $pn_moderator=null, $pa_options=null, $ps_media1=null, $ps_media2=null, $ps_media3=null, $ps_media4=null) { global $g_ui_locale_id; if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; } if(!isset($pa_options['purify'])) { $pa_options['purify'] = true; } if ((bool)$pa_options['purify']) { $o_purifier = new HTMLPurifier(); $ps_comment = $o_purifier->purify($ps_comment); $ps_name = $o_purifier->purify($ps_name); $ps_email = $o_purifier->purify($ps_email); } $t_comment = new ca_item_comments(); $t_comment->setMode(ACCESS_WRITE); $t_comment->set('table_num', $this->tableNum()); $t_comment->set('row_id', $vn_row_id); $t_comment->set('user_id', $pn_user_id); $t_comment->set('locale_id', $pn_locale_id); $t_comment->set('comment', $ps_comment); $t_comment->set('rating', $pn_rating); $t_comment->set('email', $ps_email); $t_comment->set('name', $ps_name); $t_comment->set('access', $pn_access); $t_comment->set('media1', $ps_media1, array('original_filename' => $pa_options['media1_original_filename'])); $t_comment->set('media2', $ps_media2, array('original_filename' => $pa_options['media2_original_filename'])); $t_comment->set('media3', $ps_media3, array('original_filename' => $pa_options['media3_original_filename'])); $t_comment->set('media4', $ps_media4, array('original_filename' => $pa_options['media4_original_filename'])); if (!is_null($pn_moderator)) { $t_comment->set('moderated_by_user_id', $pn_moderator); $t_comment->set('moderated_on', 'now'); }elseif($this->_CONFIG->get("dont_moderate_comments")){ $t_comment->set('moderated_on', 'now'); } $t_comment->insert(); if ($t_comment->numErrors()) { $this->errors = $t_comment->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Edits an existing comment as specified by $pn_comment_id. Will only edit comments that are attached to the * currently loaded row. If called with no row loaded editComment() will return null. If you attempt to modify * a comment not associated with the currently loaded row editComment() will return false and post an error. * Note that all parameters are mandatory in the sense that the value passed (or the default value if not passed) * will be written into the comment. For example, if you don't bother passing $ps_name then it will be set to null, even * if there's an existing name value in the field. The only exception is $pn_locale_id; if set to null or omitted then * editComment() will attempt to use the locale value in the global $g_ui_locale_id variable. If this is not set then * an error will be posted and editComment() will return false. * * @param $pn_comment_id [integer] a valid comment_id to be edited; must be related to the currently loaded row (mandatory) * @param $ps_comment [string] the text of the comment (mandatory) * @param $pn_rating [integer] a number between 1 and 5 indicating the user's rating of the row; higher is better (optional - default is null) * @param $pn_user_id [integer] A valid ca_users.user_id indicating the user who posted the comment; is null for comments from non-logged-in users (optional - default is null) * @param $pn_locale_id [integer] A valid ca_locales.locale_id indicating the language of the comment. If omitted or left null then the value in the global $g_ui_locale_id variable is used. If $g_ui_locale_id is not set and $pn_locale_id is not set then an error will occur (optional - default is to use $g_ui_locale_id) * @param $ps_name [string] Name of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null) * @param $ps_email [string] E-mail address of user posting comment. Only needs to be set if $pn_user_id is *not* set; used to identify comments posted by non-logged-in users (optional - default is null) * @param $pn_access [integer] Determines public visibility of comments; if set to 0 then comment is not visible to public; if set to 1 comment is visible (optional - default is 0) * @param $pn_moderator [integer] A valid ca_users.user_id value indicating who moderated the comment; if omitted or set to null then moderation status will not be set (optional - default is null) * @param array $pa_options Array of options. Supported options are: * purify = if true, comment, name and email are run through HTMLPurifier before being stored in the database. Default is true. * media1_original_filename = original file name to set for comment "media1" * media2_original_filename = original file name to set for comment "media2" * media3_original_filename = original file name to set for comment "media3" * media4_original_filename = original file name to set for comment "media4" */ public function editComment($pn_comment_id, $ps_comment, $pn_rating=null, $pn_user_id=null, $pn_locale_id=null, $ps_name=null, $ps_email=null, $pn_access=null, $pn_moderator=null, $pa_options=null, $ps_media1=null, $ps_media2=null, $ps_media3=null, $ps_media4=null) { global $g_ui_locale_id; if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; } $t_comment = new ca_item_comments($pn_comment_id); if (!$t_comment->getPrimaryKey()) { $this->postError(2800, _t('Comment id is invalid'), 'BaseModel->editComment()'); return false; } if ( ($t_comment->get('table_num') != $this->tableNum()) || ($t_comment->get('row_id') != $vn_row_id) ) { $this->postError(2810, _t('Comment is not part of the current row'), 'BaseModel->editComment()'); return false; } if(!isset($pa_options['purify'])) { $pa_options['purify'] = true; } if ((bool)$pa_options['purify']) { $o_purifier = new HTMLPurifier(); $ps_comment = $o_purifier->purify($ps_comment); $ps_name = $o_purifier->purify($ps_name); $ps_email = $o_purifier->purify($ps_email); } $t_comment->setMode(ACCESS_WRITE); $t_comment->set('comment', $ps_comment); $t_comment->set('rating', $pn_rating); $t_comment->set('user_id', $pn_user_id); $t_comment->set('name', $ps_name); $t_comment->set('email', $ps_email); $t_comment->set('media1', $ps_media1, array('original_filename' => $pa_options['media1_original_filename'])); $t_comment->set('media2', $ps_media2, array('original_filename' => $pa_options['media2_original_filename'])); $t_comment->set('media3', $ps_media3, array('original_filename' => $pa_options['media3_original_filename'])); $t_comment->set('media4', $ps_media4, array('original_filename' => $pa_options['media4_original_filename'])); if (!is_null($pn_moderator)) { $t_comment->set('moderated_by_user_id', $pn_moderator); $t_comment->set('moderated_on', 'now'); } if (!is_null($pn_locale_id)) { $t_comment->set('locale_id', $pn_locale_id); } $t_comment->update(); if ($t_comment->numErrors()) { $this->errors = $t_comment->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Permanently deletes the comment specified by $pn_comment_id. Will only delete comments attached to the * currently loaded row. If you attempt to delete a comment_id not attached to the current row removeComment() * will return false and post an error. If you attempt to call removeComment() with no row loaded null will be returned. * If $pn_user_id is specified then only comments created by the specified user will be deleted; if the comment being * deleted is not created by the user then false is returned and an error posted. * * @param $pn_comment_id [integer] a valid comment_id to be removed; must be related to the currently loaded row (mandatory) * @param $pn_user_id [integer] a valid ca_users.user_id value; if specified then only comments by the specified user will be deleted (optional - default is null) */ public function removeComment($pn_comment_id, $pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $t_comment = new ca_item_comments($pn_comment_id); if (!$t_comment->getPrimaryKey()) { $this->postError(2800, _t('Comment id is invalid'), 'BaseModel->removeComment()'); return false; } if ( ($t_comment->get('table_num') != $this->tableNum()) || ($t_comment->get('row_id') != $vn_row_id) ) { $this->postError(2810, _t('Comment is not part of the current row'), 'BaseModel->removeComment()'); return false; } if ($pn_user_id) { if ($t_comment->get('user_id') != $pn_user_id) { $this->postError(2820, _t('Comment was not created by specified user'), 'BaseModel->removeComment()'); return false; } } $t_comment->setMode(ACCESS_WRITE); $t_comment->delete(); if ($t_comment->numErrors()) { $this->errors = $t_comment->errors; return false; } return true; } # -------------------------------------------------------------------------------------------- /** * Removes all comments associated with the currently loaded row. Will return null if no row is currently loaded. * If the optional $ps_user_id parameter is passed then only comments created by the specified user will be removed. * * @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only comments by the specified user will be removed. (optional - default is null) */ public function removeAllComments($pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $va_comments = $this->getComments($pn_user_id); foreach($va_comments as $va_comment) { if (!$this->removeComment($va_comment['comment_id'], $pn_user_id)) { return false; } } return true; } # -------------------------------------------------------------------------------------------- /** * Returns all comments associated with the currently loaded row. Will return null if not row is currently loaded. * If the optional $ps_user_id parameter is passed then only comments created by the specified user will be returned. * If the optional $pb_moderation_status parameter is passed then only comments matching the criteria will be returned: * Passing $pb_moderation_status = TRUE will cause only moderated comments to be returned * Passing $pb_moderation_status = FALSE will cause only unmoderated comments to be returned * If you want both moderated and unmoderated comments to be returned then omit the parameter or pass a null value * * @param $pn_user_id [integer] A valid ca_users.user_id value. If specified, only comments by the specified user will be returned. (optional - default is null) * @param $pn_moderation_status [boolean] To return only unmoderated comments set to FALSE; to return only moderated comments set to TRUE; to return all comments set to null or omit */ public function getComments($pn_user_id=null, $pb_moderation_status=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $o_db = $this->getDb(); $vs_user_sql = ($pn_user_id) ? ' AND (user_id = '.intval($pn_user_id).')' : ''; $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)'; } $qr_comments = $o_db->query(" SELECT * FROM ca_item_comments WHERE (table_num = ?) AND (row_id = ?) {$vs_user_sql} {$vs_moderation_sql} ", $this->tableNum(), $vn_row_id); $va_comments = array(); while($qr_comments->nextRow()){ $va_comments[$qr_comments->get("comment_id")] = $qr_comments->getRow(); foreach(array("media1", "media2", "media3", "media4") as $vs_media_field){ $va_media_versions = array(); $va_media_versions = $qr_comments->getMediaVersions($vs_media_field); $va_media = array(); if(is_array($va_media_versions) && (sizeof($va_media_versions) > 0)){ foreach($va_media_versions as $vs_version){ $va_image_info = array(); $va_image_info = $qr_comments->getMediaInfo($vs_media_field, $vs_version); $va_image_info["TAG"] = $qr_comments->getMediaTag($vs_media_field, $vs_version); $va_image_info["URL"] = $qr_comments->getMediaUrl($vs_media_field, $vs_version); $va_media[$vs_version] = $va_image_info; } $va_comments[$qr_comments->get("comment_id")][$vs_media_field] = $va_media; } } } return $va_comments; } # -------------------------------------------------------------------------------------------- /** * Returns average user rating of item */ public function getAverageRating($pb_moderation_status=true) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)'; } $o_db = $this->getDb(); $qr_comments = $o_db->query(" SELECT avg(rating) r FROM ca_item_comments WHERE (table_num = ?) AND (row_id = ?) {$vs_moderation_sql} ", $this->tableNum(), $vn_row_id); if ($qr_comments->nextRow()) { return round($qr_comments->get('r')); } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Returns number of user ratings for item */ public function getNumRatings($pb_moderation_status=true) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)'; } $o_db = $this->getDb(); $qr_ratings = $o_db->query(" SELECT count(*) c FROM ca_item_comments WHERE (rating > 0) AND (table_num = ?) AND (row_id = ?) {$vs_moderation_sql} ", $this->tableNum(), $vn_row_id); if ($qr_ratings->nextRow()) { return round($qr_ratings->get('c')); } else { return null; } } # -------------------------------------------------------------------------------------------- /** * Return the highest rated item(s) * Return an array of primary key values */ public function getHighestRated($pb_moderation_status=true, $pn_num_to_return=1, $va_access_values = array()) { $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)'; } $vs_access_join = ""; $vs_access_where = ""; $vs_table_name = $this->tableName(); $vs_primary_key = $this->primaryKey(); if (isset($va_access_values) && is_array($va_access_values) && sizeof($va_access_values) && $this->hasField('access')) { if ($vs_table_name && $vs_primary_key) { $vs_access_join = 'INNER JOIN '.$vs_table_name.' as rel ON rel.'.$vs_primary_key." = ca_item_comments.row_id "; $vs_access_where = ' AND rel.access IN ('.join(',', $va_access_values).')'; } } $vs_deleted_sql = ''; if ($this->hasField('deleted')) { $vs_deleted_sql = " AND (rel.deleted = 0) "; } if ($vs_deleted_sql || $vs_access_where) { $vs_access_join = 'INNER JOIN '.$vs_table_name.' as rel ON rel.'.$vs_primary_key." = ca_item_comments.row_id "; } $o_db = $this->getDb(); $qr_comments = $o_db->query($x=" SELECT ca_item_comments.row_id FROM ca_item_comments {$vs_access_join} WHERE (ca_item_comments.table_num = ?) {$vs_moderation_sql} {$vs_access_where} {$vs_deleted_sql} GROUP BY ca_item_comments.row_id ORDER BY avg(ca_item_comments.rating) DESC, MAX(ca_item_comments.created_on) DESC LIMIT {$pn_num_to_return} ", $this->tableNum()); $va_row_ids = array(); while ($qr_comments->nextRow()) { $va_row_ids[] = $qr_comments->get('row_id'); } return $va_row_ids; } # -------------------------------------------------------------------------------------------- /** * Return the number of ratings * Return an integer count */ public function getRatingsCount($pb_moderation_status=true) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $vs_moderation_sql = ''; if (!is_null($pb_moderation_status)) { $vs_moderation_sql = ($pb_moderation_status) ? ' AND (ca_item_comments.moderated_on IS NOT NULL)' : ' AND (ca_item_comments.moderated_on IS NULL)'; } $o_db = $this->getDb(); $qr_comments = $o_db->query(" SELECT count(*) c FROM ca_item_comments WHERE (ca_item_comments.table_num = ?) AND (ca_item_comments.row_id = ?) {$vs_moderation_sql} ", $this->tableNum(), $vn_row_id); if ($qr_comments->nextRow()) { return $qr_comments->get('c'); } return 0; } # -------------------------------------------------------------------------------------------- /** * Increments the view count for this item * * @param int $pn_user_id User_id of user viewing item. Omit of set null if user is not logged in. * * @return bool True on success, false on error. */ public function registerItemView($pn_user_id=null) { global $g_ui_locale_id; if (!($vn_row_id = $this->getPrimaryKey())) { return null; } if (!$pn_locale_id) { $pn_locale_id = $g_ui_locale_id; } $vn_table_num = $this->tableNum(); $t_view = new ca_item_views(); $t_view->setMode(ACCESS_WRITE); $t_view->set('table_num', $vn_table_num); $t_view->set('row_id', $vn_row_id); $t_view->set('user_id', $pn_user_id); $t_view->set('locale_id', $pn_locale_id); $t_view->insert(); if ($t_view->numErrors()) { $this->errors = $t_view->errors; return false; } $o_db = $this->getDb(); // increment count $qr_res = $o_db->query(" SELECT * FROM ca_item_view_counts WHERE table_num = ? AND row_id = ? ", $vn_table_num, $vn_row_id); if ($qr_res->nextRow()) { $o_db->query(" UPDATE ca_item_view_counts SET view_count = view_count + 1 WHERE table_num = ? AND row_id = ? ", $vn_table_num, $vn_row_id); } else { $o_db->query(" INSERT INTO ca_item_view_counts (table_num, row_id, view_count) VALUES (?, ?, 1) ", $vn_table_num, $vn_row_id); } $o_cache = caGetCacheObject("caRecentlyViewedCache"); if (!is_array($va_recently_viewed_list = $o_cache->load('recentlyViewed'))) { $va_recently_viewed_list = array(); } if (!is_array($va_recently_viewed_list[$vn_table_num])) { $va_recently_viewed_list[$vn_table_num] = array(); } while(sizeof($va_recently_viewed_list[$vn_table_num]) > 100) { array_pop($va_recently_viewed_list[$vn_table_num]); } if (!in_array($vn_row_id, $va_recently_viewed_list[$vn_table_num])) { array_unshift($va_recently_viewed_list[$vn_table_num], $vn_row_id); } $o_cache->save($va_recently_viewed_list, 'recentlyViewed'); return true; } # -------------------------------------------------------------------------------------------- /** * Clears view count for the currently loaded row * * @param int $pn_user_id If set, only views from the specified user are cleared * @return bool True on success, false on error */ public function clearItemViewCount($pn_user_id=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $o_db = $this->getDb(); $vs_user_sql = ''; if ($pn_user_id) { $vs_user_sql = " AND user_id = ".intval($pn_user_id); } $qr_res = $o_db->query(" DELETE FROM ca_item_views WHERE table_num = ? AND row_id = ? {$vs_user_sql} ", $this->tableNum(), $vn_row_id); $qr_res = $o_db->query(" UPDATE ca_item_view_counts SET view_count = 0 WHERE table_num = ? AND row_id = ? {$vs_user_sql} ", $this->tableNum(), $vn_row_id); return $o_db->numErrors() ? false : true; } # -------------------------------------------------------------------------------------------- /** * Get view list for currently loaded row. * * @param int $pn_user_id If set, only views from the specified user are returned * @param array $pa_options Supported options are: * restrictToTypes = array of type names or type_ids to restrict to * hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation * checkAccess = an array of access values to filter only. Views will only be returned if the item's access setting is in the array. * @return bool True on success, false on error */ public function getViewList($pn_user_id=null, $pa_options=null) { if (!($vn_row_id = $this->getPrimaryKey())) { return null; } $o_db = $this->getDb(); $vs_limit_sql = ''; if ($pn_limit > 0) { $vs_limit_sql = "LIMIT ".intval($pn_limit); } $va_wheres = array('(civc.table_num = ?)'); if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) { $va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')'; } if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) { $va_types = caMergeTypeRestrictionLists($this, $pa_options); if (is_array($va_types) && sizeof($va_types)) { $va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')'; } } $vs_join_sql = ''; if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) { $vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id'; $va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1'; } if ($pn_user_id) { $va_wheres[] = "civ.user_id = ".intval($pn_user_id); } if ($vs_where_sql = join(' AND ', $va_wheres)) { $vs_where_sql = ' WHERE '.$vs_where_sql; } $qr_res = $o_db->query(" SELECT t.*, count(*) cnt FROM ".$this->tableName()." t INNER JOIN ca_item_views AS civ ON civ.row_id = t.".$this->primaryKey()." WHERE civ.table_num = ? AND row_id = ? {$vs_user_sql} {$vs_access_sql} GROUP BY civ.row_id ORDER BY cnt DESC {$vs_limit_sql} ", $this->tableNum(), $vn_row_id); $va_items = array(); while($qr_res->nextRow()) { $va_items[] = $qr_res->getRow(); } return $va_items; } # -------------------------------------------------------------------------------------------- /** * Returns a list of the items with the most views. * * @param int $pn_limit Limit list to the specified number of items. Defaults to 10 if not specified. * @param array $pa_options Supported options are: * restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned. * hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation. * checkAccess = an array of access values to filter only. Items will only be returned if the item's access setting is in the array. * @return bool True on success, false on error */ public function getMostViewedItems($pn_limit=10, $pa_options=null) { $o_db = $this->getDb(); $vs_limit_sql = ''; if ($pn_limit > 0) { $vs_limit_sql = "LIMIT ".intval($pn_limit); } $va_wheres = array('(civc.table_num = '.intval($this->tableNum()).')'); if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) { $va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')'; } if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) { $va_types = caMergeTypeRestrictionLists($this, $pa_options); if (is_array($va_types) && sizeof($va_types)) { $va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')'; } } $vs_join_sql = ''; if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) { $vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id'; $va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1'; } if ($this->hasField('deleted')) { $va_wheres[] = "(t.deleted = 0)"; } if ($vs_where_sql = join(' AND ', $va_wheres)) { $vs_where_sql = ' WHERE '.$vs_where_sql; } $qr_res = $o_db->query(" SELECT t.*, civc.view_count cnt FROM ".$this->tableName()." t INNER JOIN ca_item_view_counts AS civc ON civc.row_id = t.".$this->primaryKey()." {$vs_join_sql} {$vs_where_sql} ORDER BY civc.view_count DESC {$vs_limit_sql} "); $va_most_viewed_items = array(); while($qr_res->nextRow()) { $va_most_viewed_items[$qr_res->get($this->primaryKey())] = $qr_res->getRow(); } return $va_most_viewed_items; } # -------------------------------------------------------------------------------------------- /** * Returns the most recently viewed items, up to a maximum of $pn_limit (default is 10) * Note that the limit is just that – a limit. getRecentlyViewedItems() may return fewer * than the limit either because there fewer viewed items than your limit or because fetching * additional views would take too long. (To ensure adequate performance getRecentlyViewedItems() uses a cache of * recent views. If there is no cache available it will query the database to look at the most recent (4 x your limit) viewings. * If there are many views of the same item in that group then it is possible that fewer items than your limit will be returned) * * @param int $pn_limit The maximum number of items to return. Default is 10. * @param array $pa_options Supported options are: * restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned. * checkAccess = array of access values to filter results by; if defined only items with the specified access code(s) are returned * hasRepresentations = if set to a non-zero (boolean true) value only items with representations will be returned * dontUseCache = if set to true, forces list to be generated from database; default is false. * @return array List of primary key values for recently viewed items. */ public function getRecentlyViewedItems($pn_limit=10, $pa_options=null) { if (!isset($pa_options['dontUseCache']) || !$pa_options['dontUseCache']) { $o_cache = caGetCacheObject("caRecentlyViewedCache"); $va_recently_viewed_items = $o_cache->load('recentlyViewed'); $vn_table_num = $this->tableNum(); if(is_array($va_recently_viewed_items) && is_array($va_recently_viewed_items[$vn_table_num])) { if(sizeof($va_recently_viewed_items[$vn_table_num]) > $pn_limit) { $va_recently_viewed_items[$vn_table_num] = array_slice($va_recently_viewed_items[$vn_table_num], 0, $pn_limit); } return $va_recently_viewed_items[$vn_table_num]; } } $o_db = $this->getDb(); $vs_limit_sql = ''; if ($pn_limit > 0) { $vs_limit_sql = "LIMIT ".(intval($pn_limit) * 4); } $va_wheres = array('(civ.table_num = '.intval($this->tableNum()).')'); if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) { $va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')'; } if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) { $va_types = caMergeTypeRestrictionLists($this, $pa_options); if (is_array($va_types) && sizeof($va_types)) { $va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')'; } } $vs_join_sql = ''; if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) { $vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id'; $va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1'; } if ($this->hasField('deleted')) { $va_wheres[] = "(t.deleted = 0)"; } if ($vs_where_sql = join(' AND ', $va_wheres)) { $vs_where_sql = ' WHERE '.$vs_where_sql; } $qr_res = $o_db->query($vs_sql = " SELECT t.".$this->primaryKey()." FROM ".$this->tableName()." t INNER JOIN ca_item_views AS civ ON civ.row_id = t.".$this->primaryKey()." {$vs_join_sql} {$vs_where_sql} ORDER BY civ.view_id DESC {$vs_limit_sql} "); $va_recently_viewed_items = array(); $vn_c = 0; while($qr_res->nextRow() && ($vn_c < $pn_limit)) { if (!isset($va_recently_viewed_items[$vn_id = $qr_res->get($this->primaryKey())])) { $va_recently_viewed_items[$vn_id] = true; $vn_c++; } } return array_keys($va_recently_viewed_items); } # -------------------------------------------------------------------------------------------- /** * Returns a list of items recently added to the database. * * @param int $pn_limit Limit list to the specified number of items. Defaults to 10 if not specified. * @param array $pa_options Supported options are: * restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned. * hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation. * checkAccess = an array of access values to filter only. Items will only be returned if the item's access setting is in the array. * @return bool True on success, false on error */ public function getRecentlyAddedItems($pn_limit=10, $pa_options=null) { $o_db = $this->getDb(); $vs_limit_sql = ''; if ($pn_limit > 0) { $vs_limit_sql = "LIMIT ".intval($pn_limit); } $va_wheres = array(); if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) { $va_wheres[] = 't.access IN ('.join(',', $pa_options['checkAccess']).')'; } if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) { $va_types = caMergeTypeRestrictionLists($this, $pa_options); if (is_array($va_types) && sizeof($va_types)) { $va_wheres[] = 't.'.$vs_type_field_name.' IN ('.join(',', $va_types).')'; } } $vs_join_sql = ''; if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) { $vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = t.object_id'; $va_wheres[] = 'ca_objects_x_object_representations.is_primary = 1'; if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess'])) { $vs_join_sql .= ' INNER JOIN ca_object_representations ON ca_object_representations.representation_id = ca_objects_x_object_representations.representation_id'; $va_wheres[] = 'ca_object_representations.access IN ('.join(',', $pa_options['checkAccess']).')'; } } $vs_deleted_sql = ''; if ($this->hasField('deleted')) { $va_wheres[] = "(t.deleted = 0)"; } if ($vs_where_sql = join(' AND ', $va_wheres)) { $vs_where_sql = " WHERE {$vs_where_sql}"; } $vs_primary_key = $this->primaryKey(); $qr_res = $o_db->query(" SELECT t.* FROM ".$this->tableName()." t {$vs_join_sql} {$vs_where_sql} ORDER BY t.".$vs_primary_key." DESC {$vs_limit_sql} "); $va_recently_added_items = array(); while($qr_res->nextRow()) { $va_recently_added_items[$qr_res->get($this->primaryKey())] = $qr_res->getRow(); } return $va_recently_added_items; } # -------------------------------------------------------------------------------------------- /** * Return set of random rows (up to $pn_limit) subject to access restriction in $pn_access * Set $pn_access to null or omit to return items regardless of access control status * * @param int $pn_limit Limit list to the specified number of items. Defaults to 10 if not specified. * @param array $pa_options Supported options are: * restrictToTypes = array of type names or type_ids to restrict to. Only items with a type_id in the list will be returned. * hasRepresentations = if set when model is for ca_objects views are only returned when the object has at least one representation. * checkAccess = an array of access values to filter only. Items will only be returned if the item's access setting is in the array. * @return bool True on success, false on error */ public function getRandomItems($pn_limit=10, $pa_options=null) { $o_db = $this->getDb(); $vs_limit_sql = ''; if ($pn_limit > 0) { $vs_limit_sql = "LIMIT ".intval($pn_limit); } $vs_primary_key = $this->primaryKey(); $vs_table_name = $this->tableName(); $va_wheres = array(); if (is_array($pa_options['checkAccess']) && sizeof($pa_options['checkAccess']) && ($this->hasField('access'))) { $va_wheres[] = $vs_table_name.'.access IN ('.join(',', $pa_options['checkAccess']).')'; } if (method_exists($this, 'getTypeFieldName') && ($vs_type_field_name = $this->getTypeFieldName())) { $va_types = caMergeTypeRestrictionLists($this, $pa_options); if (is_array($va_types) && sizeof($va_types)) { $va_wheres[] = $vs_table_name.'.'.$vs_type_field_name.' IN ('.join(',', $va_types).')'; } } $vs_join_sql = ''; if (isset($pa_options['hasRepresentations']) && $pa_options['hasRepresentations'] && ($this->tableName() == 'ca_objects')) { $vs_join_sql = ' INNER JOIN ca_objects_x_object_representations ON ca_objects_x_object_representations.object_id = '.$vs_table_name.'.object_id'; } if ($this->hasField('deleted')) { $va_wheres[] = "{$vs_table_name}.deleted = 0"; } $vs_sql = " SELECT {$vs_table_name}.* FROM ( SELECT {$vs_table_name}.{$vs_primary_key} FROM {$vs_table_name} {$vs_join_sql} ".(sizeof($va_wheres) ? " WHERE " : "").join(" AND ", $va_wheres)." ORDER BY RAND() {$vs_limit_sql} ) AS random_items INNER JOIN {$vs_table_name} ON {$vs_table_name}.{$vs_primary_key} = random_items.{$vs_primary_key} {$vs_deleted_sql} "; $qr_res = $o_db->query($vs_sql); $va_random_items = array(); while($qr_res->nextRow()) { $va_random_items[$qr_res->get($this->primaryKey())] = $qr_res->getRow(); } return $va_random_items; } # -------------------------------------------------------------------------------------------- # Change log display # -------------------------------------------------------------------------------------------- /** * Returns change log for currently loaded row in displayable HTML format */ public function getChangeLogForDisplay($ps_css_id=null) { $o_log = new ApplicationChangeLog(); return $o_log->getChangeLogForRowForDisplay($this, $ps_css_id); } # -------------------------------------------------------------------------------------------- # # -------------------------------------------------------------------------------------------- /** * */ static public function getLoggingUnitID() { return md5(getmypid().microtime()); } # -------------------------------------------------------------------------------------------- /** * */ static public function getCurrentLoggingUnitID() { global $g_change_log_unit_id; return $g_change_log_unit_id; } # -------------------------------------------------------------------------------------------- /** * */ static public function setChangeLogUnitID() { global $g_change_log_unit_id; if (!$g_change_log_unit_id) { $g_change_log_unit_id = BaseModel::getLoggingUnitID(); return true; } return false; } # -------------------------------------------------------------------------------------------- /** * */ static public function unsetChangeLogUnitID() { global $g_change_log_unit_id; $g_change_log_unit_id = null; return true; } # -------------------------------------------------------------------------------------------- /** * Returns number of records in table, filtering out those marked as deleted or those not meeting the specific access critera * * @param array $pa_access An option array of record-level access values to filter on. If omitted no filtering on access values is done. * @return int Number of records, or null if an error occurred. */ public function getCount($pa_access=null) { $o_db = new Db(); $va_wheres = array(); if (is_array($pa_access) && sizeof($pa_access) && $this->hasField('access')) { $va_wheres[] = "(access IN (".join(',', $pa_access)."))"; } if($this->hasField('deleted')) { $va_wheres[] = '(deleted = 0)'; } $vs_where_sql = join(" AND ", $va_wheres); $qr_res = $o_db->query(" SELECT count(*) c FROM ".$this->tableName()." ".(sizeof($va_wheres) ? ' WHERE ' : '')." {$vs_where_sql} "); if ($qr_res->nextRow()) { return (int)$qr_res->get('c'); } return null; } # -------------------------------------------------------------------------------------------- /** * Sets selected attribute of field in model to new value, overriding the value coded into the model for ** the duration of the current request** * This is useful in some unusual situations where you need to have a field behave differently than normal * without making permanent changes to the model. Don't use this unless you know what you're doing. * * @param string $ps_field The field * @param string $ps_attribute The attribute of the field * @param string $ps_value The value to set the attribute to * @return bool True if attribute was set, false if set failed because the field or attribute don't exist. */ public function setFieldAttribute($ps_field, $ps_attribute, $ps_value) { if(isset($this->FIELDS[$ps_field][$ps_attribute])) { $this->FIELDS[$ps_field][$ps_attribute] = $ps_value; return true; } return false; } # -------------------------------------------------------------------------------------------- /** * Destructor */ public function __destruct() { //print "Destruct ".$this->tableName()."\n"; //print (memory_get_usage()/1024)." used in ".$this->tableName()." destructor\n"; unset($this->o_db); unset($this->_CONFIG); unset($this->_DATAMODEL); unset($this->_MEDIA_VOLUMES); unset($this->_FILE_VOLUMES); unset($this->opo_app_plugin_manager); unset($this->_TRANSACTION); parent::__destruct(); } # -------------------------------------------------------------------------------------------- } // includes for which BaseModel must already be defined require_once(__CA_LIB_DIR__."/core/TaskQueue.php"); require_once(__CA_APP_DIR__.'/models/ca_lists.php'); require_once(__CA_APP_DIR__.'/models/ca_locales.php'); require_once(__CA_APP_DIR__.'/models/ca_item_tags.php'); require_once(__CA_APP_DIR__.'/models/ca_items_x_tags.php'); require_once(__CA_APP_DIR__.'/models/ca_item_comments.php'); require_once(__CA_APP_DIR__.'/models/ca_item_views.php'); ?>
Java
/* This file is part of calliope. * * calliope 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. * * calliope 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 calliope. If not, see <http://www.gnu.org/licenses/>. */ package calliope.handler.post; import calliope.Connector; import calliope.exception.AeseException; import calliope.handler.post.importer.*; import calliope.constants.Formats; import calliope.importer.Archive; import calliope.constants.Config; import calliope.json.JSONDocument; import calliope.constants.Database; import calliope.constants.Params; import calliope.constants.JSONKeys; import java.util.ArrayList; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.fileupload.servlet.ServletFileUpload; /** * Handle import of a set of XML files from a tool like mmpupload. * @author desmond 23-7-2012 */ public class AeseXMLImportHandler extends AeseImportHandler { public void handle( HttpServletRequest request, HttpServletResponse response, String urn ) throws AeseException { try { if (ServletFileUpload.isMultipartContent(request) ) { parseImportParams( request ); Archive cortex = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_TEXT,encoding); Archive corcode = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_STIL,encoding); cortex.setStyle( style ); corcode.setStyle( style ); StageOne stage1 = new StageOne( files ); log.append( stage1.process(cortex,corcode) ); if ( stage1.hasFiles() ) { String suffix = ""; StageTwo stage2 = new StageTwo( stage1, false ); stage2.setEncoding( encoding ); log.append( stage2.process(cortex,corcode) ); StageThreeXML stage3Xml = new StageThreeXML( stage2, style, dict, hhExceptions ); stage3Xml.setStripConfig( getConfig(Config.stripper, stripperName) ); stage3Xml.setSplitConfig( getConfig(Config.splitter, splitterName) ); if ( stage3Xml.hasTEI() ) { ArrayList<File> notes = stage3Xml.getNotes(); if ( notes.size()> 0 ) { Archive nCorTex = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_TEXT,encoding); nCorTex.setStyle( style ); Archive nCorCode = new Archive(docID.getWork(), docID.getAuthor(),Formats.MVD_STIL,encoding); StageThreeXML s3notes = new StageThreeXML( style,dict, hhExceptions); s3notes.setStripConfig( getConfig(Config.stripper, stripperName) ); s3notes.setSplitConfig( getConfig(Config.splitter, splitterName) ); for ( int j=0;j<notes.size();j++ ) s3notes.add(notes.get(j)); log.append( s3notes.process(nCorTex,nCorCode) ); addToDBase(nCorTex, "cortex", "notes" ); addToDBase( nCorCode, "corcode", "notes" ); // differentiate base from notes suffix = "base"; } if ( xslt == null ) xslt = Params.XSLT_DEFAULT; String transform = getConfig(Config.xslt,xslt); JSONDocument jDoc = JSONDocument.internalise( transform ); stage3Xml.setTransform( (String) jDoc.get(JSONKeys.BODY) ); } log.append( stage3Xml.process(cortex,corcode) ); addToDBase( cortex, "cortex", suffix ); addToDBase( corcode, "corcode", suffix ); // now get the json docs and add them at the right docid // Connector.getConnection().putToDb( Database.CORTEX, // docID.get(), cortex.toMVD("cortex") ); // log.append( cortex.getLog() ); // String fullAddress = docID.get()+"/"+Formats.DEFAULT; // log.append( Connector.getConnection().putToDb( // Database.CORCODE,fullAddress, corcode.toMVD("corcode")) ); // log.append( corcode.getLog() ); } response.setContentType("text/html;charset=UTF-8"); response.getWriter().println( wrapLog() ); } } catch ( Exception e ) { throw new AeseException( e ); } } }
Java
/* * 13.5.1 Thread Creation Scheduling Parameters, P1003.1c/Draft 10, p. 120 * * COPYRIGHT (c) 1989-1999. * On-Line Applications Research Corporation (OAR). * * The license and distribution terms for this file may be * found in the file LICENSE in this distribution or at * http://www.rtems.com/license/LICENSE. */ #if HAVE_CONFIG_H #include "config.h" #endif #include <pthread.h> #include <errno.h> int pthread_attr_setschedparam( pthread_attr_t *attr, const struct sched_param *param ) { if ( !attr || !attr->is_initialized || !param ) return EINVAL; attr->schedparam = *param; return 0; }
Java
/**************************************************************** * This file is distributed under the following license: * * Copyright (C) 2010, Bernd Stramm * * 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 <QRegExp> #include <QString> #include <QStringList> #include "shortener.h" #include "network-if.h" namespace chronicon { Shortener::Shortener (QObject *parent) :QObject (parent), network (0) { } void Shortener::SetNetwork (NetworkIF * net) { network = net; connect (network, SIGNAL (ShortenReply (QUuid, QString, QString, bool)), this, SLOT (CatchShortening (QUuid, QString, QString, bool))); } void Shortener::ShortenHttp (QString status, bool & wait) { if (network == 0) { emit DoneShortening (status); return; } QRegExp regular ("(https?://)(\\S*)"); status.append (" "); QStringList linkList; QStringList wholeList; int where (0), offset(0), lenSub(0); QString link, beforeLink; while ((where = regular.indexIn (status,offset)) > 0) { lenSub = regular.matchedLength(); beforeLink = status.mid (offset, where - offset); link = regular.cap(0); if ((!link.contains ("bit.ly")) && (!link.contains ("twitpic.com")) && (link.length() > QString("http://bit.ly/12345678").length())) { linkList << link; } wholeList << beforeLink; wholeList << link; offset = where + lenSub; } wholeList << status.mid (offset, -1); shortenTag = QUuid::createUuid(); if (linkList.isEmpty ()) { wait = false; } else { messageParts[shortenTag] = wholeList; linkParts [shortenTag] = linkList; network->ShortenHttp (shortenTag,linkList); wait = true; } } void Shortener::CatchShortening (QUuid tag, QString shortUrl, QString longUrl, bool good) { /// replace the longUrl with shortUrl in the messageParts[tag] // remove the longUrl from the linkParts[tag] // if the linkParts[tag] is empty, we have replaced all the links // so send append all the messageParts[tag] and finish the message if (messageParts.find(tag) == messageParts.end()) { return; // extra, perhaps duplicates in original, or not for me } if (linkParts.find(tag) == linkParts.end()) { return; } QStringList::iterator chase; for (chase = messageParts[tag].begin(); chase != messageParts[tag].end(); chase++) { if (*chase == longUrl) { *chase = shortUrl; } } linkParts[tag].removeAll (longUrl); if (linkParts[tag].isEmpty()) { QString message = messageParts[tag].join (QString()); emit DoneShortening (message); messageParts.erase (tag); } } } // namespace
Java
<?php // $Id$ require_once("../../config.php"); require_once("lib.php"); require_once($CFG->libdir.'/gradelib.php'); $id = required_param('id', PARAM_INT); // course if (! $course = get_record("course", "id", $id)) { error("Course ID is incorrect"); } require_course_login($course); add_to_log($course->id, "assignment", "view all", "index.php?id=$course->id", ""); $strassignments = get_string("modulenameplural", "assignment"); $strassignment = get_string("modulename", "assignment"); $strassignmenttype = get_string("assignmenttype", "assignment"); $strweek = get_string("week"); $strtopic = get_string("topic"); $strname = get_string("name"); $strduedate = get_string("duedate", "assignment"); $strsubmitted = get_string("submitted", "assignment"); $strgrade = get_string("grade"); $navlinks = array(); $navlinks[] = array('name' => $strassignments, 'link' => '', 'type' => 'activity'); $navigation = build_navigation($navlinks); print_header_simple($strassignments, "", $navigation, "", "", true, "", navmenu($course)); if (!$cms = get_coursemodules_in_course('assignment', $course->id, 'm.assignmenttype, m.timedue')) { notice(get_string('noassignments', 'assignment'), "../../course/view.php?id=$course->id"); die; } $timenow = time(); $table = new object; if ($course->format == "weeks") { $table->head = array ($strweek, $strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade); $table->align = array ("center", "left", "left", "left", "right"); } else if ($course->format == "topics") { $table->head = array ($strtopic, $strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade); $table->align = array ("center", "left", "left", "left", "right"); } else { $table->head = array ($strname, $strassignmenttype, $strduedate, $strsubmitted, $strgrade); $table->align = array ("left", "left", "left", "right"); } $currentsection = ""; $types = assignment_types(); $modinfo = get_fast_modinfo($course); foreach ($modinfo->instances['assignment'] as $cm) { if (!$cm->uservisible) { continue; } $cm->timedue = $cms[$cm->id]->timedue; $cm->assignmenttype = $cms[$cm->id]->assignmenttype; $cm->idnumber = get_field('course_modules', 'idnumber', 'id', $cm->id); //hack //Show dimmed if the mod is hidden $class = $cm->visible ? '' : 'class="dimmed"'; $link = "<a $class href=\"view.php?id=$cm->id\">".format_string($cm->name)."</a>"; $printsection = ""; if ($cm->sectionnum !== $currentsection) { if ($cm->sectionnum) { $printsection = $cm->sectionnum; } if ($currentsection !== "") { $table->data[] = 'hr'; } $currentsection = $cm->sectionnum; } if (!file_exists($CFG->dirroot.'/mod/assignment/type/'.$cm->assignmenttype.'/assignment.class.php')) { continue; } require_once ($CFG->dirroot.'/mod/assignment/type/'.$cm->assignmenttype.'/assignment.class.php'); $assignmentclass = 'assignment_'.$cm->assignmenttype; $assignmentinstance = new $assignmentclass($cm->id, NULL, $cm, $course); $submitted = $assignmentinstance->submittedlink(true); $grading_info = grade_get_grades($course->id, 'mod', 'assignment', $cm->instance, $USER->id); if (isset($grading_info->items[0]) && !$grading_info->items[0]->grades[$USER->id]->hidden ) { $grade = $grading_info->items[0]->grades[$USER->id]->str_grade; } else { $grade = '-'; } $type = $types[$cm->assignmenttype]; $due = $cm->timedue ? userdate($cm->timedue) : '-'; if ($course->format == "weeks" or $course->format == "topics") { $table->data[] = array ($printsection, $link, $type, $due, $submitted, $grade); } else { $table->data[] = array ($link, $type, $due, $submitted, $grade); } } echo "<br />"; print_table($table); print_footer($course); ?>
Java
void RedboxFactory::add (Addr addr, ActionType t) { switch (t) { case ActionType::RD8 : return add_read (addr, 1); case ActionType::RD16 : return add_read (addr, 2); case ActionType::RD32 : return add_read (addr, 4); case ActionType::RD64 : return add_read (addr, 8); case ActionType::WR8 : return add_write (addr, 1); case ActionType::WR16 : return add_write (addr, 2); case ActionType::WR32 : return add_write (addr, 4); case ActionType::WR64 : return add_write (addr, 8); default : SHOW (t, "d"); ASSERT (0); } } void RedboxFactory::add_read (Addr addr, unsigned size) { ASSERT (size); read_regions.emplace_back (addr, size); } void RedboxFactory::add_write (Addr addr, unsigned size) { ASSERT (size); write_regions.emplace_back (addr, size); } void RedboxFactory::clear () { read_regions.clear (); write_regions.clear (); } Redbox *RedboxFactory::create () { Redbox *b; // Special case: we return a null pointer if both memory pools are empty. // In this case the event will continue being labelled by a null pointer // rather than a pointer to a Redbox. This is useful during the data race // detection in DataRaceAnalysis::find_data_races(), because that way we // don't even need to look inside of the red box to see if it has events, the // event will straightfowardly be discarde for DR detection if (read_regions.empty() and write_regions.empty()) return nullptr; // allocate a new Redbox and keep the pointer to it, we are the container b = new Redbox (); boxes.push_back (b); // compress the lists of memory areas compress (read_regions); compress (write_regions); // copy them to the new redbox b->readpool = read_regions; b->writepool = write_regions; #ifdef CONFIG_DEBUG if (verb_debug) b->dump (); // this will assert that the memory pools are a sorted sequence of disjoint // memory areas b->readpool.assertt (); b->writepool.assertt (); #endif // restart the internal arrays read_regions.clear (); write_regions.clear (); ASSERT (empty()); return b; } void RedboxFactory::compress (MemoryPool::Container &regions) { unsigned i, j; size_t s; // nothing to do if we have no regions; code below assumes we have at least 1 if (regions.empty ()) return; // sort the memory regions by increasing value of lower bound struct compare { bool operator() (const MemoryRegion<Addr> &a, const MemoryRegion<Addr> &b) { return a.lower < b.lower; } } cmp; std::sort (regions.begin(), regions.end(), cmp); // compress regions s = regions.size (); breakme (); for (i = 0, j = 1; j < s; ++j) { ASSERT (i < j); ASSERT (regions[i].lower <= regions[j].lower); // if the next region's lower bound is below i's region upper bound, we can // extend i's range if (regions[i].upper >= regions[j].lower) { regions[i].upper = std::max (regions[i].upper, regions[j].upper); } else { // otherwise there is a gap betwen interval i and interval j, so we // need to create a new interval at offset i+1, only if i+1 != j ++i; if (i != j) { // copy j into i regions[i] = regions[j]; } } } DEBUG ("redbox-factory: compressed %zu regions into %u", regions.size(), i+1); regions.resize (i + 1); }
Java
///** // * ClassName: MainTest.java // * Date: 2017年5月16日 // */ //package com.ojdbc.sql.test; // //import java.sql.Connection; //import java.sql.SQLException; // //import com.ojdbc.sql.ConnectionObject; //import com.ojdbc.sql.DataBase; //import com.ojdbc.sql.DataBaseEnum; //import com.ojdbc.sql.DataBaseManager; //import com.ojdbc.sql.SQLResultSet; //import com.ojdbc.sql.connection.MongoDataBaseConnection; //import com.ojdbc.sql.connection.MySQLDataBaseConnection; //import com.ojdbc.sql.connection.OracleDataBaseConnection; //import com.ojdbc.sql.connection.SQLiteDataBaseConnection; // ///** // * Author: ShaoGaige // * Description: 猪测试类 // * Log: // */ //public class MainTest { // // /** // * @param args // * @throws SQLException // */ // public static void main(String[] args) throws SQLException { // // TODO Auto-generated method stub // ConnectionObject conn; // // SQLiteDataBaseConnection sqlite = new SQLiteDataBaseConnection(); // String dataBaseURL = "jdbc:sqlite://E:/shaogaige/iNote/iNoteRun/data/iNoteData.note"; // String userName = ""; // String passWord = ""; // conn = sqlite.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // // DataBase database = new DataBase(conn); // SQLResultSet rs =database.exeSQLSelect("select * from noteinfo"); // System.out.println(rs.getRowNum()); // // MongoDataBaseConnection mongo = new MongoDataBaseConnection(); // dataBaseURL = "jdbc:mongo://172.15.103.42:10001/geoglobe"; // userName = "data"; // passWord = "data"; // conn = mongo.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // // MySQLDataBaseConnection mysql = new MySQLDataBaseConnection(); // dataBaseURL = "jdbc:mysql://172.15.103.42:3306/geoglobe"; // userName = "root"; // passWord = "root"; // conn = mysql.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // // OracleDataBaseConnection oracle = new OracleDataBaseConnection(); // dataBaseURL = "jdbc:oracle:thin:@172.15.103.43:1521:geoglobe"; // userName = "autotest"; // passWord = "autotest"; // conn = oracle.createConnection(dataBaseURL, userName, passWord); // System.out.println(conn.getMetaData().getURL()); // // DataBaseManager.getDataBase(DataBaseEnum.ORACLE, "", "", ""); // } // //}
Java
/* * ===================================================================================== * * Filename: bmp_pixmap_fill.cpp * * Description: Fill the whole bmp with one color. * * Version: 1.0 * Created: 2009年04月11日 16时45分26秒 * Revision: none * Compiler: gcc * * Author: Xu Lijian (ivenvd), ivenvd@gmail.com * Company: CUGB, China * * ===================================================================================== */ #include "bmp_pixmap.h" /* *-------------------------------------------------------------------------------------- * Class: BmpPixmap * Method: fill * Description: Fill the whole bmp with one color. *-------------------------------------------------------------------------------------- */ BmpPixmap & BmpPixmap::fill (const BmpPixel &pixel) { BmpPixmap *temp = new BmpPixmap (*this); for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { *temp->pdata [i][j] = pixel; } } return *temp; } /* ----- end of method BmpPixmap::fill ----- */ BmpPixmap & BmpPixmap::fill (Byte b, Byte g, Byte r) { BmpPixmap *temp = new BmpPixmap (*this); for (i = 0; i < height; i++) { for (j = 0; j < width; j++) { temp->pdata [i][j]->set (b, g, r); } } return *temp; } /* ----- end of method BmpPixmap::fill ----- */
Java
// This file is part of VideoPad. // // VideoPad 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. // // VideoPad 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 VideoPad; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA #pragma once #include "CaptureDevice.h" class CAudioCaptureDevice : public CCaptureDevice { public: CAudioCaptureDevice(); // init capture device by given COM object ID // HRESULT Create( CString szID ); const DWORD& GetPreferredSamplesPerSec(); const WORD& GetPreferredBitsPerSample(); const WORD& GetPreferredChannels(); const DWORD& GetSamplesPerSec(); const WORD& GetBitsPerSample(); const WORD& GetChannels(); void SetPreferredAudioSamplesPerSec( DWORD nSamplesPerSec ); void SetPreferredAudioBitsPerSample( WORD wBitsPerSample ); void SetPreferredAudioChannels( WORD nChannels ); // these functions are used by CAudioGraph to set // the current audio format information of the graph // and the device // void SetAudioSamplesPerSec( DWORD nSamplesPerSec ); void SetAudioBitsPerSample( WORD wBitsPerSample ); void SetAudioChannels( WORD nChannels ); private: DWORD m_nPreferredSamplesPerSec; WORD m_wPreferredBitsPerSample; WORD m_nPreferredChannels; DWORD m_nSamplesPerSec; WORD m_wBitsPerSample; WORD m_nChannels; };
Java
'use strict'; angular.module('eshttp') .filter('unixtostr', function() { return function(str){ var dt; dt = Date.create(str * 1000).format('{yyyy}-{MM}-{dd} {HH}:{mm}:{ss}'); if (dt == "Invalid Date") { return 'N/A'; } else { return dt; } }; });
Java
#include "thanks.h" // // EternityProject Public message START: // - To the "developers" like franciscofranco: Are you able to work on your own? Also, if you want to badly copy my commits, can you at least give credits to the proprietary of the commit you're copying? We're an opensource community, we do this for free... but we also are satisfacted of the TIME WE LOSE on the things we do. We want to work with everyone that wants to. We publish our sources. We give you all everything we do. And you? Instead of copying someone else's work, try to lose time on your own at least sorting the not working commits (yeah, I knew someone was copying my work and I've committed some fakes). You did that badly. The EternityProject Team Manager & Main Developer, --kholk // // EternityProject Public message END //
Java
<?php /* * This file is part of PHPExifTool. * * (c) 2012 Romain Neutron <imprec@gmail.com> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ namespace PHPExiftool\Driver\Tag\Microsoft; use PHPExiftool\Driver\AbstractTag; class Duration extends AbstractTag { protected $Id = 'mixed'; protected $Name = 'Duration'; protected $FullName = 'Microsoft::Xtra'; protected $GroupName = 'Microsoft'; protected $g0 = 'QuickTime'; protected $g1 = 'Microsoft'; protected $g2 = 'Video'; protected $Type = '?'; protected $Writable = false; protected $Description = 'Duration'; }
Java
#ifndef __STACK_TESTS_H_INCLUDED__ #define __STACK_TESTS_H_INCLUDED__ //------------------------------------- #include "../CppTest/cpptest.h" #include "../Raple/Headers/Stack.h" //------------------------------------- //------------------------------------- #ifdef _MSC_VER #pragma warning (disable: 4290) #endif //------------------------------------- using Raple::Stack; using Raple::StackOverflowException; using Raple::StackUnderflowException; //------------------------------------- namespace RapleTests { class StackTests : public Test::Suite { public: StackTests() { addTest(StackTests::SizeTest); addTest(StackTests::PushAndPopTest); addTest(StackTests::OverflowExceptionTest); addTest(StackTests::UnderflowExceptionTest); } private: void SizeTest() { Stack<int> s; assertEquals(0, s.Size()); s.Push(1); s.Push(2); assertEquals(2, s.Size()); s.Pop(); assertEquals(1, s.Size()); s.Pop(); assertEquals(0, s.Size()); } void PushAndPopTest() { Stack<int> s; s.Push(1); s.Push(2); s.Push(3); assertEquals(3, s.Pop()); assertEquals(2, s.Pop()); assertEquals(1, s.Pop()); } void OverflowExceptionTest() { Stack<int> s(2); s.Push(1); s.Push(2); try { s.Push(3); } catch (StackOverflowException ex) { assert(true); return; } assert(false); } void UnderflowExceptionTest() { Stack<int> s; try { s.Pop(); } catch (StackUnderflowException ex) { assert(true); return; } assert(false); } }; } #endif //__STACK_TESTS_H_INCLUDED__
Java
# Install script for directory: /home/hscore # Set the install prefix IF(NOT DEFINED CMAKE_INSTALL_PREFIX) SET(CMAKE_INSTALL_PREFIX "/home/root/hswow") ENDIF(NOT DEFINED CMAKE_INSTALL_PREFIX) STRING(REGEX REPLACE "/$" "" CMAKE_INSTALL_PREFIX "${CMAKE_INSTALL_PREFIX}") # Set the install configuration name. IF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) IF(BUILD_TYPE) STRING(REGEX REPLACE "^[^A-Za-z0-9_]+" "" CMAKE_INSTALL_CONFIG_NAME "${BUILD_TYPE}") ELSE(BUILD_TYPE) SET(CMAKE_INSTALL_CONFIG_NAME "Release") ENDIF(BUILD_TYPE) MESSAGE(STATUS "Install configuration: \"${CMAKE_INSTALL_CONFIG_NAME}\"") ENDIF(NOT DEFINED CMAKE_INSTALL_CONFIG_NAME) # Set the component getting installed. IF(NOT CMAKE_INSTALL_COMPONENT) IF(COMPONENT) MESSAGE(STATUS "Install component: \"${COMPONENT}\"") SET(CMAKE_INSTALL_COMPONENT "${COMPONENT}") ELSE(COMPONENT) SET(CMAKE_INSTALL_COMPONENT) ENDIF(COMPONENT) ENDIF(NOT CMAKE_INSTALL_COMPONENT) # Install shared libraries without execute permission? IF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) SET(CMAKE_INSTALL_SO_NO_EXE "1") ENDIF(NOT DEFINED CMAKE_INSTALL_SO_NO_EXE) IF(NOT CMAKE_INSTALL_LOCAL_ONLY) # Include the install script for each subdirectory. INCLUDE("/home/hscore/src/dep/cmake_install.cmake") INCLUDE("/home/hscore/src/src/cmake_install.cmake") ENDIF(NOT CMAKE_INSTALL_LOCAL_ONLY) IF(CMAKE_INSTALL_COMPONENT) SET(CMAKE_INSTALL_MANIFEST "install_manifest_${CMAKE_INSTALL_COMPONENT}.txt") ELSE(CMAKE_INSTALL_COMPONENT) SET(CMAKE_INSTALL_MANIFEST "install_manifest.txt") ENDIF(CMAKE_INSTALL_COMPONENT) FILE(WRITE "/home/hscore/src/${CMAKE_INSTALL_MANIFEST}" "") FOREACH(file ${CMAKE_INSTALL_MANIFEST_FILES}) FILE(APPEND "/home/hscore/src/${CMAKE_INSTALL_MANIFEST}" "${file}\n") ENDFOREACH(file)
Java
#ifndef CONTROLPANEL_INCLUDED #define CONTROLPANEL_INCLUDED #include <qwidget.h> //Added by qt3to4: #include <Q3GridLayout> #include <list> #include <q3frame.h> #include <qlayout.h> #include <qlabel.h> class Control; class MetaGear; class GearControl; class ControlPanel : public QWidget { public: ControlPanel(QWidget *panelContainerWidget, MetaGear *parentMetagear); ~ControlPanel(); Control *addControl(GearControl* gear); void addControlPanel(ControlPanel* controlPanel); QWidget *mainWidget(){return _mainFrame;} private: std::list<Control*> _controls; std::list<ControlPanel*> _controlPanels; MetaGear *_parentMetaGear; Q3Frame *_mainFrame; Q3GridLayout *_mainLayout; QLabel *_labelName; }; #endif
Java
%!TEX root = ../MC_SS17.tex \section{Büchi-Automaten} \label{sec:para5} \nextlecture \cleardoubleoddemptypage
Java
/* Copyright (c) 2003-2021, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or https://ckeditor.com/legal/ckeditor-oss-license */ CKEDITOR.plugins.setLang( 'colordialog', 'en-gb', { clear: 'Clear', highlight: 'Highlight', options: 'Colour Options', selected: 'Selected Colour', title: 'Select colour' } );
Java
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>站点列表</title> <link rel="stylesheet" href="../layui/css/layui.css"> <link type="text/css" rel="styleSheet" href="../style/common.css"> </link> <link type="text/css" rel="styleSheet" href="../style/siteList.css"> </link> <script src="https://cdn.bootcss.com/jquery/3.4.0/jquery.min.js"></script> <script src="https://cdn.bootcss.com/echarts/4.2.1-rc.2/echarts.min.js"></script> <script type="text/javascript" src="../theme/purple-passion.js"></script> <script type="text/javascript" src="../js/iconfont.js"></script> <script type="text/javascript" src="../layui/layui.js"></script> <script src="../js/template-web.js"></script> <script type="text/javascript" src="../js/common.js"></script> <script type="text/javascript" src="../js/siteList.js"></script> <script> var whdef = 100 / 1920;// 表示1920的设计图,使用100PX的默认值 var wH = window.innerHeight;// 当前窗口的高度 var wW = window.innerWidth;// 当前窗口的宽度 var rem = wW * whdef;// 以默认比例值乘以当前窗口宽度,得到该宽度下的相应FONT-SIZE值 $('html').css('font-size', rem + "px"); layui.use(['form'], function () { var form = layui.form; }); </script> </head> <body> <div class="nav" id='nav'> <a href="./index.html">运行监控</a> <a href="./management.html">经营监控</a> <a href="./warnMonitor.html">预警监控</a> <svg class="icon navLockIcon" aria-hidden="true" id="lockBtn"> <use xlink:href="#icon-lock-line"></use> </svg> </div> <div class="siderWrap" id="siderWrap" data-visible='false'> <div class="siderBtn" id="siderBtn"> <svg class="icon siderBtnIcon" aria-hidden="true"> <use xlink:href="#icon-zuojiantou"></use> </svg> </div> <div class="sider" id="sider"> <div class="clearfix"> <div class="siderHeader">监控管理气站</div> <div class="siderGeoBtn" id="siderGeoBtn">坐标图</div> </div> <div class="searchBox"> <svg class="baiyanIcon menuIcon" aria-hidden="true"> <use xlink:href="#icon-caidan"></use> </svg> <input class="searchInput" placeholder="输入关键字" /> <svg class="baiyanIcon searchIcon" aria-hidden="true"> <use xlink:href="#icon-xiazai17"></use> </svg> </div> <h5 class="title2 mgt35">全国站点监控总量</h5> <div class="dashLine"></div> <div class="dataStatistics"> <div class="digit_set"></div> <div class="digit_set"></div> <div class="digit_set"></div> <div class="digit_set set_last"></div> </div> <!-- 具体监控描述 --> <div class="siteNumWrapper clearfix"> <div>华东:123</div> <div>东北:123</div> <div>西北:123</div> </div> <h5 class="title2 mgt17">全站今日累计报警(3)</h5> <div class="dashLine"></div> <div class="warningBox clearfix"> <div> <span>运行报警</span> <span>(3)</span> </div> <div> <span>设备超期报警</span> <span>(3)</span> </div> <div> <span>维修超期报警</span> <span>(3)</span> </div> </div> <div class="mgt17"> <h5 class="title2">故障总量</h5> <span class="oneyear">2018年</span> <span class="twoyear">2019年</span> </div> <div class="dashLine"></div> <!-- 柱状图1 --> <div id="barCharts1"></div> <h5 class="title2 mgt17">全年故障处理完成率</h5> <div class="dashLine"></div> <!-- 饼图1 --> <div id="pieCharts1"></div> </div> </div> <!-- LNG按钮 --> <div id="lngBtn" data-show="false"> <div id="lngBtnHidden">LNG</div> <div id="lngBtnShow"> <svg class="icon shouqiIcon" aria-hidden="true"> <use xlink:href="#icon-zuojiantou"></use> </svg> <a class="btn private" href="./siteList.html">站点列表</a> <a class="btn private">设备列表</a> <a class="btn default">定制</a> </div> </div> <!-- 具体页面内容 --> <div class="siteList"> <div class="siteItemBox"> <div class="siteItem"> <div class="imgWrap"> <img src="../images/demo.jpg" /> </div> <div class="clearfix info"> <div class="name">众信源浦村加气站</div> <div class="success"> <img src="../images/chenggong.png"/> <span>80%</span> </div> <div class="error"> <img src="../images/shibai.png"/> <span>80%</span> </div> </div> </div> </div> </div> </body> <script type="text/html" id="tpl1"> {{each list}} <div class="siteItemBox"> <div class="siteItem"> <div class="imgWrap"> <img src="../images/demo.jpg" /> </div> <div class="clearfix info"> <div class="name">众信源浦村加气站</div> <div class="success"> <img src="../images/chenggong.png"/> <span>80%</span> </div> <div class="error"> <img src="../images/shibai.png"/> <span>80%</span> </div> </div> </div> </div> {{/each}} </script> </html>
Java
{% load i18n %} <ul class="nav nav-tabs"> <li id="tab-basic"> <a href="{% url 'settings:basic-setting' %}" class="text-center"><i class="fa fa-cubes"></i> {% trans 'Basic setting' %}</a> </li> <li id="tab-email" > <a href="{% url 'settings:email-setting' %}" class="text-center"><i class="fa fa-envelope"></i> {% trans 'Email setting' %} </a> </li> <li id="tab-email-content" > <a href="{% url 'settings:email-content-setting' %}" class="text-center"><i class="fa fa-file-text"></i> {% trans 'Email content setting' %} </a> </li> <li id="tab-ldap"> <a href="{% url 'settings:ldap-setting' %}" class="text-center"><i class="fa fa-archive"></i> {% trans 'LDAP setting' %} </a> </li> <li id="tab-terminal"> <a href="{% url 'settings:terminal-setting' %}" class="text-center"><i class="fa fa-hdd-o"></i> {% trans 'Terminal setting' %} </a> </li> <li id="tab-security"> <a href="{% url 'settings:security-setting' %}" class="text-center"><i class="fa fa-lock"></i> {% trans 'Security setting' %} </a> </li> </ul> <script> $(document).ready(function () { var path = location.pathname; if (path.endsWith('/')) { path = path.substring(0, path.length-1) } var pathList = path.split('/'); var tabId = pathList[pathList.length-1]; if (tabId === "settings") { tabId = "basic" } tabId = "#tab-" + tabId; $(tabId).addClass("active") }) </script>
Java
<?php if(!defined('kernel_entry') || !kernel_entry) die('Not A Valid Entry Point'); require_once('include/data/cls_table_view_base.php'); class cls_view_drupal_registry_d855ab16_bba7_43de_b448_7e9b9d78edec extends cls_table_view_base { private $p_column_definitions = null; function __construct() { $a = func_get_args(); $i = func_num_args(); if (method_exists($this,$f="__construct".$i)) { call_user_func_array(array($this,$f),$a); } } public function query($search_values,$limit,$offset) { require_once('include/data/table_factory/cls_table_factory.php'); $common_drupal_registry = cls_table_factory::get_common_drupal_registry(); $array_drupal_registry = $common_drupal_registry->get_drupal_registrys($this->get_db_manager(),$this->get_application(),$search_values,$limit,$offset,false); $result_array = array(); foreach($array_drupal_registry as $drupal_registry) { $drupal_registry_id = $drupal_registry->get_id(); $result_array[$drupal_registry_id]['drupal_registry.name'] = $drupal_registry->get_name(); $result_array[$drupal_registry_id]['drupal_registry.type'] = $drupal_registry->get_type(); $result_array[$drupal_registry_id]['drupal_registry.filename'] = $drupal_registry->get_filename(); $result_array[$drupal_registry_id]['drupal_registry.module'] = $drupal_registry->get_module(); $result_array[$drupal_registry_id]['drupal_registry.weight'] = $drupal_registry->get_weight(); $result_array[$drupal_registry_id]['drupal_registry.id'] = $drupal_registry->get_id(); } return $result_array; } public function get_column_definitions() { if (!is_null($this->p_column_definitions)) return $this->p_column_definitions; { $this->p_column_definitions = array(); $this->p_column_definitions['drupal_registry.name']['type'] = 'varchar'; $this->p_column_definitions['drupal_registry.type']['type'] = 'varchar'; $this->p_column_definitions['drupal_registry.filename']['type'] = 'varchar'; $this->p_column_definitions['drupal_registry.module']['type'] = 'varchar'; $this->p_column_definitions['drupal_registry.weight']['type'] = 'int4'; $this->p_column_definitions['drupal_registry.id']['type'] = 'uuid'; } return $this->p_column_definitions; } } ?>
Java
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html><head><meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>CHAI3D: /home/seb/workspace/chai3d-2.0.0/src/scenegraph/CGenericObject.h File Reference</title> <link href="doxygen.css" rel="stylesheet" type="text/css"> <link href="tabs.css" rel="stylesheet" type="text/css"> </head><body> <!-- Generated by Doxygen 1.5.5 --> <div class="navigation" id="top"> <div class="tabs"> <ul> <li><a href="index.html"><span>Main&nbsp;Page</span></a></li> <li><a href="modules.html"><span>Modules</span></a></li> <li><a href="annotated.html"><span>Classes</span></a></li> <li class="current"><a href="files.html"><span>Files</span></a></li> </ul> </div> </div> <div class="contents"> <h1>/home/seb/workspace/chai3d-2.0.0/src/scenegraph/CGenericObject.h File Reference</h1><b> Scenegraph </b> <br> Base Class. <a href="#_details">More...</a> <p> <code>#include &quot;<a class="el" href="_c_maths_8h-source.html">math/CMaths.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_draw3_d_8h-source.html">graphics/CDraw3D.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_color_8h-source.html">graphics/CColor.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_macros_g_l_8h-source.html">graphics/CMacrosGL.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_material_8h-source.html">graphics/CMaterial.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_texture2_d_8h-source.html">graphics/CTexture2D.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_collision_basics_8h-source.html">collisions/CCollisionBasics.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_interaction_basics_8h-source.html">forces/CInteractionBasics.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_generic_effect_8h-source.html">effects/CGenericEffect.h</a>&quot;</code><br> <code>#include &quot;<a class="el" href="_c_generic_type_8h-source.html">extras/CGenericType.h</a>&quot;</code><br> <code>#include &lt;typeinfo&gt;</code><br> <code>#include &lt;vector&gt;</code><br> <code>#include &lt;list&gt;</code><br> <p> <a href="_c_generic_object_8h-source.html">Go to the source code of this file.</a><table border="0" cellpadding="0" cellspacing="0"> <tr><td></td></tr> <tr><td colspan="2"><br><h2>Classes</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">class &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="classc_generic_object.html">cGenericObject</a></td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">This class is the root of basically every render-able object in CHAI. It defines a reference frame (position and rotation) and virtual methods for rendering, which are overloaded by useful subclasses. <br> . <a href="classc_generic_object.html#_details">More...</a><br></td></tr> <tr><td colspan="2"><br><h2>Enumerations</h2></td></tr> <tr><td class="memItemLeft" nowrap align="right" valign="top">enum &nbsp;</td><td class="memItemRight" valign="bottom"><a class="el" href="_c_generic_object_8h.html#b7dfc0d18c5e05621dd13575f917fb3d">chai_render_modes</a> { <b>CHAI_RENDER_MODE_RENDER_ALL</b> = 0, <b>CHAI_RENDER_MODE_NON_TRANSPARENT_ONLY</b>, <b>CHAI_RENDER_MODE_TRANSPARENT_BACK_ONLY</b>, <b>CHAI_RENDER_MODE_TRANSPARENT_FRONT_ONLY</b> }</td></tr> <tr><td class="mdescLeft">&nbsp;</td><td class="mdescRight">Constants that define specific rendering passes (see cCamera.cpp). <br></td></tr> </table> <hr><a name="_details"></a><h2>Detailed Description</h2> <b> Scenegraph </b> <br> Base Class. <p> </div> <font size=-2><br><hr><b>CHAI3D 2.0.0 documentation</b><br>Please address any questions to <a href="mailto:support@chai3d.org">support@chai3d.org</a><br> (C) 2003-2009 - <a href="http://www.chai3d.org">CHAI 3D</a><br> All Rights Reserved.
Java
//-------------------------------------------------------------------------- // Copyright (C) 2015-2016 Cisco and/or its affiliates. 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 as published // by the Free Software Foundation. You may not use, modify or distribute // this program under any other version of the GNU General Public 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 Street, Fifth Floor, Boston, MA 02110-1301, USA. //-------------------------------------------------------------------------- // rule_profiler.cc author Joel Cornett <jocornet@cisco.com> #include "rule_profiler.h" #if HAVE_CONFIG_H #include "config.h" #endif #include <algorithm> #include <functional> #include <iostream> #include <sstream> #include <vector> #include "detection/detection_options.h" #include "detection/treenodes.h" #include "hash/sfghash.h" #include "main/snort_config.h" #include "main/thread_config.h" #include "parser/parser.h" #include "target_based/snort_protocols.h" #include "profiler_printer.h" #include "profiler_stats_table.h" #include "rule_profiler_defs.h" #ifdef UNIT_TEST #include "catch/catch.hpp" #endif #define s_rule_table_title "Rule Profile Statistics" static inline OtnState& operator+=(OtnState& lhs, const OtnState& rhs) { lhs.elapsed += rhs.elapsed; lhs.elapsed_match += rhs.elapsed_match; lhs.checks += rhs.checks; lhs.matches += rhs.matches; lhs.alerts += rhs.alerts; return lhs; } namespace rule_stats { static const StatsTable::Field fields[] = { { "#", 5, '\0', 0, std::ios_base::left }, { "gid", 6, '\0', 0, std::ios_base::fmtflags() }, { "sid", 6, '\0', 0, std::ios_base::fmtflags() }, { "rev", 4, '\0', 0, std::ios_base::fmtflags() }, { "checks", 7, '\0', 0, std::ios_base::fmtflags() }, { "matches", 8, '\0', 0, std::ios_base::fmtflags() }, { "alerts", 7, '\0', 0, std::ios_base::fmtflags() }, { "time (us)", 10, '\0', 0, std::ios_base::fmtflags() }, { "avg/check", 10, '\0', 1, std::ios_base::fmtflags() }, { "avg/match", 10, '\0', 1, std::ios_base::fmtflags() }, { "avg/non-match", 14, '\0', 1, std::ios_base::fmtflags() }, { "timeouts", 9, '\0', 0, std::ios_base::fmtflags() }, { "suspends", 9, '\0', 0, std::ios_base::fmtflags() }, { nullptr, 0, '\0', 0, std::ios_base::fmtflags() } }; struct View { OtnState state; SigInfo sig_info; hr_duration elapsed() const { return state.elapsed; } hr_duration elapsed_match() const { return state.elapsed_match; } hr_duration elapsed_no_match() const { return elapsed() - elapsed_match(); } uint64_t checks() const { return state.checks; } uint64_t matches() const { return state.matches; } uint64_t no_matches() const { return checks() - matches(); } uint64_t alerts() const { return state.alerts; } uint64_t timeouts() const { return state.latency_timeouts; } uint64_t suspends() const { return state.latency_suspends; } hr_duration time_per(hr_duration d, uint64_t v) const { if ( v == 0 ) return 0_ticks; return hr_duration(d.count() / v); } hr_duration avg_match() const { return time_per(elapsed_match(), matches()); } hr_duration avg_no_match() const { return time_per(elapsed_no_match(), no_matches()); } hr_duration avg_check() const { return time_per(elapsed(), checks()); } View(const OtnState& otn_state, const SigInfo* si = nullptr) : state(otn_state) { if ( si ) // FIXIT-L J does sig_info need to be initialized otherwise? sig_info = *si; } }; static const ProfilerSorter<View> sorters[] = { { "", nullptr }, { "checks", [](const View& lhs, const View& rhs) { return lhs.checks() >= rhs.checks(); } }, { "avg_check", [](const View& lhs, const View& rhs) { return lhs.avg_check() >= rhs.avg_check(); } }, { "total_time", [](const View& lhs, const View& rhs) { return lhs.elapsed().count() >= rhs.elapsed().count(); } }, { "matches", [](const View& lhs, const View& rhs) { return lhs.matches() >= rhs.matches(); } }, { "no_matches", [](const View& lhs, const View& rhs) { return lhs.no_matches() >= rhs.no_matches(); } }, { "avg_match", [](const View& lhs, const View& rhs) { return lhs.avg_match() >= rhs.avg_match(); } }, { "avg_no_match", [](const View& lhs, const View& rhs) { return lhs.avg_no_match() >= rhs.avg_no_match(); } } }; static void consolidate_otn_states(OtnState* states) { for ( unsigned i = 1; i < ThreadConfig::get_instance_max(); ++i ) states[0] += states[i]; } static std::vector<View> build_entries() { assert(snort_conf); detection_option_tree_update_otn_stats(snort_conf->detection_option_tree_hash_table); auto* otn_map = snort_conf->otn_map; std::vector<View> entries; for ( auto* h = sfghash_findfirst(otn_map); h; h = sfghash_findnext(otn_map) ) { auto* otn = static_cast<OptTreeNode*>(h->data); assert(otn); auto* states = otn->state; consolidate_otn_states(states); auto& state = states[0]; if ( !state ) continue; // FIXIT-L J should we assert(otn->sigInfo)? entries.emplace_back(state, &otn->sigInfo); } return entries; } // FIXIT-L J logic duplicated from ProfilerPrinter static void print_single_entry(const View& v, unsigned n) { using std::chrono::duration_cast; using std::chrono::microseconds; std::ostringstream ss; { StatsTable table(fields, ss); table << StatsTable::ROW; table << n; // # table << v.sig_info.generator; // gid table << v.sig_info.id; // sid table << v.sig_info.rev; // rev table << v.checks(); // checks table << v.matches(); // matches table << v.alerts(); // alerts table << duration_cast<microseconds>(v.elapsed()).count(); // time table << duration_cast<microseconds>(v.avg_check()).count(); // avg/check table << duration_cast<microseconds>(v.avg_match()).count(); // avg/match table << duration_cast<microseconds>(v.avg_no_match()).count(); // avg/non-match table << v.timeouts(); table << v.suspends(); } LogMessage("%s", ss.str().c_str()); } // FIXIT-L J logic duplicated from ProfilerPrinter static void print_entries(std::vector<View>& entries, ProfilerSorter<View> sort, unsigned count) { std::ostringstream ss; { StatsTable table(fields, ss); table << StatsTable::SEP; table << s_rule_table_title; if ( count ) table << " (worst " << count; else table << " (all"; if ( sort ) table << ", sorted by " << sort.name; table << ")\n"; table << StatsTable::HEADER; } LogMessage("%s", ss.str().c_str()); if ( !count || count > entries.size() ) count = entries.size(); if ( sort ) std::partial_sort(entries.begin(), entries.begin() + count, entries.end(), sort); for ( unsigned i = 0; i < count; ++i ) print_single_entry(entries[i], i + 1); } } void show_rule_profiler_stats(const RuleProfilerConfig& config) { if ( !config.show ) return; auto entries = rule_stats::build_entries(); // if there aren't any eval'd rules, don't sort or print if ( entries.empty() ) return; auto sort = rule_stats::sorters[config.sort]; // FIXIT-L J do we eventually want to be able print rule totals, too? print_entries(entries, sort, config.count); } void reset_rule_profiler_stats() { assert(snort_conf); auto* otn_map = snort_conf->otn_map; for ( auto* h = sfghash_findfirst(otn_map); h; h = sfghash_findnext(otn_map) ) { auto* otn = static_cast<OptTreeNode*>(h->data); assert(otn); auto* rtn = getRtnFromOtn(otn); if ( !rtn || !is_network_protocol(rtn->proto) ) continue; for ( unsigned i = 0; i < ThreadConfig::get_instance_max(); ++i ) { auto& state = otn->state[i]; state = OtnState(); } } } void RuleContext::stop(bool match) { if ( finished ) return; finished = true; stats.update(sw.get(), match); } #ifdef UNIT_TEST namespace { using RuleEntryVector = std::vector<rule_stats::View>; using RuleStatsVector = std::vector<OtnState>; } // anonymous namespace static inline bool operator==(const RuleEntryVector& lhs, const RuleStatsVector& rhs) { if ( lhs.size() != rhs.size() ) return false; for ( unsigned i = 0; i < lhs.size(); ++i ) if ( lhs[i].state != rhs[i] ) return false; return true; } static inline OtnState make_otn_state( hr_duration elapsed, hr_duration elapsed_match, uint64_t checks, uint64_t matches) { OtnState state; state.elapsed = elapsed; state.elapsed_match = elapsed_match; state.checks = checks; state.matches = matches; return state; } static inline rule_stats::View make_rule_entry( hr_duration elapsed, hr_duration elapsed_match, uint64_t checks, uint64_t matches) { return { make_otn_state(elapsed, elapsed_match, checks, matches), nullptr }; } static void avoid_optimization() { for ( int i = 0; i < 1024; ++i ); } TEST_CASE( "otn state", "[profiler][rule_profiler]" ) { OtnState state_a; state_a.elapsed = 1_ticks; state_a.elapsed_match = 2_ticks; state_a.elapsed_no_match = 2_ticks; state_a.checks = 1; state_a.matches = 2; state_a.noalerts = 3; state_a.alerts = 4; SECTION( "incremental addition" ) { OtnState state_b; state_b.elapsed = 4_ticks; state_b.elapsed_match = 5_ticks; state_b.elapsed_no_match = 6_ticks; state_b.checks = 5; state_b.matches = 6; state_b.noalerts = 7; state_b.alerts = 8; state_a += state_b; CHECK( state_a.elapsed == 5_ticks ); CHECK( state_a.elapsed_match == 7_ticks ); CHECK( state_a.checks == 6 ); CHECK( state_a.matches == 8 ); CHECK( state_a.alerts == 12 ); } SECTION( "reset" ) { state_a = OtnState(); CHECK( state_a.elapsed == 0_ticks ); CHECK( state_a.elapsed_match == 0_ticks ); CHECK( state_a.checks == 0 ); CHECK( state_a.matches == 0 ); CHECK( state_a.alerts == 0 ); } SECTION( "bool()" ) { CHECK( state_a ); OtnState state_c = OtnState(); CHECK_FALSE( state_c ); state_c.elapsed = 1_ticks; CHECK( state_c ); state_c.elapsed = 0_ticks; state_c.checks = 1; CHECK( state_c ); } } TEST_CASE( "rule entry", "[profiler][rule_profiler]" ) { SigInfo sig_info; auto entry = make_rule_entry(3_ticks, 2_ticks, 3, 2); entry.state.alerts = 77; entry.state.latency_timeouts = 5; entry.state.latency_suspends = 2; SECTION( "copy assignment" ) { auto copy = entry; CHECK( copy.sig_info.generator == entry.sig_info.generator ); CHECK( copy.sig_info.id == entry.sig_info.id ); CHECK( copy.sig_info.rev == entry.sig_info.rev ); CHECK( copy.state == entry.state ); } SECTION( "copy construction" ) { rule_stats::View copy(entry); CHECK( copy.sig_info.generator == entry.sig_info.generator ); CHECK( copy.sig_info.id == entry.sig_info.id ); CHECK( copy.sig_info.rev == entry.sig_info.rev ); CHECK( copy.state == entry.state ); } SECTION( "elapsed" ) { CHECK( entry.elapsed() == 3_ticks ); } SECTION( "elapsed_match" ) { CHECK( entry.elapsed_match() == 2_ticks ); } SECTION( "elapsed_no_match" ) { CHECK( entry.elapsed_no_match() == 1_ticks ); } SECTION( "checks" ) { CHECK( entry.checks() == 3 ); } SECTION( "matches" ) { CHECK( entry.matches() == 2 ); } SECTION( "no_matches" ) { CHECK( entry.no_matches() == 1 ); } SECTION( "alerts" ) { CHECK( entry.alerts() == 77 ); } SECTION( "timeouts" ) { CHECK( entry.timeouts() == 5 ); } SECTION( "suspends" ) { CHECK( entry.suspends() == 2 ); } SECTION( "avg_match" ) { auto ticks = entry.avg_match(); INFO( ticks.count() << " == " << (1_ticks).count() ); CHECK( ticks == 1_ticks ); } SECTION( "avg_no_match" ) { auto ticks = entry.avg_no_match(); INFO( ticks.count() << " == " << (1_ticks).count() ); CHECK( ticks == 1_ticks ); } SECTION( "avg_check" ) { auto ticks = entry.avg_check(); INFO( ticks.count() << " == " << (1_ticks).count() ); CHECK( ticks == 1_ticks ); } } TEST_CASE( "rule profiler sorting", "[profiler][rule_profiler]" ) { using Sort = RuleProfilerConfig::Sort; SECTION( "checks" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 0, 0), make_rule_entry(0_ticks, 0_ticks, 1, 0), make_rule_entry(0_ticks, 0_ticks, 2, 0) }; RuleStatsVector expected { make_otn_state(0_ticks, 0_ticks, 2, 0), make_otn_state(0_ticks, 0_ticks, 1, 0), make_otn_state(0_ticks, 0_ticks, 0, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_CHECKS]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "avg_check" ) { RuleEntryVector entries { make_rule_entry(2_ticks, 0_ticks, 2, 0), make_rule_entry(8_ticks, 0_ticks, 4, 0), make_rule_entry(4_ticks, 0_ticks, 1, 0) }; RuleStatsVector expected { make_otn_state(4_ticks, 0_ticks, 1, 0), make_otn_state(8_ticks, 0_ticks, 4, 0), make_otn_state(2_ticks, 0_ticks, 2, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_CHECK]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "total_time" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 0, 0), make_rule_entry(1_ticks, 0_ticks, 0, 0), make_rule_entry(2_ticks, 0_ticks, 0, 0) }; RuleStatsVector expected { make_otn_state(2_ticks, 0_ticks, 0, 0), make_otn_state(1_ticks, 0_ticks, 0, 0), make_otn_state(0_ticks, 0_ticks, 0, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_TOTAL_TIME]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "matches" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 0, 0), make_rule_entry(0_ticks, 0_ticks, 0, 1), make_rule_entry(0_ticks, 0_ticks, 0, 2) }; RuleStatsVector expected { make_otn_state(0_ticks, 0_ticks, 0, 2), make_otn_state(0_ticks, 0_ticks, 0, 1), make_otn_state(0_ticks, 0_ticks, 0, 0) }; const auto& sorter = rule_stats::sorters[Sort::SORT_MATCHES]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "no matches" ) { RuleEntryVector entries { make_rule_entry(0_ticks, 0_ticks, 4, 3), make_rule_entry(0_ticks, 0_ticks, 3, 1), make_rule_entry(0_ticks, 0_ticks, 4, 1) }; RuleStatsVector expected { make_otn_state(0_ticks, 0_ticks, 4, 1), make_otn_state(0_ticks, 0_ticks, 3, 1), make_otn_state(0_ticks, 0_ticks, 4, 3) }; const auto& sorter = rule_stats::sorters[Sort::SORT_NO_MATCHES]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "avg match" ) { RuleEntryVector entries { make_rule_entry(4_ticks, 0_ticks, 0, 2), make_rule_entry(6_ticks, 0_ticks, 0, 2), make_rule_entry(8_ticks, 0_ticks, 0, 2) }; RuleStatsVector expected { make_otn_state(8_ticks, 0_ticks, 0, 2), make_otn_state(6_ticks, 0_ticks, 0, 2), make_otn_state(4_ticks, 0_ticks, 0, 2) }; const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_MATCH]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } SECTION( "avg no match" ) { RuleEntryVector entries { make_rule_entry(4_ticks, 0_ticks, 6, 2), make_rule_entry(6_ticks, 0_ticks, 5, 2), make_rule_entry(8_ticks, 0_ticks, 2, 0) }; RuleStatsVector expected { make_otn_state(8_ticks, 0_ticks, 2, 0), make_otn_state(6_ticks, 0_ticks, 5, 2), make_otn_state(4_ticks, 0_ticks, 6, 2) }; const auto& sorter = rule_stats::sorters[Sort::SORT_AVG_NO_MATCH]; std::partial_sort(entries.begin(), entries.end(), entries.end(), sorter); CHECK( entries == expected ); } } TEST_CASE( "rule profiler time context", "[profiler][rule_profiler]" ) { dot_node_state_t stats; stats.elapsed = 0_ticks; stats.checks = 0; stats.elapsed_match = 0_ticks; SECTION( "automatically updates stats" ) { { RuleContext ctx(stats); avoid_optimization(); } INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed > 0_ticks ); CHECK( stats.checks == 1 ); INFO( "elapsed_match: " << stats.elapsed_match.count() ); CHECK( stats.elapsed_match == 0_ticks ); } SECTION( "explicitly calling stop" ) { dot_node_state_t save; SECTION( "stop(true)" ) { { RuleContext ctx(stats); avoid_optimization(); ctx.stop(true); INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed > 0_ticks ); CHECK( stats.checks == 1 ); CHECK( stats.elapsed_match == stats.elapsed ); save = stats; } } SECTION( "stop(false)" ) { { RuleContext ctx(stats); avoid_optimization(); ctx.stop(false); INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed > 0_ticks ); CHECK( stats.checks == 1 ); CHECK( stats.elapsed_match == 0_ticks ); save = stats; } } INFO( "elapsed: " << stats.elapsed.count() ); CHECK( stats.elapsed == save.elapsed ); CHECK( stats.elapsed_match == save.elapsed_match ); CHECK( stats.checks == save.checks ); } } #endif
Java
// Copyright (C) 2015 Dave Griffiths // // 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. // messy scheme interface #include <unistd.h> #include <sys/time.h> #include <time.h> #include "scheme.h" #include "scheme-private.h" ///// starwisp stuff ////////////////////////// #ifdef ANDROID_NDK #include <android/log.h> #endif #include "engine/engine.h" #include "engine/shader.h" #include "core/geometry.h" #include "core/osc.h" #include "fluxa/graph.h" #include "fluxa/time.h" #include "audio.h" graph *m_audio_graph = NULL; audio_device *m_audio_device = NULL; char *starwisp_data = NULL; #ifdef USE_SQLITE #include "core/db_container.h" db_container the_db_container; #include "core/idmap.h" idmap the_idmap; #endif pointer scheme_interface(scheme *sc, enum scheme_opcodes op) { switch (op) { ///////////// FLUXUS case OP_ALOG: #ifdef ANDROID_NDK __android_log_print(ANDROID_LOG_INFO, "starwisp", string_value(car(sc->args))); #endif s_return(sc,sc->F); case OP_SEND: if (is_string(car(sc->args))) { if (starwisp_data!=NULL) { #ifdef ANDROID_NDK __android_log_print(ANDROID_LOG_INFO, "starwisp", "deleting starwisp data: something is wrong!"); #endif free(starwisp_data); } starwisp_data=strdup(string_value(car(sc->args))); } s_return(sc,sc->F); case OP_OPEN_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args))) { the_db_container.add(string_value(car(sc->args)), new db(string_value(car(sc->args)))); s_return(sc,sc->T); } #endif s_return(sc,sc->F); } case OP_EXEC_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args)) && is_string(cadr(sc->args))) { db *d=the_db_container.get(string_value(car(sc->args))); if (d!=NULL) { s_return(sc,db_exec(sc,d)); } } #endif s_return(sc,sc->F); } case OP_INSERT_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args)) && is_string(cadr(sc->args))) { db *d=the_db_container.get(string_value(car(sc->args))); if (d!=NULL) { db_exec(sc,d); s_return(sc,mk_integer(sc,d->last_rowid())); } } #endif s_return(sc,sc->F); } /* case OP_INSERT_BLOB_DB: { #ifndef FLX_RPI if (is_string(car(sc->args)) && is_string(caddr(sc->args)) && is_string(cadddr(sc->args)) && is_string(caddddr(sc->args)) && is_string(cadddddr(sc->args))) { db *d=the_db_container.get(string_value(car(sc->args))); if (d!=NULL) { db_exec(sc,d); s_return(sc,mk_integer(sc,d->last_rowid())); } } #endif s_return(sc,sc->F); } */ case OP_STATUS_DB: { #ifdef USE_SQLITE if (is_string(car(sc->args))) { s_return(sc,mk_string(sc,the_db_container.status())); } #endif s_return(sc,sc->F); } case OP_TIME: { timeval t; // stop valgrind complaining t.tv_sec=0; t.tv_usec=0; gettimeofday(&t,NULL); s_return(sc,cons(sc,mk_integer(sc,t.tv_sec), cons(sc,mk_integer(sc,t.tv_usec),sc->NIL))); } case OP_NTP_TIME: { spiralcore::time t; t.set_to_now(); s_return(sc,cons(sc,mk_integer(sc,t.seconds), cons(sc,mk_integer(sc,t.fraction),sc->NIL))); } case OP_NTP_TIME_ADD: { spiralcore::time t(ivalue(car(car(sc->args))), ivalue(cadr(car(sc->args)))); t+=rvalue(cadr(sc->args)); s_return(sc,cons(sc,mk_integer(sc,t.seconds), cons(sc,mk_integer(sc,t.fraction),sc->NIL))); } case OP_NTP_TIME_DIFF: { spiralcore::time t(ivalue(car(car(sc->args))), ivalue(cadr(car(sc->args)))); spiralcore::time t2(ivalue(car(cadr(sc->args))), ivalue(cadr(cadr(sc->args)))); s_return(sc,mk_real(sc,t.get_difference(t2))); } case OP_NTP_TIME_GTR: { spiralcore::time t(ivalue(car(car(sc->args))), ivalue(cadr(car(sc->args)))); spiralcore::time t2(ivalue(car(cadr(sc->args))), ivalue(cadr(cadr(sc->args)))); if (t>t2) s_return(sc,sc->T); else s_return(sc,sc->F); } case OP_DATETIME: { timeval t; // stop valgrind complaining t.tv_sec=0; t.tv_usec=0; gettimeofday(&t,NULL); struct tm *now = gmtime((time_t *)&t.tv_sec); /* note: now->tm_year is the number of years SINCE 1900. On the year 2000, this will be 100 not 0. Do a man gmtime for more information */ s_return(sc,cons(sc,mk_integer(sc,now->tm_year + 1900), cons(sc,mk_integer(sc,now->tm_mon + 1), cons(sc,mk_integer(sc,now->tm_mday), cons(sc,mk_integer(sc,now->tm_hour), cons(sc,mk_integer(sc,now->tm_min), cons(sc,mk_integer(sc,now->tm_sec), sc->NIL))))))); } #ifdef USE_SQLITE case OP_ID_MAP_ADD: { the_idmap.add( string_value(car(sc->args)), ivalue(cadr(sc->args))); s_return(sc,sc->F); } case OP_ID_MAP_GET: { s_return( sc,mk_integer(sc,the_idmap.get( string_value(car(sc->args))))); } #endif //////////////////// fluxa ///////////////////////////////////////// case OP_SYNTH_INIT: { // name,buf,sr,synths m_audio_device = new audio_device(string_value(car(sc->args)), ivalue(cadr(sc->args)), ivalue(caddr(sc->args)), ivalue(cadddr(sc->args))); m_audio_graph = new graph(ivalue(caddddr(sc->args)),ivalue(caddr(sc->args))); m_audio_device->start_graph(m_audio_graph); s_return(sc,sc->F); } break; case OP_AUDIO_CHECK: { m_audio_device->check_audio(); s_return(sc,sc->F); } break; case OP_SYNTH_RECORD: { m_audio_device->start_recording(string_value(car(sc->args))); s_return(sc,sc->F); } break; case OP_AUDIO_EQ: { m_audio_device->m_left_eq.set_low(rvalue(car(sc->args))); m_audio_device->m_right_eq.set_low(rvalue(car(sc->args))); m_audio_device->m_left_eq.set_mid(rvalue(cadr(sc->args))); m_audio_device->m_right_eq.set_mid(rvalue(cadr(sc->args))); m_audio_device->m_left_eq.set_high(rvalue(caddr(sc->args))); m_audio_device->m_right_eq.set_high(rvalue(caddr(sc->args))); s_return(sc,sc->F); } break; case OP_AUDIO_COMP: { m_audio_device->m_left_comp.set_attack(rvalue(car(sc->args))); m_audio_device->m_right_comp.set_attack(rvalue(car(sc->args))); m_audio_device->m_left_comp.set_release(rvalue(cadr(sc->args))); m_audio_device->m_right_comp.set_release(rvalue(cadr(sc->args))); m_audio_device->m_left_comp.set_threshold(rvalue(caddr(sc->args))); m_audio_device->m_right_comp.set_threshold(rvalue(caddr(sc->args))); m_audio_device->m_left_comp.set_slope(rvalue(cadddr(sc->args))); m_audio_device->m_right_comp.set_slope(rvalue(cadddr(sc->args))); s_return(sc,sc->F); } break; case OP_SYNTH_CRT: { m_audio_graph ->create(ivalue(car(sc->args)), (graph::node_type)(ivalue(cadr(sc->args))), rvalue(caddr(sc->args))); s_return(sc,sc->F); } break; case OP_SYNTH_CON: { m_audio_graph ->connect(ivalue(car(sc->args)), ivalue(cadr(sc->args)), ivalue(caddr(sc->args))); s_return(sc,sc->F); } break; case OP_SYNTH_PLY: { m_audio_graph ->play(ivalue(car(sc->args)), ivalue(cadr(sc->args)), ivalue(caddr(sc->args)), rvalue(cadddr(sc->args))); s_return(sc,sc->F); } break; case OP_SLEEP: { usleep(ivalue(car(sc->args))); s_return(sc,sc->F); } break; case OP_FMOD: { s_return(sc,mk_real(sc,fmod(rvalue(car(sc->args)),rvalue(cadr(sc->args))))); } break; case OP_OSC_SEND: { const char *url=string_value(car(sc->args)); const char *name=string_value(cadr(sc->args)); const char *types=string_value(caddr(sc->args)); pointer data=cadddr(sc->args); // figure out size of the data packet u32 data_size=0; for (u32 i=0; i<strlen(types); ++i) { switch(types[i]) { case 'f': data_size+=sizeof(float); break; case 'i': data_size+=sizeof(int); break; case 'l': data_size+=sizeof(long long); break; case 's': data_size+=strlen(string_value(list_ref(sc,data,i)))+1; break; } } // build data packet char *packet = new char[data_size]; u32 data_pos=0; for (u32 i=0; i<strlen(types); ++i) { switch(types[i]) { case 'f': { float v=rvalue(list_ref(sc,data,i)); memcpy(packet+data_pos,&v,sizeof(float)); data_pos+=sizeof(float); } break; case 'i': { int v=ivalue(list_ref(sc,data,i)); memcpy(packet+data_pos,&v,sizeof(int)); data_pos+=sizeof(int); } break; case 'l': /*float v=ivalue(list_ref(sc,data,i)); memcpy(packet+data_pos,&v,sizeof(float)); data_pos+=sizeof(long long); */ break; case 's': { char *str=string_value(list_ref(sc,data,i)); memcpy(packet+data_pos,str,strlen(str)); data_pos+=strlen(string_value(list_ref(sc,data,i))); packet[data_pos]=0; // null terminator data_pos++; } break; } } network_osc::send(url,name,types,packet,data_size); delete[] packet; s_return(sc,sc->F); } break; //////////////////// fluxus ///////////////////////////////////////// case OP_PUSH: engine::get()->push(); s_return(sc,sc->F); case OP_POP: engine::get()->pop(); s_return(sc,sc->F); case OP_GRAB: engine::get()->grab(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_UNGRAB: engine::get()->ungrab(); s_return(sc,sc->F); case OP_PARENT: engine::get()->parent(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_LOCK_CAMERA: engine::get()->lock_camera(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_IDENTITY: engine::get()->identity(); s_return(sc,sc->F); case OP_TRANSLATE: engine::get()->translate(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); s_return(sc,sc->F); case OP_SCALE: if (!is_vector(car(sc->args))) // uniform scale with one arg { engine::get()->scale(rvalue(car(sc->args)), rvalue(car(sc->args)), rvalue(car(sc->args))); } else { engine::get()->scale(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); } s_return(sc,sc->F); case OP_ROTATE: engine::get()->rotate(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); s_return(sc,sc->F); case OP_AIM: engine::get()->aim(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(cadr(sc->args),0)), rvalue(vector_elem(cadr(sc->args),1)), rvalue(vector_elem(cadr(sc->args),2))); s_return(sc,sc->F); case OP_CONCAT: { mat44 t = mat44(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(car(sc->args),3)), rvalue(vector_elem(car(sc->args),4)), rvalue(vector_elem(car(sc->args),5)), rvalue(vector_elem(car(sc->args),6)), rvalue(vector_elem(car(sc->args),7)), rvalue(vector_elem(car(sc->args),8)), rvalue(vector_elem(car(sc->args),9)), rvalue(vector_elem(car(sc->args),10)), rvalue(vector_elem(car(sc->args),11)), rvalue(vector_elem(car(sc->args),12)), rvalue(vector_elem(car(sc->args),13)), rvalue(vector_elem(car(sc->args),14)), rvalue(vector_elem(car(sc->args),15))); t.transpose(); engine::get()->concat(t); s_return(sc,sc->F); } case OP_COLOUR: engine::get()->colour(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(car(sc->args),3))); s_return(sc,sc->F); case OP_HINT: { u32 h=ivalue(car(sc->args)); switch (h) { case 0: engine::get()->hint(HINT_NONE); break; //??? case 1: engine::get()->hint(HINT_SOLID); break; case 2: engine::get()->hint(HINT_WIRE); break; case 3: engine::get()->hint(HINT_NORMAL); break; case 4: engine::get()->hint(HINT_POINTS); break; case 5: engine::get()->hint(HINT_AALIAS); break; case 6: engine::get()->hint(HINT_BOUND); break; case 7: engine::get()->hint(HINT_UNLIT); break; case 8: engine::get()->hint(HINT_VERTCOLS); break; case 9: engine::get()->hint(HINT_ORIGIN); break; case 10: engine::get()->hint(HINT_CAST_SHADOW); break; case 11: engine::get()->hint(HINT_IGNORE_DEPTH); break; case 12: engine::get()->hint(HINT_DEPTH_SORT); break; case 13: engine::get()->hint(HINT_LAZY_PARENT); break; case 14: engine::get()->hint(HINT_CULL_CCW); break; case 15: engine::get()->hint(HINT_WIRE_STIPPLED); break; case 16: engine::get()->hint(HINT_SPHERE_MAP); break; case 17: engine::get()->hint(HINT_FRUSTUM_CULL); break; case 18: engine::get()->hint(HINT_NORMALISE); break; case 19: engine::get()->hint(HINT_NOBLEND); break; case 20: engine::get()->hint(HINT_NOZWRITE); break; } s_return(sc,sc->F); } case OP_DESTROY: engine::get()->destroy(rvalue(car(sc->args))); s_return(sc,sc->F); case OP_LINE_WIDTH: engine::get()->line_width(rvalue(car(sc->args))); s_return(sc,sc->F); case OP_TEXTURE: engine::get()->texture(rvalue(car(sc->args))); s_return(sc,sc->F); case OP_SHADER: engine::get()->set_shader(string_value(car(sc->args)), string_value(cadr(sc->args))); s_return(sc,sc->F); case OP_SHADER_SET: { shader *shader = engine::get()->get_current_shader(); shader->apply(); char *name = string_value(car(sc->args)); pointer arg=cadr(sc->args); if (is_vector(arg)) { switch (ivalue(arg)) { case 3: { vec3 vec(rvalue(vector_elem(arg,0)), rvalue(vector_elem(arg,1)), rvalue(vector_elem(arg,2))); shader->set_vector(name,vec); } break; case 16: { mat44 mat(rvalue(vector_elem(arg,0)), rvalue(vector_elem(arg,1)), rvalue(vector_elem(arg,2)), rvalue(vector_elem(arg,3)), rvalue(vector_elem(arg,4)), rvalue(vector_elem(arg,5)), rvalue(vector_elem(arg,6)), rvalue(vector_elem(arg,7)), rvalue(vector_elem(arg,8)), rvalue(vector_elem(arg,9)), rvalue(vector_elem(arg,10)), rvalue(vector_elem(arg,11)), rvalue(vector_elem(arg,12)), rvalue(vector_elem(arg,13)), rvalue(vector_elem(arg,14)), rvalue(vector_elem(arg,15))); shader->set_matrix(name,mat); } break; } } else { if (is_number(arg)) { if (num_is_integer(arg)) { shader->set_int(name,ivalue(arg)); } else { shader->set_float(name,rvalue(arg)); } } } shader->unapply(); s_return(sc,sc->F); } case OP_LOAD_TEXTURE: s_return(sc,mk_integer(sc,engine::get()->get_texture(string_value(car(sc->args))))); case OP_DRAW_INSTANCE: engine::get()->draw_instance(ivalue(car(sc->args))); s_return(sc,sc->F); case OP_BUILD_CUBE: s_return(sc,mk_integer(sc,engine::get()->build_cube())); case OP_LOAD_OBJ: s_return(sc,mk_integer(sc,engine::get()->load_obj(string_value(car(sc->args))))); case OP_RAW_OBJ: s_return(sc,mk_integer(sc,engine::get()->raw_obj(string_value(car(sc->args))))); case OP_BUILD_TEXT: s_return(sc,mk_integer(sc,engine::get()->build_text( string_value(car(sc->args))))); case OP_BUILD_JELLYFISH: s_return(sc,mk_integer(sc,engine::get()->build_jellyfish(ivalue(car(sc->args))))); case OP_BUILD_INSTANCE: s_return(sc,mk_integer(sc,engine::get()->build_instance(ivalue(car(sc->args))))); case OP_BUILD_POLYGONS: s_return(sc,mk_integer(sc,engine::get()->build_polygons( ivalue(car(sc->args)), ivalue(cadr(sc->args)) ))); case OP_GET_TRANSFORM: { flx_real *m=&(engine::get()->get_transform()->m[0][0]); pointer v=mk_vector(sc,16); int i=0; for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,m[i])); } s_return(sc,v); } case OP_GET_GLOBAL_TRANSFORM: { mat44 mat=engine::get()->get_global_transform(); flx_real *m=&(mat.m[0][0]); pointer v=mk_vector(sc,16); int i=0; for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,m[i])); } s_return(sc,v); } case OP_GET_CAMERA_TRANSFORM: { flx_real *m=&(engine::get()->get_camera_transform()->m[0][0]); pointer v=mk_vector(sc,16); int i=0; for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,m[i])); } s_return(sc,v); } case OP_GET_SCREEN_SIZE: { unsigned int *s=engine::get()->get_screensize(); pointer v=mk_vector(sc,2); set_vector_elem(v,0,mk_real(sc,s[0])); set_vector_elem(v,1,mk_real(sc,s[1])); s_return(sc,v); } case OP_APPLY_TRANSFORM: engine::get()->apply_transform(); s_return(sc,sc->F); case OP_CLEAR: engine::get()->clear(); s_return(sc,sc->F); case OP_CLEAR_COLOUR: engine::get()->clear_colour(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2)), rvalue(vector_elem(car(sc->args),3))); s_return(sc,sc->F); case OP_PDATA_SIZE: s_return(sc,mk_integer(sc,engine::get()->pdata_size())); case OP_PDATA_ADD: engine::get()->pdata_add(string_value(car(sc->args))); s_return(sc,sc->F); case OP_PDATA_REF: { vec3* vec=engine::get()->pdata_get(string_value(car(sc->args)), ivalue(cadr(sc->args))); pointer v=mk_vector(sc,3); if (vec) { set_vector_elem(v,0,mk_real(sc,vec->x)); set_vector_elem(v,1,mk_real(sc,vec->y)); set_vector_elem(v,2,mk_real(sc,vec->z)); } s_return(sc,v); } case OP_PDATA_SET: { vec3 vec(rvalue(vector_elem(caddr(sc->args),0)), rvalue(vector_elem(caddr(sc->args),1)), rvalue(vector_elem(caddr(sc->args),2))); engine::get()->pdata_set(string_value(car(sc->args)), ivalue(cadr(sc->args)), vec); s_return(sc,sc->F); } case OP_SET_TEXT: { engine::get()->text_set(string_value(car(sc->args))); s_return(sc,sc->F); } case OP_TEXT_PARAMS: { engine::get()->text_params(string_value(list_ref(sc,sc->args,0)), rvalue(list_ref(sc,sc->args,1)), rvalue(list_ref(sc,sc->args,2)), ivalue(list_ref(sc,sc->args,3)), ivalue(list_ref(sc,sc->args,4)), rvalue(list_ref(sc,sc->args,5)), rvalue(list_ref(sc,sc->args,6)), rvalue(list_ref(sc,sc->args,7)), rvalue(list_ref(sc,sc->args,8)), rvalue(list_ref(sc,sc->args,9)), rvalue(list_ref(sc,sc->args,10))); s_return(sc,sc->F); } case OP_RECALC_BB: { engine::get()->recalc_bb(); s_return(sc,sc->F); } case OP_BB_POINT_INTERSECT: { vec3 pvec(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); s_return(sc,mk_integer(sc,engine::get()->bb_point_intersect(pvec,rvalue(cadr(sc->args))))); } case OP_GEO_LINE_INTERSECT: { vec3 svec(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); vec3 evec(rvalue(vector_elem(cadr(sc->args),0)), rvalue(vector_elem(cadr(sc->args),1)), rvalue(vector_elem(cadr(sc->args),2))); bb::list *points=engine::get()->geo_line_intersect(svec,evec); if (points!=NULL) { pointer list=sc->NIL; intersect_point *p=static_cast<intersect_point*>(points->m_head); while (p!=NULL) { list=cons(sc,mk_real(sc,p->m_t),list); pointer blend=sc->NIL; intersect_point::blend *b= static_cast<intersect_point::blend*> (p->m_blends.m_head); while (b!=NULL) { pointer v=mk_vector(sc,3); set_vector_elem(v,0,mk_real(sc,b->m_blend.x)); set_vector_elem(v,1,mk_real(sc,b->m_blend.y)); set_vector_elem(v,2,mk_real(sc,b->m_blend.z)); pointer l=sc->NIL; l=cons(sc,mk_string(sc,b->m_name),v); blend=cons(sc,l,blend); b=static_cast<intersect_point::blend*>(b->m_next); } list=cons(sc,blend,list); p=static_cast<intersect_point*>(p->m_next); } s_return(sc,list); } s_return(sc,sc->F); } case OP_GET_LINE_INTERSECT: { vec3 svec(rvalue(vector_elem(car(sc->args),0)), rvalue(vector_elem(car(sc->args),1)), rvalue(vector_elem(car(sc->args),2))); vec3 evec(rvalue(vector_elem(cadr(sc->args),0)), rvalue(vector_elem(cadr(sc->args),1)), rvalue(vector_elem(cadr(sc->args),2))); s_return(sc,mk_integer(sc,engine::get()->get_line_intersect(svec,evec))); } case OP_MINVERSE: { mat44 inm; int i=0; for (i=0; i<16; i++) { inm.arr()[i]=rvalue(vector_elem(car(sc->args),i)); } inm=inm.inverse(); pointer v=mk_vector(sc,16); for (i=0; i<16; i++) { set_vector_elem(v,i,mk_real(sc,inm.arr()[i])); } s_return(sc,v); } case OP_BITWISE_IOR: { s_return(sc,mk_integer(sc, ivalue(car(sc->args))| ivalue(cadr(sc->args))| ivalue(caddr(sc->args)) )); } case OP_BLEND_MODE: { u32 src = GL_SRC_ALPHA; u32 dst = GL_ONE_MINUS_SRC_ALPHA; u32 s = ivalue(car(sc->args)); u32 d = ivalue(cadr(sc->args)); if (s==0) src=GL_ZERO; else if (s==1) src=GL_ONE; else if (s==2) src=GL_DST_COLOR; else if (s==3) src=GL_ONE_MINUS_DST_COLOR; else if (s==4) src=GL_SRC_ALPHA; else if (s==5) src=GL_ONE_MINUS_SRC_ALPHA; else if (s==6) src=GL_DST_ALPHA; else if (s==7) src=GL_ONE_MINUS_DST_ALPHA; else if (s==8) src=GL_SRC_ALPHA_SATURATE; if (d==0) dst=GL_ZERO; else if (d==1) dst=GL_ONE; else if (d==9) dst=GL_SRC_COLOR; else if (d==10) dst=GL_ONE_MINUS_SRC_COLOR; else if (d==4) dst=GL_SRC_ALPHA; else if (d==5) dst=GL_ONE_MINUS_SRC_ALPHA; else if (d==6) dst=GL_DST_ALPHA; else if (d==7) dst=GL_ONE_MINUS_DST_ALPHA; engine::get()->blend_mode(src,dst); s_return(sc,sc->F); } default: snprintf(sc->strbuff,STRBUFFSIZE,"%d: illegal operator", sc->op); Error_0(sc,sc->strbuff); } //////////////////// }
Java
/* * Copyright 2008-2009 Sun Microsystems, Inc. All Rights Reserved. * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER. * * This code is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License version 2 only, as * published by the Free Software Foundation. Sun designates this * particular file as subject to the "Classpath" exception as provided * by Sun in the LICENSE file that accompanied this code. * * This code 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 * version 2 for more details (a copy is included in the LICENSE file that * accompanied this code). * * You should have received a copy of the GNU General Public License version * 2 along with this work; if not, write to the Free Software Foundation, * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA. * * Please contact Sun Microsystems, Inc., 4150 Network Circle, Santa Clara, * CA 95054 USA or visit www.sun.com if you need additional information or * have any questions. */ #include "jni.h" #include "jni_util.h" #include "jvm.h" #include "jlong.h" #include <dlfcn.h> #include <errno.h> #include <sys/acl.h> #include "sun_nio_fs_SolarisNativeDispatcher.h" static void throwUnixException(JNIEnv* env, int errnum) { jobject x = JNU_NewObjectByName(env, "sun/nio/fs/UnixException", "(I)V", errnum); if (x != NULL) { (*env)->Throw(env, x); } } JNIEXPORT void JNICALL Java_sun_nio_fs_SolarisNativeDispatcher_init(JNIEnv *env, jclass clazz) { } JNIEXPORT jint JNICALL Java_sun_nio_fs_SolarisNativeDispatcher_facl(JNIEnv* env, jclass this, jint fd, jint cmd, jint nentries, jlong address) { void* aclbufp = jlong_to_ptr(address); int n = -1; n = facl((int)fd, (int)cmd, (int)nentries, aclbufp); if (n == -1) { throwUnixException(env, errno); } return (jint)n; }
Java
#include "TreeFactory.h" #include "RobotFactory.h" #include "Robot.h" #include "kinematic/Tree.h" #include "kinematic/Enums.h" #include <vector> #include <list> using namespace matrices; using namespace manip_core::enums; using namespace manip_core::enums::robot; namespace factories { const Vector3 unitx(1, 0, 0); const Vector3 unity(0, 1, 0); const Vector3 unitz(0, 0, 1); const Vector3 unit1(sqrt(14.0)/8.0, 1.0/8.0, 7.0/8.0); const Vector3 zero(0,0,0); struct RobotFactoryPimpl{ RobotFactoryPimpl() { // NOTHING } ~RobotFactoryPimpl() { // NOTHING } // TODO Joint that do not move Robot* CreateHuman(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::Human); Tree* rightLeg = treeFact_.CreateTree( RightLeg, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLeg, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArm, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanEscalade(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanEscalade); Tree* rightLeg = treeFact_.CreateTree( RightLegEscalade, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegEscalade, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArmEscalade, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmEscalade, Vector3(0.0, 0.4, 1.3), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanCanap(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanCanap); Tree* rightLeg = treeFact_.CreateTree( RightLegCanap, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegCanap, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArmCanap, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmCanap, Vector3(0.0, 0.4, 1.3), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanCrouch(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorsoCrouch, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::Human); Tree* rightLeg = treeFact_.CreateTree( RightLegCrouch, Vector3(0.1, -0.2, 0.), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegCrouch, Vector3(0.1, 0.2 , 0.), 1); Tree* rightArm = treeFact_.CreateTree( RightArmCrouch, Vector3(1.3, -0.4, 0.), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmCrouch, Vector3(1.3, 0.4, 0.), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(1.2,0,0), 1); res->AddTree(leftArm, matrices::Vector3(1.2,0,0), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanCrouch180(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorsoCrouch180, Vector3(0, 0., 0), 4), manip_core::enums::robot::Human); Tree* rightLeg = treeFact_.CreateTree( RightLegCrouch180, Vector3(0.1, -0.2, 0.), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegCrouch180, Vector3(0.1, 0.2 , 0.), 1); Tree* rightArm = treeFact_.CreateTree( RightArmCrouch180, Vector3(1.3, -0.4, 0.), 2); Tree* leftArm = treeFact_.CreateTree( LeftArmCrouch180, Vector3(1.3, 0.4, 0.), 3); //rightArm->SetBoundaryRadius(rightArm->GetBoundaryRadius() * 8 / 10 ); //leftArm->SetBoundaryRadius(leftArm->GetBoundaryRadius() * 8 / 10 ); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(1.2,0,0), 1); res->AddTree(leftArm, matrices::Vector3(1.2,0,0), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanWalk(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 4), manip_core::enums::robot::HumanWalk); Tree* rightLeg = treeFact_.CreateTree( RightLegWalk, Vector3(0.0, -0.2, 0.1), 0); Tree* leftLeg = treeFact_.CreateTree( LeftLegWalk, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArm, Vector3(0.0, -0.4, 1.3), 2); Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 1); res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateHumanEllipse(const Matrix4& robotBasis) const { Robot* res = new Robot(robotBasis, treeFact_.CreateTree( HumanTorso, Vector3(0.0, 0., 0), 1), manip_core::enums::robot::HumanEllipse); //Tree* rightLeg = treeFact_.CreateTree( RightLegWalk, Vector3(0.0, -0.2, 0.1), 0); //Tree* leftLeg = treeFact_.CreateTree( LeftLegWalk, Vector3(0.0, 0.2 , 0.1), 1); Tree* rightArm = treeFact_.CreateTree( RightArmEllipse, Vector3(0.0, -0.4, 1.3), 0); //Tree* leftArm = treeFact_.CreateTree( LeftArm, Vector3(0.0, 0.4, 1.3), 3); /*res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0);*/ res->AddTree(rightArm, matrices::Vector3(0,0,1.2), 0); //res->AddTree(leftArm, matrices::Vector3(0,0,1.2), 1); /*rightLeg->LockTarget(rightLeg->GetTarget()); leftLeg->LockTarget(leftLeg->GetTarget());*/ //rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.6))); //leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); return res; } Robot* CreateQuadruped(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( QuadrupedTorso, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::Quadruped); factories::TreeFactory factory; Tree* rightLeg = treeFact_.CreateTree( QuadrupedLegRight, Vector3(-1.2, -0.25, -0.1), 0); Tree* leftLeg = treeFact_.CreateTree( QuadrupedLegLeft, Vector3(-1.2, 0.25 , -0.1), 1); Tree* leftArm = treeFact_.CreateTree( QuadrupedLegLeft, Vector3(0.3, 0.25 , -0.1), 2); Tree* rightArm = treeFact_.CreateTree( QuadrupedLegRight, Vector3(0.3, -0.25, -0.1), 3); res->AddTree(rightLeg, matrices::Vector3(-1.2,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(-1.2,0,0), 0); res->AddTree(leftArm, matrices::Vector3(0.3,0,0), 1); res->AddTree(rightArm, matrices::Vector3(0.3,0,0), 1); /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/ rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4))); leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4))); return res; } Robot* CreateQuadrupedDown(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( QuadrupedTorso, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::Quadruped); factories::TreeFactory factory; Tree* rightLeg = treeFact_.CreateTree( QuadrupedLegDownRight, Vector3(0.0, -0.25, -0.1), 0); Tree* leftLeg = treeFact_.CreateTree( QuadrupedLegDownLeft, Vector3(0.0, 0.25 , -0.1), 1); Tree* leftArm = treeFact_.CreateTree( QuadrupedLegDownLeft, Vector3(1.5, 0.25 , -0.1), 2); Tree* rightArm = treeFact_.CreateTree( QuadrupedLegDownRight, Vector3(1.5, -0.25, -0.1), 3); res->AddTree(rightLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftLeg, matrices::Vector3(0,0,0), 0); res->AddTree(leftArm, matrices::Vector3(1.5,0,0), 1); res->AddTree(rightArm, matrices::Vector3(1.5,0,0), 1); /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/ rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4))); leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4))); return res; } Robot* CreateSpider(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorso, Vector3(0.0, 0., 0.0), 8), manip_core::enums::robot::Spider); factories::TreeFactory factory; Vector3 zeroAngle(0.25, 0, 0); Tree* t1 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 0); Tree* t2 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 1); Tree* t3 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 2); Tree* t4 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 3); Tree* t5 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 4); Tree* t6 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 5); Tree* t7 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 6); Tree* t8 = treeFact_.CreateTree( SpiderLeg, zeroAngle, 7); matrices::Vector3 position(0,0,0); res->AddTree(t1,position, 1); res->AddTree(t2,position, 1); res->AddTree(t3,position, 1); res->AddTree(t4,position, 1); res->AddTree(t5,position, 1); res->AddTree(t6,position, 1); res->AddTree(t7,position, 1); res->AddTree(t8,position, 1); /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3(-0.3, 0, -1.3))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.5, 0, -1.3))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.3, 0, -1.3)));*/ /*rightLeg->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightLeg->GetPosition() + Vector3( -0.3, 0, -1.4))); leftLeg ->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), leftLeg->GetPosition() + Vector3( 0.3, 0, -1.4))); rightArm->LockTarget(matrix4TimesVect3(res->ToWorldCoordinates(), rightArm->GetPosition() + Vector3( 0.4, 0, -1.4))); leftArm->LockTarget (matrix4TimesVect3(res->ToWorldCoordinates(), leftArm->GetPosition() + Vector3( -0.4, 0, -1.4)));*/ return res; } Robot* CreateSpiderRace(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorsoRace, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::SpiderRace); factories::TreeFactory factory; Vector3 zeroAngle(0.25, 0, 0); Tree* t1 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 0); Tree* t2 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 1); Tree* t3 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 2); Tree* t4 = treeFact_.CreateTree( SpiderLegRace, zeroAngle, 3); matrices::Vector3 position(0,0,0); res->AddTree(t1,position, 1); res->AddTree(t2,position, 1); res->AddTree(t3,position, 1); res->AddTree(t4,position, 1); return res; } Robot* CreateSpiderSix(const Matrix4& robotBasis) const { // TODO Remove order neccessity to create ids ... Robot* res = new Robot(robotBasis, treeFact_.CreateTree( SpiderTorsoRace, Vector3(0.0, 0., 0.0), 4), manip_core::enums::robot::SpiderSix); factories::TreeFactory factory; Vector3 zeroAngle(0.25, 0, 0); Tree* t1 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 0); Tree* t2 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 1); Tree* t3 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 2); Tree* t4 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 3); Tree* t5 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 4); Tree* t6 = treeFact_.CreateTree( SpiderLegSix, zeroAngle, 5); matrices::Vector3 position(0,0,0); res->AddTree(t1,position, 1); res->AddTree(t2,position, 1); res->AddTree(t3,position, 1); res->AddTree(t4,position, 1); res->AddTree(t5,position, 1); res->AddTree(t6,position, 1); return res; } TreeFactory treeFact_; }; } using namespace factories; RobotFactory::RobotFactory() : pImpl_(new RobotFactoryPimpl()) { // NOTHING } RobotFactory::~RobotFactory() { // NOTHING } Robot* RobotFactory::CreateRobot(const eRobots robots, const Matrix4& robotBasis) const { switch (robots) { case Human: { return pImpl_->CreateHuman(robotBasis); } case HumanWalk: { return pImpl_->CreateHumanWalk(robotBasis); } case HumanEscalade: { return pImpl_->CreateHumanEscalade(robotBasis); } case HumanCanap: { return pImpl_->CreateHumanCanap(robotBasis); } case HumanEllipse: { return pImpl_->CreateHumanEllipse(robotBasis); } case Quadruped: { return pImpl_->CreateQuadruped(robotBasis); } case QuadrupedDown: { return pImpl_->CreateQuadrupedDown(robotBasis); } case Spider: { return pImpl_->CreateSpider(robotBasis); } case SpiderSix: { return pImpl_->CreateSpiderSix(robotBasis); } case SpiderRace: { return pImpl_->CreateSpiderRace(robotBasis); } case HumanCrouch: { return pImpl_->CreateHumanCrouch(robotBasis); } case HumanCrouch180: { return pImpl_->CreateHumanCrouch180(robotBasis); } default: throw(std::exception()); } } /* bool IsSpine(const joint_def_t* root) { const std::string headTag("head"); std::string taf(root->tag); return (root->nbChildren_ == 0) ? (taf == headTag) : IsSpine(root->children[0]); } const joint_def_t* RetrieveSpine(std::list<const joint_def_t*>& trees) { for(std::list<const joint_def_t*>::const_iterator it = trees.begin(); it!= trees.end(); ++it) { if(IsSpine(*it)) { const joint_def_t* res = (*it); trees.remove(*it); return res; } } return 0; } void GetTrees(const joint_def_t* root, std::list<const joint_def_t*>& trees) { if(root->is_simple() && !root->is_locked()) { trees.push_back(root); } else { for(unsigned int i = 0; i < root->nbChildren_; ++i) { GetTrees(root->children[i], trees); } } } #include "Pi.h" #include "kinematic/Com.h" #include "kinematic/Joint.h" #include "kinematic/Tree.h" Joint* GetLast(Tree* tree) { Joint* j = tree->GetRoot(); while(j) { if(j->pChild_) j = j->pChild_; else return j; } return 0; } void ReadOneJointDef(matrices::Vector3 root, const joint_def_t* jointDef, Tree* tree, const ComFactory& comFact_) { const Vector3 unitx(1, 0, 0); const Vector3 unity(0, 1, 0); const Vector3 unitz(0, 0, 1); const Vector3 vectors []= {unitx, unity, unitz}; Joint* previous = GetLast(tree); matrices::Vector3 attach(jointDef->offset[0], jointDef->offset[1], jointDef->offset[2]); attach += root; bool lastIsEffector = jointDef->nbChildren_ == 0; for(int i = 0; i < 3; ++ i) { Joint* j = new Joint(attach, vectors[i], (lastIsEffector && i == 2) ? EFFECTOR : JOINT, comFact_.CreateCom(None) , RADIAN(jointDef->minAngleValues[i]), RADIAN(jointDef->maxAngleValues[i]), RADIAN(jointDef->defaultAngleValues[i]), rotation::eRotation(i)); if(previous) { tree->InsertChild(previous, j); } else { tree->InsertRoot(j); } previous = j; } if(!lastIsEffector) ReadOneJointDef(attach, jointDef->children[0], tree, comFact_); } Tree* MakeTree(const joint_def_t* root, unsigned int& id) { assert(root->is_simple()); const ComFactory comFact; Tree* tree = new Tree(id++); const joint_def_t* current_joint = root; matrices::Vector3 attach(0,0,0); ReadOneJointDef(attach, root, tree, comFact); return tree; } Robot* RobotFactory::CreateRobot(const joint_def_t& joint, const Matrix4& robotBasis) const { std::list<const joint_def_t*> trees; GetTrees(&joint, trees); const joint_def_t * spine = RetrieveSpine(trees); unsigned int id = 0; unsigned int torsoIndex = trees.size(); Robot* res = new Robot(robotBasis, MakeTree(spine, torsoIndex)); for(std::list<const joint_def_t*>::const_iterator it = trees.begin(); it!= trees.end(); ++it) { matrices::Vector3 offset((*it)->offset[0], (*it)->offset[1], (*it)->offset[2]); res->AddTree( MakeTree((*it), id), offset, 0); // TODO find good column joint for rendering } return res; }*/
Java
<!DOCTYPE html> <html lang="en"> <head> <?php ////////////////////////////////////////////////////// ///Copyright 2015 Luna Claudio,Rebolloso Leandro./// //////////////////////////////////////////////////// // //This file is part of ARSoftware. //ARSoftware 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. // //ARSoftware 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. ?> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <meta name="description" content=""> <meta name="author" content=""> <title>ARSoftware</title> <?php include_once($_SERVER["DOCUMENT_ROOT"]."/arsoftware/utiles/headerAdmin.php"); include_once($docRootSitio."modelo/Administrador.php"); #Paginación $limit=15; if(is_numeric($_GET['pagina']) && $_GET['pagina']>=1){ $offset = ($_GET['pagina']-1) * $limit; } else{ $offset=0; } #Orden por defecto if(!isset($_GET['campoOrder']) && !isset($_GET['order']) ){ $order = "DESC"; } else{ $campoOrder = $_GET['campoOrder']; $order = $_GET['order']; } #incluyo clases include_once($docRootSitio."modelo/Marca.php"); #nuevo objeto $mar1 = new Marca(); $adm1 = new Administrador(); $usuario = $_SESSION["nombreUsuario"]; $mar1->setNombreUsuario($usuario); $_marcas = $mar1->listarMarcas($offset,$limit,$campoOrder,$order); $_nombre = $adm1->listarAdministradorins2($usuario); #getCantRegistros $cantRegistros = $mar1->getCantRegistros(); $cantPaginas = ceil($cantRegistros/$limit); ?> <!-- Bootstrap Core CSS --> <link href="<?php echo $httpHostSitio?>plantilla/css/bootstrap.min.css" rel="stylesheet"> <!-- Custom CSS --> <link href="<?php echo $httpHostSitio?>plantilla/css/sb-admin.css" rel="stylesheet"> <!-- Morris Charts CSS --> <link href="<?php echo $httpHostSitio?>plantilla/css/plugins/morris.css" rel="stylesheet"> <!-- Custom Fonts --> <link href="<?php echo $httpHostSitio?>plantilla/font-awesome-4.1.0/css/font-awesome.min.css" rel="stylesheet" type="text/css"> <script src="<?php echo $httpHostSitio?>jquery/jquery-1.11.1.js"></script> <script src="<?php echo $httpHostSitio?>plantilla/js/bootstrap.min.js"></script> <!-- HTML5 Shim and Respond.js IE8 support of HTML5 elements and media queries --> <!-- WARNING: Respond.js doesn't work if you view the page via file:// --> <!--[if lt IE 9]> <script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script> <script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script> <![endif]--> </head> <body> <div id="wrapper"> <!-- Navigation --> <nav class="navbar navbar-inverse navbar-fixed-top" role="navigation"> <!-- Brand and toggle get grouped for better mobile display --> <div class="navbar-header"> <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-ex1-collapse"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <div onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/administradores/principalAdministradorAR.php')"; style="height: 52px; width:225px; max-width: 100%; background: #FFFFFF; background-image: url(<?php echo $httpHostSitio?>plantilla/imagenes/logotipoe.png);"></div> </div> <ul class="nav navbar-right top-nav"> <li class="dropdown"> <a href="principalAdministrador.php" class="dropdown-toggle" data-toggle="dropdown"><i class="fa fa-user"></i> <?php echo $_nombre['nombre'].' '.$_nombre['apellido']?> <b class="caret"></b></a> <ul class="dropdown-menu"> <li> <a href="<?php echo $httpHostSitio?>utiles/ctrlLogout.php"><i class="fa fa-fw fa-power-off"></i> Salir</a> </li> </ul> </li> </ul> <!-- Sidebar Menu Items - These collapse to the responsive navigation menu on small screens --> <div class="collapse navbar-collapse navbar-ex1-collapse"> <?php include_once($docRootSitio."utiles/menuAdministradorAR.php");?> </div> <!-- /.navbar-collapse --> </nav> <div id="page-wrapper"> <div class="container-fluid"> </div> <!-- /.container-fluid ------------------------------------------------------------------------------------------------------> <div class="row"> <div class="col-lg-12"> <h1 class="page-header"> Marcas Netbooks </h1> <ol class="breadcrumb"> <li class="active"> <i class="fa fa-dashboard"></i> Marcas Netbooks </li> </ol> </div> </div> <?php if($_GET['insert']==1){?> <div class="alert alert-success"> <strong>La Marca Se Agrego Exitosamente.</strong> </div> <?php }?> <?php if($_GET['update']==1){?> <div class="alert alert-success"> <strong>La Marca Se Modificó Exitosamente.</strong> </div> <?php }?> <?php if($_GET['delete']==1){?> <div class="alert alert-success"> <strong>La Marca Se Elimino Exitosamente.</strong> </div> <?php }?> <p> <button type="button" class="btn btn-primary" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/netescuela/listarNetbooks.php')" > Remanente Netbook</button> <button type="button" class="btn btn-success" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/prestamo/listarPrestamos.php')" > Prestamos Netbook</button> <button type="button" class="btn btn-warning" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/marcas/listarMarcas.php')" > Marcas Netbooks</button> <button type="button" class="btn btn-danger" onclick="location = ('<?php echo $httpHostSitio?>modulos/back-end/marcas/agregarMarca.php')" > Agregar Marca Netbooks</button> </p> <?php if(!isset($_GET['order']) || $_GET['order']=="DESC"){ $order = "ASC"; } else{ $order = "DESC"; } if(count($_marcas)){?> <table class="table table-bordered table-hover table-striped"> <tr> <td> <center><b>Nombre</b></center> </td> <td> <center><b>Acciones</b></center> </td> </tr> <?php for($i=1;$i<=count($_marcas);$i++){ if($i%2==0){ $class="class='alt'"; $classTh="class='specalt'"; } else{ $class=""; $classTh="class='spec'"; } ?> <tr> <td> <center><?php echo $_marcas[$i]['nombre']?></center> </td> <td> <div id="celdaAcciones"> <center><form method="post" action="modificarMarca.php"> <input type="hidden" name="Marca" value="<?php echo $_marcas[$i]['id']?>"> <input type="submit" value="Editar" class="btn btn-primary"> </form></center> </div> <div id="celdaAcciones"> <center><form method="post" action="eliminarMarca.php"> <input type="hidden" name="Marca" value="<?php echo $_marcas[$i]['id']?>"> <input type="submit" value="Eliminar" class="btn btn-success" onclick="return confirm('¿Está seguro que desea eliminar la siguiente marca <?php echo $_marcas[$i]['nombre']?>?');"> </form></center> </div> </td> </tr> <?php }?> </table> <div id="paginacion"> <?php if(!is_numeric($_GET['pagina']) || $_GET['pagina']<=1){ $_GET['pagina'] = 1; } else{ $paginaAnterior=$_GET['pagina']-1; if(isset($_GET['campoOrder']) && isset($_GET['order'])){ $campoOrder = $_GET['campoOrder'];+ $order = $_GET['order']; $criteriosOrder = "&campoOrder=$campoOrder&order=$order"; } ?> <a href="listarMarcas.php?pagina=<?php echo $paginaAnterior?><?php echo $criteriosOrder?>">Anterior</a> <?php }?> Página <?php echo $_GET['pagina']?>/<?php echo $cantPaginas?> de <?php echo $cantRegistros?> registros <?php if($_GET['pagina']<$cantPaginas){ $paginaSiguiente=$_GET['pagina']+1; if(isset($_GET['campoOrder']) && isset($_GET['order'])){ $campoOrder = $_GET['campoOrder'];+ $order = $_GET['order']; $criteriosOrder = "&campoOrder=$campoOrder&order=$order"; } ?> <a href="listarMarcas.php?pagina=<?php echo $paginaSiguiente?><?php echo $criteriosOrder?>">Siguiente</a> <?php }?> </div> <?php } else{?> <div class="alert alert-info"> <center><strong>Aviso! </strong> No existen marcas de netbooks cargadas.</center> </div> <?php }?> </div><!-- Fin container-fluid ------------------------------------------------------------------------------------------------------> <!-- /#page-wrapper --> <!-- /#wrapper --> <!-- jQuery Version 1.11.0 --> <script src="js/jquery-1.11.0.js"></script> <!-- Bootstrap Core JavaScript --> <script src="js/bootstrap.min.js"></script> <!-- Morris Charts JavaScript --> <script src="js/plugins/morris/raphael.min.js"></script> <script src="js/plugins/morris/morris.min.js"></script> <script src="js/plugins/morris/morris-data.js"></script> </body> </html>
Java
/* * SSLv3/TLSv1 server-side functions * * Copyright (C) 2006-2015, ARM Limited, All Rights Reserved * SPDX-License-Identifier: Apache-2.0 * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * This file is part of mbed TLS (https://tls.mbed.org) */ #if !defined(MBEDTLS_CONFIG_FILE) #include "mbedtls/config.h" #else #include MBEDTLS_CONFIG_FILE #endif #if defined(MBEDTLS_SSL_SRV_C) #if defined(MBEDTLS_PLATFORM_C) #include "mbedtls/platform.h" #else #include <stdlib.h> #define mbedtls_calloc calloc #define mbedtls_free free #endif #include "mbedtls/ssl.h" #include "mbedtls/ssl_internal.h" #include "mbedtls/debug.h" #include "mbedtls/error.h" #include "mbedtls/platform_util.h" #include <string.h> #if defined(MBEDTLS_ECP_C) #include "mbedtls/ecp.h" #endif #if defined(MBEDTLS_HAVE_TIME) #include "mbedtls/platform_time.h" #endif #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) int mbedtls_ssl_set_client_transport_id( mbedtls_ssl_context *ssl, const unsigned char *info, size_t ilen ) { if( ssl->conf->endpoint != MBEDTLS_SSL_IS_SERVER ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); mbedtls_free( ssl->cli_id ); if( ( ssl->cli_id = mbedtls_calloc( 1, ilen ) ) == NULL ) return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); memcpy( ssl->cli_id, info, ilen ); ssl->cli_id_len = ilen; return( 0 ); } void mbedtls_ssl_conf_dtls_cookies( mbedtls_ssl_config *conf, mbedtls_ssl_cookie_write_t *f_cookie_write, mbedtls_ssl_cookie_check_t *f_cookie_check, void *p_cookie ) { conf->f_cookie_write = f_cookie_write; conf->f_cookie_check = f_cookie_check; conf->p_cookie = p_cookie; } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) static int ssl_parse_servername_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t servername_list_size, hostname_len; const unsigned char *p; MBEDTLS_SSL_DEBUG_MSG( 3, ( "parse ServerName extension" ) ); if( len < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } servername_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( servername_list_size + 2 != len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } p = buf + 2; while( servername_list_size > 2 ) { hostname_len = ( ( p[1] << 8 ) | p[2] ); if( hostname_len + 3 > servername_list_size ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( p[0] == MBEDTLS_TLS_EXT_SERVERNAME_HOSTNAME ) { ret = ssl->conf->f_sni( ssl->conf->p_sni, ssl, p + 3, hostname_len ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "ssl_sni_wrapper", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNRECOGNIZED_NAME ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } return( 0 ); } servername_list_size -= hostname_len + 3; p += hostname_len + 3; } if( servername_list_size != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } return( 0 ); } #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static int ssl_conf_has_psk_or_cb( mbedtls_ssl_config const *conf ) { if( conf->f_psk != NULL ) return( 1 ); if( conf->psk_identity_len == 0 || conf->psk_identity == NULL ) return( 0 ); if( conf->psk != NULL && conf->psk_len != 0 ) return( 1 ); #if defined(MBEDTLS_USE_PSA_CRYPTO) if( conf->psk_opaque != 0 ) return( 1 ); #endif /* MBEDTLS_USE_PSA_CRYPTO */ return( 0 ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) static int ssl_use_opaque_psk( mbedtls_ssl_context const *ssl ) { if( ssl->conf->f_psk != NULL ) { /* If we've used a callback to select the PSK, * the static configuration is irrelevant. */ if( ssl->handshake->psk_opaque != 0 ) return( 1 ); return( 0 ); } if( ssl->conf->psk_opaque != 0 ) return( 1 ); return( 0 ); } #endif /* MBEDTLS_USE_PSA_CRYPTO */ #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ static int ssl_parse_renegotiation_info( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { /* Check verify-data in constant-time. The length OTOH is no secret */ if( len != 1 + ssl->verify_data_len || buf[0] != ssl->verify_data_len || mbedtls_ssl_safer_memcmp( buf + 1, ssl->peer_verify_data, ssl->verify_data_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-matching renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } else #endif /* MBEDTLS_SSL_RENEGOTIATION */ { if( len != 1 || buf[0] != 0x0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "non-zero length renegotiation info" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; } return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* * Status of the implementation of signature-algorithms extension: * * Currently, we are only considering the signature-algorithm extension * to pick a ciphersuite which allows us to send the ServerKeyExchange * message with a signature-hash combination that the user allows. * * We do *not* check whether all certificates in our certificate * chain are signed with an allowed signature-hash pair. * This needs to be done at a later stage. * */ static int ssl_parse_signature_algorithms_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t sig_alg_list_size; const unsigned char *p; const unsigned char *end = buf + len; mbedtls_md_type_t md_cur; mbedtls_pk_type_t sig_cur; if ( len < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } sig_alg_list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( sig_alg_list_size + 2 != len || sig_alg_list_size % 2 != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Currently we only guarantee signing the ServerKeyExchange message according * to the constraints specified in this extension (see above), so it suffices * to remember only one suitable hash for each possible signature algorithm. * * This will change when we also consider certificate signatures, * in which case we will need to remember the whole signature-hash * pair list from the extension. */ for( p = buf + 2; p < end; p += 2 ) { /* Silently ignore unknown signature or hash algorithms. */ if( ( sig_cur = mbedtls_ssl_pk_alg_from_sig( p[1] ) ) == MBEDTLS_PK_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext" " unknown sig alg encoding %d", p[1] ) ); continue; } /* Check if we support the hash the user proposes */ md_cur = mbedtls_ssl_md_alg_from_hash( p[0] ); if( md_cur == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:" " unknown hash alg encoding %d", p[0] ) ); continue; } if( mbedtls_ssl_check_sig_hash( ssl, md_cur ) == 0 ) { mbedtls_ssl_sig_hash_set_add( &ssl->handshake->hash_algs, sig_cur, md_cur ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext:" " match sig %d and hash %d", sig_cur, md_cur ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: " "hash alg %d not supported", md_cur ) ); } } return( 0 ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_parse_supported_elliptic_curves( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_size, our_size; const unsigned char *p; const mbedtls_ecp_curve_info *curve_info, **curves; if ( len < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } list_size = ( ( buf[0] << 8 ) | ( buf[1] ) ); if( list_size + 2 != len || list_size % 2 != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Should never happen unless client duplicates the extension */ if( ssl->handshake->curves != NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Don't allow our peer to make us allocate too much memory, * and leave room for a final 0 */ our_size = list_size / 2 + 1; if( our_size > MBEDTLS_ECP_DP_MAX ) our_size = MBEDTLS_ECP_DP_MAX; if( ( curves = mbedtls_calloc( our_size, sizeof( *curves ) ) ) == NULL ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INTERNAL_ERROR ); return( MBEDTLS_ERR_SSL_ALLOC_FAILED ); } ssl->handshake->curves = curves; p = buf + 2; while( list_size > 0 && our_size > 1 ) { curve_info = mbedtls_ecp_curve_info_from_tls_id( ( p[0] << 8 ) | p[1] ); if( curve_info != NULL ) { *curves++ = curve_info; our_size--; } list_size -= 2; p += 2; } return( 0 ); } static int ssl_parse_supported_point_formats( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_size; const unsigned char *p; if( len == 0 || (size_t)( buf[0] + 1 ) != len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } list_size = buf[0]; p = buf + 1; while( list_size > 0 ) { if( p[0] == MBEDTLS_ECP_PF_UNCOMPRESSED || p[0] == MBEDTLS_ECP_PF_COMPRESSED ) { #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) ssl->handshake->ecdh_ctx.point_format = p[0]; #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ssl->handshake->ecjpake_ctx.point_format = p[0]; #endif MBEDTLS_SSL_DEBUG_MSG( 4, ( "point format selected: %d", p[0] ) ); return( 0 ); } list_size--; p++; } return( 0 ); } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static int ssl_parse_ecjpake_kkpp( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( mbedtls_ecjpake_check( &ssl->handshake->ecjpake_ctx ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "skip ecjpake kkpp extension" ) ); return( 0 ); } if( ( ret = mbedtls_ecjpake_read_round_one( &ssl->handshake->ecjpake_ctx, buf, len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_one", ret ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( ret ); } /* Only mark the extension as OK when we're sure it is */ ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static int ssl_parse_max_fragment_length_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 1 || buf[0] >= MBEDTLS_SSL_MAX_FRAG_LEN_INVALID ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->session_negotiate->mfl_code = buf[0]; return( 0 ); } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) static int ssl_parse_cid_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t peer_cid_len; /* CID extension only makes sense in DTLS */ if( ssl->conf->transport != MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Quoting draft-ietf-tls-dtls-connection-id-05 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05 * * struct { * opaque cid<0..2^8-1>; * } ConnectionId; */ if( len < 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } peer_cid_len = *buf++; len--; if( len != peer_cid_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Ignore CID if the user has disabled its use. */ if( ssl->negotiate_cid == MBEDTLS_SSL_CID_DISABLED ) { /* Leave ssl->handshake->cid_in_use in its default * value of MBEDTLS_SSL_CID_DISABLED. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "Client sent CID extension, but CID disabled" ) ); return( 0 ); } if( peer_cid_len > MBEDTLS_SSL_CID_OUT_LEN_MAX ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->handshake->cid_in_use = MBEDTLS_SSL_CID_ENABLED; ssl->handshake->peer_cid_len = (uint8_t) peer_cid_len; memcpy( ssl->handshake->peer_cid, buf, peer_cid_len ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "Use of CID extension negotiated" ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "Client CID", buf, peer_cid_len ); return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) static int ssl_parse_truncated_hmac_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ((void) buf); if( ssl->conf->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_ENABLED ) ssl->session_negotiate->trunc_hmac = MBEDTLS_SSL_TRUNC_HMAC_ENABLED; return( 0 ); } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) static int ssl_parse_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ((void) buf); if( ssl->conf->encrypt_then_mac == MBEDTLS_SSL_ETM_ENABLED && ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl->session_negotiate->encrypt_then_mac = MBEDTLS_SSL_ETM_ENABLED; } return( 0 ); } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) static int ssl_parse_extended_ms_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { if( len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ((void) buf); if( ssl->conf->extended_ms == MBEDTLS_SSL_EXTENDED_MS_ENABLED && ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 ) { ssl->handshake->extended_ms = MBEDTLS_SSL_EXTENDED_MS_ENABLED; } return( 0 ); } #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_parse_session_ticket_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t len ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_ssl_session session; mbedtls_ssl_session_init( &session ); if( ssl->conf->f_ticket_parse == NULL || ssl->conf->f_ticket_write == NULL ) { return( 0 ); } /* Remember the client asked us to send a new ticket */ ssl->handshake->new_session_ticket = 1; MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket length: %d", len ) ); if( len == 0 ) return( 0 ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket rejected: renegotiating" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ /* * Failures are ok: just ignore the ticket and proceed. */ if( ( ret = ssl->conf->f_ticket_parse( ssl->conf->p_ticket, &session, buf, len ) ) != 0 ) { mbedtls_ssl_session_free( &session ); if( ret == MBEDTLS_ERR_SSL_INVALID_MAC ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is not authentic" ) ); else if( ret == MBEDTLS_ERR_SSL_SESSION_TICKET_EXPIRED ) MBEDTLS_SSL_DEBUG_MSG( 3, ( "ticket is expired" ) ); else MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_parse", ret ); return( 0 ); } /* * Keep the session ID sent by the client, since we MUST send it back to * inform them we're accepting the ticket (RFC 5077 section 3.4) */ session.id_len = ssl->session_negotiate->id_len; memcpy( &session.id, ssl->session_negotiate->id, session.id_len ); mbedtls_ssl_session_free( ssl->session_negotiate ); memcpy( ssl->session_negotiate, &session, sizeof( mbedtls_ssl_session ) ); /* Zeroize instead of free as we copied the content */ mbedtls_platform_zeroize( &session, sizeof( mbedtls_ssl_session ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from ticket" ) ); ssl->handshake->resume = 1; /* Don't send a new ticket after all, this one is OK */ ssl->handshake->new_session_ticket = 0; return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_ALPN) static int ssl_parse_alpn_ext( mbedtls_ssl_context *ssl, const unsigned char *buf, size_t len ) { size_t list_len, cur_len, ours_len; const unsigned char *theirs, *start, *end; const char **ours; /* If ALPN not configured, just ignore the extension */ if( ssl->conf->alpn_list == NULL ) return( 0 ); /* * opaque ProtocolName<1..2^8-1>; * * struct { * ProtocolName protocol_name_list<2..2^16-1> * } ProtocolNameList; */ /* Min length is 2 (list_len) + 1 (name_len) + 1 (name) */ if( len < 4 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } list_len = ( buf[0] << 8 ) | buf[1]; if( list_len != len - 2 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Validate peer's list (lengths) */ start = buf + 2; end = buf + len; for( theirs = start; theirs != end; theirs += cur_len ) { cur_len = *theirs++; /* Current identifier must fit in list */ if( cur_len > (size_t)( end - theirs ) ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* Empty strings MUST NOT be included */ if( cur_len == 0 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_ILLEGAL_PARAMETER ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } /* * Use our order of preference */ for( ours = ssl->conf->alpn_list; *ours != NULL; ours++ ) { ours_len = strlen( *ours ); for( theirs = start; theirs != end; theirs += cur_len ) { cur_len = *theirs++; if( cur_len == ours_len && memcmp( theirs, *ours, cur_len ) == 0 ) { ssl->alpn_chosen = *ours; return( 0 ); } } } /* If we get there, no match was found */ mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_NO_APPLICATION_PROTOCOL ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif /* MBEDTLS_SSL_ALPN */ /* * Auxiliary functions for ServerHello parsing and related actions */ #if defined(MBEDTLS_X509_CRT_PARSE_C) /* * Return 0 if the given key uses one of the acceptable curves, -1 otherwise */ #if defined(MBEDTLS_ECDSA_C) static int ssl_check_key_curve( mbedtls_pk_context *pk, const mbedtls_ecp_curve_info **curves ) { const mbedtls_ecp_curve_info **crv = curves; mbedtls_ecp_group_id grp_id = mbedtls_pk_ec( *pk )->grp.id; while( *crv != NULL ) { if( (*crv)->grp_id == grp_id ) return( 0 ); crv++; } return( -1 ); } #endif /* MBEDTLS_ECDSA_C */ /* * Try picking a certificate for this ciphersuite, * return 0 on success and -1 on failure. */ static int ssl_pick_cert( mbedtls_ssl_context *ssl, const mbedtls_ssl_ciphersuite_t * ciphersuite_info ) { mbedtls_ssl_key_cert *cur, *list, *fallback = NULL; mbedtls_pk_type_t pk_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ); uint32_t flags; #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_key_cert != NULL ) list = ssl->handshake->sni_key_cert; else #endif list = ssl->conf->key_cert; if( pk_alg == MBEDTLS_PK_NONE ) return( 0 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite requires certificate" ) ); if( list == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "server has no certificate" ) ); return( -1 ); } for( cur = list; cur != NULL; cur = cur->next ) { flags = 0; MBEDTLS_SSL_DEBUG_CRT( 3, "candidate certificate chain, certificate", cur->cert ); if( ! mbedtls_pk_can_do( &cur->cert->pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: key type" ) ); continue; } /* * This avoids sending the client a cert it'll reject based on * keyUsage or other extensions. * * It also allows the user to provision different certificates for * different uses based on keyUsage, eg if they want to avoid signing * and decrypting with the same RSA key. */ if( mbedtls_ssl_check_cert_usage( cur->cert, ciphersuite_info, MBEDTLS_SSL_IS_SERVER, &flags ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: " "(extended) key usage extension" ) ); continue; } #if defined(MBEDTLS_ECDSA_C) if( pk_alg == MBEDTLS_PK_ECDSA && ssl_check_key_curve( &cur->cert->pk, ssl->handshake->curves ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate mismatch: elliptic curve" ) ); continue; } #endif /* * Try to select a SHA-1 certificate for pre-1.2 clients, but still * present them a SHA-higher cert rather than failing if it's the only * one we got that satisfies the other conditions. */ if( ssl->minor_ver < MBEDTLS_SSL_MINOR_VERSION_3 && cur->cert->sig_md != MBEDTLS_MD_SHA1 ) { if( fallback == NULL ) fallback = cur; { MBEDTLS_SSL_DEBUG_MSG( 3, ( "certificate not preferred: " "sha-2 with pre-TLS 1.2 client" ) ); continue; } } /* If we get there, we got a winner */ break; } if( cur == NULL ) cur = fallback; /* Do not update ssl->handshake->key_cert unless there is a match */ if( cur != NULL ) { ssl->handshake->key_cert = cur; MBEDTLS_SSL_DEBUG_CRT( 3, "selected certificate chain, certificate", ssl->handshake->key_cert->cert ); return( 0 ); } return( -1 ); } #endif /* MBEDTLS_X509_CRT_PARSE_C */ /* * Check if a given ciphersuite is suitable for use with our config/keys/etc * Sets ciphersuite_info only if the suite matches. */ static int ssl_ciphersuite_match( mbedtls_ssl_context *ssl, int suite_id, const mbedtls_ssl_ciphersuite_t **ciphersuite_info ) { const mbedtls_ssl_ciphersuite_t *suite_info; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) mbedtls_pk_type_t sig_type; #endif suite_info = mbedtls_ssl_ciphersuite_from_id( suite_id ); if( suite_info == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "trying ciphersuite: %s", suite_info->name ) ); if( suite_info->min_minor_ver > ssl->minor_ver || suite_info->max_minor_ver < ssl->minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: version" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( suite_info->flags & MBEDTLS_CIPHERSUITE_NODTLS ) ) return( 0 ); #endif #if defined(MBEDTLS_ARC4_C) if( ssl->conf->arc4_disabled == MBEDTLS_SSL_ARC4_DISABLED && suite_info->cipher == MBEDTLS_CIPHER_ARC4_128 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: rc4" ) ); return( 0 ); } #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( suite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE && ( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_ECJPAKE_KKPP_OK ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: ecjpake " "not configured or ext missing" ) ); return( 0 ); } #endif #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) if( mbedtls_ssl_ciphersuite_uses_ec( suite_info ) && ( ssl->handshake->curves == NULL || ssl->handshake->curves[0] == NULL ) ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: " "no common elliptic curve" ) ); return( 0 ); } #endif #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) /* If the ciphersuite requires a pre-shared key and we don't * have one, skip it now rather than failing later */ if( mbedtls_ssl_ciphersuite_uses_psk( suite_info ) && ssl_conf_has_psk_or_cb( ssl->conf ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no pre-shared key" ) ); return( 0 ); } #endif #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* If the ciphersuite requires signing, check whether * a suitable hash algorithm is present. */ if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { sig_type = mbedtls_ssl_get_ciphersuite_sig_alg( suite_info ); if( sig_type != MBEDTLS_PK_NONE && mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_type ) == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: no suitable hash algorithm " "for signature algorithm %d", sig_type ) ); return( 0 ); } } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_X509_CRT_PARSE_C) /* * Final check: if ciphersuite requires us to have a * certificate/key of a particular type: * - select the appropriate certificate if we have one, or * - try the next ciphersuite if we don't * This must be done last since we modify the key_cert list. */ if( ssl_pick_cert( ssl, suite_info ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciphersuite mismatch: " "no suitable certificate" ) ); return( 0 ); } #endif *ciphersuite_info = suite_info; return( 0 ); } #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO) static int ssl_parse_client_hello_v2( mbedtls_ssl_context *ssl ) { int ret, got_common_suite; unsigned int i, j; size_t n; unsigned int ciph_len, sess_len, chal_len; unsigned char *buf, *p; const int *ciphersuites; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello v2" ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "client hello v2 illegal for renegotiation" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ buf = ssl->in_hdr; MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, 5 ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message type: %d", buf[2] ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, message len.: %d", ( ( buf[0] & 0x7F ) << 8 ) | buf[1] ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v2, max. version: [%d:%d]", buf[3], buf[4] ) ); /* * SSLv2 Client Hello * * Record layer: * 0 . 1 message length * * SSL layer: * 2 . 2 message type * 3 . 4 protocol version */ if( buf[2] != MBEDTLS_SSL_HS_CLIENT_HELLO || buf[3] != MBEDTLS_SSL_MAJOR_VERSION_3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } n = ( ( buf[0] << 8 ) | buf[1] ) & 0x7FFF; if( n < 17 || n > 512 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->major_ver = MBEDTLS_SSL_MAJOR_VERSION_3; ssl->minor_ver = ( buf[4] <= ssl->conf->max_minor_ver ) ? buf[4] : ssl->conf->max_minor_ver; if( ssl->minor_ver < ssl->conf->min_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum" " [%d:%d] < [%d:%d]", ssl->major_ver, ssl->minor_ver, ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); } ssl->handshake->max_major_ver = buf[3]; ssl->handshake->max_minor_ver = buf[4]; if( ( ret = mbedtls_ssl_fetch_input( ssl, 2 + n ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } ssl->handshake->update_checksum( ssl, buf + 2, n ); buf = ssl->in_msg; n = ssl->in_left - 5; /* * 0 . 1 ciphersuitelist length * 2 . 3 session id length * 4 . 5 challenge length * 6 . .. ciphersuitelist * .. . .. session id * .. . .. challenge */ MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, n ); ciph_len = ( buf[0] << 8 ) | buf[1]; sess_len = ( buf[2] << 8 ) | buf[3]; chal_len = ( buf[4] << 8 ) | buf[5]; MBEDTLS_SSL_DEBUG_MSG( 3, ( "ciph_len: %d, sess_len: %d, chal_len: %d", ciph_len, sess_len, chal_len ) ); /* * Make sure each parameter length is valid */ if( ciph_len < 3 || ( ciph_len % 3 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( sess_len > 32 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( chal_len < 8 || chal_len > 32 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( n != 6 + ciph_len + sess_len + chal_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist", buf + 6, ciph_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 6 + ciph_len, sess_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, challenge", buf + 6 + ciph_len + sess_len, chal_len ); p = buf + 6 + ciph_len; ssl->session_negotiate->id_len = sess_len; memset( ssl->session_negotiate->id, 0, sizeof( ssl->session_negotiate->id ) ); memcpy( ssl->session_negotiate->id, p, ssl->session_negotiate->id_len ); p += sess_len; memset( ssl->handshake->randbytes, 0, 64 ); memcpy( ssl->handshake->randbytes + 32 - chal_len, p, chal_len ); /* * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */ for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 ) { if( p[0] == 0 && p[1] == 0 && p[2] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV " "during renegotiation" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif /* MBEDTLS_SSL_RENEGOTIATION */ ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; break; } } #if defined(MBEDTLS_SSL_FALLBACK_SCSV) for( i = 0, p = buf + 6; i < ciph_len; i += 3, p += 3 ) { if( p[0] == 0 && p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) && p[2] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ) & 0xff ) ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "received FALLBACK_SCSV" ) ); if( ssl->minor_ver < ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } break; } } #endif /* MBEDTLS_SSL_FALLBACK_SCSV */ got_common_suite = 0; ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver]; ciphersuite_info = NULL; #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE) for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 ) for( i = 0; ciphersuites[i] != 0; i++ ) #else for( i = 0; ciphersuites[i] != 0; i++ ) for( j = 0, p = buf + 6; j < ciph_len; j += 3, p += 3 ) #endif { if( p[0] != 0 || p[1] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) || p[2] != ( ( ciphersuites[i] ) & 0xFF ) ) continue; got_common_suite = 1; if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i], &ciphersuite_info ) ) != 0 ) return( ret ); if( ciphersuite_info != NULL ) goto have_ciphersuite_v2; } if( got_common_suite ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, " "but none of them usable" ) ); return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE ); } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) ); return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); } have_ciphersuite_v2: MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) ); ssl->session_negotiate->ciphersuite = ciphersuites[i]; ssl->handshake->ciphersuite_info = ciphersuite_info; /* * SSLv2 Client Hello relevant renegotiation security checks */ if( ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->in_left = 0; ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello v2" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO */ /* This function doesn't alert on errors that happen early during ClientHello parsing because they might indicate that the client is not talking SSL/TLS at all and would not understand our alert. */ static int ssl_parse_client_hello( mbedtls_ssl_context *ssl ) { int ret, got_common_suite; size_t i, j; size_t ciph_offset, comp_offset, ext_offset; size_t msg_len, ciph_len, sess_len, comp_len, ext_len; #if defined(MBEDTLS_SSL_PROTO_DTLS) size_t cookie_offset, cookie_len; #endif unsigned char *buf, *p, *ext; #if defined(MBEDTLS_SSL_RENEGOTIATION) int renegotiation_info_seen = 0; #endif int handshake_failure = 0; const int *ciphersuites; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; int major, minor; /* If there is no signature-algorithm extension present, * we need to fall back to the default values for allowed * signature-hash pairs. */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) int sig_hash_alg_ext_present = 0; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client hello" ) ); #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) read_record_header: #endif /* * If renegotiating, then the input was read with mbedtls_ssl_read_record(), * otherwise read it ourselves manually in order to support SSLv2 * ClientHello, which doesn't use the same record layer format. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE ) #endif { if( ( ret = mbedtls_ssl_fetch_input( ssl, 5 ) ) != 0 ) { /* No alert on a read error. */ MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } } buf = ssl->in_hdr; #if defined(MBEDTLS_SSL_SRV_SUPPORT_SSLV2_CLIENT_HELLO) #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_STREAM ) #endif if( ( buf[0] & 0x80 ) != 0 ) return( ssl_parse_client_hello_v2( ssl ) ); #endif MBEDTLS_SSL_DEBUG_BUF( 4, "record header", buf, mbedtls_ssl_in_hdr_len( ssl ) ); /* * SSLv3/TLS Client Hello * * Record layer: * 0 . 0 message type * 1 . 2 protocol version * 3 . 11 DTLS: epoch + record sequence number * 3 . 4 message length */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message type: %d", buf[0] ) ); if( buf[0] != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, message len.: %d", ( ssl->in_len[0] << 8 ) | ssl->in_len[1] ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, protocol version: [%d:%d]", buf[1], buf[2] ) ); mbedtls_ssl_read_version( &major, &minor, ssl->conf->transport, buf + 1 ); /* According to RFC 5246 Appendix E.1, the version here is typically * "{03,00}, the lowest version number supported by the client, [or] the * value of ClientHello.client_version", so the only meaningful check here * is the major version shouldn't be less than 3 */ if( major < MBEDTLS_SSL_MAJOR_VERSION_3 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* For DTLS if this is the initial handshake, remember the client sequence * number to use it in our next message (RFC 6347 4.2.1) */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM #if defined(MBEDTLS_SSL_RENEGOTIATION) && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE #endif ) { /* Epoch should be 0 for initial handshakes */ if( ssl->in_ctr[0] != 0 || ssl->in_ctr[1] != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } memcpy( ssl->cur_out_ctr + 2, ssl->in_ctr + 2, 6 ); #if defined(MBEDTLS_SSL_DTLS_ANTI_REPLAY) if( mbedtls_ssl_dtls_replay_check( ssl ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "replayed record, discarding" ) ); ssl->next_record_offset = 0; ssl->in_left = 0; goto read_record_header; } /* No MAC to check yet, so we can update right now */ mbedtls_ssl_dtls_replay_update( ssl ); #endif } #endif /* MBEDTLS_SSL_PROTO_DTLS */ msg_len = ( ssl->in_len[0] << 8 ) | ssl->in_len[1]; #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { /* Set by mbedtls_ssl_read_record() */ msg_len = ssl->in_hslen; } else #endif { if( msg_len > MBEDTLS_SSL_IN_CONTENT_LEN ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } if( ( ret = mbedtls_ssl_fetch_input( ssl, mbedtls_ssl_in_hdr_len( ssl ) + msg_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_fetch_input", ret ); return( ret ); } /* Done reading this record, get ready for the next one */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ssl->next_record_offset = msg_len + mbedtls_ssl_in_hdr_len( ssl ); else #endif ssl->in_left = 0; } buf = ssl->in_msg; MBEDTLS_SSL_DEBUG_BUF( 4, "record contents", buf, msg_len ); ssl->handshake->update_checksum( ssl, buf, msg_len ); /* * Handshake layer: * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 5 DTLS only: message seqence number * 6 . 8 DTLS only: fragment offset * 9 . 11 DTLS only: fragment length */ if( msg_len < mbedtls_ssl_hs_hdr_len( ssl ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake type: %d", buf[0] ) ); if( buf[0] != MBEDTLS_SSL_HS_CLIENT_HELLO ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, handshake len.: %d", ( buf[1] << 16 ) | ( buf[2] << 8 ) | buf[3] ) ); /* We don't support fragmentation of ClientHello (yet?) */ if( buf[1] != 0 || msg_len != mbedtls_ssl_hs_hdr_len( ssl ) + ( ( buf[2] << 8 ) | buf[3] ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { /* * Copy the client's handshake message_seq on initial handshakes, * check sequence number on renego. */ #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { /* This couldn't be done in ssl_prepare_handshake_record() */ unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; if( cli_msg_seq != ssl->handshake->in_msg_seq ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message_seq: " "%d (expected %d)", cli_msg_seq, ssl->handshake->in_msg_seq ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ssl->handshake->in_msg_seq++; } else #endif { unsigned int cli_msg_seq = ( ssl->in_msg[4] << 8 ) | ssl->in_msg[5]; ssl->handshake->out_msg_seq = cli_msg_seq; ssl->handshake->in_msg_seq = cli_msg_seq + 1; } /* * For now we don't support fragmentation, so make sure * fragment_offset == 0 and fragment_length == length */ if( ssl->in_msg[6] != 0 || ssl->in_msg[7] != 0 || ssl->in_msg[8] != 0 || memcmp( ssl->in_msg + 1, ssl->in_msg + 9, 3 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "ClientHello fragmentation not supported" ) ); return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); } } #endif /* MBEDTLS_SSL_PROTO_DTLS */ buf += mbedtls_ssl_hs_hdr_len( ssl ); msg_len -= mbedtls_ssl_hs_hdr_len( ssl ); /* * ClientHello layer: * 0 . 1 protocol version * 2 . 33 random bytes (starting with 4 bytes of Unix time) * 34 . 35 session id length (1 byte) * 35 . 34+x session id * 35+x . 35+x DTLS only: cookie length (1 byte) * 36+x . .. DTLS only: cookie * .. . .. ciphersuite list length (2 bytes) * .. . .. ciphersuite list * .. . .. compression alg. list length (1 byte) * .. . .. compression alg. list * .. . .. extensions length (2 bytes, optional) * .. . .. extensions (optional) */ /* * Minimal length (with everything empty and extensions omitted) is * 2 + 32 + 1 + 2 + 1 = 38 bytes. Check that first, so that we can * read at least up to session id length without worrying. */ if( msg_len < 38 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Check and save the protocol version */ MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, version", buf, 2 ); mbedtls_ssl_read_version( &ssl->major_ver, &ssl->minor_ver, ssl->conf->transport, buf ); ssl->handshake->max_major_ver = ssl->major_ver; ssl->handshake->max_minor_ver = ssl->minor_ver; if( ssl->major_ver < ssl->conf->min_major_ver || ssl->minor_ver < ssl->conf->min_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "client only supports ssl smaller than minimum" " [%d:%d] < [%d:%d]", ssl->major_ver, ssl->minor_ver, ssl->conf->min_major_ver, ssl->conf->min_minor_ver ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_PROTOCOL_VERSION ); } if( ssl->major_ver > ssl->conf->max_major_ver ) { ssl->major_ver = ssl->conf->max_major_ver; ssl->minor_ver = ssl->conf->max_minor_ver; } else if( ssl->minor_ver > ssl->conf->max_minor_ver ) ssl->minor_ver = ssl->conf->max_minor_ver; /* * Save client random (inc. Unix time) */ MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, random bytes", buf + 2, 32 ); memcpy( ssl->handshake->randbytes, buf + 2, 32 ); /* * Check the session ID length and save session ID */ sess_len = buf[34]; if( sess_len > sizeof( ssl->session_negotiate->id ) || sess_len + 34 + 2 > msg_len ) /* 2 for cipherlist length field */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, session id", buf + 35, sess_len ); ssl->session_negotiate->id_len = sess_len; memset( ssl->session_negotiate->id, 0, sizeof( ssl->session_negotiate->id ) ); memcpy( ssl->session_negotiate->id, buf + 35, ssl->session_negotiate->id_len ); /* * Check the cookie length and content */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) { cookie_offset = 35 + sess_len; cookie_len = buf[cookie_offset]; if( cookie_offset + 1 + cookie_len + 2 > msg_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_PROTOCOL_VERSION ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, cookie", buf + cookie_offset + 1, cookie_len ); #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) if( ssl->conf->f_cookie_check != NULL #if defined(MBEDTLS_SSL_RENEGOTIATION) && ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE #endif ) { if( ssl->conf->f_cookie_check( ssl->conf->p_cookie, buf + cookie_offset + 1, cookie_len, ssl->cli_id, ssl->cli_id_len ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification failed" ) ); ssl->handshake->verify_cookie_len = 1; } else { MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification passed" ) ); ssl->handshake->verify_cookie_len = 0; } } else #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ { /* We know we didn't send a cookie, so it should be empty */ if( cookie_len != 0 ) { /* This may be an attacker's probe, so don't send an alert */ MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "cookie verification skipped" ) ); } /* * Check the ciphersuitelist length (will be parsed later) */ ciph_offset = cookie_offset + 1 + cookie_len; } else #endif /* MBEDTLS_SSL_PROTO_DTLS */ ciph_offset = 35 + sess_len; ciph_len = ( buf[ciph_offset + 0] << 8 ) | ( buf[ciph_offset + 1] ); if( ciph_len < 2 || ciph_len + 2 + ciph_offset + 1 > msg_len || /* 1 for comp. alg. len */ ( ciph_len % 2 ) != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, ciphersuitelist", buf + ciph_offset + 2, ciph_len ); /* * Check the compression algorithms length and pick one */ comp_offset = ciph_offset + 2 + ciph_len; comp_len = buf[comp_offset]; if( comp_len < 1 || comp_len > 16 || comp_len + comp_offset + 1 > msg_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } MBEDTLS_SSL_DEBUG_BUF( 3, "client hello, compression", buf + comp_offset + 1, comp_len ); ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL; #if defined(MBEDTLS_ZLIB_SUPPORT) for( i = 0; i < comp_len; ++i ) { if( buf[comp_offset + 1 + i] == MBEDTLS_SSL_COMPRESS_DEFLATE ) { ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_DEFLATE; break; } } #endif /* See comments in ssl_write_client_hello() */ #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) ssl->session_negotiate->compression = MBEDTLS_SSL_COMPRESS_NULL; #endif /* Do not parse the extensions if the protocol is SSLv3 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) ) { #endif /* * Check the extension length */ ext_offset = comp_offset + 1 + comp_len; if( msg_len > ext_offset ) { if( msg_len < ext_offset + 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ext_len = ( buf[ext_offset + 0] << 8 ) | ( buf[ext_offset + 1] ); if( ( ext_len > 0 && ext_len < 4 ) || msg_len != ext_offset + 2 + ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } else ext_len = 0; ext = buf + ext_offset + 2; MBEDTLS_SSL_DEBUG_BUF( 3, "client hello extensions", ext, ext_len ); while( ext_len != 0 ) { unsigned int ext_id; unsigned int ext_size; if ( ext_len < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } ext_id = ( ( ext[0] << 8 ) | ( ext[1] ) ); ext_size = ( ( ext[2] << 8 ) | ( ext[3] ) ); if( ext_size + 4 > ext_len ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } switch( ext_id ) { #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) case MBEDTLS_TLS_EXT_SERVERNAME: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ServerName extension" ) ); if( ssl->conf->f_sni == NULL ) break; ret = ssl_parse_servername_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_SERVER_NAME_INDICATION */ case MBEDTLS_TLS_EXT_RENEGOTIATION_INFO: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found renegotiation extension" ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) renegotiation_info_seen = 1; #endif ret = ssl_parse_renegotiation_info( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) case MBEDTLS_TLS_EXT_SIG_ALG: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found signature_algorithms extension" ) ); ret = ssl_parse_signature_algorithms_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); sig_hash_alg_ext_present = 1; break; #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) case MBEDTLS_TLS_EXT_SUPPORTED_ELLIPTIC_CURVES: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported elliptic curves extension" ) ); ret = ssl_parse_supported_elliptic_curves( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; case MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found supported point formats extension" ) ); ssl->handshake->cli_exts |= MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT; ret = ssl_parse_supported_point_formats( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) case MBEDTLS_TLS_EXT_ECJPAKE_KKPP: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found ecjpake kkpp extension" ) ); ret = ssl_parse_ecjpake_kkpp( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) case MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found max fragment length extension" ) ); ret = ssl_parse_max_fragment_length_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) case MBEDTLS_TLS_EXT_TRUNCATED_HMAC: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found truncated hmac extension" ) ); ret = ssl_parse_truncated_hmac_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) case MBEDTLS_TLS_EXT_CID: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found CID extension" ) ); ret = ssl_parse_cid_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) case MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found encrypt then mac extension" ) ); ret = ssl_parse_encrypt_then_mac_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) case MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found extended master secret extension" ) ); ret = ssl_parse_extended_ms_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) case MBEDTLS_TLS_EXT_SESSION_TICKET: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found session ticket extension" ) ); ret = ssl_parse_session_ticket_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_SESSION_TICKETS */ #if defined(MBEDTLS_SSL_ALPN) case MBEDTLS_TLS_EXT_ALPN: MBEDTLS_SSL_DEBUG_MSG( 3, ( "found alpn extension" ) ); ret = ssl_parse_alpn_ext( ssl, ext + 4, ext_size ); if( ret != 0 ) return( ret ); break; #endif /* MBEDTLS_SSL_SESSION_TICKETS */ default: MBEDTLS_SSL_DEBUG_MSG( 3, ( "unknown extension found: %d (ignoring)", ext_id ) ); } ext_len -= 4 + ext_size; ext += 4 + ext_size; if( ext_len > 0 && ext_len < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client hello message" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_DECODE_ERROR ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } } #if defined(MBEDTLS_SSL_PROTO_SSL3) } #endif #if defined(MBEDTLS_SSL_FALLBACK_SCSV) for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 ) { if( p[0] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE >> 8 ) & 0xff ) && p[1] == (unsigned char)( ( MBEDTLS_SSL_FALLBACK_SCSV_VALUE ) & 0xff ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "received FALLBACK_SCSV" ) ); if( ssl->minor_ver < ssl->conf->max_minor_ver ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "inapropriate fallback" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_INAPROPRIATE_FALLBACK ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } break; } } #endif /* MBEDTLS_SSL_FALLBACK_SCSV */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) /* * Try to fall back to default hash SHA1 if the client * hasn't provided any preferred signature-hash combinations. */ if( sig_hash_alg_ext_present == 0 ) { mbedtls_md_type_t md_default = MBEDTLS_MD_SHA1; if( mbedtls_ssl_check_sig_hash( ssl, md_default ) != 0 ) md_default = MBEDTLS_MD_NONE; mbedtls_ssl_sig_hash_set_const_hash( &ssl->handshake->hash_algs, md_default ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 && MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED */ /* * Check for TLS_EMPTY_RENEGOTIATION_INFO_SCSV */ for( i = 0, p = buf + ciph_offset + 2; i < ciph_len; i += 2, p += 2 ) { if( p[0] == 0 && p[1] == MBEDTLS_SSL_EMPTY_RENEGOTIATION_INFO ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "received TLS_EMPTY_RENEGOTIATION_INFO " ) ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "received RENEGOTIATION SCSV " "during renegotiation" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } #endif ssl->secure_renegotiation = MBEDTLS_SSL_SECURE_RENEGOTIATION; break; } } /* * Renegotiation security checks */ if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_BREAK_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation, breaking off handshake" ) ); handshake_failure = 1; } #if defined(MBEDTLS_SSL_RENEGOTIATION) else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_SECURE_RENEGOTIATION && renegotiation_info_seen == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension missing (secure)" ) ); handshake_failure = 1; } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && ssl->conf->allow_legacy_renegotiation == MBEDTLS_SSL_LEGACY_NO_RENEGOTIATION ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "legacy renegotiation not allowed" ) ); handshake_failure = 1; } else if( ssl->renego_status == MBEDTLS_SSL_RENEGOTIATION_IN_PROGRESS && ssl->secure_renegotiation == MBEDTLS_SSL_LEGACY_RENEGOTIATION && renegotiation_info_seen == 1 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "renegotiation_info extension present (legacy)" ) ); handshake_failure = 1; } #endif /* MBEDTLS_SSL_RENEGOTIATION */ if( handshake_failure == 1 ) { mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_HELLO ); } /* * Search for a matching ciphersuite * (At the end because we need information from the EC-based extensions * and certificate from the SNI callback triggered by the SNI extension.) */ got_common_suite = 0; ciphersuites = ssl->conf->ciphersuite_list[ssl->minor_ver]; ciphersuite_info = NULL; #if defined(MBEDTLS_SSL_SRV_RESPECT_CLIENT_PREFERENCE) for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) for( i = 0; ciphersuites[i] != 0; i++ ) #else for( i = 0; ciphersuites[i] != 0; i++ ) for( j = 0, p = buf + ciph_offset + 2; j < ciph_len; j += 2, p += 2 ) #endif { if( p[0] != ( ( ciphersuites[i] >> 8 ) & 0xFF ) || p[1] != ( ( ciphersuites[i] ) & 0xFF ) ) continue; got_common_suite = 1; if( ( ret = ssl_ciphersuite_match( ssl, ciphersuites[i], &ciphersuite_info ) ) != 0 ) return( ret ); if( ciphersuite_info != NULL ) goto have_ciphersuite; } if( got_common_suite ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got ciphersuites in common, " "but none of them usable" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_NO_USABLE_CIPHERSUITE ); } else { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no ciphersuites in common" ) ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_HANDSHAKE_FAILURE ); return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); } have_ciphersuite: MBEDTLS_SSL_DEBUG_MSG( 2, ( "selected ciphersuite: %s", ciphersuite_info->name ) ); ssl->session_negotiate->ciphersuite = ciphersuites[i]; ssl->handshake->ciphersuite_info = ciphersuite_info; ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_recv_flight_completed( ssl ); #endif /* Debugging-only output for testsuite */ #if defined(MBEDTLS_DEBUG_C) && \ defined(MBEDTLS_SSL_PROTO_TLS1_2) && \ defined(MBEDTLS_KEY_EXCHANGE_WITH_CERT_ENABLED) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_alg( ciphersuite_info ); if( sig_alg != MBEDTLS_PK_NONE ) { mbedtls_md_type_t md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_alg ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "client hello v3, signature_algorithm ext: %d", mbedtls_ssl_hash_from_md_alg( md_alg ) ) ); } else { MBEDTLS_SSL_DEBUG_MSG( 3, ( "no hash algorithm for signature algorithm " "%d - should not happen", sig_alg ) ); } } #endif MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client hello" ) ); return( 0 ); } #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) static void ssl_write_truncated_hmac_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->session_negotiate->trunc_hmac == MBEDTLS_SSL_TRUNC_HMAC_DISABLED ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding truncated hmac extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_TRUNCATED_HMAC ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_TRUNCATED_HMAC */ #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) static void ssl_write_cid_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; size_t ext_len; const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; *olen = 0; /* Skip writing the extension if we don't want to use it or if * the client hasn't offered it. */ if( ssl->handshake->cid_in_use == MBEDTLS_SSL_CID_DISABLED ) return; /* ssl->own_cid_len is at most MBEDTLS_SSL_CID_IN_LEN_MAX * which is at most 255, so the increment cannot overflow. */ if( end < p || (size_t)( end - p ) < (unsigned)( ssl->own_cid_len + 5 ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding CID extension" ) ); /* * Quoting draft-ietf-tls-dtls-connection-id-05 * https://tools.ietf.org/html/draft-ietf-tls-dtls-connection-id-05 * * struct { * opaque cid<0..2^8-1>; * } ConnectionId; */ *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_CID ) & 0xFF ); ext_len = (size_t) ssl->own_cid_len + 1; *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ext_len ) & 0xFF ); *p++ = (uint8_t) ssl->own_cid_len; memcpy( p, ssl->own_cid, ssl->own_cid_len ); *olen = ssl->own_cid_len + 5; } #endif /* MBEDTLS_SSL_DTLS_CONNECTION_ID */ #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) static void ssl_write_encrypt_then_mac_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; const mbedtls_ssl_ciphersuite_t *suite = NULL; const mbedtls_cipher_info_t *cipher = NULL; if( ssl->session_negotiate->encrypt_then_mac == MBEDTLS_SSL_ETM_DISABLED || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { *olen = 0; return; } /* * RFC 7366: "If a server receives an encrypt-then-MAC request extension * from a client and then selects a stream or Authenticated Encryption * with Associated Data (AEAD) ciphersuite, it MUST NOT send an * encrypt-then-MAC response extension back to the client." */ if( ( suite = mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ) ) == NULL || ( cipher = mbedtls_cipher_info_from_type( suite->cipher ) ) == NULL || cipher->mode != MBEDTLS_MODE_CBC ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding encrypt then mac extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ENCRYPT_THEN_MAC ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_ENCRYPT_THEN_MAC */ #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) static void ssl_write_extended_ms_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->handshake->extended_ms == MBEDTLS_SSL_EXTENDED_MS_DISABLED || ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_0 ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding extended master secret " "extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_EXTENDED_MASTER_SECRET ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_EXTENDED_MASTER_SECRET */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static void ssl_write_session_ticket_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->handshake->new_session_ticket == 0 ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding session ticket extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SESSION_TICKET ) & 0xFF ); *p++ = 0x00; *p++ = 0x00; *olen = 4; } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ static void ssl_write_renegotiation_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->secure_renegotiation != MBEDTLS_SSL_SECURE_RENEGOTIATION ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, secure renegotiation extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_RENEGOTIATION_INFO ) & 0xFF ); #if defined(MBEDTLS_SSL_RENEGOTIATION) if( ssl->renego_status != MBEDTLS_SSL_INITIAL_HANDSHAKE ) { *p++ = 0x00; *p++ = ( ssl->verify_data_len * 2 + 1 ) & 0xFF; *p++ = ssl->verify_data_len * 2 & 0xFF; memcpy( p, ssl->peer_verify_data, ssl->verify_data_len ); p += ssl->verify_data_len; memcpy( p, ssl->own_verify_data, ssl->verify_data_len ); p += ssl->verify_data_len; } else #endif /* MBEDTLS_SSL_RENEGOTIATION */ { *p++ = 0x00; *p++ = 0x01; *p++ = 0x00; } *olen = p - buf; } #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) static void ssl_write_max_fragment_length_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; if( ssl->session_negotiate->mfl_code == MBEDTLS_SSL_MAX_FRAG_LEN_NONE ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, max_fragment_length extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_MAX_FRAGMENT_LENGTH ) & 0xFF ); *p++ = 0x00; *p++ = 1; *p++ = ssl->session_negotiate->mfl_code; *olen = 5; } #endif /* MBEDTLS_SSL_MAX_FRAGMENT_LENGTH */ #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static void ssl_write_supported_point_formats_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { unsigned char *p = buf; ((void) ssl); if( ( ssl->handshake->cli_exts & MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS_PRESENT ) == 0 ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, supported_point_formats extension" ) ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_SUPPORTED_POINT_FORMATS ) & 0xFF ); *p++ = 0x00; *p++ = 2; *p++ = 1; *p++ = MBEDTLS_ECP_PF_UNCOMPRESSED; *olen = 6; } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C || MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) static void ssl_write_ecjpake_kkpp_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p = buf; const unsigned char *end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; size_t kkpp_len; *olen = 0; /* Skip costly computation if not needed */ if( ssl->handshake->ciphersuite_info->key_exchange != MBEDTLS_KEY_EXCHANGE_ECJPAKE ) return; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, ecjpake kkpp extension" ) ); if( end - p < 4 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "buffer too small" ) ); return; } *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( MBEDTLS_TLS_EXT_ECJPAKE_KKPP ) & 0xFF ); ret = mbedtls_ecjpake_write_round_one( &ssl->handshake->ecjpake_ctx, p + 2, end - p - 2, &kkpp_len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1 , "mbedtls_ecjpake_write_round_one", ret ); return; } *p++ = (unsigned char)( ( kkpp_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( kkpp_len ) & 0xFF ); *olen = kkpp_len + 4; } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ #if defined(MBEDTLS_SSL_ALPN ) static void ssl_write_alpn_ext( mbedtls_ssl_context *ssl, unsigned char *buf, size_t *olen ) { if( ssl->alpn_chosen == NULL ) { *olen = 0; return; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, adding alpn extension" ) ); /* * 0 . 1 ext identifier * 2 . 3 ext length * 4 . 5 protocol list length * 6 . 6 protocol name length * 7 . 7+n protocol name */ buf[0] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN >> 8 ) & 0xFF ); buf[1] = (unsigned char)( ( MBEDTLS_TLS_EXT_ALPN ) & 0xFF ); *olen = 7 + strlen( ssl->alpn_chosen ); buf[2] = (unsigned char)( ( ( *olen - 4 ) >> 8 ) & 0xFF ); buf[3] = (unsigned char)( ( ( *olen - 4 ) ) & 0xFF ); buf[4] = (unsigned char)( ( ( *olen - 6 ) >> 8 ) & 0xFF ); buf[5] = (unsigned char)( ( ( *olen - 6 ) ) & 0xFF ); buf[6] = (unsigned char)( ( ( *olen - 7 ) ) & 0xFF ); memcpy( buf + 7, ssl->alpn_chosen, *olen - 7 ); } #endif /* MBEDTLS_ECDH_C || MBEDTLS_ECDSA_C */ #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) static int ssl_write_hello_verify_request( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *p = ssl->out_msg + 4; unsigned char *cookie_len_byte; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write hello verify request" ) ); /* * struct { * ProtocolVersion server_version; * opaque cookie<0..2^8-1>; * } HelloVerifyRequest; */ /* The RFC is not clear on this point, but sending the actual negotiated * version looks like the most interoperable thing to do. */ mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, p ); MBEDTLS_SSL_DEBUG_BUF( 3, "server version", p, 2 ); p += 2; /* If we get here, f_cookie_check is not null */ if( ssl->conf->f_cookie_write == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "inconsistent cookie callbacks" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } /* Skip length byte until we know the length */ cookie_len_byte = p++; if( ( ret = ssl->conf->f_cookie_write( ssl->conf->p_cookie, &p, ssl->out_buf + MBEDTLS_SSL_OUT_BUFFER_LEN, ssl->cli_id, ssl->cli_id_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "f_cookie_write", ret ); return( ret ); } *cookie_len_byte = (unsigned char)( p - ( cookie_len_byte + 1 ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "cookie sent", cookie_len_byte + 1, *cookie_len_byte ); ssl->out_msglen = p - ssl->out_msg; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_HELLO_VERIFY_REQUEST; ssl->state = MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write hello verify request" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ static int ssl_write_server_hello( mbedtls_ssl_context *ssl ) { #if defined(MBEDTLS_HAVE_TIME) mbedtls_time_t t; #endif int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t olen, ext_len = 0, n; unsigned char *buf, *p; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello" ) ); #if defined(MBEDTLS_SSL_DTLS_HELLO_VERIFY) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->verify_cookie_len != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "client hello was not authenticated" ) ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) ); return( ssl_write_hello_verify_request( ssl ) ); } #endif /* MBEDTLS_SSL_DTLS_HELLO_VERIFY */ if( ssl->conf->f_rng == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no RNG provided") ); return( MBEDTLS_ERR_SSL_NO_RNG ); } /* * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 5 protocol version * 6 . 9 UNIX time() * 10 . 37 random bytes */ buf = ssl->out_msg; p = buf + 4; mbedtls_ssl_write_version( ssl->major_ver, ssl->minor_ver, ssl->conf->transport, p ); p += 2; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen version: [%d:%d]", buf[4], buf[5] ) ); #if defined(MBEDTLS_HAVE_TIME) t = mbedtls_time( NULL ); *p++ = (unsigned char)( t >> 24 ); *p++ = (unsigned char)( t >> 16 ); *p++ = (unsigned char)( t >> 8 ); *p++ = (unsigned char)( t ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, current time: %lu", t ) ); #else if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 4 ) ) != 0 ) return( ret ); p += 4; #endif /* MBEDTLS_HAVE_TIME */ if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, p, 28 ) ) != 0 ) return( ret ); p += 28; memcpy( ssl->handshake->randbytes + 32, buf + 6, 32 ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, random bytes", buf + 6, 32 ); /* * Resume is 0 by default, see ssl_handshake_init(). * It may be already set to 1 by ssl_parse_session_ticket_ext(). * If not, try looking up session ID in our cache. */ if( ssl->handshake->resume == 0 && #if defined(MBEDTLS_SSL_RENEGOTIATION) ssl->renego_status == MBEDTLS_SSL_INITIAL_HANDSHAKE && #endif ssl->session_negotiate->id_len != 0 && ssl->conf->f_get_cache != NULL && ssl->conf->f_get_cache( ssl->conf->p_cache, ssl->session_negotiate ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 3, ( "session successfully restored from cache" ) ); ssl->handshake->resume = 1; } if( ssl->handshake->resume == 0 ) { /* * New session, create a new session id, * unless we're about to issue a session ticket */ ssl->state++; #if defined(MBEDTLS_HAVE_TIME) ssl->session_negotiate->start = mbedtls_time( NULL ); #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) if( ssl->handshake->new_session_ticket != 0 ) { ssl->session_negotiate->id_len = n = 0; memset( ssl->session_negotiate->id, 0, 32 ); } else #endif /* MBEDTLS_SSL_SESSION_TICKETS */ { ssl->session_negotiate->id_len = n = 32; if( ( ret = ssl->conf->f_rng( ssl->conf->p_rng, ssl->session_negotiate->id, n ) ) != 0 ) return( ret ); } } else { /* * Resuming a session */ n = ssl->session_negotiate->id_len; ssl->state = MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC; if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); return( ret ); } } /* * 38 . 38 session id length * 39 . 38+n session id * 39+n . 40+n chosen ciphersuite * 41+n . 41+n chosen compression alg. * 42+n . 43+n extensions length * 44+n . 43+n+m extensions */ *p++ = (unsigned char) ssl->session_negotiate->id_len; memcpy( p, ssl->session_negotiate->id, ssl->session_negotiate->id_len ); p += ssl->session_negotiate->id_len; MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, session id len.: %d", n ) ); MBEDTLS_SSL_DEBUG_BUF( 3, "server hello, session id", buf + 39, n ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "%s session has been resumed", ssl->handshake->resume ? "a" : "no" ) ); *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite >> 8 ); *p++ = (unsigned char)( ssl->session_negotiate->ciphersuite ); *p++ = (unsigned char)( ssl->session_negotiate->compression ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, chosen ciphersuite: %s", mbedtls_ssl_get_ciphersuite_name( ssl->session_negotiate->ciphersuite ) ) ); MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, compress alg.: 0x%02X", ssl->session_negotiate->compression ) ); /* Do not write the extensions if the protocol is SSLv3 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) if( ( ssl->major_ver != 3 ) || ( ssl->minor_ver != 0 ) ) { #endif /* * First write extensions, then the total length */ ssl_write_renegotiation_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #if defined(MBEDTLS_SSL_MAX_FRAGMENT_LENGTH) ssl_write_max_fragment_length_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_TRUNCATED_HMAC) ssl_write_truncated_hmac_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_DTLS_CONNECTION_ID) ssl_write_cid_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_ENCRYPT_THEN_MAC) ssl_write_encrypt_then_mac_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_EXTENDED_MASTER_SECRET) ssl_write_extended_ms_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_SESSION_TICKETS) ssl_write_session_ticket_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_ECDH_C) || defined(MBEDTLS_ECDSA_C) || \ defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if ( mbedtls_ssl_ciphersuite_uses_ec( mbedtls_ssl_ciphersuite_from_id( ssl->session_negotiate->ciphersuite ) ) ) { ssl_write_supported_point_formats_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; } #endif #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) ssl_write_ecjpake_kkpp_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif #if defined(MBEDTLS_SSL_ALPN) ssl_write_alpn_ext( ssl, p + 2 + ext_len, &olen ); ext_len += olen; #endif MBEDTLS_SSL_DEBUG_MSG( 3, ( "server hello, total extension length: %d", ext_len ) ); if( ext_len > 0 ) { *p++ = (unsigned char)( ( ext_len >> 8 ) & 0xFF ); *p++ = (unsigned char)( ( ext_len ) & 0xFF ); p += ext_len; } #if defined(MBEDTLS_SSL_PROTO_SSL3) } #endif ssl->out_msglen = p - buf; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_HELLO; ret = mbedtls_ssl_write_handshake_msg( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello" ) ); return( ret ); } #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED) static int ssl_write_certificate_request( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) ); if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_write_certificate_request( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; uint16_t dn_size, total_dn_size; /* excluding length bytes */ size_t ct_len, sa_len; /* including length bytes */ unsigned char *buf, *p; const unsigned char * const end = ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN; const mbedtls_x509_crt *crt; int authmode; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write certificate request" ) ); ssl->state++; #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_authmode != MBEDTLS_SSL_VERIFY_UNSET ) authmode = ssl->handshake->sni_authmode; else #endif authmode = ssl->conf->authmode; if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) || authmode == MBEDTLS_SSL_VERIFY_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write certificate request" ) ); return( 0 ); } /* * 0 . 0 handshake type * 1 . 3 handshake length * 4 . 4 cert type count * 5 .. m-1 cert types * m .. m+1 sig alg length (TLS 1.2 only) * m+1 .. n-1 SignatureAndHashAlgorithms (TLS 1.2 only) * n .. n+1 length of all DNs * n+2 .. n+3 length of DN 1 * n+4 .. ... Distinguished Name #1 * ... .. ... length of DN 2, etc. */ buf = ssl->out_msg; p = buf + 4; /* * Supported certificate types * * ClientCertificateType certificate_types<1..2^8-1>; * enum { (255) } ClientCertificateType; */ ct_len = 0; #if defined(MBEDTLS_RSA_C) p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_RSA_SIGN; #endif #if defined(MBEDTLS_ECDSA_C) p[1 + ct_len++] = MBEDTLS_SSL_CERT_TYPE_ECDSA_SIGN; #endif p[0] = (unsigned char) ct_len++; p += ct_len; sa_len = 0; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) /* * Add signature_algorithms for verify (TLS 1.2) * * SignatureAndHashAlgorithm supported_signature_algorithms<2..2^16-2>; * * struct { * HashAlgorithm hash; * SignatureAlgorithm signature; * } SignatureAndHashAlgorithm; * * enum { (255) } HashAlgorithm; * enum { (255) } SignatureAlgorithm; */ if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { const int *cur; /* * Supported signature algorithms */ for( cur = ssl->conf->sig_hashes; *cur != MBEDTLS_MD_NONE; cur++ ) { unsigned char hash = mbedtls_ssl_hash_from_md_alg( *cur ); if( MBEDTLS_SSL_HASH_NONE == hash || mbedtls_ssl_set_calc_verify_md( ssl, hash ) ) continue; #if defined(MBEDTLS_RSA_C) p[2 + sa_len++] = hash; p[2 + sa_len++] = MBEDTLS_SSL_SIG_RSA; #endif #if defined(MBEDTLS_ECDSA_C) p[2 + sa_len++] = hash; p[2 + sa_len++] = MBEDTLS_SSL_SIG_ECDSA; #endif } p[0] = (unsigned char)( sa_len >> 8 ); p[1] = (unsigned char)( sa_len ); sa_len += 2; p += sa_len; } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ /* * DistinguishedName certificate_authorities<0..2^16-1>; * opaque DistinguishedName<1..2^16-1>; */ p += 2; total_dn_size = 0; if( ssl->conf->cert_req_ca_list == MBEDTLS_SSL_CERT_REQ_CA_LIST_ENABLED ) { /* NOTE: If trusted certificates are provisioned * via a CA callback (configured through * `mbedtls_ssl_conf_ca_cb()`, then the * CertificateRequest is currently left empty. */ #if defined(MBEDTLS_SSL_SERVER_NAME_INDICATION) if( ssl->handshake->sni_ca_chain != NULL ) crt = ssl->handshake->sni_ca_chain; else #endif crt = ssl->conf->ca_chain; while( crt != NULL && crt->version != 0 ) { /* It follows from RFC 5280 A.1 that this length * can be represented in at most 11 bits. */ dn_size = (uint16_t) crt->subject_raw.len; if( end < p || (size_t)( end - p ) < 2 + (size_t) dn_size ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "skipping CAs: buffer too short" ) ); break; } *p++ = (unsigned char)( dn_size >> 8 ); *p++ = (unsigned char)( dn_size ); memcpy( p, crt->subject_raw.p, dn_size ); p += dn_size; MBEDTLS_SSL_DEBUG_BUF( 3, "requested DN", p - dn_size, dn_size ); total_dn_size += 2 + dn_size; crt = crt->next; } } ssl->out_msglen = p - buf; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_CERTIFICATE_REQUEST; ssl->out_msg[4 + ct_len + sa_len] = (unsigned char)( total_dn_size >> 8 ); ssl->out_msg[5 + ct_len + sa_len] = (unsigned char)( total_dn_size ); ret = mbedtls_ssl_write_handshake_msg( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write certificate request" ) ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) static int ssl_get_ecdh_params_from_cert( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; if( ! mbedtls_pk_can_do( mbedtls_ssl_own_key( ssl ), MBEDTLS_PK_ECKEY ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "server key not ECDH capable" ) ); return( MBEDTLS_ERR_SSL_PK_TYPE_MISMATCH ); } if( ( ret = mbedtls_ecdh_get_params( &ssl->handshake->ecdh_ctx, mbedtls_pk_ec( *mbedtls_ssl_own_key( ssl ) ), MBEDTLS_ECDH_OURS ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ecdh_get_params" ), ret ); return( ret ); } return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \ defined(MBEDTLS_SSL_ASYNC_PRIVATE) static int ssl_resume_server_key_exchange( mbedtls_ssl_context *ssl, size_t *signature_len ) { /* Append the signature to ssl->out_msg, leaving 2 bytes for the * signature length which will be added in ssl_write_server_key_exchange * after the call to ssl_prepare_server_key_exchange. * ssl_write_server_key_exchange also takes care of incrementing * ssl->out_msglen. */ unsigned char *sig_start = ssl->out_msg + ssl->out_msglen + 2; size_t sig_max_len = ( ssl->out_buf + MBEDTLS_SSL_OUT_CONTENT_LEN - sig_start ); int ret = ssl->conf->f_async_resume( ssl, sig_start, signature_len, sig_max_len ); if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) { ssl->handshake->async_in_progress = 0; mbedtls_ssl_set_async_operation_data( ssl, NULL ); } MBEDTLS_SSL_DEBUG_RET( 2, "ssl_resume_server_key_exchange", ret ); return( ret ); } #endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && defined(MBEDTLS_SSL_ASYNC_PRIVATE) */ /* Prepare the ServerKeyExchange message, up to and including * calculating the signature if any, but excluding formatting the * signature and sending the message. */ static int ssl_prepare_server_key_exchange( mbedtls_ssl_context *ssl, size_t *signature_len ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED) #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) unsigned char *dig_signed = NULL; #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PFS_ENABLED */ (void) ciphersuite_info; /* unused in some configurations */ #if !defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) (void) signature_len; #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ ssl->out_msglen = 4; /* header (type:1, length:3) to be written later */ /* * * Part 1: Provide key exchange parameters for chosen ciphersuite. * */ /* * - ECJPAKE key exchanges */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; ret = mbedtls_ecjpake_write_round_two( &ssl->handshake->ecjpake_ctx, ssl->out_msg + ssl->out_msglen, MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, &len, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_write_round_two", ret ); return( ret ); } ssl->out_msglen += len; } #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ /* * For (EC)DHE key exchanges with PSK, parameters are prefixed by support * identity hint (RFC 4279, Sec. 3). Until someone needs this feature, * we use empty support identity hints here. **/ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { ssl->out_msg[ssl->out_msglen++] = 0x00; ssl->out_msg[ssl->out_msglen++] = 0x00; } #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ /* * - DHE key exchanges */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED) if( mbedtls_ssl_ciphersuite_uses_dhe( ciphersuite_info ) ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; if( ssl->conf->dhm_P.p == NULL || ssl->conf->dhm_G.p == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no DH parameters set" ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } /* * Ephemeral DH parameters: * * struct { * opaque dh_p<1..2^16-1>; * opaque dh_g<1..2^16-1>; * opaque dh_Ys<1..2^16-1>; * } ServerDHParams; */ if( ( ret = mbedtls_dhm_set_group( &ssl->handshake->dhm_ctx, &ssl->conf->dhm_P, &ssl->conf->dhm_G ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_set_group", ret ); return( ret ); } if( ( ret = mbedtls_dhm_make_params( &ssl->handshake->dhm_ctx, (int) mbedtls_mpi_size( &ssl->handshake->dhm_ctx.P ), ssl->out_msg + ssl->out_msglen, &len, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_make_params", ret ); return( ret ); } #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) dig_signed = ssl->out_msg + ssl->out_msglen; #endif ssl->out_msglen += len; MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: X ", &ssl->handshake->dhm_ctx.X ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: P ", &ssl->handshake->dhm_ctx.P ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: G ", &ssl->handshake->dhm_ctx.G ); MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GX", &ssl->handshake->dhm_ctx.GX ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_DHE_ENABLED */ /* * - ECDHE key exchanges */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED) if( mbedtls_ssl_ciphersuite_uses_ecdhe( ciphersuite_info ) ) { /* * Ephemeral ECDH parameters: * * struct { * ECParameters curve_params; * ECPoint public; * } ServerECDHParams; */ const mbedtls_ecp_curve_info **curve = NULL; const mbedtls_ecp_group_id *gid; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t len = 0; /* Match our preference list against the offered curves */ for( gid = ssl->conf->curve_list; *gid != MBEDTLS_ECP_DP_NONE; gid++ ) for( curve = ssl->handshake->curves; *curve != NULL; curve++ ) if( (*curve)->grp_id == *gid ) goto curve_matching_done; curve_matching_done: if( curve == NULL || *curve == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "no matching curve for ECDHE" ) ); return( MBEDTLS_ERR_SSL_NO_CIPHER_CHOSEN ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "ECDHE curve: %s", (*curve)->name ) ); if( ( ret = mbedtls_ecdh_setup( &ssl->handshake->ecdh_ctx, (*curve)->grp_id ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecp_group_load", ret ); return( ret ); } if( ( ret = mbedtls_ecdh_make_params( &ssl->handshake->ecdh_ctx, &len, ssl->out_msg + ssl->out_msglen, MBEDTLS_SSL_OUT_CONTENT_LEN - ssl->out_msglen, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_make_params", ret ); return( ret ); } #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) dig_signed = ssl->out_msg + ssl->out_msglen; #endif ssl->out_msglen += len; MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Q ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDHE_ENABLED */ /* * * Part 2: For key exchanges involving the server signing the * exchange parameters, compute and add the signature here. * */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) if( mbedtls_ssl_ciphersuite_uses_server_signature( ciphersuite_info ) ) { size_t dig_signed_len = ssl->out_msg + ssl->out_msglen - dig_signed; size_t hashlen = 0; unsigned char hash[MBEDTLS_MD_MAX_SIZE]; int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; /* * 2.1: Choose hash algorithm: * A: For TLS 1.2, obey signature-hash-algorithm extension * to choose appropriate hash. * B: For SSL3, TLS1.0, TLS1.1 and ECDHE_ECDSA, use SHA1 * (RFC 4492, Sec. 5.4) * C: Otherwise, use MD5 + SHA1 (RFC 4346, Sec. 7.4.3) */ mbedtls_md_type_t md_alg; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) mbedtls_pk_type_t sig_alg = mbedtls_ssl_get_ciphersuite_sig_pk_alg( ciphersuite_info ); if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { /* A: For TLS 1.2, obey signature-hash-algorithm extension * (RFC 5246, Sec. 7.4.1.4.1). */ if( sig_alg == MBEDTLS_PK_NONE || ( md_alg = mbedtls_ssl_sig_hash_set_find( &ssl->handshake->hash_algs, sig_alg ) ) == MBEDTLS_MD_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); /* (... because we choose a cipher suite * only if there is a matching hash.) */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA ) { /* B: Default hash SHA1 */ md_alg = MBEDTLS_MD_SHA1; } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ { /* C: MD5 + SHA1 */ md_alg = MBEDTLS_MD_NONE; } MBEDTLS_SSL_DEBUG_MSG( 3, ( "pick hash algorithm %d for signing", md_alg ) ); /* * 2.2: Compute the hash to be signed */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( md_alg == MBEDTLS_MD_NONE ) { hashlen = 36; ret = mbedtls_ssl_get_key_exchange_md_ssl_tls( ssl, hash, dig_signed, dig_signed_len ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || \ MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( md_alg != MBEDTLS_MD_NONE ) { ret = mbedtls_ssl_get_key_exchange_md_tls1_2( ssl, hash, &hashlen, dig_signed, dig_signed_len, md_alg ); if( ret != 0 ) return( ret ); } else #endif /* MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 || \ MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } MBEDTLS_SSL_DEBUG_BUF( 3, "parameters hash", hash, hashlen ); /* * 2.3: Compute and add the signature */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { /* * For TLS 1.2, we need to specify signature and hash algorithm * explicitly through a prefix to the signature. * * struct { * HashAlgorithm hash; * SignatureAlgorithm signature; * } SignatureAndHashAlgorithm; * * struct { * SignatureAndHashAlgorithm algorithm; * opaque signature<0..2^16-1>; * } DigitallySigned; * */ ssl->out_msg[ssl->out_msglen++] = mbedtls_ssl_hash_from_md_alg( md_alg ); ssl->out_msg[ssl->out_msglen++] = mbedtls_ssl_sig_from_pk_alg( sig_alg ); } #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if( ssl->conf->f_async_sign_start != NULL ) { ret = ssl->conf->f_async_sign_start( ssl, mbedtls_ssl_own_cert( ssl ), md_alg, hash, hashlen ); switch( ret ) { case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH: /* act as if f_async_sign was null */ break; case 0: ssl->handshake->async_in_progress = 1; return( ssl_resume_server_key_exchange( ssl, signature_len ) ); case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS: ssl->handshake->async_in_progress = 1; return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ); default: MBEDTLS_SSL_DEBUG_RET( 1, "f_async_sign_start", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ if( mbedtls_ssl_own_key( ssl ) == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no private key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } /* Append the signature to ssl->out_msg, leaving 2 bytes for the * signature length which will be added in ssl_write_server_key_exchange * after the call to ssl_prepare_server_key_exchange. * ssl_write_server_key_exchange also takes care of incrementing * ssl->out_msglen. */ if( ( ret = mbedtls_pk_sign( mbedtls_ssl_own_key( ssl ), md_alg, hash, hashlen, ssl->out_msg + ssl->out_msglen + 2, signature_len, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_sign", ret ); return( ret ); } } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ return( 0 ); } /* Prepare the ServerKeyExchange message and send it. For ciphersuites * that do not include a ServerKeyExchange message, do nothing. Either * way, if successful, move on to the next step in the SSL state * machine. */ static int ssl_write_server_key_exchange( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t signature_len = 0; #if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED) const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; #endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server key exchange" ) ); #if defined(MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED) /* Extract static ECDH parameters and abort if ServerKeyExchange * is not needed. */ if( mbedtls_ssl_ciphersuite_no_pfs( ciphersuite_info ) ) { /* For suites involving ECDH, extract DH parameters * from certificate at this point. */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED) if( mbedtls_ssl_ciphersuite_uses_ecdh( ciphersuite_info ) ) { ssl_get_ecdh_params_from_cert( ssl ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_ECDH_ENABLED */ /* Key exchanges not involving ephemeral keys don't use * ServerKeyExchange, so end here. */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip write server key exchange" ) ); ssl->state++; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_NON_PFS_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && \ defined(MBEDTLS_SSL_ASYNC_PRIVATE) /* If we have already prepared the message and there is an ongoing * signature operation, resume signing. */ if( ssl->handshake->async_in_progress != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming signature operation" ) ); ret = ssl_resume_server_key_exchange( ssl, &signature_len ); } else #endif /* defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) && defined(MBEDTLS_SSL_ASYNC_PRIVATE) */ { /* ServerKeyExchange is needed. Prepare the message. */ ret = ssl_prepare_server_key_exchange( ssl, &signature_len ); } if( ret != 0 ) { /* If we're starting to write a new message, set ssl->out_msglen * to 0. But if we're resuming after an asynchronous message, * out_msglen is the amount of data written so far and mst be * preserved. */ if( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange (pending)" ) ); else ssl->out_msglen = 0; return( ret ); } /* If there is a signature, write its length. * ssl_prepare_server_key_exchange already wrote the signature * itself at its proper place in the output buffer. */ #if defined(MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED) if( signature_len != 0 ) { ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len >> 8 ); ssl->out_msg[ssl->out_msglen++] = (unsigned char)( signature_len ); MBEDTLS_SSL_DEBUG_BUF( 3, "my signature", ssl->out_msg + ssl->out_msglen, signature_len ); /* Skip over the already-written signature */ ssl->out_msglen += signature_len; } #endif /* MBEDTLS_KEY_EXCHANGE_WITH_SERVER_SIGNATURE_ENABLED */ /* Add header and send. */ ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_KEY_EXCHANGE; ssl->state++; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server key exchange" ) ); return( 0 ); } static int ssl_write_server_hello_done( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write server hello done" ) ); ssl->out_msglen = 4; ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_SERVER_HELLO_DONE; ssl->state++; #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM ) mbedtls_ssl_send_flight_completed( ssl ); #endif if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_flight_transmit", ret ); return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write server hello done" ) ); return( 0 ); } #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) static int ssl_parse_client_dh_public( mbedtls_ssl_context *ssl, unsigned char **p, const unsigned char *end ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t n; /* * Receive G^Y mod P, premaster = (G^Y)^X mod P */ if( *p + 2 > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } n = ( (*p)[0] << 8 ) | (*p)[1]; *p += 2; if( *p + n > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ( ret = mbedtls_dhm_read_public( &ssl->handshake->dhm_ctx, *p, n ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_read_public", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP ); } *p += n; MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: GY", &ssl->handshake->dhm_ctx.GY ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) static int ssl_resume_decrypt_pms( mbedtls_ssl_context *ssl, unsigned char *peer_pms, size_t *peer_pmslen, size_t peer_pmssize ) { int ret = ssl->conf->f_async_resume( ssl, peer_pms, peer_pmslen, peer_pmssize ); if( ret != MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) { ssl->handshake->async_in_progress = 0; mbedtls_ssl_set_async_operation_data( ssl, NULL ); } MBEDTLS_SSL_DEBUG_RET( 2, "ssl_decrypt_encrypted_pms", ret ); return( ret ); } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ static int ssl_decrypt_encrypted_pms( mbedtls_ssl_context *ssl, const unsigned char *p, const unsigned char *end, unsigned char *peer_pms, size_t *peer_pmslen, size_t peer_pmssize ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; mbedtls_pk_context *private_key = mbedtls_ssl_own_key( ssl ); mbedtls_pk_context *public_key = &mbedtls_ssl_own_cert( ssl )->pk; size_t len = mbedtls_pk_get_len( public_key ); #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) /* If we have already started decoding the message and there is an ongoing * decryption operation, resume signing. */ if( ssl->handshake->async_in_progress != 0 ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "resuming decryption operation" ) ); return( ssl_resume_decrypt_pms( ssl, peer_pms, peer_pmslen, peer_pmssize ) ); } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ /* * Prepare to decrypt the premaster using own private RSA key */ #if defined(MBEDTLS_SSL_PROTO_TLS1) || defined(MBEDTLS_SSL_PROTO_TLS1_1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_0 ) { if ( p + 2 > end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( *p++ != ( ( len >> 8 ) & 0xFF ) || *p++ != ( ( len ) & 0xFF ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } } #endif if( p + len != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } /* * Decrypt the premaster secret */ #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if( ssl->conf->f_async_decrypt_start != NULL ) { ret = ssl->conf->f_async_decrypt_start( ssl, mbedtls_ssl_own_cert( ssl ), p, len ); switch( ret ) { case MBEDTLS_ERR_SSL_HW_ACCEL_FALLTHROUGH: /* act as if f_async_decrypt_start was null */ break; case 0: ssl->handshake->async_in_progress = 1; return( ssl_resume_decrypt_pms( ssl, peer_pms, peer_pmslen, peer_pmssize ) ); case MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS: ssl->handshake->async_in_progress = 1; return( MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ); default: MBEDTLS_SSL_DEBUG_RET( 1, "f_async_decrypt_start", ret ); return( ret ); } } #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ if( ! mbedtls_pk_can_do( private_key, MBEDTLS_PK_RSA ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no RSA private key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } ret = mbedtls_pk_decrypt( private_key, p, len, peer_pms, peer_pmslen, peer_pmssize, ssl->conf->f_rng, ssl->conf->p_rng ); return( ret ); } static int ssl_parse_encrypted_pms( mbedtls_ssl_context *ssl, const unsigned char *p, const unsigned char *end, size_t pms_offset ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; unsigned char *pms = ssl->handshake->premaster + pms_offset; unsigned char ver[2]; unsigned char fake_pms[48], peer_pms[48]; unsigned char mask; size_t i, peer_pmslen; unsigned int diff; /* In case of a failure in decryption, the decryption may write less than * 2 bytes of output, but we always read the first two bytes. It doesn't * matter in the end because diff will be nonzero in that case due to * peer_pmslen being less than 48, and we only care whether diff is 0. * But do initialize peer_pms for robustness anyway. This also makes * memory analyzers happy (don't access uninitialized memory, even * if it's an unsigned char). */ peer_pms[0] = peer_pms[1] = ~0; ret = ssl_decrypt_encrypted_pms( ssl, p, end, peer_pms, &peer_pmslen, sizeof( peer_pms ) ); #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if ( ret == MBEDTLS_ERR_SSL_ASYNC_IN_PROGRESS ) return( ret ); #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ mbedtls_ssl_write_version( ssl->handshake->max_major_ver, ssl->handshake->max_minor_ver, ssl->conf->transport, ver ); /* Avoid data-dependent branches while checking for invalid * padding, to protect against timing-based Bleichenbacher-type * attacks. */ diff = (unsigned int) ret; diff |= peer_pmslen ^ 48; diff |= peer_pms[0] ^ ver[0]; diff |= peer_pms[1] ^ ver[1]; /* mask = diff ? 0xff : 0x00 using bit operations to avoid branches */ /* MSVC has a warning about unary minus on unsigned, but this is * well-defined and precisely what we want to do here */ #if defined(_MSC_VER) #pragma warning( push ) #pragma warning( disable : 4146 ) #endif mask = - ( ( diff | - diff ) >> ( sizeof( unsigned int ) * 8 - 1 ) ); #if defined(_MSC_VER) #pragma warning( pop ) #endif /* * Protection against Bleichenbacher's attack: invalid PKCS#1 v1.5 padding * must not cause the connection to end immediately; instead, send a * bad_record_mac later in the handshake. * To protect against timing-based variants of the attack, we must * not have any branch that depends on whether the decryption was * successful. In particular, always generate the fake premaster secret, * regardless of whether it will ultimately influence the output or not. */ ret = ssl->conf->f_rng( ssl->conf->p_rng, fake_pms, sizeof( fake_pms ) ); if( ret != 0 ) { /* It's ok to abort on an RNG failure, since this does not reveal * anything about the RSA decryption. */ return( ret ); } #if defined(MBEDTLS_SSL_DEBUG_ALL) if( diff != 0 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); #endif if( sizeof( ssl->handshake->premaster ) < pms_offset || sizeof( ssl->handshake->premaster ) - pms_offset < 48 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } ssl->handshake->pmslen = 48; /* Set pms to either the true or the fake PMS, without * data-dependent branches. */ for( i = 0; i < ssl->handshake->pmslen; i++ ) pms[i] = ( mask & fake_pms[i] ) | ( (~mask) & peer_pms[i] ); return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED) static int ssl_parse_client_psk_identity( mbedtls_ssl_context *ssl, unsigned char **p, const unsigned char *end ) { int ret = 0; uint16_t n; if( ssl_conf_has_psk_or_cb( ssl->conf ) == 0 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "got no pre-shared key" ) ); return( MBEDTLS_ERR_SSL_PRIVATE_KEY_REQUIRED ); } /* * Receive client pre-shared key identity name */ if( end - *p < 2 ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } n = ( (*p)[0] << 8 ) | (*p)[1]; *p += 2; if( n == 0 || n > end - *p ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ssl->conf->f_psk != NULL ) { if( ssl->conf->f_psk( ssl->conf->p_psk, ssl, *p, n ) != 0 ) ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } else { /* Identity is not a big secret since clients send it in the clear, * but treat it carefully anyway, just in case */ if( n != ssl->conf->psk_identity_len || mbedtls_ssl_safer_memcmp( ssl->conf->psk_identity, *p, n ) != 0 ) { ret = MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY; } } if( ret == MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ) { MBEDTLS_SSL_DEBUG_BUF( 3, "Unknown PSK identity", *p, n ); mbedtls_ssl_send_alert_message( ssl, MBEDTLS_SSL_ALERT_LEVEL_FATAL, MBEDTLS_SSL_ALERT_MSG_UNKNOWN_PSK_IDENTITY ); return( MBEDTLS_ERR_SSL_UNKNOWN_IDENTITY ); } *p += n; return( 0 ); } #endif /* MBEDTLS_KEY_EXCHANGE_SOME_PSK_ENABLED */ static int ssl_parse_client_key_exchange( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; const mbedtls_ssl_ciphersuite_t *ciphersuite_info; unsigned char *p, *end; ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse client key exchange" ) ); #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) && \ ( defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) ) if( ( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) && ( ssl->handshake->async_in_progress != 0 ) ) { /* We've already read a record and there is an asynchronous * operation in progress to decrypt it. So skip reading the * record. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "will resume decryption of previously-read record" ) ); } else #endif if( ( ret = mbedtls_ssl_read_record( ssl, 1 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_read_record", ret ); return( ret ); } p = ssl->in_msg + mbedtls_ssl_hs_hdr_len( ssl ); end = ssl->in_msg + ssl->in_hslen; if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ssl->in_msg[0] != MBEDTLS_SSL_HS_CLIENT_KEY_EXCHANGE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } #if defined(MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_RSA ) { if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret ); return( ret ); } if( p != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ( ret = mbedtls_dhm_calc_secret( &ssl->handshake->dhm_ctx, ssl->handshake->premaster, MBEDTLS_PREMASTER_SIZE, &ssl->handshake->pmslen, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_dhm_calc_secret", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS ); } MBEDTLS_SSL_DEBUG_MPI( 3, "DHM: K ", &ssl->handshake->dhm_ctx.K ); } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED) || \ defined(MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_RSA || ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA ) { if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx, p, end - p) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_QP ); if( ( ret = mbedtls_ecdh_calc_secret( &ssl->handshake->ecdh_ctx, &ssl->handshake->pmslen, ssl->handshake->premaster, MBEDTLS_MPI_MAX_SIZE, ssl->conf->f_rng, ssl->conf->p_rng ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_calc_secret", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_CS ); } MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_Z ); } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_RSA_ENABLED || MBEDTLS_KEY_EXCHANGE_ECDH_ECDSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_PSK ) { if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } if( p != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* For opaque PSKs, we perform the PSK-to-MS derivation atomatically * and skip the intermediate PMS. */ if( ssl_use_opaque_psk( ssl ) == 1 ) MBEDTLS_SSL_DEBUG_MSG( 1, ( "skip PMS generation for opaque PSK" ) ); else #endif /* MBEDTLS_USE_PSA_CRYPTO */ if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA_PSK ) { #if defined(MBEDTLS_SSL_ASYNC_PRIVATE) if ( ssl->handshake->async_in_progress != 0 ) { /* There is an asynchronous operation in progress to * decrypt the encrypted premaster secret, so skip * directly to resuming this operation. */ MBEDTLS_SSL_DEBUG_MSG( 3, ( "PSK identity already parsed" ) ); /* Update p to skip the PSK identity. ssl_parse_encrypted_pms * won't actually use it, but maintain p anyway for robustness. */ p += ssl->conf->psk_identity_len + 2; } else #endif /* MBEDTLS_SSL_ASYNC_PRIVATE */ if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only. */ if( ssl_use_opaque_psk( ssl ) == 1 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 2 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_encrypted_pms" ), ret ); return( ret ); } if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_DHE_PSK ) { if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } if( ( ret = ssl_parse_client_dh_public( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_dh_public" ), ret ); return( ret ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only. */ if( ssl_use_opaque_psk( ssl ) == 1 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif if( p != end ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad client key exchange" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE ); } if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_DHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECDHE_PSK ) { if( ( ret = ssl_parse_client_psk_identity( ssl, &p, end ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_client_psk_identity" ), ret ); return( ret ); } if( ( ret = mbedtls_ecdh_read_public( &ssl->handshake->ecdh_ctx, p, end - p ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecdh_read_public", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_CLIENT_KEY_EXCHANGE_RP ); } #if defined(MBEDTLS_USE_PSA_CRYPTO) /* Opaque PSKs are currently only supported for PSK-only. */ if( ssl_use_opaque_psk( ssl ) == 1 ) return( MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE ); #endif MBEDTLS_SSL_DEBUG_ECDH( 3, &ssl->handshake->ecdh_ctx, MBEDTLS_DEBUG_ECDH_QP ); if( ( ret = mbedtls_ssl_psk_derive_premaster( ssl, ciphersuite_info->key_exchange ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_psk_derive_premaster", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECDHE_PSK_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_RSA_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_RSA ) { if( ( ret = ssl_parse_encrypted_pms( ssl, p, end, 0 ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "ssl_parse_parse_encrypted_pms_secret" ), ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_RSA_ENABLED */ #if defined(MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED) if( ciphersuite_info->key_exchange == MBEDTLS_KEY_EXCHANGE_ECJPAKE ) { ret = mbedtls_ecjpake_read_round_two( &ssl->handshake->ecjpake_ctx, p, end - p ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_read_round_two", ret ); return( MBEDTLS_ERR_SSL_BAD_HS_SERVER_KEY_EXCHANGE ); } ret = mbedtls_ecjpake_derive_secret( &ssl->handshake->ecjpake_ctx, ssl->handshake->premaster, 32, &ssl->handshake->pmslen, ssl->conf->f_rng, ssl->conf->p_rng ); if( ret != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ecjpake_derive_secret", ret ); return( ret ); } } else #endif /* MBEDTLS_KEY_EXCHANGE_ECJPAKE_ENABLED */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( ( ret = mbedtls_ssl_derive_keys( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_derive_keys", ret ); return( ret ); } ssl->state++; MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse client key exchange" ) ); return( 0 ); } #if !defined(MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED) static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl ) { const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) ); if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } #else /* !MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ static int ssl_parse_certificate_verify( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_SSL_FEATURE_UNAVAILABLE; size_t i, sig_len; unsigned char hash[48]; unsigned char *hash_start = hash; size_t hashlen; #if defined(MBEDTLS_SSL_PROTO_TLS1_2) mbedtls_pk_type_t pk_alg; #endif mbedtls_md_type_t md_alg; const mbedtls_ssl_ciphersuite_t *ciphersuite_info = ssl->handshake->ciphersuite_info; mbedtls_pk_context * peer_pk; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> parse certificate verify" ) ); if( !mbedtls_ssl_ciphersuite_cert_req_allowed( ciphersuite_info ) ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } #if defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) if( ssl->session_negotiate->peer_cert == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } #else /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert_digest == NULL ) { MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= skip parse certificate verify" ) ); ssl->state++; return( 0 ); } #endif /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* Read the message without adding it to the checksum */ ret = mbedtls_ssl_read_record( ssl, 0 /* no checksum update */ ); if( 0 != ret ) { MBEDTLS_SSL_DEBUG_RET( 1, ( "mbedtls_ssl_read_record" ), ret ); return( ret ); } ssl->state++; /* Process the message contents */ if( ssl->in_msgtype != MBEDTLS_SSL_MSG_HANDSHAKE || ssl->in_msg[0] != MBEDTLS_SSL_HS_CERTIFICATE_VERIFY ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } i = mbedtls_ssl_hs_hdr_len( ssl ); #if !defined(MBEDTLS_SSL_KEEP_PEER_CERTIFICATE) peer_pk = &ssl->handshake->peer_pubkey; #else /* !MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ if( ssl->session_negotiate->peer_cert == NULL ) { /* Should never happen */ return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } peer_pk = &ssl->session_negotiate->peer_cert->pk; #endif /* MBEDTLS_SSL_KEEP_PEER_CERTIFICATE */ /* * struct { * SignatureAndHashAlgorithm algorithm; -- TLS 1.2 only * opaque signature<0..2^16-1>; * } DigitallySigned; */ #if defined(MBEDTLS_SSL_PROTO_SSL3) || defined(MBEDTLS_SSL_PROTO_TLS1) || \ defined(MBEDTLS_SSL_PROTO_TLS1_1) if( ssl->minor_ver != MBEDTLS_SSL_MINOR_VERSION_3 ) { md_alg = MBEDTLS_MD_NONE; hashlen = 36; /* For ECDSA, use SHA-1, not MD-5 + SHA-1 */ if( mbedtls_pk_can_do( peer_pk, MBEDTLS_PK_ECDSA ) ) { hash_start += 16; hashlen -= 16; md_alg = MBEDTLS_MD_SHA1; } } else #endif /* MBEDTLS_SSL_PROTO_SSL3 || MBEDTLS_SSL_PROTO_TLS1 || MBEDTLS_SSL_PROTO_TLS1_1 */ #if defined(MBEDTLS_SSL_PROTO_TLS1_2) if( ssl->minor_ver == MBEDTLS_SSL_MINOR_VERSION_3 ) { if( i + 2 > ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } /* * Hash */ md_alg = mbedtls_ssl_md_alg_from_hash( ssl->in_msg[i] ); if( md_alg == MBEDTLS_MD_NONE || mbedtls_ssl_set_calc_verify_md( ssl, ssl->in_msg[i] ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg" " for verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } #if !defined(MBEDTLS_MD_SHA1) if( MBEDTLS_MD_SHA1 == md_alg ) hash_start += 16; #endif /* Info from md_alg will be used instead */ hashlen = 0; i++; /* * Signature */ if( ( pk_alg = mbedtls_ssl_pk_alg_from_sig( ssl->in_msg[i] ) ) == MBEDTLS_PK_NONE ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "peer not adhering to requested sig_alg" " for verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } /* * Check the certificate's key type matches the signature alg */ if( !mbedtls_pk_can_do( peer_pk, pk_alg ) ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "sig_alg doesn't match cert key" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } i++; } else #endif /* MBEDTLS_SSL_PROTO_TLS1_2 */ { MBEDTLS_SSL_DEBUG_MSG( 1, ( "should never happen" ) ); return( MBEDTLS_ERR_SSL_INTERNAL_ERROR ); } if( i + 2 > ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } sig_len = ( ssl->in_msg[i] << 8 ) | ssl->in_msg[i+1]; i += 2; if( i + sig_len != ssl->in_hslen ) { MBEDTLS_SSL_DEBUG_MSG( 1, ( "bad certificate verify message" ) ); return( MBEDTLS_ERR_SSL_BAD_HS_CERTIFICATE_VERIFY ); } /* Calculate hash and verify signature */ { size_t dummy_hlen; ssl->handshake->calc_verify( ssl, hash, &dummy_hlen ); } if( ( ret = mbedtls_pk_verify( peer_pk, md_alg, hash_start, hashlen, ssl->in_msg + i, sig_len ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_pk_verify", ret ); return( ret ); } mbedtls_ssl_update_handshake_status( ssl ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= parse certificate verify" ) ); return( ret ); } #endif /* MBEDTLS_KEY_EXCHANGE_CERT_REQ_ALLOWED_ENABLED */ #if defined(MBEDTLS_SSL_SESSION_TICKETS) static int ssl_write_new_session_ticket( mbedtls_ssl_context *ssl ) { int ret = MBEDTLS_ERR_ERROR_CORRUPTION_DETECTED; size_t tlen; uint32_t lifetime; MBEDTLS_SSL_DEBUG_MSG( 2, ( "=> write new session ticket" ) ); ssl->out_msgtype = MBEDTLS_SSL_MSG_HANDSHAKE; ssl->out_msg[0] = MBEDTLS_SSL_HS_NEW_SESSION_TICKET; /* * struct { * uint32 ticket_lifetime_hint; * opaque ticket<0..2^16-1>; * } NewSessionTicket; * * 4 . 7 ticket_lifetime_hint (0 = unspecified) * 8 . 9 ticket_len (n) * 10 . 9+n ticket content */ if( ( ret = ssl->conf->f_ticket_write( ssl->conf->p_ticket, ssl->session_negotiate, ssl->out_msg + 10, ssl->out_msg + MBEDTLS_SSL_OUT_CONTENT_LEN, &tlen, &lifetime ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_ticket_write", ret ); tlen = 0; } ssl->out_msg[4] = ( lifetime >> 24 ) & 0xFF; ssl->out_msg[5] = ( lifetime >> 16 ) & 0xFF; ssl->out_msg[6] = ( lifetime >> 8 ) & 0xFF; ssl->out_msg[7] = ( lifetime ) & 0xFF; ssl->out_msg[8] = (unsigned char)( ( tlen >> 8 ) & 0xFF ); ssl->out_msg[9] = (unsigned char)( ( tlen ) & 0xFF ); ssl->out_msglen = 10 + tlen; /* * Morally equivalent to updating ssl->state, but NewSessionTicket and * ChangeCipherSpec share the same state. */ ssl->handshake->new_session_ticket = 0; if( ( ret = mbedtls_ssl_write_handshake_msg( ssl ) ) != 0 ) { MBEDTLS_SSL_DEBUG_RET( 1, "mbedtls_ssl_write_handshake_msg", ret ); return( ret ); } MBEDTLS_SSL_DEBUG_MSG( 2, ( "<= write new session ticket" ) ); return( 0 ); } #endif /* MBEDTLS_SSL_SESSION_TICKETS */ /* * SSL handshake -- server side -- single step */ int mbedtls_ssl_handshake_server_step( mbedtls_ssl_context *ssl ) { int ret = 0; if( ssl->state == MBEDTLS_SSL_HANDSHAKE_OVER || ssl->handshake == NULL ) return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); MBEDTLS_SSL_DEBUG_MSG( 2, ( "server state: %d", ssl->state ) ); if( ( ret = mbedtls_ssl_flush_output( ssl ) ) != 0 ) return( ret ); #if defined(MBEDTLS_SSL_PROTO_DTLS) if( ssl->conf->transport == MBEDTLS_SSL_TRANSPORT_DATAGRAM && ssl->handshake->retransmit_state == MBEDTLS_SSL_RETRANS_SENDING ) { if( ( ret = mbedtls_ssl_flight_transmit( ssl ) ) != 0 ) return( ret ); } #endif /* MBEDTLS_SSL_PROTO_DTLS */ switch( ssl->state ) { case MBEDTLS_SSL_HELLO_REQUEST: ssl->state = MBEDTLS_SSL_CLIENT_HELLO; break; /* * <== ClientHello */ case MBEDTLS_SSL_CLIENT_HELLO: ret = ssl_parse_client_hello( ssl ); break; #if defined(MBEDTLS_SSL_PROTO_DTLS) case MBEDTLS_SSL_SERVER_HELLO_VERIFY_REQUEST_SENT: return( MBEDTLS_ERR_SSL_HELLO_VERIFY_REQUIRED ); #endif /* * ==> ServerHello * Certificate * ( ServerKeyExchange ) * ( CertificateRequest ) * ServerHelloDone */ case MBEDTLS_SSL_SERVER_HELLO: ret = ssl_write_server_hello( ssl ); break; case MBEDTLS_SSL_SERVER_CERTIFICATE: ret = mbedtls_ssl_write_certificate( ssl ); break; case MBEDTLS_SSL_SERVER_KEY_EXCHANGE: ret = ssl_write_server_key_exchange( ssl ); break; case MBEDTLS_SSL_CERTIFICATE_REQUEST: ret = ssl_write_certificate_request( ssl ); break; case MBEDTLS_SSL_SERVER_HELLO_DONE: ret = ssl_write_server_hello_done( ssl ); break; /* * <== ( Certificate/Alert ) * ClientKeyExchange * ( CertificateVerify ) * ChangeCipherSpec * Finished */ case MBEDTLS_SSL_CLIENT_CERTIFICATE: ret = mbedtls_ssl_parse_certificate( ssl ); break; case MBEDTLS_SSL_CLIENT_KEY_EXCHANGE: ret = ssl_parse_client_key_exchange( ssl ); break; case MBEDTLS_SSL_CERTIFICATE_VERIFY: ret = ssl_parse_certificate_verify( ssl ); break; case MBEDTLS_SSL_CLIENT_CHANGE_CIPHER_SPEC: ret = mbedtls_ssl_parse_change_cipher_spec( ssl ); break; case MBEDTLS_SSL_CLIENT_FINISHED: ret = mbedtls_ssl_parse_finished( ssl ); break; /* * ==> ( NewSessionTicket ) * ChangeCipherSpec * Finished */ case MBEDTLS_SSL_SERVER_CHANGE_CIPHER_SPEC: #if defined(MBEDTLS_SSL_SESSION_TICKETS) if( ssl->handshake->new_session_ticket != 0 ) ret = ssl_write_new_session_ticket( ssl ); else #endif ret = mbedtls_ssl_write_change_cipher_spec( ssl ); break; case MBEDTLS_SSL_SERVER_FINISHED: ret = mbedtls_ssl_write_finished( ssl ); break; case MBEDTLS_SSL_FLUSH_BUFFERS: MBEDTLS_SSL_DEBUG_MSG( 2, ( "handshake: done" ) ); ssl->state = MBEDTLS_SSL_HANDSHAKE_WRAPUP; break; case MBEDTLS_SSL_HANDSHAKE_WRAPUP: mbedtls_ssl_handshake_wrapup( ssl ); break; default: MBEDTLS_SSL_DEBUG_MSG( 1, ( "invalid state %d", ssl->state ) ); return( MBEDTLS_ERR_SSL_BAD_INPUT_DATA ); } return( ret ); } #endif /* MBEDTLS_SSL_SRV_C */
Java
/* -*- c-basic-offset: 4 indent-tabs-mode: nil -*- vi:set ts=8 sts=4 sw=4: */ /* Rosegarden A MIDI and audio sequencer and musical notation editor. Copyright 2000-2018 the Rosegarden development team. Other copyrights also apply to some parts of this work. Please see the AUTHORS file and individual file headers for details. 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. See the file COPYING included with this distribution for more information. */ #define RG_MODULE_STRING "[TrackButtons]" #include "TrackButtons.h" #include "TrackLabel.h" #include "TrackVUMeter.h" #include "misc/Debug.h" #include "misc/Strings.h" #include "base/AudioPluginInstance.h" #include "base/Composition.h" #include "base/Device.h" #include "base/Instrument.h" #include "base/InstrumentStaticSignals.h" #include "base/MidiProgram.h" #include "base/Studio.h" #include "base/Track.h" #include "commands/segment/RenameTrackCommand.h" #include "document/RosegardenDocument.h" #include "document/CommandHistory.h" #include "gui/application/RosegardenMainWindow.h" #include "gui/general/GUIPalette.h" #include "gui/general/IconLoader.h" #include "gui/seqmanager/SequenceManager.h" #include "gui/widgets/LedButton.h" #include "sound/AudioFileManager.h" #include "sound/ControlBlock.h" #include "sound/PluginIdentifier.h" #include "sequencer/RosegardenSequencer.h" #include <QApplication> #include <QLayout> #include <QMessageBox> #include <QCursor> #include <QFrame> #include <QIcon> #include <QLabel> #include <QObject> #include <QPixmap> #include <QMenu> #include <QSignalMapper> #include <QString> #include <QTimer> #include <QWidget> #include <QStackedWidget> #include <QToolTip> namespace Rosegarden { // Constants const int TrackButtons::m_borderGap = 1; const int TrackButtons::m_buttonGap = 8; const int TrackButtons::m_vuWidth = 20; const int TrackButtons::m_vuSpacing = 2; TrackButtons::TrackButtons(RosegardenDocument* doc, int trackCellHeight, int trackLabelWidth, bool showTrackLabels, int overallHeight, QWidget* parent) : QFrame(parent), m_doc(doc), m_layout(new QVBoxLayout(this)), m_recordSigMapper(new QSignalMapper(this)), m_muteSigMapper(new QSignalMapper(this)), m_soloSigMapper(new QSignalMapper(this)), m_clickedSigMapper(new QSignalMapper(this)), m_instListSigMapper(new QSignalMapper(this)), m_tracks(doc->getComposition().getNbTracks()), // m_offset(4), m_cellSize(trackCellHeight), m_trackLabelWidth(trackLabelWidth), m_popupTrackPos(0), m_lastSelected(-1) { setFrameStyle(Plain); QPalette pal = palette(); pal.setColor(backgroundRole(), QColor(0xDD, 0xDD, 0xDD)); pal.setColor(foregroundRole(), Qt::black); setPalette(pal); // when we create the widget, what are we looking at? if (showTrackLabels) { m_labelDisplayMode = TrackLabel::ShowTrack; } else { m_labelDisplayMode = TrackLabel::ShowInstrument; } m_layout->setMargin(0); // Set the spacing between vertical elements m_layout->setSpacing(m_borderGap); // Now draw the buttons and labels and meters // makeButtons(); m_layout->addStretch(20); connect(m_recordSigMapper, SIGNAL(mapped(int)), this, SLOT(slotToggleRecord(int))); connect(m_muteSigMapper, SIGNAL(mapped(int)), this, SLOT(slotToggleMute(int))); connect(m_soloSigMapper, SIGNAL(mapped(int)), this, SLOT(slotToggleSolo(int))); // connect signal mappers connect(m_instListSigMapper, SIGNAL(mapped(int)), this, SLOT(slotInstrumentMenu(int))); connect(m_clickedSigMapper, SIGNAL(mapped(int)), this, SLOT(slotTrackSelected(int))); // We have to force the height for the moment // setMinimumHeight(overallHeight); m_doc->getComposition().addObserver(this); // We do not care about documentChanged() because if the // document is changing, we are going away. A new TrackButtons // is created for each new document. //connect(RosegardenMainWindow::self(), // SIGNAL(documentChanged(RosegardenDocument *)), // SLOT(slotNewDocument(RosegardenDocument *))); } TrackButtons::~TrackButtons() { // CRASH! Probably m_doc is gone... // Probably don't need to disconnect as we only go away when the // doc and composition do. shared_ptr would help here. // m_doc->getComposition().removeObserver(this); } void TrackButtons::updateUI(Track *track) { if (!track) return; int pos = track->getPosition(); if (pos < 0 || pos >= m_tracks) return; // *** Archive Background QFrame *hbox = m_trackHBoxes.at(pos); if (track->isArchived()) { // Go with the dark gray background. QPalette palette = hbox->palette(); palette.setColor(hbox->backgroundRole(), QColor(0x88, 0x88, 0x88)); hbox->setPalette(palette); } else { // Go with the parent's background color. QColor parentBackground = palette().color(backgroundRole()); QPalette palette = hbox->palette(); palette.setColor(hbox->backgroundRole(), parentBackground); hbox->setPalette(palette); } // *** Mute LED if (track->isMuted()) { m_muteLeds[pos]->off(); } else { m_muteLeds[pos]->on(); } // *** Record LED Instrument *ins = m_doc->getStudio().getInstrumentById(track->getInstrument()); m_recordLeds[pos]->setColor(getRecordLedColour(ins)); // Note: setRecord() used to be used to do this. But that would // set the track in the composition to record as well as setting // the button on the UI. This seems better and works fine. bool recording = m_doc->getComposition().isTrackRecording(track->getId()); setRecordButton(pos, recording); // *** Solo LED // ??? An Led::setState(bool) would be handy. m_soloLeds[pos]->setState(track->isSolo() ? Led::On : Led::Off); // *** Track Label TrackLabel *label = m_trackLabels[pos]; if (!label) return; // In case the tracks have been moved around, update the mapping. label->setId(track->getId()); setButtonMapping(label, track->getId()); label->setPosition(pos); if (track->getLabel() == "") { if (ins && ins->getType() == Instrument::Audio) { label->setTrackName(tr("<untitled audio>")); } else { label->setTrackName(tr("<untitled>")); } } else { label->setTrackName(strtoqstr(track->getLabel())); label->setShortName(strtoqstr(track->getShortLabel())); } initInstrumentNames(ins, label); label->updateLabel(); } void TrackButtons::makeButtons() { if (!m_doc) return; //RG_DEBUG << "makeButtons()"; // Create a horizontal box filled with widgets for each track for (int i = 0; i < m_tracks; ++i) { Track *track = m_doc->getComposition().getTrackByPosition(i); if (!track) continue; QFrame *trackHBox = makeButton(track); if (trackHBox) { trackHBox->setObjectName("TrackButtonFrame"); m_layout->addWidget(trackHBox); m_trackHBoxes.push_back(trackHBox); } } populateButtons(); } void TrackButtons::setButtonMapping(TrackLabel* trackLabel, TrackId trackId) { m_clickedSigMapper->setMapping(trackLabel, trackId); m_instListSigMapper->setMapping(trackLabel, trackId); } void TrackButtons::initInstrumentNames(Instrument *ins, TrackLabel *label) { if (!label) return; if (ins) { label->setPresentationName(ins->getLocalizedPresentationName()); if (ins->sendsProgramChange()) { label->setProgramChangeName( QObject::tr(ins->getProgramName().c_str())); } else { label->setProgramChangeName(""); } } else { label->setPresentationName(tr("<no instrument>")); } } void TrackButtons::populateButtons() { //RG_DEBUG << "populateButtons()"; // For each track, copy info from Track object to the widgets for (int i = 0; i < m_tracks; ++i) { Track *track = m_doc->getComposition().getTrackByPosition(i); if (!track) continue; updateUI(track); } } void TrackButtons::slotToggleMute(int pos) { //RG_DEBUG << "TrackButtons::slotToggleMute( position =" << pos << ")"; if (!m_doc) return; if (pos < 0 || pos >= m_tracks) return; Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(pos); if (!track) return; // Toggle the mute state track->setMuted(!track->isMuted()); // Notify observers comp.notifyTrackChanged(track); m_doc->slotDocumentModified(); } void TrackButtons::toggleSolo() { if (!m_doc) return; Composition &comp = m_doc->getComposition(); int pos = comp.getTrackPositionById(comp.getSelectedTrack()); if (pos == -1) return; slotToggleSolo(pos); } void TrackButtons::slotToggleSolo(int pos) { //RG_DEBUG << "slotToggleSolo( position =" << pos << ")"; if (!m_doc) return; if (pos < 0 || pos >= m_tracks) return; Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(pos); if (!track) return; bool state = !track->isSolo(); // If we're setting solo on this track and shift isn't being held down, // clear solo on all tracks (canceling mode). If shift is being held // down, multiple tracks can be put into solo (latching mode). if (state && QApplication::keyboardModifiers() != Qt::ShiftModifier) { // For each track for (int i = 0; i < m_tracks; ++i) { // Except the one that is being toggled. if (i == pos) continue; Track *track2 = comp.getTrackByPosition(i); if (!track2) continue; if (track2->isSolo()) { // Clear solo track2->setSolo(false); comp.notifyTrackChanged(track2); } } } // Toggle the solo state track->setSolo(state); // Notify observers comp.notifyTrackChanged(track); m_doc->slotDocumentModified(); } void TrackButtons::removeButtons(int position) { //RG_DEBUG << "removeButtons() - deleting track button at position:" << position; if (position < 0 || position >= m_tracks) { RG_DEBUG << "%%%%%%%%% BIG PROBLEM : TrackButtons::removeButtons() was passed a non-existing index\n"; return; } std::vector<TrackLabel*>::iterator tit = m_trackLabels.begin(); tit += position; m_trackLabels.erase(tit); std::vector<TrackVUMeter*>::iterator vit = m_trackMeters.begin(); vit += position; m_trackMeters.erase(vit); std::vector<LedButton*>::iterator mit = m_muteLeds.begin(); mit += position; m_muteLeds.erase(mit); mit = m_recordLeds.begin(); mit += position; m_recordLeds.erase(mit); m_soloLeds.erase(m_soloLeds.begin() + position); // Delete all child widgets (button, led, label...) delete m_trackHBoxes[position]; m_trackHBoxes[position] = nullptr; std::vector<QFrame*>::iterator it = m_trackHBoxes.begin(); it += position; m_trackHBoxes.erase(it); } void TrackButtons::slotUpdateTracks() { //RG_DEBUG << "slotUpdateTracks()"; #if 0 static QTime t; RG_DEBUG << " elapsed: " << t.restart(); #endif if (!m_doc) return; Composition &comp = m_doc->getComposition(); const int newNbTracks = comp.getNbTracks(); if (newNbTracks < 0) { RG_WARNING << "slotUpdateTracks(): WARNING: New number of tracks was negative:" << newNbTracks; return; } //RG_DEBUG << "TrackButtons::slotUpdateTracks > newNbTracks = " << newNbTracks; // If a track or tracks were deleted if (newNbTracks < m_tracks) { // For each deleted track, remove a button from the end. for (int i = m_tracks; i > newNbTracks; --i) removeButtons(i - 1); } else if (newNbTracks > m_tracks) { // if added // For each added track for (int i = m_tracks; i < newNbTracks; ++i) { Track *track = m_doc->getComposition().getTrackByPosition(i); if (track) { // Make a new button QFrame *trackHBox = makeButton(track); if (trackHBox) { trackHBox->show(); // Add the new button to the layout. m_layout->insertWidget(i, trackHBox); m_trackHBoxes.push_back(trackHBox); } } else RG_DEBUG << "TrackButtons::slotUpdateTracks - can't find TrackId for position " << i; } } m_tracks = newNbTracks; if (m_tracks != (int)m_trackHBoxes.size()) RG_DEBUG << "WARNING TrackButtons::slotUpdateTracks(): m_trackHBoxes.size() != m_tracks"; if (m_tracks != (int)m_trackLabels.size()) RG_DEBUG << "WARNING TrackButtons::slotUpdateTracks(): m_trackLabels.size() != m_tracks"; // For each track for (int i = 0; i < m_tracks; ++i) { Track *track = comp.getTrackByPosition(i); if (!track) continue; // *** Set Track Size *** // Track height can change when the user moves segments around and // they overlap. m_trackHBoxes[i]->setMinimumSize(labelWidth(), trackHeight(track->getId())); m_trackHBoxes[i]->setFixedHeight(trackHeight(track->getId())); } populateButtons(); // This is necessary to update the widgets's sizeHint to reflect any change in child widget sizes // Make the TrackButtons QFrame big enough to hold all the track buttons. // Some may have grown taller due to segments that overlap. // Note: This appears to no longer be needed. But it doesn't hurt. adjustSize(); } void TrackButtons::slotToggleRecord(int position) { //RG_DEBUG << "TrackButtons::slotToggleRecord(" << position << ")"; if (position < 0 || position >= m_tracks) return; if (!m_doc) return; Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(position); if (!track) return; // Toggle bool state = !comp.isTrackRecording(track->getId()); // Update the Track comp.setTrackRecording(track->getId(), state); comp.notifyTrackChanged(track); m_doc->checkAudioPath(track); } void TrackButtons::setRecordButton(int position, bool record) { if (position < 0 || position >= m_tracks) return; m_recordLeds[position]->setState(record ? Led::On : Led::Off); } void TrackButtons::selectTrack(int position) { if (position < 0 || position >= m_tracks) return; // No sense doing anything if the selection isn't changing if (position == m_lastSelected) return; // Unselect the previously selected if (m_lastSelected >= 0 && m_lastSelected < m_tracks) { m_trackLabels[m_lastSelected]->setSelected(false); } // Select the newly selected m_trackLabels[position]->setSelected(true); m_lastSelected = position; } #if 0 // unused std::vector<int> TrackButtons::getHighlightedTracks() { std::vector<int> retList; for (int i = 0; i < m_trackLabels.size(); ++i) { if (m_trackLabels[i]->isSelected()) retList.push_back(i); } return retList; } #endif void TrackButtons::slotRenameTrack(QString longLabel, QString shortLabel, TrackId trackId) { if (!m_doc) return; Track *track = m_doc->getComposition().getTrackById(trackId); if (!track) return; TrackLabel *label = m_trackLabels[track->getPosition()]; // If neither label is changing, skip it if (label->getTrackName() == longLabel && QString::fromStdString(track->getShortLabel()) == shortLabel) return; // Rename the track CommandHistory::getInstance()->addCommand( new RenameTrackCommand(&m_doc->getComposition(), trackId, longLabel, shortLabel)); } void TrackButtons::slotSetTrackMeter(float value, int position) { if (position < 0 || position >= m_tracks) return; m_trackMeters[position]->setLevel(value); } void TrackButtons::slotSetMetersByInstrument(float value, InstrumentId id) { Composition &comp = m_doc->getComposition(); for (int i = 0; i < m_tracks; ++i) { Track *track = comp.getTrackByPosition(i); if (track && track->getInstrument() == id) { m_trackMeters[i]->setLevel(value); } } } void TrackButtons::slotInstrumentMenu(int trackId) { //RG_DEBUG << "TrackButtons::slotInstrumentMenu( trackId =" << trackId << ")"; Composition &comp = m_doc->getComposition(); const int position = comp.getTrackById(trackId)->getPosition(); Track *track = comp.getTrackByPosition(position); Instrument *instrument = nullptr; if (track != nullptr) { instrument = m_doc->getStudio().getInstrumentById( track->getInstrument()); } // *** Force The Track Label To Show The Presentation Name *** // E.g. "General MIDI Device #1" m_trackLabels[position]->forcePresentationName(true); m_trackLabels[position]->updateLabel(); // *** Launch The Popup *** // Yes, well as we might've changed the Device name in the // Device/Bank dialog then we reload the whole menu here. QMenu instrumentPopup(this); populateInstrumentPopup(instrument, &instrumentPopup); // Store the popup item position for slotInstrumentSelected(). m_popupTrackPos = position; instrumentPopup.exec(QCursor::pos()); // *** Restore The Track Label *** // Turn off the presentation name m_trackLabels[position]->forcePresentationName(false); m_trackLabels[position]->updateLabel(); } // ??? Break this stuff off into an InstrumentPopup class. This class is too // big. void TrackButtons::populateInstrumentPopup(Instrument *thisTrackInstr, QMenu* instrumentPopup) { // pixmaps for icons to show connection states as variously colored boxes // ??? Factor out the icon-related stuff to make this routine clearer. // getIcon(Instrument *) would be ideal, but might not be easy. // getIcon(Device *) would also be needed. static QPixmap connectedPixmap, unconnectedPixmap, connectedUsedPixmap, unconnectedUsedPixmap, connectedSelectedPixmap, unconnectedSelectedPixmap; static bool havePixmaps = false; if (!havePixmaps) { IconLoader il; connectedPixmap = il.loadPixmap("connected"); connectedUsedPixmap = il.loadPixmap("connected-used"); connectedSelectedPixmap = il.loadPixmap("connected-selected"); unconnectedPixmap = il.loadPixmap("unconnected"); unconnectedUsedPixmap = il.loadPixmap("unconnected-used"); unconnectedSelectedPixmap = il.loadPixmap("unconnected-selected"); havePixmaps = true; } Composition &comp = m_doc->getComposition(); // clear the popup instrumentPopup->clear(); QMenu *currentSubMenu = nullptr; // position index int count = 0; int currentDevId = -1; // Get the list Studio &studio = m_doc->getStudio(); InstrumentList list = studio.getPresentationInstruments(); // For each instrument for (InstrumentList::iterator it = list.begin(); it != list.end(); ++it) { if (!(*it)) continue; // sanity check // get the Localized instrument name, with the string hackery performed // in Instrument QString iname((*it)->getLocalizedPresentationName()); // translate the program name // // Note we are converting the string from std to Q back to std then to // C. This is obviously ridiculous, but the fact that we have programName // here at all makes me think it exists as some kind of necessary hack // to coax tr() into behaving nicely. I decided to change it as little // as possible to get it to compile, and not refactor this down to the // simplest way to call tr() on a C string. QString programName(strtoqstr((*it)->getProgramName())); programName = QObject::tr(programName.toStdString().c_str()); Device *device = (*it)->getDevice(); DeviceId devId = device->getId(); bool connectedIcon = false; // Determine the proper program name and whether it is connected if ((*it)->getType() == Instrument::SoftSynth) { programName = ""; AudioPluginInstance *plugin = (*it)->getPlugin(Instrument::SYNTH_PLUGIN_POSITION); if (plugin) { // we don't translate any plugin program names or other texts programName = strtoqstr(plugin->getDisplayName()); connectedIcon = (plugin->getIdentifier() != ""); } } else if ((*it)->getType() == Instrument::Audio) { connectedIcon = true; } else { QString conn = RosegardenSequencer::getInstance()-> getConnection(devId); connectedIcon = (conn != ""); } // These two are for selecting the correct icon to display. bool instrUsedByMe = false; bool instrUsedByAnyone = false; if (thisTrackInstr && thisTrackInstr->getId() == (*it)->getId()) { instrUsedByMe = true; instrUsedByAnyone = true; } // If we have switched to a new device, we'll create a new submenu if (devId != (DeviceId)(currentDevId)) { currentDevId = int(devId); // For selecting the correct icon to display. bool deviceUsedByAnyone = false; if (instrUsedByMe) deviceUsedByAnyone = true; else { for (Composition::trackcontainer::iterator tit = comp.getTracks().begin(); tit != comp.getTracks().end(); ++tit) { if (tit->second->getInstrument() == (*it)->getId()) { instrUsedByAnyone = true; deviceUsedByAnyone = true; break; } Instrument *instr = studio.getInstrumentById(tit->second->getInstrument()); if (instr && (instr->getDevice()->getId() == devId)) { deviceUsedByAnyone = true; } } } QIcon icon (connectedIcon ? (deviceUsedByAnyone ? connectedUsedPixmap : connectedPixmap) : (deviceUsedByAnyone ? unconnectedUsedPixmap : unconnectedPixmap)); // Create a submenu for this device QMenu *subMenu = new QMenu(instrumentPopup); subMenu->setMouseTracking(true); subMenu->setIcon(icon); // Not needed so long as AA_DontShowIconsInMenus is false. //subMenu->menuAction()->setIconVisibleInMenu(true); // Menu title QString deviceName = QObject::tr(device->getName().c_str()); subMenu->setTitle(deviceName); // QObject name subMenu->setObjectName(deviceName); // Add the submenu to the popup menu instrumentPopup->addMenu(subMenu); // Connect the submenu to slotInstrumentSelected() connect(subMenu, SIGNAL(triggered(QAction*)), this, SLOT(slotInstrumentSelected(QAction*))); currentSubMenu = subMenu; } else if (!instrUsedByMe) { // Search the tracks to see if anyone else is using this // instrument for (Composition::trackcontainer::iterator tit = comp.getTracks().begin(); tit != comp.getTracks().end(); ++tit) { if (tit->second->getInstrument() == (*it)->getId()) { instrUsedByAnyone = true; break; } } } QIcon icon (connectedIcon ? (instrUsedByAnyone ? instrUsedByMe ? connectedSelectedPixmap : connectedUsedPixmap : connectedPixmap) : (instrUsedByAnyone ? instrUsedByMe ? unconnectedSelectedPixmap : unconnectedUsedPixmap : unconnectedPixmap)); // Create an action for this instrument QAction* action = new QAction(instrumentPopup); action->setIcon(icon); // Not needed so long as AA_DontShowIconsInMenus is false. //action->setIconVisibleInMenu(true); // Action text if (programName != "") iname += " (" + programName + ")"; action->setText(iname); // Item index used to find the proper instrument once the user makes // a selection from the menu. action->setData(QVariant(count)); // QObject object name. action->setObjectName(iname + QString(count)); // Add the action to the current submenu if (currentSubMenu) currentSubMenu->addAction(action); // Next item index count++; } } void TrackButtons::slotInstrumentSelected(QAction* action) { // The action data field has the instrument index. slotInstrumentSelected(action->data().toInt()); } void TrackButtons::selectInstrument(Track *track, Instrument *instrument) { // Inform the rest of the system of the instrument change. // ??? This routine needs to go for two reasons: // // 1. TrackParameterBox calls this. UI to UI connections should be // avoided. It would be better to copy/paste this over to TPB // to avoid the connection. But then we have double-maintenance. // See reason 2. // // 2. The UI shouldn't know so much about the other objects in the // system. The following updates should be done by their // respective objects. // // A "TrackStaticSignals::instrumentChanged(Track *, Instrument *)" // notification is probably the best way to get rid of this routine. // It could be emitted from Track::setInstrument(). Normally emitting // from setters is bad, but in this case, it is necessary. We need // to know about every single change when it occurs. // Then ControlBlockSignalHandler (new class to avoid deriving // ControlBlock from QObject), InstrumentSignalHandler (new class to // handle signals for all Instrument instances), and // SequenceManager (already derives from QObject, might want to // consider a new SequenceManagerSignalHandler to avoid additional // dependency on QObject) can connect and do what needs to be done in // response. Rationale for this over doc modified is that we // can't simply refresh everything (Instrument::sendChannelSetup() // sends out data), and it is expensive to detect what has actually // changed (we would have to cache the Track->Instrument mapping and // check it for changes). const TrackId trackId = track->getId(); // *** ControlBlock ControlBlock::getInstance()-> setInstrumentForTrack(trackId, instrument->getId()); // *** Send out BS/PC // Make sure the Device is in sync with the Instrument's settings. instrument->sendChannelSetup(); // *** SequenceManager // In case the sequencer is currently playing, we need to regenerate // all the events with the new channel number. Composition &comp = m_doc->getComposition(); SequenceManager *sequenceManager = m_doc->getSequenceManager(); // For each segment in the composition for (Composition::iterator i = comp.begin(); i != comp.end(); ++i) { Segment *segment = (*i); // If this Segment is on this Track, let SequenceManager know // that the Instrument has changed. // Segments on this track are now playing on a new // instrument, so they're no longer ready (making them // ready is done just-in-time elsewhere), nor is thru // channel ready. if (segment->getTrack() == trackId) sequenceManager->segmentInstrumentChanged(segment); } } void TrackButtons::slotInstrumentSelected(int instrumentIndex) { //RG_DEBUG << "slotInstrumentSelected(): instrumentIndex =" << instrumentIndex; Instrument *instrument = m_doc->getStudio().getInstrumentFromList(instrumentIndex); //RG_DEBUG << "slotInstrumentSelected(): instrument " << inst; if (!instrument) { RG_WARNING << "slotInstrumentSelected(): WARNING: Can't find Instrument"; return; } Composition &comp = m_doc->getComposition(); Track *track = comp.getTrackByPosition(m_popupTrackPos); if (!track) { RG_WARNING << "slotInstrumentSelected(): WARNING: Can't find Track"; return; } // No change? Bail. if (instrument->getId() == track->getInstrument()) return; // Select the new instrument for the track. // ??? This sends a trackChanged() notification. It shouldn't. We should // send one here. track->setInstrument(instrument->getId()); // ??? This is what we should do. //comp.notifyTrackChanged(track); m_doc->slotDocumentModified(); // Notify IPB, ControlBlock, and SequenceManager. selectInstrument(track, instrument); } void TrackButtons::changeLabelDisplayMode(TrackLabel::DisplayMode mode) { // Set new mode m_labelDisplayMode = mode; // For each track, set the display mode and update. for (int i = 0; i < m_tracks; i++) { m_trackLabels[i]->setDisplayMode(mode); m_trackLabels[i]->updateLabel(); } } void TrackButtons::slotSynchroniseWithComposition() { //RG_DEBUG << "slotSynchroniseWithComposition()"; Composition &comp = m_doc->getComposition(); for (int i = 0; i < m_tracks; i++) { updateUI(comp.getTrackByPosition(i)); } } #if 0 void TrackButtons::slotLabelSelected(int position) { Track *track = m_doc->getComposition().getTrackByPosition(position); if (track) { emit trackSelected(track->getId()); } } #endif void TrackButtons::slotTPBInstrumentSelected(TrackId trackId, int instrumentIndex) { //RG_DEBUG << "TrackButtons::slotTPBInstrumentSelected( trackId =" << trackId << ", instrumentIndex =" << instrumentIndex << ")"; // Set the position for slotInstrumentSelected(). // ??? This isn't good. Should have a selectTrack() that takes the // track position and the instrument index. slotInstrumentSelected() // could call it. m_popupTrackPos = m_doc->getComposition().getTrackById(trackId)->getPosition(); slotInstrumentSelected(instrumentIndex); } int TrackButtons::labelWidth() { return m_trackLabelWidth - ((m_cellSize - m_buttonGap) * 2 + m_vuSpacing * 2 + m_vuWidth); } int TrackButtons::trackHeight(TrackId trackId) { int multiple = m_doc-> getComposition().getMaxContemporaneousSegmentsOnTrack(trackId); if (multiple == 0) multiple = 1; return m_cellSize * multiple - m_borderGap; } QFrame* TrackButtons::makeButton(Track *track) { if (track == nullptr) return nullptr; TrackId trackId = track->getId(); // *** Horizontal Box *** QFrame *trackHBox = new QFrame(this); QHBoxLayout *hblayout = new QHBoxLayout(trackHBox); trackHBox->setLayout(hblayout); hblayout->setMargin(0); hblayout->setSpacing(0); trackHBox->setMinimumSize(labelWidth(), trackHeight(trackId)); trackHBox->setFixedHeight(trackHeight(trackId)); trackHBox->setFrameShape(QFrame::StyledPanel); trackHBox->setFrameShadow(QFrame::Raised); // We will be changing the background color, so turn on auto-fill. trackHBox->setAutoFillBackground(true); // Insert a little gap hblayout->addSpacing(m_vuSpacing); // *** VU Meter *** TrackVUMeter *vuMeter = new TrackVUMeter(trackHBox, VUMeter::PeakHold, m_vuWidth, m_buttonGap, track->getPosition()); m_trackMeters.push_back(vuMeter); hblayout->addWidget(vuMeter); // Insert a little gap hblayout->addSpacing(m_vuSpacing); // *** Mute LED *** LedButton *mute = new LedButton( GUIPalette::getColour(GUIPalette::MuteTrackLED), trackHBox); mute->setToolTip(tr("Mute track")); hblayout->addWidget(mute); connect(mute, SIGNAL(stateChanged(bool)), m_muteSigMapper, SLOT(map())); m_muteSigMapper->setMapping(mute, track->getPosition()); m_muteLeds.push_back(mute); mute->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap); // *** Record LED *** Rosegarden::Instrument *ins = m_doc->getStudio().getInstrumentById(track->getInstrument()); LedButton *record = new LedButton(getRecordLedColour(ins), trackHBox); record->setToolTip(tr("Record on this track")); hblayout->addWidget(record); connect(record, SIGNAL(stateChanged(bool)), m_recordSigMapper, SLOT(map())); m_recordSigMapper->setMapping(record, track->getPosition()); m_recordLeds.push_back(record); record->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap); // *** Solo LED *** LedButton *solo = new LedButton( GUIPalette::getColour(GUIPalette::SoloTrackLED), trackHBox); solo->setToolTip(tr("Solo track")); hblayout->addWidget(solo); connect(solo, SIGNAL(stateChanged(bool)), m_soloSigMapper, SLOT(map())); m_soloSigMapper->setMapping(solo, track->getPosition()); m_soloLeds.push_back(solo); solo->setFixedSize(m_cellSize - m_buttonGap, m_cellSize - m_buttonGap); // *** Track Label *** TrackLabel *trackLabel = new TrackLabel(trackId, track->getPosition(), trackHBox); hblayout->addWidget(trackLabel); hblayout->addSpacing(m_vuSpacing); trackLabel->setDisplayMode(m_labelDisplayMode); trackLabel->setFixedSize(labelWidth(), m_cellSize - m_buttonGap); trackLabel->setFixedHeight(m_cellSize - m_buttonGap); trackLabel->setIndent(7); connect(trackLabel, &TrackLabel::renameTrack, this, &TrackButtons::slotRenameTrack); m_trackLabels.push_back(trackLabel); // Connect it setButtonMapping(trackLabel, trackId); connect(trackLabel, SIGNAL(changeToInstrumentList()), m_instListSigMapper, SLOT(map())); connect(trackLabel, SIGNAL(clicked()), m_clickedSigMapper, SLOT(map())); return trackHBox; } QColor TrackButtons::getRecordLedColour(Instrument *ins) { if (!ins) return Qt::white; switch (ins->getType()) { case Instrument::Audio: return GUIPalette::getColour(GUIPalette::RecordAudioTrackLED); case Instrument::SoftSynth: return GUIPalette::getColour(GUIPalette::RecordSoftSynthTrackLED); case Instrument::Midi: return GUIPalette::getColour(GUIPalette::RecordMIDITrackLED); case Instrument::InvalidInstrument: default: RG_DEBUG << "TrackButtons::slotUpdateTracks() - invalid instrument type, this is probably a BUG!"; return Qt::green; } } void TrackButtons::tracksAdded(const Composition *, std::vector<TrackId> &/*trackIds*/) { //RG_DEBUG << "TrackButtons::tracksAdded()"; // ??? This is a bit heavy-handed as it just adds a track button, then // recreates all the track buttons. We might be able to just add the // one that is needed. slotUpdateTracks(); } void TrackButtons::trackChanged(const Composition *, Track* track) { //RG_DEBUG << "trackChanged()"; //RG_DEBUG << " Position:" << track->getPosition(); //RG_DEBUG << " Armed:" << track->isArmed(); updateUI(track); } void TrackButtons::tracksDeleted(const Composition *, std::vector<TrackId> &/*trackIds*/) { //RG_DEBUG << "TrackButtons::tracksDeleted()"; // ??? This is a bit heavy-handed as it just deletes a track button, // then recreates all the track buttons. We might be able to just // delete the one that is going away. slotUpdateTracks(); } void TrackButtons::trackSelectionChanged(const Composition *, TrackId trackId) { //RG_DEBUG << "TrackButtons::trackSelectionChanged()" << trackId; Track *track = m_doc->getComposition().getTrackById(trackId); selectTrack(track->getPosition()); } void TrackButtons::segmentRemoved(const Composition *, Segment *) { // If recording causes the track heights to change, this makes sure // they go back if needed when recording stops. slotUpdateTracks(); } void TrackButtons::slotTrackSelected(int trackId) { // Select the track. m_doc->getComposition().setSelectedTrack(trackId); // Old notification mechanism // ??? This should be replaced with emitDocumentModified() below. m_doc->getComposition().notifyTrackSelectionChanged(trackId); // Older mechanism. Keeping this until we can completely replace it // with emitDocumentModified() below. emit trackSelected(trackId); // New notification mechanism. // This should replace all others. m_doc->emitDocumentModified(); } void TrackButtons::slotDocumentModified(bool) { // Full and immediate update. // ??? Note that updates probably happen elsewhere. This will result // in duplicate updates. All other updates should be removed and // this should be the only update. slotUpdateTracks(); } }
Java
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Navigation; namespace SupCarLocator.ViewModel { class PageViewModelBase : BaseViewModel { protected NavigationContext NavigationContext; protected NavigationService NavigationService; public virtual void OnNavigatedTo(NavigationContext navigationContext, NavigationService navigationService) { NavigationContext = navigationContext; NavigationService = navigationService; } } }
Java
/* * xHCI host controller driver * * Copyright (C) 2008 Intel Corp. * * Author: Sarah Sharp * Some code borrowed from the Linux EHCI driver. * * 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., 675 Mass Ave, Cambridge, MA 02139, USA. */ /* * Ring initialization rules: * 1. Each segment is initialized to zero, except for link TRBs. * 2. Ring cycle state = 0. This represents Producer Cycle State (PCS) or * Consumer Cycle State (CCS), depending on ring function. * 3. Enqueue pointer = dequeue pointer = address of first TRB in the segment. * * Ring behavior rules: * 1. A ring is empty if enqueue == dequeue. This means there will always be at * least one free TRB in the ring. This is useful if you want to turn that * into a link TRB and expand the ring. * 2. When incrementing an enqueue or dequeue pointer, if the next TRB is a * link TRB, then load the pointer with the address in the link TRB. If the * link TRB had its toggle bit set, you may need to update the ring cycle * state (see cycle bit rules). You may have to do this multiple times * until you reach a non-link TRB. * 3. A ring is full if enqueue++ (for the definition of increment above) * equals the dequeue pointer. * * Cycle bit rules: * 1. When a consumer increments a dequeue pointer and encounters a toggle bit * in a link TRB, it must toggle the ring cycle state. * 2. When a producer increments an enqueue pointer and encounters a toggle bit * in a link TRB, it must toggle the ring cycle state. * * Producer rules: * 1. Check if ring is full before you enqueue. * 2. Write the ring cycle state to the cycle bit in the TRB you're enqueuing. * Update enqueue pointer between each write (which may update the ring * cycle state). * 3. Notify consumer. If SW is producer, it rings the doorbell for command * and endpoint rings. If HC is the producer for the event ring, * and it generates an interrupt according to interrupt modulation rules. * * Consumer rules: * 1. Check if TRB belongs to you. If the cycle bit == your ring cycle state, * the TRB is owned by the consumer. * 2. Update dequeue pointer (which may update the ring cycle state) and * continue processing TRBs until you reach a TRB which is not owned by you. * 3. Notify the producer. SW is the consumer for the event ring, and it * updates event ring dequeue pointer. HC is the consumer for the command and * endpoint rings; it generates events on the event ring for these. */ #include <linux/scatterlist.h> #include <linux/slab.h> #include "xhci.h" static int handle_cmd_in_cmd_wait_list(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev, struct xhci_event_cmd *event); /* * Returns zero if the TRB isn't in this segment, otherwise it returns the DMA * address of the TRB. */ dma_addr_t xhci_trb_virt_to_dma(struct xhci_segment *seg, union xhci_trb *trb) { unsigned long segment_offset; if (!seg || !trb || trb < seg->trbs) return 0; /* offset in TRBs */ segment_offset = trb - seg->trbs; if (segment_offset > TRBS_PER_SEGMENT) return 0; return seg->dma + (segment_offset * sizeof(*trb)); } /* Does this link TRB point to the first segment in a ring, * or was the previous TRB the last TRB on the last segment in the ERST? */ static bool last_trb_on_last_seg(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment *seg, union xhci_trb *trb) { if (ring == xhci->event_ring) return (trb == &seg->trbs[TRBS_PER_SEGMENT]) && (seg->next == xhci->event_ring->first_seg); else return le32_to_cpu(trb->link.control) & LINK_TOGGLE; } /* Is this TRB a link TRB or was the last TRB the last TRB in this event ring * segment? I.e. would the updated event TRB pointer step off the end of the * event seg? */ static int last_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment *seg, union xhci_trb *trb) { if (ring == xhci->event_ring) return trb == &seg->trbs[TRBS_PER_SEGMENT]; else return TRB_TYPE_LINK_LE32(trb->link.control); } static int enqueue_is_link_trb(struct xhci_ring *ring) { struct xhci_link_trb *link = &ring->enqueue->link; return TRB_TYPE_LINK_LE32(link->control); } /* Updates trb to point to the next TRB in the ring, and updates seg if the next * TRB is in a new segment. This does not skip over link TRBs, and it does not * effect the ring dequeue or enqueue pointers. */ static void next_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, struct xhci_segment **seg, union xhci_trb **trb) { if (last_trb(xhci, ring, *seg, *trb)) { *seg = (*seg)->next; *trb = ((*seg)->trbs); } else { (*trb)++; } } /* * See Cycle bit rules. SW is the consumer for the event ring only. * Don't make a ring full of link TRBs. That would be dumb and this would loop. */ static void inc_deq(struct xhci_hcd *xhci, struct xhci_ring *ring) { union xhci_trb *next; unsigned long long addr; ring->deq_updates++; /* If this is not event ring, there is one more usable TRB */ if (ring->type != TYPE_EVENT && !last_trb(xhci, ring, ring->deq_seg, ring->dequeue)) ring->num_trbs_free++; next = ++(ring->dequeue); /* Update the dequeue pointer further if that was a link TRB or we're at * the end of an event ring segment (which doesn't have link TRBS) */ while (last_trb(xhci, ring, ring->deq_seg, next)) { if (ring->type == TYPE_EVENT && last_trb_on_last_seg(xhci, ring, ring->deq_seg, next)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } ring->deq_seg = ring->deq_seg->next; ring->dequeue = ring->deq_seg->trbs; next = ring->dequeue; } addr = (unsigned long long) xhci_trb_virt_to_dma(ring->deq_seg, ring->dequeue); } /* * See Cycle bit rules. SW is the consumer for the event ring only. * Don't make a ring full of link TRBs. That would be dumb and this would loop. * * If we've just enqueued a TRB that is in the middle of a TD (meaning the * chain bit is set), then set the chain bit in all the following link TRBs. * If we've enqueued the last TRB in a TD, make sure the following link TRBs * have their chain bit cleared (so that each Link TRB is a separate TD). * * Section 6.4.4.1 of the 0.95 spec says link TRBs cannot have the chain bit * set, but other sections talk about dealing with the chain bit set. This was * fixed in the 0.96 specification errata, but we have to assume that all 0.95 * xHCI hardware can't handle the chain bit being cleared on a link TRB. * * @more_trbs_coming: Will you enqueue more TRBs before calling * prepare_transfer()? */ static void inc_enq(struct xhci_hcd *xhci, struct xhci_ring *ring, bool more_trbs_coming) { u32 chain; union xhci_trb *next; unsigned long long addr; chain = le32_to_cpu(ring->enqueue->generic.field[3]) & TRB_CHAIN; /* If this is not event ring, there is one less usable TRB */ if (ring->type != TYPE_EVENT && !last_trb(xhci, ring, ring->enq_seg, ring->enqueue)) ring->num_trbs_free--; next = ++(ring->enqueue); ring->enq_updates++; /* Update the dequeue pointer further if that was a link TRB or we're at * the end of an event ring segment (which doesn't have link TRBS) */ while (last_trb(xhci, ring, ring->enq_seg, next)) { if (ring->type != TYPE_EVENT) { /* * If the caller doesn't plan on enqueueing more * TDs before ringing the doorbell, then we * don't want to give the link TRB to the * hardware just yet. We'll give the link TRB * back in prepare_ring() just before we enqueue * the TD at the top of the ring. */ if (!chain && !more_trbs_coming) break; /* If we're not dealing with 0.95 hardware or * isoc rings on AMD 0.96 host, * carry over the chain bit of the previous TRB * (which may mean the chain bit is cleared). */ if (!(ring->type == TYPE_ISOC && (xhci->quirks & XHCI_AMD_0x96_HOST)) && !xhci_link_trb_quirk(xhci)) { next->link.control &= cpu_to_le32(~TRB_CHAIN); next->link.control |= cpu_to_le32(chain); } /* Give this link TRB to the hardware */ wmb(); next->link.control ^= cpu_to_le32(TRB_CYCLE); /* Toggle the cycle bit after the last ring segment. */ if (last_trb_on_last_seg(xhci, ring, ring->enq_seg, next)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } } ring->enq_seg = ring->enq_seg->next; ring->enqueue = ring->enq_seg->trbs; next = ring->enqueue; } addr = (unsigned long long) xhci_trb_virt_to_dma(ring->enq_seg, ring->enqueue); } /* * Check to see if there's room to enqueue num_trbs on the ring and make sure * enqueue pointer will not advance into dequeue segment. See rules above. */ static inline int room_on_ring(struct xhci_hcd *xhci, struct xhci_ring *ring, unsigned int num_trbs) { int num_trbs_in_deq_seg; if (ring->num_trbs_free < num_trbs) return 0; if (ring->type != TYPE_COMMAND && ring->type != TYPE_EVENT) { num_trbs_in_deq_seg = ring->dequeue - ring->deq_seg->trbs; if (ring->num_trbs_free < num_trbs + num_trbs_in_deq_seg) return 0; } return 1; } /* Ring the host controller doorbell after placing a command on the ring */ void xhci_ring_cmd_db(struct xhci_hcd *xhci) { xhci_dbg(xhci, "// Ding dong!\n"); xhci_writel(xhci, DB_VALUE_HOST, &xhci->dba->doorbell[0]); /* Flush PCI posted writes */ xhci_readl(xhci, &xhci->dba->doorbell[0]); } void xhci_ring_ep_doorbell(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id) { __le32 __iomem *db_addr = &xhci->dba->doorbell[slot_id]; struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; unsigned int ep_state = ep->ep_state; /* Don't ring the doorbell for this endpoint if there are pending * cancellations because we don't want to interrupt processing. * We don't want to restart any stream rings if there's a set dequeue * pointer command pending because the device can choose to start any * stream once the endpoint is on the HW schedule. * FIXME - check all the stream rings for pending cancellations. */ if ((ep_state & EP_HALT_PENDING) || (ep_state & SET_DEQ_PENDING) || (ep_state & EP_HALTED)) return; xhci_writel(xhci, DB_VALUE(ep_index, stream_id), db_addr); /* The CPU has better things to do at this point than wait for a * write-posting flush. It'll get there soon enough. */ } /* Ring the doorbell for any rings with pending URBs */ static void ring_doorbell_for_active_rings(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index) { unsigned int stream_id; struct xhci_virt_ep *ep; ep = &xhci->devs[slot_id]->eps[ep_index]; /* A ring has pending URBs if its TD list is not empty */ if (!(ep->ep_state & EP_HAS_STREAMS)) { if (!(list_empty(&ep->ring->td_list))) xhci_ring_ep_doorbell(xhci, slot_id, ep_index, 0); return; } for (stream_id = 1; stream_id < ep->stream_info->num_streams; stream_id++) { struct xhci_stream_info *stream_info = ep->stream_info; if (!list_empty(&stream_info->stream_rings[stream_id]->td_list)) xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id); } } /* * Find the segment that trb is in. Start searching in start_seg. * If we must move past a segment that has a link TRB with a toggle cycle state * bit set, then we will toggle the value pointed at by cycle_state. */ static struct xhci_segment *find_trb_seg( struct xhci_segment *start_seg, union xhci_trb *trb, int *cycle_state) { struct xhci_segment *cur_seg = start_seg; struct xhci_generic_trb *generic_trb; while (cur_seg->trbs > trb || &cur_seg->trbs[TRBS_PER_SEGMENT - 1] < trb) { generic_trb = &cur_seg->trbs[TRBS_PER_SEGMENT - 1].generic; if (generic_trb->field[3] & cpu_to_le32(LINK_TOGGLE)) *cycle_state ^= 0x1; cur_seg = cur_seg->next; if (cur_seg == start_seg) /* Looped over the entire list. Oops! */ return NULL; } return cur_seg; } static struct xhci_ring *xhci_triad_to_transfer_ring(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id) { struct xhci_virt_ep *ep; ep = &xhci->devs[slot_id]->eps[ep_index]; /* Common case: no streams */ if (!(ep->ep_state & EP_HAS_STREAMS)) return ep->ring; if (stream_id == 0) { xhci_warn(xhci, "WARN: Slot ID %u, ep index %u has streams, " "but URB has no stream ID.\n", slot_id, ep_index); return NULL; } if (stream_id < ep->stream_info->num_streams) return ep->stream_info->stream_rings[stream_id]; xhci_warn(xhci, "WARN: Slot ID %u, ep index %u has " "stream IDs 1 to %u allocated, " "but stream ID %u is requested.\n", slot_id, ep_index, ep->stream_info->num_streams - 1, stream_id); return NULL; } /* Get the right ring for the given URB. * If the endpoint supports streams, boundary check the URB's stream ID. * If the endpoint doesn't support streams, return the singular endpoint ring. */ static struct xhci_ring *xhci_urb_to_transfer_ring(struct xhci_hcd *xhci, struct urb *urb) { return xhci_triad_to_transfer_ring(xhci, urb->dev->slot_id, xhci_get_endpoint_index(&urb->ep->desc), urb->stream_id); } /* * Move the xHC's endpoint ring dequeue pointer past cur_td. * Record the new state of the xHC's endpoint ring dequeue segment, * dequeue pointer, and new consumer cycle state in state. * Update our internal representation of the ring's dequeue pointer. * * We do this in three jumps: * - First we update our new ring state to be the same as when the xHC stopped. * - Then we traverse the ring to find the segment that contains * the last TRB in the TD. We toggle the xHC's new cycle state when we pass * any link TRBs with the toggle cycle bit set. * - Finally we move the dequeue state one TRB further, toggling the cycle bit * if we've moved it past a link TRB with the toggle cycle bit set. * * Some of the uses of xhci_generic_trb are grotty, but if they're done * with correct __le32 accesses they should work fine. Only users of this are * in here. */ void xhci_find_new_dequeue_state(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_td *cur_td, struct xhci_dequeue_state *state) { struct xhci_virt_device *dev = xhci->devs[slot_id]; struct xhci_ring *ep_ring; struct xhci_generic_trb *trb; struct xhci_ep_ctx *ep_ctx; dma_addr_t addr; ep_ring = xhci_triad_to_transfer_ring(xhci, slot_id, ep_index, stream_id); if (!ep_ring) { xhci_warn(xhci, "WARN can't find new dequeue state " "for invalid stream ID %u.\n", stream_id); return; } state->new_cycle_state = 0; xhci_dbg(xhci, "Finding segment containing stopped TRB.\n"); state->new_deq_seg = find_trb_seg(cur_td->start_seg, dev->eps[ep_index].stopped_trb, &state->new_cycle_state); if (!state->new_deq_seg) { WARN_ON(1); return; } /* Dig out the cycle state saved by the xHC during the stop ep cmd */ xhci_dbg(xhci, "Finding endpoint context\n"); ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index); state->new_cycle_state = 0x1 & le64_to_cpu(ep_ctx->deq); state->new_deq_ptr = cur_td->last_trb; xhci_dbg(xhci, "Finding segment containing last TRB in TD.\n"); state->new_deq_seg = find_trb_seg(state->new_deq_seg, state->new_deq_ptr, &state->new_cycle_state); if (!state->new_deq_seg) { WARN_ON(1); return; } trb = &state->new_deq_ptr->generic; if (TRB_TYPE_LINK_LE32(trb->field[3]) && (trb->field[3] & cpu_to_le32(LINK_TOGGLE))) state->new_cycle_state ^= 0x1; next_trb(xhci, ep_ring, &state->new_deq_seg, &state->new_deq_ptr); /* * If there is only one segment in a ring, find_trb_seg()'s while loop * will not run, and it will return before it has a chance to see if it * needs to toggle the cycle bit. It can't tell if the stalled transfer * ended just before the link TRB on a one-segment ring, or if the TD * wrapped around the top of the ring, because it doesn't have the TD in * question. Look for the one-segment case where stalled TRB's address * is greater than the new dequeue pointer address. */ if (ep_ring->first_seg == ep_ring->first_seg->next && state->new_deq_ptr < dev->eps[ep_index].stopped_trb) state->new_cycle_state ^= 0x1; xhci_dbg(xhci, "Cycle state = 0x%x\n", state->new_cycle_state); /* Don't update the ring cycle state for the producer (us). */ xhci_dbg(xhci, "New dequeue segment = %p (virtual)\n", state->new_deq_seg); addr = xhci_trb_virt_to_dma(state->new_deq_seg, state->new_deq_ptr); xhci_dbg(xhci, "New dequeue pointer = 0x%llx (DMA)\n", (unsigned long long) addr); } /* flip_cycle means flip the cycle bit of all but the first and last TRB. * (The last TRB actually points to the ring enqueue pointer, which is not part * of this TD.) This is used to remove partially enqueued isoc TDs from a ring. */ static void td_to_noop(struct xhci_hcd *xhci, struct xhci_ring *ep_ring, struct xhci_td *cur_td, bool flip_cycle) { struct xhci_segment *cur_seg; union xhci_trb *cur_trb; for (cur_seg = cur_td->start_seg, cur_trb = cur_td->first_trb; true; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) { /* Unchain any chained Link TRBs, but * leave the pointers intact. */ cur_trb->generic.field[3] &= cpu_to_le32(~TRB_CHAIN); /* Flip the cycle bit (link TRBs can't be the first * or last TRB). */ if (flip_cycle) cur_trb->generic.field[3] ^= cpu_to_le32(TRB_CYCLE); xhci_dbg(xhci, "Cancel (unchain) link TRB\n"); xhci_dbg(xhci, "Address = %p (0x%llx dma); " "in seg %p (0x%llx dma)\n", cur_trb, (unsigned long long)xhci_trb_virt_to_dma(cur_seg, cur_trb), cur_seg, (unsigned long long)cur_seg->dma); } else { cur_trb->generic.field[0] = 0; cur_trb->generic.field[1] = 0; cur_trb->generic.field[2] = 0; /* Preserve only the cycle bit of this TRB */ cur_trb->generic.field[3] &= cpu_to_le32(TRB_CYCLE); /* Flip the cycle bit except on the first or last TRB */ if (flip_cycle && cur_trb != cur_td->first_trb && cur_trb != cur_td->last_trb) cur_trb->generic.field[3] ^= cpu_to_le32(TRB_CYCLE); cur_trb->generic.field[3] |= cpu_to_le32( TRB_TYPE(TRB_TR_NOOP)); xhci_dbg(xhci, "TRB to noop at offset 0x%llx\n", (unsigned long long) xhci_trb_virt_to_dma(cur_seg, cur_trb)); } if (cur_trb == cur_td->last_trb) break; } } static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_segment *deq_seg, union xhci_trb *deq_ptr, u32 cycle_state); void xhci_queue_new_dequeue_state(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_dequeue_state *deq_state) { struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; xhci_dbg(xhci, "Set TR Deq Ptr cmd, new deq seg = %p (0x%llx dma), " "new deq ptr = %p (0x%llx dma), new cycle = %u\n", deq_state->new_deq_seg, (unsigned long long)deq_state->new_deq_seg->dma, deq_state->new_deq_ptr, (unsigned long long)xhci_trb_virt_to_dma(deq_state->new_deq_seg, deq_state->new_deq_ptr), deq_state->new_cycle_state); queue_set_tr_deq(xhci, slot_id, ep_index, stream_id, deq_state->new_deq_seg, deq_state->new_deq_ptr, (u32) deq_state->new_cycle_state); /* Stop the TD queueing code from ringing the doorbell until * this command completes. The HC won't set the dequeue pointer * if the ring is running, and ringing the doorbell starts the * ring running. */ ep->ep_state |= SET_DEQ_PENDING; } static void xhci_stop_watchdog_timer_in_irq(struct xhci_hcd *xhci, struct xhci_virt_ep *ep) { ep->ep_state &= ~EP_HALT_PENDING; /* Can't del_timer_sync in interrupt, so we attempt to cancel. If the * timer is running on another CPU, we don't decrement stop_cmds_pending * (since we didn't successfully stop the watchdog timer). */ if (del_timer(&ep->stop_cmd_timer)) ep->stop_cmds_pending--; } /* Must be called with xhci->lock held in interrupt context */ static void xhci_giveback_urb_in_irq(struct xhci_hcd *xhci, struct xhci_td *cur_td, int status, char *adjective) { struct usb_hcd *hcd; struct urb *urb; struct urb_priv *urb_priv; urb = cur_td->urb; urb_priv = urb->hcpriv; urb_priv->td_cnt++; hcd = bus_to_hcd(urb->dev->bus); /* Only giveback urb when this is the last td in urb */ if (urb_priv->td_cnt == urb_priv->length) { if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) { xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs--; if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) usb_amd_quirk_pll_enable(); } } usb_hcd_unlink_urb_from_ep(hcd, urb); spin_unlock(&xhci->lock); usb_hcd_giveback_urb(hcd, urb, status); xhci_urb_free_priv(xhci, urb_priv); spin_lock(&xhci->lock); } } /* * When we get a command completion for a Stop Endpoint Command, we need to * unlink any cancelled TDs from the ring. There are two ways to do that: * * 1. If the HW was in the middle of processing the TD that needs to be * cancelled, then we must move the ring's dequeue pointer past the last TRB * in the TD with a Set Dequeue Pointer Command. * 2. Otherwise, we turn all the TRBs in the TD into No-op TRBs (with the chain * bit cleared) so that the HW will skip over them. */ static void handle_stopped_endpoint(struct xhci_hcd *xhci, union xhci_trb *trb, struct xhci_event_cmd *event) { unsigned int slot_id; unsigned int ep_index; struct xhci_virt_device *virt_dev; struct xhci_ring *ep_ring; struct xhci_virt_ep *ep; struct list_head *entry; struct xhci_td *cur_td = NULL; struct xhci_td *last_unlinked_td; struct xhci_dequeue_state deq_state; if (unlikely(TRB_TO_SUSPEND_PORT( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])))) { slot_id = TRB_TO_SLOT_ID( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])); virt_dev = xhci->devs[slot_id]; if (virt_dev) handle_cmd_in_cmd_wait_list(xhci, virt_dev, event); else xhci_warn(xhci, "Stop endpoint command " "completion for disabled slot %u\n", slot_id); return; } memset(&deq_state, 0, sizeof(deq_state)); slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); ep = &xhci->devs[slot_id]->eps[ep_index]; if (list_empty(&ep->cancelled_td_list)) { xhci_stop_watchdog_timer_in_irq(xhci, ep); ep->stopped_td = NULL; ep->stopped_trb = NULL; ring_doorbell_for_active_rings(xhci, slot_id, ep_index); return; } /* Fix up the ep ring first, so HW stops executing cancelled TDs. * We have the xHCI lock, so nothing can modify this list until we drop * it. We're also in the event handler, so we can't get re-interrupted * if another Stop Endpoint command completes */ list_for_each(entry, &ep->cancelled_td_list) { cur_td = list_entry(entry, struct xhci_td, cancelled_td_list); xhci_dbg(xhci, "Removing canceled TD starting at 0x%llx (dma).\n", (unsigned long long)xhci_trb_virt_to_dma( cur_td->start_seg, cur_td->first_trb)); ep_ring = xhci_urb_to_transfer_ring(xhci, cur_td->urb); if (!ep_ring) { /* This shouldn't happen unless a driver is mucking * with the stream ID after submission. This will * leave the TD on the hardware ring, and the hardware * will try to execute it, and may access a buffer * that has already been freed. In the best case, the * hardware will execute it, and the event handler will * ignore the completion event for that TD, since it was * removed from the td_list for that endpoint. In * short, don't muck with the stream ID after * submission. */ xhci_warn(xhci, "WARN Cancelled URB %p " "has invalid stream ID %u.\n", cur_td->urb, cur_td->urb->stream_id); goto remove_finished_td; } /* * If we stopped on the TD we need to cancel, then we have to * move the xHC endpoint ring dequeue pointer past this TD. */ if (cur_td == ep->stopped_td) xhci_find_new_dequeue_state(xhci, slot_id, ep_index, cur_td->urb->stream_id, cur_td, &deq_state); else td_to_noop(xhci, ep_ring, cur_td, false); remove_finished_td: /* * The event handler won't see a completion for this TD anymore, * so remove it from the endpoint ring's TD list. Keep it in * the cancelled TD list for URB completion later. */ list_del_init(&cur_td->td_list); } last_unlinked_td = cur_td; xhci_stop_watchdog_timer_in_irq(xhci, ep); /* If necessary, queue a Set Transfer Ring Dequeue Pointer command */ if (deq_state.new_deq_ptr && deq_state.new_deq_seg) { xhci_queue_new_dequeue_state(xhci, slot_id, ep_index, ep->stopped_td->urb->stream_id, &deq_state); xhci_ring_cmd_db(xhci); } else { /* Otherwise ring the doorbell(s) to restart queued transfers */ ring_doorbell_for_active_rings(xhci, slot_id, ep_index); } ep->stopped_td = NULL; ep->stopped_trb = NULL; /* * Drop the lock and complete the URBs in the cancelled TD list. * New TDs to be cancelled might be added to the end of the list before * we can complete all the URBs for the TDs we already unlinked. * So stop when we've completed the URB for the last TD we unlinked. */ do { cur_td = list_entry(ep->cancelled_td_list.next, struct xhci_td, cancelled_td_list); list_del_init(&cur_td->cancelled_td_list); /* Clean up the cancelled URB */ /* Doesn't matter what we pass for status, since the core will * just overwrite it (because the URB has been unlinked). */ xhci_giveback_urb_in_irq(xhci, cur_td, 0, "cancelled"); /* Stop processing the cancelled list if the watchdog timer is * running. */ if (xhci->xhc_state & XHCI_STATE_DYING) return; } while (cur_td != last_unlinked_td); /* Return to the event handler with xhci->lock re-acquired */ } /* Watchdog timer function for when a stop endpoint command fails to complete. * In this case, we assume the host controller is broken or dying or dead. The * host may still be completing some other events, so we have to be careful to * let the event ring handler and the URB dequeueing/enqueueing functions know * through xhci->state. * * The timer may also fire if the host takes a very long time to respond to the * command, and the stop endpoint command completion handler cannot delete the * timer before the timer function is called. Another endpoint cancellation may * sneak in before the timer function can grab the lock, and that may queue * another stop endpoint command and add the timer back. So we cannot use a * simple flag to say whether there is a pending stop endpoint command for a * particular endpoint. * * Instead we use a combination of that flag and a counter for the number of * pending stop endpoint commands. If the timer is the tail end of the last * stop endpoint command, and the endpoint's command is still pending, we assume * the host is dying. */ void xhci_stop_endpoint_command_watchdog(unsigned long arg) { struct xhci_hcd *xhci; struct xhci_virt_ep *ep; struct xhci_virt_ep *temp_ep; struct xhci_ring *ring; struct xhci_td *cur_td; int ret, i, j; unsigned long flags; ep = (struct xhci_virt_ep *) arg; xhci = ep->xhci; spin_lock_irqsave(&xhci->lock, flags); ep->stop_cmds_pending--; if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "Stop EP timer ran, but another timer marked " "xHCI as DYING, exiting.\n"); spin_unlock_irqrestore(&xhci->lock, flags); return; } if (!(ep->stop_cmds_pending == 0 && (ep->ep_state & EP_HALT_PENDING))) { xhci_dbg(xhci, "Stop EP timer ran, but no command pending, " "exiting.\n"); spin_unlock_irqrestore(&xhci->lock, flags); return; } xhci_warn(xhci, "xHCI host not responding to stop endpoint command.\n"); xhci_warn(xhci, "Assuming host is dying, halting host.\n"); /* Oops, HC is dead or dying or at least not responding to the stop * endpoint command. */ xhci->xhc_state |= XHCI_STATE_DYING; /* Disable interrupts from the host controller and start halting it */ xhci_quiesce(xhci); spin_unlock_irqrestore(&xhci->lock, flags); ret = xhci_halt(xhci); spin_lock_irqsave(&xhci->lock, flags); if (ret < 0) { /* This is bad; the host is not responding to commands and it's * not allowing itself to be halted. At least interrupts are * disabled. If we call usb_hc_died(), it will attempt to * disconnect all device drivers under this host. Those * disconnect() methods will wait for all URBs to be unlinked, * so we must complete them. */ xhci_warn(xhci, "Non-responsive xHCI host is not halting.\n"); xhci_warn(xhci, "Completing active URBs anyway.\n"); /* We could turn all TDs on the rings to no-ops. This won't * help if the host has cached part of the ring, and is slow if * we want to preserve the cycle bit. Skip it and hope the host * doesn't touch the memory. */ } for (i = 0; i < MAX_HC_SLOTS; i++) { if (!xhci->devs[i]) continue; for (j = 0; j < 31; j++) { temp_ep = &xhci->devs[i]->eps[j]; ring = temp_ep->ring; if (!ring) continue; xhci_dbg(xhci, "Killing URBs for slot ID %u, " "ep index %u\n", i, j); while (!list_empty(&ring->td_list)) { cur_td = list_first_entry(&ring->td_list, struct xhci_td, td_list); list_del_init(&cur_td->td_list); if (!list_empty(&cur_td->cancelled_td_list)) list_del_init(&cur_td->cancelled_td_list); xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN, "killed"); } while (!list_empty(&temp_ep->cancelled_td_list)) { cur_td = list_first_entry( &temp_ep->cancelled_td_list, struct xhci_td, cancelled_td_list); list_del_init(&cur_td->cancelled_td_list); xhci_giveback_urb_in_irq(xhci, cur_td, -ESHUTDOWN, "killed"); } } } spin_unlock_irqrestore(&xhci->lock, flags); xhci_dbg(xhci, "Calling usb_hc_died()\n"); usb_hc_died(xhci_to_hcd(xhci)->primary_hcd); xhci_dbg(xhci, "xHCI host controller is dead.\n"); } static void update_ring_for_set_deq_completion(struct xhci_hcd *xhci, struct xhci_virt_device *dev, struct xhci_ring *ep_ring, unsigned int ep_index) { union xhci_trb *dequeue_temp; int num_trbs_free_temp; bool revert = false; num_trbs_free_temp = ep_ring->num_trbs_free; dequeue_temp = ep_ring->dequeue; while (ep_ring->dequeue != dev->eps[ep_index].queued_deq_ptr) { /* We have more usable TRBs */ ep_ring->num_trbs_free++; ep_ring->dequeue++; if (last_trb(xhci, ep_ring, ep_ring->deq_seg, ep_ring->dequeue)) { if (ep_ring->dequeue == dev->eps[ep_index].queued_deq_ptr) break; ep_ring->deq_seg = ep_ring->deq_seg->next; ep_ring->dequeue = ep_ring->deq_seg->trbs; } if (ep_ring->dequeue == dequeue_temp) { revert = true; break; } } if (revert) { xhci_dbg(xhci, "Unable to find new dequeue pointer\n"); ep_ring->num_trbs_free = num_trbs_free_temp; } } /* * When we get a completion for a Set Transfer Ring Dequeue Pointer command, * we need to clear the set deq pending flag in the endpoint ring state, so that * the TD queueing code can ring the doorbell again. We also need to ring the * endpoint doorbell to restart the ring, but only if there aren't more * cancellations pending. */ static void handle_set_deq_completion(struct xhci_hcd *xhci, struct xhci_event_cmd *event, union xhci_trb *trb) { unsigned int slot_id; unsigned int ep_index; unsigned int stream_id; struct xhci_ring *ep_ring; struct xhci_virt_device *dev; struct xhci_ep_ctx *ep_ctx; struct xhci_slot_ctx *slot_ctx; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); stream_id = TRB_TO_STREAM_ID(le32_to_cpu(trb->generic.field[2])); dev = xhci->devs[slot_id]; ep_ring = xhci_stream_id_to_ring(dev, ep_index, stream_id); if (!ep_ring) { xhci_warn(xhci, "WARN Set TR deq ptr command for " "freed stream ID %u\n", stream_id); /* XXX: Harmless??? */ dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING; return; } ep_ctx = xhci_get_ep_ctx(xhci, dev->out_ctx, ep_index); slot_ctx = xhci_get_slot_ctx(xhci, dev->out_ctx); if (GET_COMP_CODE(le32_to_cpu(event->status)) != COMP_SUCCESS) { unsigned int ep_state; unsigned int slot_state; switch (GET_COMP_CODE(le32_to_cpu(event->status))) { case COMP_TRB_ERR: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd invalid because " "of stream ID configuration\n"); break; case COMP_CTX_STATE: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed due " "to incorrect slot or ep state.\n"); ep_state = le32_to_cpu(ep_ctx->ep_info); ep_state &= EP_STATE_MASK; slot_state = le32_to_cpu(slot_ctx->dev_state); slot_state = GET_SLOT_STATE(slot_state); xhci_dbg(xhci, "Slot state = %u, EP state = %u\n", slot_state, ep_state); break; case COMP_EBADSLT: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd failed because " "slot %u was not enabled.\n", slot_id); break; default: xhci_warn(xhci, "WARN Set TR Deq Ptr cmd with unknown " "completion code of %u.\n", GET_COMP_CODE(le32_to_cpu(event->status))); break; } /* OK what do we do now? The endpoint state is hosed, and we * should never get to this point if the synchronization between * queueing, and endpoint state are correct. This might happen * if the device gets disconnected after we've finished * cancelling URBs, which might not be an error... */ } else { xhci_dbg(xhci, "Successful Set TR Deq Ptr cmd, deq = @%08llx\n", le64_to_cpu(ep_ctx->deq)); if (xhci_trb_virt_to_dma(dev->eps[ep_index].queued_deq_seg, dev->eps[ep_index].queued_deq_ptr) == (le64_to_cpu(ep_ctx->deq) & ~(EP_CTX_CYCLE_MASK))) { /* Update the ring's dequeue segment and dequeue pointer * to reflect the new position. */ update_ring_for_set_deq_completion(xhci, dev, ep_ring, ep_index); } else { xhci_warn(xhci, "Mismatch between completed Set TR Deq " "Ptr command & xHCI internal state.\n"); xhci_warn(xhci, "ep deq seg = %p, deq ptr = %p\n", dev->eps[ep_index].queued_deq_seg, dev->eps[ep_index].queued_deq_ptr); } } dev->eps[ep_index].ep_state &= ~SET_DEQ_PENDING; dev->eps[ep_index].queued_deq_seg = NULL; dev->eps[ep_index].queued_deq_ptr = NULL; /* Restart any rings with pending URBs */ ring_doorbell_for_active_rings(xhci, slot_id, ep_index); } static void handle_reset_ep_completion(struct xhci_hcd *xhci, struct xhci_event_cmd *event, union xhci_trb *trb) { int slot_id; unsigned int ep_index; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(trb->generic.field[3])); ep_index = TRB_TO_EP_INDEX(le32_to_cpu(trb->generic.field[3])); /* This command will only fail if the endpoint wasn't halted, * but we don't care. */ xhci_dbg(xhci, "Ignoring reset ep completion code of %u\n", GET_COMP_CODE(le32_to_cpu(event->status))); /* HW with the reset endpoint quirk needs to have a configure endpoint * command complete before the endpoint can be used. Queue that here * because the HW can't handle two commands being queued in a row. */ if (xhci->quirks & XHCI_RESET_EP_QUIRK) { xhci_dbg(xhci, "Queueing configure endpoint command\n"); xhci_queue_configure_endpoint(xhci, xhci->devs[slot_id]->in_ctx->dma, slot_id, false); xhci_ring_cmd_db(xhci); } else { /* Clear our internal halted state and restart the ring(s) */ xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED; ring_doorbell_for_active_rings(xhci, slot_id, ep_index); } } /* Check to see if a command in the device's command queue matches this one. * Signal the completion or free the command, and return 1. Return 0 if the * completed command isn't at the head of the command list. */ static int handle_cmd_in_cmd_wait_list(struct xhci_hcd *xhci, struct xhci_virt_device *virt_dev, struct xhci_event_cmd *event) { struct xhci_command *command; if (list_empty(&virt_dev->cmd_list)) return 0; command = list_entry(virt_dev->cmd_list.next, struct xhci_command, cmd_list); if (xhci->cmd_ring->dequeue != command->command_trb) return 0; command->status = GET_COMP_CODE(le32_to_cpu(event->status)); list_del(&command->cmd_list); if (command->completion) complete(command->completion); else xhci_free_command(xhci, command); return 1; } static void handle_cmd_completion(struct xhci_hcd *xhci, struct xhci_event_cmd *event) { int slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); u64 cmd_dma; dma_addr_t cmd_dequeue_dma; struct xhci_input_control_ctx *ctrl_ctx; struct xhci_virt_device *virt_dev; unsigned int ep_index; struct xhci_ring *ep_ring; unsigned int ep_state; cmd_dma = le64_to_cpu(event->cmd_trb); cmd_dequeue_dma = xhci_trb_virt_to_dma(xhci->cmd_ring->deq_seg, xhci->cmd_ring->dequeue); /* Is the command ring deq ptr out of sync with the deq seg ptr? */ if (cmd_dequeue_dma == 0) { xhci->error_bitmask |= 1 << 4; return; } /* Does the DMA address match our internal dequeue pointer address? */ if (cmd_dma != (u64) cmd_dequeue_dma) { xhci->error_bitmask |= 1 << 5; return; } switch (le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3]) & TRB_TYPE_BITMASK) { case TRB_TYPE(TRB_ENABLE_SLOT): if (GET_COMP_CODE(le32_to_cpu(event->status)) == COMP_SUCCESS) xhci->slot_id = slot_id; else xhci->slot_id = 0; complete(&xhci->addr_dev); break; case TRB_TYPE(TRB_DISABLE_SLOT): if (xhci->devs[slot_id]) { if (xhci->quirks & XHCI_EP_LIMIT_QUIRK) /* Delete default control endpoint resources */ xhci_free_device_endpoint_resources(xhci, xhci->devs[slot_id], true); xhci_free_virt_device(xhci, slot_id); } break; case TRB_TYPE(TRB_CONFIG_EP): virt_dev = xhci->devs[slot_id]; if (handle_cmd_in_cmd_wait_list(xhci, virt_dev, event)) break; /* * Configure endpoint commands can come from the USB core * configuration or alt setting changes, or because the HW * needed an extra configure endpoint command after a reset * endpoint command or streams were being configured. * If the command was for a halted endpoint, the xHCI driver * is not waiting on the configure endpoint command. */ ctrl_ctx = xhci_get_input_control_ctx(xhci, virt_dev->in_ctx); /* Input ctx add_flags are the endpoint index plus one */ ep_index = xhci_last_valid_endpoint(le32_to_cpu(ctrl_ctx->add_flags)) - 1; /* A usb_set_interface() call directly after clearing a halted * condition may race on this quirky hardware. Not worth * worrying about, since this is prototype hardware. Not sure * if this will work for streams, but streams support was * untested on this prototype. */ if (xhci->quirks & XHCI_RESET_EP_QUIRK && ep_index != (unsigned int) -1 && le32_to_cpu(ctrl_ctx->add_flags) - SLOT_FLAG == le32_to_cpu(ctrl_ctx->drop_flags)) { ep_ring = xhci->devs[slot_id]->eps[ep_index].ring; ep_state = xhci->devs[slot_id]->eps[ep_index].ep_state; if (!(ep_state & EP_HALTED)) goto bandwidth_change; xhci_dbg(xhci, "Completed config ep cmd - " "last ep index = %d, state = %d\n", ep_index, ep_state); /* Clear internal halted state and restart ring(s) */ xhci->devs[slot_id]->eps[ep_index].ep_state &= ~EP_HALTED; ring_doorbell_for_active_rings(xhci, slot_id, ep_index); break; } bandwidth_change: xhci_dbg(xhci, "Completed config ep cmd\n"); xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->devs[slot_id]->cmd_completion); break; case TRB_TYPE(TRB_EVAL_CONTEXT): virt_dev = xhci->devs[slot_id]; if (handle_cmd_in_cmd_wait_list(xhci, virt_dev, event)) break; xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->devs[slot_id]->cmd_completion); break; case TRB_TYPE(TRB_ADDR_DEV): xhci->devs[slot_id]->cmd_status = GET_COMP_CODE(le32_to_cpu(event->status)); complete(&xhci->addr_dev); break; case TRB_TYPE(TRB_STOP_RING): handle_stopped_endpoint(xhci, xhci->cmd_ring->dequeue, event); break; case TRB_TYPE(TRB_SET_DEQ): handle_set_deq_completion(xhci, event, xhci->cmd_ring->dequeue); break; case TRB_TYPE(TRB_CMD_NOOP): break; case TRB_TYPE(TRB_RESET_EP): handle_reset_ep_completion(xhci, event, xhci->cmd_ring->dequeue); break; case TRB_TYPE(TRB_RESET_DEV): xhci_dbg(xhci, "Completed reset device command.\n"); slot_id = TRB_TO_SLOT_ID( le32_to_cpu(xhci->cmd_ring->dequeue->generic.field[3])); virt_dev = xhci->devs[slot_id]; if (virt_dev) handle_cmd_in_cmd_wait_list(xhci, virt_dev, event); else xhci_warn(xhci, "Reset device command completion " "for disabled slot %u\n", slot_id); break; case TRB_TYPE(TRB_NEC_GET_FW): if (!(xhci->quirks & XHCI_NEC_HOST)) { xhci->error_bitmask |= 1 << 6; break; } xhci_dbg(xhci, "NEC firmware version %2x.%02x\n", NEC_FW_MAJOR(le32_to_cpu(event->status)), NEC_FW_MINOR(le32_to_cpu(event->status))); break; default: /* Skip over unknown commands on the event ring */ xhci->error_bitmask |= 1 << 6; break; } inc_deq(xhci, xhci->cmd_ring); } static void handle_vendor_event(struct xhci_hcd *xhci, union xhci_trb *event) { u32 trb_type; trb_type = TRB_FIELD_TO_TYPE(le32_to_cpu(event->generic.field[3])); xhci_dbg(xhci, "Vendor specific event TRB type = %u\n", trb_type); if (trb_type == TRB_NEC_CMD_COMP && (xhci->quirks & XHCI_NEC_HOST)) handle_cmd_completion(xhci, &event->event_cmd); } /* @port_id: the one-based port ID from the hardware (indexed from array of all * port registers -- USB 3.0 and USB 2.0). * * Returns a zero-based port number, which is suitable for indexing into each of * the split roothubs' port arrays and bus state arrays. * Add one to it in order to call xhci_find_slot_id_by_port. */ static unsigned int find_faked_portnum_from_hw_portnum(struct usb_hcd *hcd, struct xhci_hcd *xhci, u32 port_id) { unsigned int i; unsigned int num_similar_speed_ports = 0; /* port_id from the hardware is 1-based, but port_array[], usb3_ports[], * and usb2_ports are 0-based indexes. Count the number of similar * speed ports, up to 1 port before this port. */ for (i = 0; i < (port_id - 1); i++) { u8 port_speed = xhci->port_array[i]; /* * Skip ports that don't have known speeds, or have duplicate * Extended Capabilities port speed entries. */ if (port_speed == 0 || port_speed == DUPLICATE_ENTRY) continue; /* * USB 3.0 ports are always under a USB 3.0 hub. USB 2.0 and * 1.1 ports are under the USB 2.0 hub. If the port speed * matches the device speed, it's a similar speed port. */ if ((port_speed == 0x03) == (hcd->speed == HCD_USB3)) num_similar_speed_ports++; } return num_similar_speed_ports; } static void handle_device_notification(struct xhci_hcd *xhci, union xhci_trb *event) { u32 slot_id; struct usb_device *udev; slot_id = TRB_TO_SLOT_ID(event->generic.field[3]); if (!xhci->devs[slot_id]) { xhci_warn(xhci, "Device Notification event for " "unused slot %u\n", slot_id); return; } xhci_dbg(xhci, "Device Wake Notification event for slot ID %u\n", slot_id); udev = xhci->devs[slot_id]->udev; if (udev && udev->parent) usb_wakeup_notification(udev->parent, udev->portnum); } static void handle_port_status(struct xhci_hcd *xhci, union xhci_trb *event) { struct usb_hcd *hcd; u32 port_id; u32 temp, temp1; int max_ports; int slot_id; unsigned int faked_port_index; u8 major_revision; struct xhci_bus_state *bus_state; __le32 __iomem **port_array; bool bogus_port_status = false; /* Port status change events always have a successful completion code */ if (GET_COMP_CODE(le32_to_cpu(event->generic.field[2])) != COMP_SUCCESS) { xhci_warn(xhci, "WARN: xHC returned failed port status event\n"); xhci->error_bitmask |= 1 << 8; } port_id = GET_PORT_ID(le32_to_cpu(event->generic.field[0])); xhci_dbg(xhci, "Port Status Change Event for port %d\n", port_id); max_ports = HCS_MAX_PORTS(xhci->hcs_params1); if ((port_id <= 0) || (port_id > max_ports)) { xhci_warn(xhci, "Invalid port id %d\n", port_id); bogus_port_status = true; goto cleanup; } /* Figure out which usb_hcd this port is attached to: * is it a USB 3.0 port or a USB 2.0/1.1 port? */ major_revision = xhci->port_array[port_id - 1]; if (major_revision == 0) { xhci_warn(xhci, "Event for port %u not in " "Extended Capabilities, ignoring.\n", port_id); bogus_port_status = true; goto cleanup; } if (major_revision == DUPLICATE_ENTRY) { xhci_warn(xhci, "Event for port %u duplicated in" "Extended Capabilities, ignoring.\n", port_id); bogus_port_status = true; goto cleanup; } /* * Hardware port IDs reported by a Port Status Change Event include USB * 3.0 and USB 2.0 ports. We want to check if the port has reported a * resume event, but we first need to translate the hardware port ID * into the index into the ports on the correct split roothub, and the * correct bus_state structure. */ /* Find the right roothub. */ hcd = xhci_to_hcd(xhci); if ((major_revision == 0x03) != (hcd->speed == HCD_USB3)) hcd = xhci->shared_hcd; bus_state = &xhci->bus_state[hcd_index(hcd)]; if (hcd->speed == HCD_USB3) port_array = xhci->usb3_ports; else port_array = xhci->usb2_ports; /* Find the faked port hub number */ faked_port_index = find_faked_portnum_from_hw_portnum(hcd, xhci, port_id); temp = xhci_readl(xhci, port_array[faked_port_index]); if (hcd->state == HC_STATE_SUSPENDED) { xhci_dbg(xhci, "resume root hub\n"); usb_hcd_resume_root_hub(hcd); } if ((temp & PORT_PLC) && (temp & PORT_PLS_MASK) == XDEV_RESUME) { xhci_dbg(xhci, "port resume event for port %d\n", port_id); temp1 = xhci_readl(xhci, &xhci->op_regs->command); if (!(temp1 & CMD_RUN)) { xhci_warn(xhci, "xHC is not running.\n"); goto cleanup; } if (DEV_SUPERSPEED(temp)) { xhci_dbg(xhci, "remote wake SS port %d\n", port_id); /* Set a flag to say the port signaled remote wakeup, * so we can tell the difference between the end of * device and host initiated resume. */ bus_state->port_remote_wakeup |= 1 << faked_port_index; xhci_test_and_clear_bit(xhci, port_array, faked_port_index, PORT_PLC); xhci_set_link_state(xhci, port_array, faked_port_index, XDEV_U0); /* Need to wait until the next link state change * indicates the device is actually in U0. */ bogus_port_status = true; goto cleanup; } else { xhci_dbg(xhci, "resume HS port %d\n", port_id); bus_state->resume_done[faked_port_index] = jiffies + msecs_to_jiffies(20); mod_timer(&hcd->rh_timer, bus_state->resume_done[faked_port_index]); /* Do the rest in GetPortStatus */ } } if ((temp & PORT_PLC) && (temp & PORT_PLS_MASK) == XDEV_U0 && DEV_SUPERSPEED(temp)) { xhci_dbg(xhci, "resume SS port %d finished\n", port_id); /* We've just brought the device into U0 through either the * Resume state after a device remote wakeup, or through the * U3Exit state after a host-initiated resume. If it's a device * initiated remote wake, don't pass up the link state change, * so the roothub behavior is consistent with external * USB 3.0 hub behavior. */ slot_id = xhci_find_slot_id_by_port(hcd, xhci, faked_port_index + 1); if (slot_id && xhci->devs[slot_id]) xhci_ring_device(xhci, slot_id); if (bus_state->port_remote_wakeup && (1 << faked_port_index)) { bus_state->port_remote_wakeup &= ~(1 << faked_port_index); xhci_test_and_clear_bit(xhci, port_array, faked_port_index, PORT_PLC); usb_wakeup_notification(hcd->self.root_hub, faked_port_index + 1); bogus_port_status = true; goto cleanup; } } if (hcd->speed != HCD_USB3) xhci_test_and_clear_bit(xhci, port_array, faked_port_index, PORT_PLC); cleanup: /* Update event ring dequeue pointer before dropping the lock */ inc_deq(xhci, xhci->event_ring); /* Don't make the USB core poll the roothub if we got a bad port status * change event. Besides, at that point we can't tell which roothub * (USB 2.0 or USB 3.0) to kick. */ if (bogus_port_status) return; spin_unlock(&xhci->lock); /* Pass this up to the core */ usb_hcd_poll_rh_status(hcd); spin_lock(&xhci->lock); } /* * This TD is defined by the TRBs starting at start_trb in start_seg and ending * at end_trb, which may be in another segment. If the suspect DMA address is a * TRB in this TD, this function returns that TRB's segment. Otherwise it * returns 0. */ struct xhci_segment *trb_in_td(struct xhci_segment *start_seg, union xhci_trb *start_trb, union xhci_trb *end_trb, dma_addr_t suspect_dma) { dma_addr_t start_dma; dma_addr_t end_seg_dma; dma_addr_t end_trb_dma; struct xhci_segment *cur_seg; start_dma = xhci_trb_virt_to_dma(start_seg, start_trb); cur_seg = start_seg; do { if (start_dma == 0) return NULL; /* We may get an event for a Link TRB in the middle of a TD */ end_seg_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[TRBS_PER_SEGMENT - 1]); /* If the end TRB isn't in this segment, this is set to 0 */ end_trb_dma = xhci_trb_virt_to_dma(cur_seg, end_trb); if (end_trb_dma > 0) { /* The end TRB is in this segment, so suspect should be here */ if (start_dma <= end_trb_dma) { if (suspect_dma >= start_dma && suspect_dma <= end_trb_dma) return cur_seg; } else { /* Case for one segment with * a TD wrapped around to the top */ if ((suspect_dma >= start_dma && suspect_dma <= end_seg_dma) || (suspect_dma >= cur_seg->dma && suspect_dma <= end_trb_dma)) return cur_seg; } return NULL; } else { /* Might still be somewhere in this segment */ if (suspect_dma >= start_dma && suspect_dma <= end_seg_dma) return cur_seg; } cur_seg = cur_seg->next; start_dma = xhci_trb_virt_to_dma(cur_seg, &cur_seg->trbs[0]); } while (cur_seg != start_seg); return NULL; } static void xhci_cleanup_halted_endpoint(struct xhci_hcd *xhci, unsigned int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_td *td, union xhci_trb *event_trb) { struct xhci_virt_ep *ep = &xhci->devs[slot_id]->eps[ep_index]; ep->ep_state |= EP_HALTED; ep->stopped_td = td; ep->stopped_trb = event_trb; ep->stopped_stream = stream_id; xhci_queue_reset_ep(xhci, slot_id, ep_index); xhci_cleanup_stalled_ring(xhci, td->urb->dev, ep_index); ep->stopped_td = NULL; ep->stopped_trb = NULL; ep->stopped_stream = 0; xhci_ring_cmd_db(xhci); } /* Check if an error has halted the endpoint ring. The class driver will * cleanup the halt for a non-default control endpoint if we indicate a stall. * However, a babble and other errors also halt the endpoint ring, and the class * driver won't clear the halt in that case, so we need to issue a Set Transfer * Ring Dequeue Pointer command manually. */ static int xhci_requires_manual_halt_cleanup(struct xhci_hcd *xhci, struct xhci_ep_ctx *ep_ctx, unsigned int trb_comp_code) { /* TRB completion codes that may require a manual halt cleanup */ if (trb_comp_code == COMP_TX_ERR || trb_comp_code == COMP_BABBLE || trb_comp_code == COMP_SPLIT_ERR) /* The 0.96 spec says a babbling control endpoint * is not halted. The 0.96 spec says it is. Some HW * claims to be 0.95 compliant, but it halts the control * endpoint anyway. Check if a babble halted the * endpoint. */ if ((ep_ctx->ep_info & cpu_to_le32(EP_STATE_MASK)) == cpu_to_le32(EP_STATE_HALTED)) return 1; return 0; } int xhci_is_vendor_info_code(struct xhci_hcd *xhci, unsigned int trb_comp_code) { if (trb_comp_code >= 224 && trb_comp_code <= 255) { /* Vendor defined "informational" completion code, * treat as not-an-error. */ xhci_dbg(xhci, "Vendor defined info completion code %u\n", trb_comp_code); xhci_dbg(xhci, "Treating code as success.\n"); return 1; } return 0; } /* * Finish the td processing, remove the td from td list; * Return 1 if the urb can be given back. */ static int finish_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status, bool skip) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct urb *urb = NULL; struct xhci_ep_ctx *ep_ctx; int ret = 0; struct urb_priv *urb_priv; u32 trb_comp_code; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); if (skip) goto td_cleanup; if (trb_comp_code == COMP_STOP_INVAL || trb_comp_code == COMP_STOP) { /* The Endpoint Stop Command completion will take care of any * stopped TDs. A stopped TD may be restarted, so don't update * the ring dequeue pointer or take this TD off any lists yet. */ ep->stopped_td = td; ep->stopped_trb = event_trb; return 0; } else { if (trb_comp_code == COMP_STALL) { /* The transfer is completed from the driver's * perspective, but we need to issue a set dequeue * command for this stalled endpoint to move the dequeue * pointer past the TD. We can't do that here because * the halt condition must be cleared first. Let the * USB class driver clear the stall later. */ ep->stopped_td = td; ep->stopped_trb = event_trb; ep->stopped_stream = ep_ring->stream_id; } else if (xhci_requires_manual_halt_cleanup(xhci, ep_ctx, trb_comp_code)) { /* Other types of errors halt the endpoint, but the * class driver doesn't call usb_reset_endpoint() unless * the error is -EPIPE. Clear the halted status in the * xHCI hardware manually. */ xhci_cleanup_halted_endpoint(xhci, slot_id, ep_index, ep_ring->stream_id, td, event_trb); } else { /* Update ring dequeue pointer */ while (ep_ring->dequeue != td->last_trb) inc_deq(xhci, ep_ring); inc_deq(xhci, ep_ring); } td_cleanup: /* Clean up the endpoint's TD list */ urb = td->urb; urb_priv = urb->hcpriv; /* Do one last check of the actual transfer length. * If the host controller said we transferred more data than * the buffer length, urb->actual_length will be a very big * number (since it's unsigned). Play it safe and say we didn't * transfer anything. */ if (urb->actual_length > urb->transfer_buffer_length) { xhci_warn(xhci, "URB transfer length is wrong, " "xHC issue? req. len = %u, " "act. len = %u\n", urb->transfer_buffer_length, urb->actual_length); urb->actual_length = 0; if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } list_del_init(&td->td_list); /* Was this TD slated to be cancelled but completed anyway? */ if (!list_empty(&td->cancelled_td_list)) list_del_init(&td->cancelled_td_list); urb_priv->td_cnt++; /* Giveback the urb when all the tds are completed */ if (urb_priv->td_cnt == urb_priv->length) { ret = 1; if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) { xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs--; if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) usb_amd_quirk_pll_enable(); } } } } return ret; } /* * Process control tds, update urb status and actual_length. */ static int process_ctrl_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct xhci_ep_ctx *ep_ctx; u32 trb_comp_code; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); switch (trb_comp_code) { case COMP_SUCCESS: if (event_trb == ep_ring->dequeue) { xhci_warn(xhci, "WARN: Success on ctrl setup TRB " "without IOC set??\n"); *status = -ESHUTDOWN; } else if (event_trb != td->last_trb) { xhci_warn(xhci, "WARN: Success on ctrl data TRB " "without IOC set??\n"); *status = -ESHUTDOWN; } else { *status = 0; } break; case COMP_SHORT_TX: if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; break; case COMP_STOP_INVAL: case COMP_STOP: return finish_td(xhci, td, event_trb, event, ep, status, false); default: if (!xhci_requires_manual_halt_cleanup(xhci, ep_ctx, trb_comp_code)) break; xhci_dbg(xhci, "TRB error code %u, " "halted endpoint index = %u\n", trb_comp_code, ep_index); /* else fall through */ case COMP_STALL: /* Did we transfer part of the data (middle) phase? */ if (event_trb != ep_ring->dequeue && event_trb != td->last_trb) td->urb->actual_length = td->urb->transfer_buffer_length - TRB_LEN(le32_to_cpu(event->transfer_len)); else td->urb->actual_length = 0; xhci_cleanup_halted_endpoint(xhci, slot_id, ep_index, 0, td, event_trb); return finish_td(xhci, td, event_trb, event, ep, status, true); } /* * Did we transfer any data, despite the errors that might have * happened? I.e. did we get past the setup stage? */ if (event_trb != ep_ring->dequeue) { /* The event was for the status stage */ if (event_trb == td->last_trb) { if (td->urb->actual_length != 0) { /* Don't overwrite a previously set error code */ if ((*status == -EINPROGRESS || *status == 0) && (td->urb->transfer_flags & URB_SHORT_NOT_OK)) /* Did we already see a short data * stage? */ *status = -EREMOTEIO; } else { td->urb->actual_length = td->urb->transfer_buffer_length; } } else { /* Maybe the event was for the data stage? */ td->urb->actual_length = td->urb->transfer_buffer_length - TRB_LEN(le32_to_cpu(event->transfer_len)); xhci_dbg(xhci, "Waiting for status " "stage event\n"); return 0; } } return finish_td(xhci, td, event_trb, event, ep, status, false); } /* * Process isochronous tds, update urb packet status and actual_length. */ static int process_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; int idx; int len = 0; union xhci_trb *cur_trb; struct xhci_segment *cur_seg; struct usb_iso_packet_descriptor *frame; u32 trb_comp_code; bool skip_td = false; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); urb_priv = td->urb->hcpriv; idx = urb_priv->td_cnt; frame = &td->urb->iso_frame_desc[idx]; /* handle completion code */ switch (trb_comp_code) { case COMP_SUCCESS: frame->status = 0; break; case COMP_SHORT_TX: frame->status = td->urb->transfer_flags & URB_SHORT_NOT_OK ? -EREMOTEIO : 0; break; case COMP_BW_OVER: frame->status = -ECOMM; skip_td = true; break; case COMP_BUFF_OVER: case COMP_BABBLE: frame->status = -EOVERFLOW; skip_td = true; break; case COMP_DEV_ERR: case COMP_STALL: frame->status = -EPROTO; skip_td = true; break; case COMP_STOP: case COMP_STOP_INVAL: break; default: frame->status = -1; break; } if (trb_comp_code == COMP_SUCCESS || skip_td) { frame->actual_length = frame->length; td->urb->actual_length += frame->length; } else { for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg; cur_trb != event_trb; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (!TRB_TYPE_NOOP_LE32(cur_trb->generic.field[3]) && !TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) len += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])); } len += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])) - TRB_LEN(le32_to_cpu(event->transfer_len)); if (trb_comp_code != COMP_STOP_INVAL) { frame->actual_length = len; td->urb->actual_length += len; } } return finish_td(xhci, td, event_trb, event, ep, status, false); } static int skip_isoc_td(struct xhci_hcd *xhci, struct xhci_td *td, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct usb_iso_packet_descriptor *frame; int idx; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); urb_priv = td->urb->hcpriv; idx = urb_priv->td_cnt; frame = &td->urb->iso_frame_desc[idx]; /* The transfer is partly done. */ frame->status = -EXDEV; /* calc actual length */ frame->actual_length = 0; /* Update ring dequeue pointer */ while (ep_ring->dequeue != td->last_trb) inc_deq(xhci, ep_ring); inc_deq(xhci, ep_ring); return finish_td(xhci, td, NULL, event, ep, status, true); } /* * Process bulk and interrupt tds, update urb status and actual_length. */ static int process_bulk_intr_td(struct xhci_hcd *xhci, struct xhci_td *td, union xhci_trb *event_trb, struct xhci_transfer_event *event, struct xhci_virt_ep *ep, int *status) { struct xhci_ring *ep_ring; union xhci_trb *cur_trb; struct xhci_segment *cur_seg; u32 trb_comp_code; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); switch (trb_comp_code) { case COMP_SUCCESS: /* Double check that the HW transferred everything. */ if (event_trb != td->last_trb) { xhci_warn(xhci, "WARN Successful completion " "on short TX\n"); if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } else { *status = 0; } break; case COMP_SHORT_TX: if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; break; default: /* Others already handled above */ break; } if (trb_comp_code == COMP_SHORT_TX) xhci_dbg(xhci, "ep %#x - asked for %d bytes, " "%d bytes untransferred\n", td->urb->ep->desc.bEndpointAddress, td->urb->transfer_buffer_length, TRB_LEN(le32_to_cpu(event->transfer_len))); /* Fast path - was this the last TRB in the TD for this URB? */ if (event_trb == td->last_trb) { if (TRB_LEN(le32_to_cpu(event->transfer_len)) != 0) { td->urb->actual_length = td->urb->transfer_buffer_length - TRB_LEN(le32_to_cpu(event->transfer_len)); if (td->urb->transfer_buffer_length < td->urb->actual_length) { xhci_warn(xhci, "HC gave bad length " "of %d bytes left\n", TRB_LEN(le32_to_cpu(event->transfer_len))); td->urb->actual_length = 0; if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } /* Don't overwrite a previously set error code */ if (*status == -EINPROGRESS) { if (td->urb->transfer_flags & URB_SHORT_NOT_OK) *status = -EREMOTEIO; else *status = 0; } } else { td->urb->actual_length = td->urb->transfer_buffer_length; /* Ignore a short packet completion if the * untransferred length was zero. */ if (*status == -EREMOTEIO) *status = 0; } } else { /* Slow path - walk the list, starting from the dequeue * pointer, to get the actual length transferred. */ td->urb->actual_length = 0; for (cur_trb = ep_ring->dequeue, cur_seg = ep_ring->deq_seg; cur_trb != event_trb; next_trb(xhci, ep_ring, &cur_seg, &cur_trb)) { if (!TRB_TYPE_NOOP_LE32(cur_trb->generic.field[3]) && !TRB_TYPE_LINK_LE32(cur_trb->generic.field[3])) td->urb->actual_length += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])); } /* If the ring didn't stop on a Link or No-op TRB, add * in the actual bytes transferred from the Normal TRB */ if (trb_comp_code != COMP_STOP_INVAL) td->urb->actual_length += TRB_LEN(le32_to_cpu(cur_trb->generic.field[2])) - TRB_LEN(le32_to_cpu(event->transfer_len)); } return finish_td(xhci, td, event_trb, event, ep, status, false); } /* * If this function returns an error condition, it means it got a Transfer * event with a corrupted Slot ID, Endpoint ID, or TRB DMA address. * At this point, the host controller is probably hosed and should be reset. */ static int handle_tx_event(struct xhci_hcd *xhci, struct xhci_transfer_event *event) { struct xhci_virt_device *xdev; struct xhci_virt_ep *ep; struct xhci_ring *ep_ring; unsigned int slot_id; int ep_index; struct xhci_td *td = NULL; dma_addr_t event_dma; struct xhci_segment *event_seg; union xhci_trb *event_trb; struct urb *urb = NULL; int status = -EINPROGRESS; struct urb_priv *urb_priv; struct xhci_ep_ctx *ep_ctx; struct list_head *tmp; u32 trb_comp_code; int ret = 0; int td_num = 0; slot_id = TRB_TO_SLOT_ID(le32_to_cpu(event->flags)); xdev = xhci->devs[slot_id]; if (!xdev) { xhci_err(xhci, "ERROR Transfer event pointed to bad slot\n"); xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n", (unsigned long long) xhci_trb_virt_to_dma( xhci->event_ring->deq_seg, xhci->event_ring->dequeue), lower_32_bits(le64_to_cpu(event->buffer)), upper_32_bits(le64_to_cpu(event->buffer)), le32_to_cpu(event->transfer_len), le32_to_cpu(event->flags)); xhci_dbg(xhci, "Event ring:\n"); xhci_debug_segment(xhci, xhci->event_ring->deq_seg); return -ENODEV; } /* Endpoint ID is 1 based, our index is zero based */ ep_index = TRB_TO_EP_ID(le32_to_cpu(event->flags)) - 1; ep = &xdev->eps[ep_index]; ep_ring = xhci_dma_to_transfer_ring(ep, le64_to_cpu(event->buffer)); ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); if (!ep_ring || (le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK) == EP_STATE_DISABLED) { xhci_err(xhci, "ERROR Transfer event for disabled endpoint " "or incorrect stream ring\n"); xhci_err(xhci, "@%016llx %08x %08x %08x %08x\n", (unsigned long long) xhci_trb_virt_to_dma( xhci->event_ring->deq_seg, xhci->event_ring->dequeue), lower_32_bits(le64_to_cpu(event->buffer)), upper_32_bits(le64_to_cpu(event->buffer)), le32_to_cpu(event->transfer_len), le32_to_cpu(event->flags)); xhci_dbg(xhci, "Event ring:\n"); xhci_debug_segment(xhci, xhci->event_ring->deq_seg); return -ENODEV; } /* Count current td numbers if ep->skip is set */ if (ep->skip) { list_for_each(tmp, &ep_ring->td_list) td_num++; } event_dma = le64_to_cpu(event->buffer); trb_comp_code = GET_COMP_CODE(le32_to_cpu(event->transfer_len)); /* Look for common error cases */ switch (trb_comp_code) { /* Skip codes that require special handling depending on * transfer type */ case COMP_SUCCESS: case COMP_SHORT_TX: break; case COMP_STOP: xhci_dbg(xhci, "Stopped on Transfer TRB\n"); break; case COMP_STOP_INVAL: xhci_dbg(xhci, "Stopped on No-op or Link TRB\n"); break; case COMP_STALL: xhci_dbg(xhci, "Stalled endpoint\n"); ep->ep_state |= EP_HALTED; status = -EPIPE; break; case COMP_TRB_ERR: xhci_warn(xhci, "WARN: TRB error on endpoint\n"); status = -EILSEQ; break; case COMP_SPLIT_ERR: case COMP_TX_ERR: xhci_dbg(xhci, "Transfer error on endpoint\n"); status = -EPROTO; break; case COMP_BABBLE: xhci_dbg(xhci, "Babble error on endpoint\n"); status = -EOVERFLOW; break; case COMP_DB_ERR: xhci_warn(xhci, "WARN: HC couldn't access mem fast enough\n"); status = -ENOSR; break; case COMP_BW_OVER: xhci_warn(xhci, "WARN: bandwidth overrun event on endpoint\n"); break; case COMP_BUFF_OVER: xhci_warn(xhci, "WARN: buffer overrun event on endpoint\n"); break; case COMP_UNDERRUN: /* * When the Isoch ring is empty, the xHC will generate * a Ring Overrun Event for IN Isoch endpoint or Ring * Underrun Event for OUT Isoch endpoint. */ xhci_dbg(xhci, "underrun event on endpoint\n"); if (!list_empty(&ep_ring->td_list)) xhci_dbg(xhci, "Underrun Event for slot %d ep %d " "still with TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); goto cleanup; case COMP_OVERRUN: xhci_dbg(xhci, "overrun event on endpoint\n"); if (!list_empty(&ep_ring->td_list)) xhci_dbg(xhci, "Overrun Event for slot %d ep %d " "still with TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); goto cleanup; case COMP_DEV_ERR: xhci_warn(xhci, "WARN: detect an incompatible device"); status = -EPROTO; break; case COMP_MISSED_INT: /* * When encounter missed service error, one or more isoc tds * may be missed by xHC. * Set skip flag of the ep_ring; Complete the missed tds as * short transfer when process the ep_ring next time. */ ep->skip = true; xhci_dbg(xhci, "Miss service interval error, set skip flag\n"); goto cleanup; default: if (xhci_is_vendor_info_code(xhci, trb_comp_code)) { status = 0; break; } xhci_warn(xhci, "ERROR Unknown event condition, HC probably " "busted\n"); goto cleanup; } do { /* This TRB should be in the TD at the head of this ring's * TD list. */ if (list_empty(&ep_ring->td_list)) { xhci_warn(xhci, "WARN Event TRB for slot %d ep %d " "with no TDs queued?\n", TRB_TO_SLOT_ID(le32_to_cpu(event->flags)), ep_index); xhci_dbg(xhci, "Event TRB with TRB type ID %u\n", (le32_to_cpu(event->flags) & TRB_TYPE_BITMASK)>>10); xhci_print_trb_offsets(xhci, (union xhci_trb *) event); if (ep->skip) { ep->skip = false; xhci_dbg(xhci, "td_list is empty while skip " "flag set. Clear skip flag.\n"); } ret = 0; goto cleanup; } /* We've skipped all the TDs on the ep ring when ep->skip set */ if (ep->skip && td_num == 0) { ep->skip = false; xhci_dbg(xhci, "All tds on the ep_ring skipped. " "Clear skip flag.\n"); ret = 0; goto cleanup; } td = list_entry(ep_ring->td_list.next, struct xhci_td, td_list); if (ep->skip) td_num--; /* Is this a TRB in the currently executing TD? */ event_seg = trb_in_td(ep_ring->deq_seg, ep_ring->dequeue, td->last_trb, event_dma); /* * Skip the Force Stopped Event. The event_trb(event_dma) of FSE * is not in the current TD pointed by ep_ring->dequeue because * that the hardware dequeue pointer still at the previous TRB * of the current TD. The previous TRB maybe a Link TD or the * last TRB of the previous TD. The command completion handle * will take care the rest. */ if (!event_seg && (trb_comp_code == COMP_STOP || trb_comp_code == COMP_STOP_INVAL)) { ret = 0; goto cleanup; } if (!event_seg) { if (!ep->skip || !usb_endpoint_xfer_isoc(&td->urb->ep->desc)) { /* Some host controllers give a spurious * successful event after a short transfer. * Ignore it. */ if ((xhci->quirks & XHCI_SPURIOUS_SUCCESS) && ep_ring->last_td_was_short) { ep_ring->last_td_was_short = false; ret = 0; goto cleanup; } /* HC is busted, give up! */ xhci_err(xhci, "ERROR Transfer event TRB DMA ptr not " "part of current TD\n"); return -ESHUTDOWN; } ret = skip_isoc_td(xhci, td, event, ep, &status); goto cleanup; } if (trb_comp_code == COMP_SHORT_TX) ep_ring->last_td_was_short = true; else ep_ring->last_td_was_short = false; if (ep->skip) { xhci_dbg(xhci, "Found td. Clear skip flag.\n"); ep->skip = false; } event_trb = &event_seg->trbs[(event_dma - event_seg->dma) / sizeof(*event_trb)]; /* * No-op TRB should not trigger interrupts. * If event_trb is a no-op TRB, it means the * corresponding TD has been cancelled. Just ignore * the TD. */ if (TRB_TYPE_NOOP_LE32(event_trb->generic.field[3])) { xhci_dbg(xhci, "event_trb is a no-op TRB. Skip it\n"); goto cleanup; } /* Now update the urb's actual_length and give back to * the core */ if (usb_endpoint_xfer_control(&td->urb->ep->desc)) ret = process_ctrl_td(xhci, td, event_trb, event, ep, &status); else if (usb_endpoint_xfer_isoc(&td->urb->ep->desc)) ret = process_isoc_td(xhci, td, event_trb, event, ep, &status); else ret = process_bulk_intr_td(xhci, td, event_trb, event, ep, &status); cleanup: /* * Do not update event ring dequeue pointer if ep->skip is set. * Will roll back to continue process missed tds. */ if (trb_comp_code == COMP_MISSED_INT || !ep->skip) { inc_deq(xhci, xhci->event_ring); } if (ret) { urb = td->urb; urb_priv = urb->hcpriv; /* Leave the TD around for the reset endpoint function * to use(but only if it's not a control endpoint, * since we already queued the Set TR dequeue pointer * command for stalled control endpoints). */ if (usb_endpoint_xfer_control(&urb->ep->desc) || (trb_comp_code != COMP_STALL && trb_comp_code != COMP_BABBLE)) xhci_urb_free_priv(xhci, urb_priv); usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb); if ((urb->actual_length != urb->transfer_buffer_length && (urb->transfer_flags & URB_SHORT_NOT_OK)) || (status != 0 && !usb_endpoint_xfer_isoc(&urb->ep->desc))) xhci_dbg(xhci, "Giveback URB %p, len = %d, " "expected = %x, status = %d\n", urb, urb->actual_length, urb->transfer_buffer_length, status); spin_unlock(&xhci->lock); /* EHCI, UHCI, and OHCI always unconditionally set the * urb->status of an isochronous endpoint to 0. */ if (usb_pipetype(urb->pipe) == PIPE_ISOCHRONOUS) status = 0; usb_hcd_giveback_urb(bus_to_hcd(urb->dev->bus), urb, status); spin_lock(&xhci->lock); } /* * If ep->skip is set, it means there are missed tds on the * endpoint ring need to take care of. * Process them as short transfer until reach the td pointed by * the event. */ } while (ep->skip && trb_comp_code != COMP_MISSED_INT); return 0; } /* * This function handles all OS-owned events on the event ring. It may drop * xhci->lock between event processing (e.g. to pass up port status changes). * Returns >0 for "possibly more events to process" (caller should call again), * otherwise 0 if done. In future, <0 returns should indicate error code. */ static int xhci_handle_event(struct xhci_hcd *xhci) { union xhci_trb *event; int update_ptrs = 1; int ret; if (!xhci->event_ring || !xhci->event_ring->dequeue) { xhci->error_bitmask |= 1 << 1; return 0; } event = xhci->event_ring->dequeue; /* Does the HC or OS own the TRB? */ if ((le32_to_cpu(event->event_cmd.flags) & TRB_CYCLE) != xhci->event_ring->cycle_state) { xhci->error_bitmask |= 1 << 2; return 0; } /* * Barrier between reading the TRB_CYCLE (valid) flag above and any * speculative reads of the event's flags/data below. */ rmb(); /* FIXME: Handle more event types. */ switch ((le32_to_cpu(event->event_cmd.flags) & TRB_TYPE_BITMASK)) { case TRB_TYPE(TRB_COMPLETION): handle_cmd_completion(xhci, &event->event_cmd); break; case TRB_TYPE(TRB_PORT_STATUS): handle_port_status(xhci, event); update_ptrs = 0; break; case TRB_TYPE(TRB_TRANSFER): ret = handle_tx_event(xhci, &event->trans_event); if (ret < 0) xhci->error_bitmask |= 1 << 9; else update_ptrs = 0; break; case TRB_TYPE(TRB_DEV_NOTE): handle_device_notification(xhci, event); break; default: if ((le32_to_cpu(event->event_cmd.flags) & TRB_TYPE_BITMASK) >= TRB_TYPE(48)) handle_vendor_event(xhci, event); else xhci->error_bitmask |= 1 << 3; } /* Any of the above functions may drop and re-acquire the lock, so check * to make sure a watchdog timer didn't mark the host as non-responsive. */ if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "xHCI host dying, returning from " "event handler.\n"); return 0; } if (update_ptrs) /* Update SW event ring dequeue pointer */ inc_deq(xhci, xhci->event_ring); /* Are there more items on the event ring? Caller will call us again to * check. */ return 1; } /* * xHCI spec says we can get an interrupt, and if the HC has an error condition, * we might get bad data out of the event ring. Section 4.10.2.7 has a list of * indicators of an event TRB error, but we check the status *first* to be safe. */ irqreturn_t xhci_irq(struct usb_hcd *hcd) { struct xhci_hcd *xhci = hcd_to_xhci(hcd); u32 status; union xhci_trb *trb; u64 temp_64; union xhci_trb *event_ring_deq; dma_addr_t deq; spin_lock(&xhci->lock); trb = xhci->event_ring->dequeue; /* Check if the xHC generated the interrupt, or the irq is shared */ status = xhci_readl(xhci, &xhci->op_regs->status); if (status == 0xffffffff) goto hw_died; if (!(status & STS_EINT)) { spin_unlock(&xhci->lock); return IRQ_NONE; } if (status & STS_FATAL) { xhci_warn(xhci, "WARNING: Host System Error\n"); xhci_halt(xhci); hw_died: spin_unlock(&xhci->lock); return -ESHUTDOWN; } /* * Clear the op reg interrupt status first, * so we can receive interrupts from other MSI-X interrupters. * Write 1 to clear the interrupt status. */ status |= STS_EINT; xhci_writel(xhci, status, &xhci->op_regs->status); /* FIXME when MSI-X is supported and there are multiple vectors */ /* Clear the MSI-X event interrupt status */ if (hcd->irq) { u32 irq_pending; /* Acknowledge the PCI interrupt */ irq_pending = xhci_readl(xhci, &xhci->ir_set->irq_pending); irq_pending |= IMAN_IP; xhci_writel(xhci, irq_pending, &xhci->ir_set->irq_pending); } if (xhci->xhc_state & XHCI_STATE_DYING) { xhci_dbg(xhci, "xHCI dying, ignoring interrupt. " "Shouldn't IRQs be disabled?\n"); /* Clear the event handler busy flag (RW1C); * the event ring should be empty. */ temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue); xhci_write_64(xhci, temp_64 | ERST_EHB, &xhci->ir_set->erst_dequeue); spin_unlock(&xhci->lock); return IRQ_HANDLED; } event_ring_deq = xhci->event_ring->dequeue; /* FIXME this should be a delayed service routine * that clears the EHB. */ while (xhci_handle_event(xhci) > 0) {} temp_64 = xhci_read_64(xhci, &xhci->ir_set->erst_dequeue); /* If necessary, update the HW's version of the event ring deq ptr. */ if (event_ring_deq != xhci->event_ring->dequeue) { deq = xhci_trb_virt_to_dma(xhci->event_ring->deq_seg, xhci->event_ring->dequeue); if (deq == 0) xhci_warn(xhci, "WARN something wrong with SW event " "ring dequeue ptr.\n"); /* Update HC event ring dequeue pointer */ temp_64 &= ERST_PTR_MASK; temp_64 |= ((u64) deq & (u64) ~ERST_PTR_MASK); } /* Clear the event handler busy flag (RW1C); event ring is empty. */ temp_64 |= ERST_EHB; xhci_write_64(xhci, temp_64, &xhci->ir_set->erst_dequeue); spin_unlock(&xhci->lock); return IRQ_HANDLED; } irqreturn_t xhci_msi_irq(int irq, struct usb_hcd *hcd) { return xhci_irq(hcd); } /**** Endpoint Ring Operations ****/ /* * Generic function for queueing a TRB on a ring. * The caller must have checked to make sure there's room on the ring. * * @more_trbs_coming: Will you enqueue more TRBs before calling * prepare_transfer()? */ static void queue_trb(struct xhci_hcd *xhci, struct xhci_ring *ring, bool more_trbs_coming, u32 field1, u32 field2, u32 field3, u32 field4) { struct xhci_generic_trb *trb; trb = &ring->enqueue->generic; trb->field[0] = cpu_to_le32(field1); trb->field[1] = cpu_to_le32(field2); trb->field[2] = cpu_to_le32(field3); trb->field[3] = cpu_to_le32(field4); inc_enq(xhci, ring, more_trbs_coming); } /* * Does various checks on the endpoint ring, and makes it ready to queue num_trbs. * FIXME allocate segments if the ring is full. */ static int prepare_ring(struct xhci_hcd *xhci, struct xhci_ring *ep_ring, u32 ep_state, unsigned int num_trbs, gfp_t mem_flags) { unsigned int num_trbs_needed; /* Make sure the endpoint has been added to xHC schedule */ switch (ep_state) { case EP_STATE_DISABLED: /* * USB core changed config/interfaces without notifying us, * or hardware is reporting the wrong state. */ xhci_warn(xhci, "WARN urb submitted to disabled ep\n"); return -ENOENT; case EP_STATE_ERROR: xhci_warn(xhci, "WARN waiting for error on ep to be cleared\n"); /* FIXME event handling code for error needs to clear it */ /* XXX not sure if this should be -ENOENT or not */ return -EINVAL; case EP_STATE_HALTED: xhci_dbg(xhci, "WARN halted endpoint, queueing URB anyway.\n"); case EP_STATE_STOPPED: case EP_STATE_RUNNING: break; default: xhci_err(xhci, "ERROR unknown endpoint state for ep\n"); /* * FIXME issue Configure Endpoint command to try to get the HC * back into a known state. */ return -EINVAL; } while (1) { if (room_on_ring(xhci, ep_ring, num_trbs)) break; if (ep_ring == xhci->cmd_ring) { xhci_err(xhci, "Do not support expand command ring\n"); return -ENOMEM; } xhci_dbg(xhci, "ERROR no room on ep ring, " "try ring expansion\n"); num_trbs_needed = num_trbs - ep_ring->num_trbs_free; if (xhci_ring_expansion(xhci, ep_ring, num_trbs_needed, mem_flags)) { xhci_err(xhci, "Ring expansion failed\n"); return -ENOMEM; } }; if (enqueue_is_link_trb(ep_ring)) { struct xhci_ring *ring = ep_ring; union xhci_trb *next; next = ring->enqueue; while (last_trb(xhci, ring, ring->enq_seg, next)) { /* If we're not dealing with 0.95 hardware or isoc rings * on AMD 0.96 host, clear the chain bit. */ if (!xhci_link_trb_quirk(xhci) && !(ring->type == TYPE_ISOC && (xhci->quirks & XHCI_AMD_0x96_HOST))) next->link.control &= cpu_to_le32(~TRB_CHAIN); else next->link.control |= cpu_to_le32(TRB_CHAIN); wmb(); next->link.control ^= cpu_to_le32(TRB_CYCLE); /* Toggle the cycle bit after the last ring segment. */ if (last_trb_on_last_seg(xhci, ring, ring->enq_seg, next)) { ring->cycle_state = (ring->cycle_state ? 0 : 1); } ring->enq_seg = ring->enq_seg->next; ring->enqueue = ring->enq_seg->trbs; next = ring->enqueue; } } return 0; } static int prepare_transfer(struct xhci_hcd *xhci, struct xhci_virt_device *xdev, unsigned int ep_index, unsigned int stream_id, unsigned int num_trbs, struct urb *urb, unsigned int td_index, gfp_t mem_flags) { int ret; struct urb_priv *urb_priv; struct xhci_td *td; struct xhci_ring *ep_ring; struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); ep_ring = xhci_stream_id_to_ring(xdev, ep_index, stream_id); if (!ep_ring) { xhci_dbg(xhci, "Can't prepare ring for bad stream ID %u\n", stream_id); return -EINVAL; } ret = prepare_ring(xhci, ep_ring, le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK, num_trbs, mem_flags); if (ret) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[td_index]; INIT_LIST_HEAD(&td->td_list); INIT_LIST_HEAD(&td->cancelled_td_list); if (td_index == 0) { ret = usb_hcd_link_urb_to_ep(bus_to_hcd(urb->dev->bus), urb); if (unlikely(ret)) return ret; } td->urb = urb; /* Add this TD to the tail of the endpoint ring's TD list */ list_add_tail(&td->td_list, &ep_ring->td_list); td->start_seg = ep_ring->enq_seg; td->first_trb = ep_ring->enqueue; urb_priv->td[td_index] = td; return 0; } static unsigned int count_sg_trbs_needed(struct xhci_hcd *xhci, struct urb *urb) { int num_sgs, num_trbs, running_total, temp, i; struct scatterlist *sg; sg = NULL; num_sgs = urb->num_mapped_sgs; temp = urb->transfer_buffer_length; num_trbs = 0; for_each_sg(urb->sg, sg, num_sgs, i) { unsigned int len = sg_dma_len(sg); /* Scatter gather list entries may cross 64KB boundaries */ running_total = TRB_MAX_BUFF_SIZE - (sg_dma_address(sg) & (TRB_MAX_BUFF_SIZE - 1)); running_total &= TRB_MAX_BUFF_SIZE - 1; if (running_total != 0) num_trbs++; /* How many more 64KB chunks to transfer, how many more TRBs? */ while (running_total < sg_dma_len(sg) && running_total < temp) { num_trbs++; running_total += TRB_MAX_BUFF_SIZE; } len = min_t(int, len, temp); temp -= len; if (temp == 0) break; } return num_trbs; } static void check_trb_math(struct urb *urb, int num_trbs, int running_total) { if (num_trbs != 0) dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated number of " "TRBs, %d left\n", __func__, urb->ep->desc.bEndpointAddress, num_trbs); if (running_total != urb->transfer_buffer_length) dev_err(&urb->dev->dev, "%s - ep %#x - Miscalculated tx length, " "queued %#x (%d), asked for %#x (%d)\n", __func__, urb->ep->desc.bEndpointAddress, running_total, running_total, urb->transfer_buffer_length, urb->transfer_buffer_length); } static void giveback_first_trb(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, int start_cycle, struct xhci_generic_trb *start_trb) { /* * Pass all the TRBs to the hardware at once and make sure this write * isn't reordered. */ wmb(); if (start_cycle) start_trb->field[3] |= cpu_to_le32(start_cycle); else start_trb->field[3] &= cpu_to_le32(~TRB_CYCLE); xhci_ring_ep_doorbell(xhci, slot_id, ep_index, stream_id); } /* * xHCI uses normal TRBs for both bulk and interrupt. When the interrupt * endpoint is to be serviced, the xHC will consume (at most) one TD. A TD * (comprised of sg list entries) can take several service intervals to * transmit. */ int xhci_queue_intr_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ep_ctx *ep_ctx = xhci_get_ep_ctx(xhci, xhci->devs[slot_id]->out_ctx, ep_index); int xhci_interval; int ep_interval; xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info)); ep_interval = urb->interval; /* Convert to microframes */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) ep_interval *= 8; /* FIXME change this to a warning and a suggestion to use the new API * to set the polling interval (once the API is added). */ if (xhci_interval != ep_interval) { if (printk_ratelimit()) dev_dbg(&urb->dev->dev, "Driver uses different interval" " (%d microframe%s) than xHCI " "(%d microframe%s)\n", ep_interval, ep_interval == 1 ? "" : "s", xhci_interval, xhci_interval == 1 ? "" : "s"); urb->interval = xhci_interval; /* Convert back to frames for LS/FS devices */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->interval /= 8; } return xhci_queue_bulk_tx(xhci, mem_flags, urb, slot_id, ep_index); } /* * The TD size is the number of bytes remaining in the TD (including this TRB), * right shifted by 10. * It must fit in bits 21:17, so it can't be bigger than 31. */ static u32 xhci_td_remainder(unsigned int remainder) { u32 max = (1 << (21 - 17 + 1)) - 1; if ((remainder >> 10) >= max) return max << 17; else return (remainder >> 10) << 17; } /* * For xHCI 1.0 host controllers, TD size is the number of packets remaining in * the TD (*not* including this TRB). * * Total TD packet count = total_packet_count = * roundup(TD size in bytes / wMaxPacketSize) * * Packets transferred up to and including this TRB = packets_transferred = * rounddown(total bytes transferred including this TRB / wMaxPacketSize) * * TD size = total_packet_count - packets_transferred * * It must fit in bits 21:17, so it can't be bigger than 31. */ static u32 xhci_v1_0_td_remainder(int running_total, int trb_buff_len, unsigned int total_packet_count, struct urb *urb) { int packets_transferred; /* One TRB with a zero-length data packet. */ if (running_total == 0 && trb_buff_len == 0) return 0; /* All the TRB queueing functions don't count the current TRB in * running_total. */ packets_transferred = (running_total + trb_buff_len) / usb_endpoint_maxp(&urb->ep->desc); return xhci_td_remainder(total_packet_count - packets_transferred); } static int queue_bulk_sg_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; unsigned int num_trbs; struct urb_priv *urb_priv; struct xhci_td *td; struct scatterlist *sg; int num_sgs; int trb_buff_len, this_sg_len, running_total; unsigned int total_packet_count; bool first_trb; u64 addr; bool more_trbs_coming; struct xhci_generic_trb *start_trb; int start_cycle; ep_ring = xhci_urb_to_transfer_ring(xhci, urb); if (!ep_ring) return -EINVAL; num_trbs = count_sg_trbs_needed(xhci, urb); num_sgs = urb->num_mapped_sgs; total_packet_count = roundup(urb->transfer_buffer_length, usb_endpoint_maxp(&urb->ep->desc)); trb_buff_len = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (trb_buff_len < 0) return trb_buff_len; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; running_total = 0; /* * How much data is in the first TRB? * * There are three forces at work for TRB buffer pointers and lengths: * 1. We don't want to walk off the end of this sg-list entry buffer. * 2. The transfer length that the driver requested may be smaller than * the amount of memory allocated for this scatter-gather list. * 3. TRBs buffers can't cross 64KB boundaries. */ sg = urb->sg; addr = (u64) sg_dma_address(sg); this_sg_len = sg_dma_len(sg); trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)); trb_buff_len = min_t(int, trb_buff_len, this_sg_len); if (trb_buff_len > urb->transfer_buffer_length) trb_buff_len = urb->transfer_buffer_length; first_trb = true; /* Queue the first TRB, even if it's zero-length */ do { u32 field = 0; u32 length_field = 0; u32 remainder = 0; /* Don't change the cycle bit of the first TRB until later */ if (first_trb) { first_trb = false; if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; /* Chain all the TRBs together; clear the chain bit in the last * TRB to indicate it's the last TRB in the chain. */ if (num_trbs > 1) { field |= TRB_CHAIN; } else { /* FIXME - add check for ZERO_PACKET flag before this */ td->last_trb = ep_ring->enqueue; field |= TRB_IOC; } /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; if (TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)) < trb_buff_len) { xhci_warn(xhci, "WARN: sg dma xfer crosses 64KB boundaries!\n"); xhci_dbg(xhci, "Next boundary at %#x, end dma = %#x\n", (unsigned int) (addr + TRB_MAX_BUFF_SIZE) & ~(TRB_MAX_BUFF_SIZE - 1), (unsigned int) addr + trb_buff_len); } /* Set the TRB length, TD size, and interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( urb->transfer_buffer_length - running_total); } else { remainder = xhci_v1_0_td_remainder(running_total, trb_buff_len, total_packet_count, urb); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); if (num_trbs > 1) more_trbs_coming = true; else more_trbs_coming = false; queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field | TRB_TYPE(TRB_NORMAL)); --num_trbs; running_total += trb_buff_len; /* Calculate length for next transfer -- * Are we done queueing all the TRBs for this sg entry? */ this_sg_len -= trb_buff_len; if (this_sg_len == 0) { --num_sgs; if (num_sgs == 0) break; sg = sg_next(sg); addr = (u64) sg_dma_address(sg); this_sg_len = sg_dma_len(sg); } else { addr += trb_buff_len; } trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & (TRB_MAX_BUFF_SIZE - 1)); trb_buff_len = min_t(int, trb_buff_len, this_sg_len); if (running_total + trb_buff_len > urb->transfer_buffer_length) trb_buff_len = urb->transfer_buffer_length - running_total; } while (running_total < urb->transfer_buffer_length); check_trb_math(urb, num_trbs, running_total); giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; } /* This is very similar to what ehci-q.c qtd_fill() does */ int xhci_queue_bulk_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct xhci_td *td; int num_trbs; struct xhci_generic_trb *start_trb; bool first_trb; bool more_trbs_coming; int start_cycle; u32 field, length_field; int running_total, trb_buff_len, ret; unsigned int total_packet_count; u64 addr; if (urb->num_sgs) return queue_bulk_sg_tx(xhci, mem_flags, urb, slot_id, ep_index); ep_ring = xhci_urb_to_transfer_ring(xhci, urb); if (!ep_ring) return -EINVAL; num_trbs = 0; /* How much data is (potentially) left before the 64KB boundary? */ running_total = TRB_MAX_BUFF_SIZE - (urb->transfer_dma & (TRB_MAX_BUFF_SIZE - 1)); running_total &= TRB_MAX_BUFF_SIZE - 1; /* If there's some data on this 64KB chunk, or we have to send a * zero-length transfer, we need at least one TRB */ if (running_total != 0 || urb->transfer_buffer_length == 0) num_trbs++; /* How many more 64KB chunks to transfer, how many more TRBs? */ while (running_total < urb->transfer_buffer_length) { num_trbs++; running_total += TRB_MAX_BUFF_SIZE; } /* FIXME: this doesn't deal with URB_ZERO_PACKET - need one more */ ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (ret < 0) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; running_total = 0; total_packet_count = roundup(urb->transfer_buffer_length, usb_endpoint_maxp(&urb->ep->desc)); /* How much data is in the first TRB? */ addr = (u64) urb->transfer_dma; trb_buff_len = TRB_MAX_BUFF_SIZE - (urb->transfer_dma & (TRB_MAX_BUFF_SIZE - 1)); if (trb_buff_len > urb->transfer_buffer_length) trb_buff_len = urb->transfer_buffer_length; first_trb = true; /* Queue the first TRB, even if it's zero-length */ do { u32 remainder = 0; field = 0; /* Don't change the cycle bit of the first TRB until later */ if (first_trb) { first_trb = false; if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; /* Chain all the TRBs together; clear the chain bit in the last * TRB to indicate it's the last TRB in the chain. */ if (num_trbs > 1) { field |= TRB_CHAIN; } else { /* FIXME - add check for ZERO_PACKET flag before this */ td->last_trb = ep_ring->enqueue; field |= TRB_IOC; } /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; /* Set the TRB length, TD size, and interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( urb->transfer_buffer_length - running_total); } else { remainder = xhci_v1_0_td_remainder(running_total, trb_buff_len, total_packet_count, urb); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); if (num_trbs > 1) more_trbs_coming = true; else more_trbs_coming = false; queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field | TRB_TYPE(TRB_NORMAL)); --num_trbs; running_total += trb_buff_len; /* Calculate length for next transfer */ addr += trb_buff_len; trb_buff_len = urb->transfer_buffer_length - running_total; if (trb_buff_len > TRB_MAX_BUFF_SIZE) trb_buff_len = TRB_MAX_BUFF_SIZE; } while (running_total < urb->transfer_buffer_length); check_trb_math(urb, num_trbs, running_total); giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; } /* Caller must have locked xhci->lock */ int xhci_queue_ctrl_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; int num_trbs; int ret; struct usb_ctrlrequest *setup; struct xhci_generic_trb *start_trb; int start_cycle; u32 field, length_field; struct urb_priv *urb_priv; struct xhci_td *td; ep_ring = xhci_urb_to_transfer_ring(xhci, urb); if (!ep_ring) return -EINVAL; /* * Need to copy setup packet into setup TRB, so we can't use the setup * DMA address. */ if (!urb->setup_packet) return -EINVAL; /* 1 TRB for setup, 1 for status */ num_trbs = 2; /* * Don't need to check if we need additional event data and normal TRBs, * since data in control transfers will never get bigger than 16MB * XXX: can we get a buffer that crosses 64KB boundaries? */ if (urb->transfer_buffer_length > 0) num_trbs++; ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, num_trbs, urb, 0, mem_flags); if (ret < 0) return ret; urb_priv = urb->hcpriv; td = urb_priv->td[0]; /* * Don't give the first TRB to the hardware (by toggling the cycle bit) * until we've finished creating all the other TRBs. The ring's cycle * state may change as we enqueue the other TRBs, so save it too. */ start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; /* Queue setup TRB - see section 6.4.1.2.1 */ /* FIXME better way to translate setup_packet into two u32 fields? */ setup = (struct usb_ctrlrequest *) urb->setup_packet; field = 0; field |= TRB_IDT | TRB_TYPE(TRB_SETUP); if (start_cycle == 0) field |= 0x1; /* xHCI 1.0 6.4.1.2.1: Transfer Type field */ if (xhci->hci_version == 0x100) { if (urb->transfer_buffer_length > 0) { if (setup->bRequestType & USB_DIR_IN) field |= TRB_TX_TYPE(TRB_DATA_IN); else field |= TRB_TX_TYPE(TRB_DATA_OUT); } } queue_trb(xhci, ep_ring, true, setup->bRequestType | setup->bRequest << 8 | le16_to_cpu(setup->wValue) << 16, le16_to_cpu(setup->wIndex) | le16_to_cpu(setup->wLength) << 16, TRB_LEN(8) | TRB_INTR_TARGET(0), /* Immediate data in pointer */ field); /* If there's data, queue data TRBs */ /* Only set interrupt on short packet for IN endpoints */ if (usb_urb_dir_in(urb)) field = TRB_ISP | TRB_TYPE(TRB_DATA); else field = TRB_TYPE(TRB_DATA); length_field = TRB_LEN(urb->transfer_buffer_length) | xhci_td_remainder(urb->transfer_buffer_length) | TRB_INTR_TARGET(0); if (urb->transfer_buffer_length > 0) { if (setup->bRequestType & USB_DIR_IN) field |= TRB_DIR_IN; queue_trb(xhci, ep_ring, true, lower_32_bits(urb->transfer_dma), upper_32_bits(urb->transfer_dma), length_field, field | ep_ring->cycle_state); } /* Save the DMA address of the last TRB in the TD */ td->last_trb = ep_ring->enqueue; /* Queue status TRB - see Table 7 and sections 4.11.2.2 and 6.4.1.2.3 */ /* If the device sent data, the status stage is an OUT transfer */ if (urb->transfer_buffer_length > 0 && setup->bRequestType & USB_DIR_IN) field = 0; else field = TRB_DIR_IN; queue_trb(xhci, ep_ring, false, 0, 0, TRB_INTR_TARGET(0), /* Event on completion */ field | TRB_IOC | TRB_TYPE(TRB_STATUS) | ep_ring->cycle_state); giveback_first_trb(xhci, slot_id, ep_index, 0, start_cycle, start_trb); return 0; } static int count_isoc_trbs_needed(struct xhci_hcd *xhci, struct urb *urb, int i) { int num_trbs = 0; u64 addr, td_len; addr = (u64) (urb->transfer_dma + urb->iso_frame_desc[i].offset); td_len = urb->iso_frame_desc[i].length; num_trbs = DIV_ROUND_UP(td_len + (addr & (TRB_MAX_BUFF_SIZE - 1)), TRB_MAX_BUFF_SIZE); if (num_trbs == 0) num_trbs++; return num_trbs; } /* * The transfer burst count field of the isochronous TRB defines the number of * bursts that are required to move all packets in this TD. Only SuperSpeed * devices can burst up to bMaxBurst number of packets per service interval. * This field is zero based, meaning a value of zero in the field means one * burst. Basically, for everything but SuperSpeed devices, this field will be * zero. Only xHCI 1.0 host controllers support this field. */ static unsigned int xhci_get_burst_count(struct xhci_hcd *xhci, struct usb_device *udev, struct urb *urb, unsigned int total_packet_count) { unsigned int max_burst; if (xhci->hci_version < 0x100 || udev->speed != USB_SPEED_SUPER) return 0; max_burst = urb->ep->ss_ep_comp.bMaxBurst; return roundup(total_packet_count, max_burst + 1) - 1; } /* * Returns the number of packets in the last "burst" of packets. This field is * valid for all speeds of devices. USB 2.0 devices can only do one "burst", so * the last burst packet count is equal to the total number of packets in the * TD. SuperSpeed endpoints can have up to 3 bursts. All but the last burst * must contain (bMaxBurst + 1) number of packets, but the last burst can * contain 1 to (bMaxBurst + 1) packets. */ static unsigned int xhci_get_last_burst_packet_count(struct xhci_hcd *xhci, struct usb_device *udev, struct urb *urb, unsigned int total_packet_count) { unsigned int max_burst; unsigned int residue; if (xhci->hci_version < 0x100) return 0; switch (udev->speed) { case USB_SPEED_SUPER: /* bMaxBurst is zero based: 0 means 1 packet per burst */ max_burst = urb->ep->ss_ep_comp.bMaxBurst; residue = total_packet_count % (max_burst + 1); /* If residue is zero, the last burst contains (max_burst + 1) * number of packets, but the TLBPC field is zero-based. */ if (residue == 0) return max_burst; return residue - 1; default: if (total_packet_count == 0) return 0; return total_packet_count - 1; } } /* This is for isoc transfer */ static int xhci_queue_isoc_tx(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_ring *ep_ring; struct urb_priv *urb_priv; struct xhci_td *td; int num_tds, trbs_per_td; struct xhci_generic_trb *start_trb; bool first_trb; int start_cycle; u32 field, length_field; int running_total, trb_buff_len, td_len, td_remain_len, ret; u64 start_addr, addr; int i, j; bool more_trbs_coming; ep_ring = xhci->devs[slot_id]->eps[ep_index].ring; num_tds = urb->number_of_packets; if (num_tds < 1) { xhci_dbg(xhci, "Isoc URB with zero packets?\n"); return -EINVAL; } start_addr = (u64) urb->transfer_dma; start_trb = &ep_ring->enqueue->generic; start_cycle = ep_ring->cycle_state; urb_priv = urb->hcpriv; /* Queue the first TRB, even if it's zero-length */ for (i = 0; i < num_tds; i++) { unsigned int total_packet_count; unsigned int burst_count; unsigned int residue; first_trb = true; running_total = 0; addr = start_addr + urb->iso_frame_desc[i].offset; td_len = urb->iso_frame_desc[i].length; td_remain_len = td_len; total_packet_count = roundup(td_len, usb_endpoint_maxp(&urb->ep->desc)); /* A zero-length transfer still involves at least one packet. */ if (total_packet_count == 0) total_packet_count++; burst_count = xhci_get_burst_count(xhci, urb->dev, urb, total_packet_count); residue = xhci_get_last_burst_packet_count(xhci, urb->dev, urb, total_packet_count); trbs_per_td = count_isoc_trbs_needed(xhci, urb, i); ret = prepare_transfer(xhci, xhci->devs[slot_id], ep_index, urb->stream_id, trbs_per_td, urb, i, mem_flags); if (ret < 0) { if (i == 0) return ret; goto cleanup; } td = urb_priv->td[i]; for (j = 0; j < trbs_per_td; j++) { u32 remainder = 0; field = TRB_TBC(burst_count) | TRB_TLBPC(residue); if (first_trb) { /* Queue the isoc TRB */ field |= TRB_TYPE(TRB_ISOC); /* Assume URB_ISO_ASAP is set */ field |= TRB_SIA; if (i == 0) { if (start_cycle == 0) field |= 0x1; } else field |= ep_ring->cycle_state; first_trb = false; } else { /* Queue other normal TRBs */ field |= TRB_TYPE(TRB_NORMAL); field |= ep_ring->cycle_state; } /* Only set interrupt on short packet for IN EPs */ if (usb_urb_dir_in(urb)) field |= TRB_ISP; /* Chain all the TRBs together; clear the chain bit in * the last TRB to indicate it's the last TRB in the * chain. */ if (j < trbs_per_td - 1) { field |= TRB_CHAIN; more_trbs_coming = true; } else { td->last_trb = ep_ring->enqueue; field |= TRB_IOC; if (xhci->hci_version == 0x100) { /* Set BEI bit except for the last td */ if (i < num_tds - 1) field |= TRB_BEI; } more_trbs_coming = false; } /* Calculate TRB length */ trb_buff_len = TRB_MAX_BUFF_SIZE - (addr & ((1 << TRB_MAX_BUFF_SHIFT) - 1)); if (trb_buff_len > td_remain_len) trb_buff_len = td_remain_len; /* Set the TRB length, TD size, & interrupter fields. */ if (xhci->hci_version < 0x100) { remainder = xhci_td_remainder( td_len - running_total); } else { remainder = xhci_v1_0_td_remainder( running_total, trb_buff_len, total_packet_count, urb); } length_field = TRB_LEN(trb_buff_len) | remainder | TRB_INTR_TARGET(0); queue_trb(xhci, ep_ring, more_trbs_coming, lower_32_bits(addr), upper_32_bits(addr), length_field, field); running_total += trb_buff_len; addr += trb_buff_len; td_remain_len -= trb_buff_len; } /* Check TD length */ if (running_total != td_len) { xhci_err(xhci, "ISOC TD length unmatch\n"); ret = -EINVAL; goto cleanup; } } if (xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs == 0) { if (xhci->quirks & XHCI_AMD_PLL_FIX) usb_amd_quirk_pll_disable(); } xhci_to_hcd(xhci)->self.bandwidth_isoc_reqs++; giveback_first_trb(xhci, slot_id, ep_index, urb->stream_id, start_cycle, start_trb); return 0; cleanup: /* Clean up a partially enqueued isoc transfer. */ for (i--; i >= 0; i--) list_del_init(&urb_priv->td[i]->td_list); /* Use the first TD as a temporary variable to turn the TDs we've queued * into No-ops with a software-owned cycle bit. That way the hardware * won't accidentally start executing bogus TDs when we partially * overwrite them. td->first_trb and td->start_seg are already set. */ urb_priv->td[0]->last_trb = ep_ring->enqueue; /* Every TRB except the first & last will have its cycle bit flipped. */ td_to_noop(xhci, ep_ring, urb_priv->td[0], true); /* Reset the ring enqueue back to the first TRB and its cycle bit. */ ep_ring->enqueue = urb_priv->td[0]->first_trb; ep_ring->enq_seg = urb_priv->td[0]->start_seg; ep_ring->cycle_state = start_cycle; ep_ring->num_trbs_free = ep_ring->num_trbs_free_temp; usb_hcd_unlink_urb_from_ep(bus_to_hcd(urb->dev->bus), urb); return ret; } /* * Check transfer ring to guarantee there is enough room for the urb. * Update ISO URB start_frame and interval. * Update interval as xhci_queue_intr_tx does. Just use xhci frame_index to * update the urb->start_frame by now. * Always assume URB_ISO_ASAP set, and NEVER use urb->start_frame as input. */ int xhci_queue_isoc_tx_prepare(struct xhci_hcd *xhci, gfp_t mem_flags, struct urb *urb, int slot_id, unsigned int ep_index) { struct xhci_virt_device *xdev; struct xhci_ring *ep_ring; struct xhci_ep_ctx *ep_ctx; int start_frame; int xhci_interval; int ep_interval; int num_tds, num_trbs, i; int ret; xdev = xhci->devs[slot_id]; ep_ring = xdev->eps[ep_index].ring; ep_ctx = xhci_get_ep_ctx(xhci, xdev->out_ctx, ep_index); num_trbs = 0; num_tds = urb->number_of_packets; for (i = 0; i < num_tds; i++) num_trbs += count_isoc_trbs_needed(xhci, urb, i); /* Check the ring to guarantee there is enough room for the whole urb. * Do not insert any td of the urb to the ring if the check failed. */ ret = prepare_ring(xhci, ep_ring, le32_to_cpu(ep_ctx->ep_info) & EP_STATE_MASK, num_trbs, mem_flags); if (ret) return ret; start_frame = xhci_readl(xhci, &xhci->run_regs->microframe_index); start_frame &= 0x3fff; urb->start_frame = start_frame; if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->start_frame >>= 3; xhci_interval = EP_INTERVAL_TO_UFRAMES(le32_to_cpu(ep_ctx->ep_info)); ep_interval = urb->interval; /* Convert to microframes */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) ep_interval *= 8; /* FIXME change this to a warning and a suggestion to use the new API * to set the polling interval (once the API is added). */ if (xhci_interval != ep_interval) { if (printk_ratelimit()) dev_dbg(&urb->dev->dev, "Driver uses different interval" " (%d microframe%s) than xHCI " "(%d microframe%s)\n", ep_interval, ep_interval == 1 ? "" : "s", xhci_interval, xhci_interval == 1 ? "" : "s"); urb->interval = xhci_interval; /* Convert back to frames for LS/FS devices */ if (urb->dev->speed == USB_SPEED_LOW || urb->dev->speed == USB_SPEED_FULL) urb->interval /= 8; } ep_ring->num_trbs_free_temp = ep_ring->num_trbs_free; return xhci_queue_isoc_tx(xhci, mem_flags, urb, slot_id, ep_index); } /**** Command Ring Operations ****/ /* Generic function for queueing a command TRB on the command ring. * Check to make sure there's room on the command ring for one command TRB. * Also check that there's room reserved for commands that must not fail. * If this is a command that must not fail, meaning command_must_succeed = TRUE, * then only check for the number of reserved spots. * Don't decrement xhci->cmd_ring_reserved_trbs after we've queued the TRB * because the command event handler may want to resubmit a failed command. */ static int queue_command(struct xhci_hcd *xhci, u32 field1, u32 field2, u32 field3, u32 field4, bool command_must_succeed) { int reserved_trbs = xhci->cmd_ring_reserved_trbs; int ret; if (!command_must_succeed) reserved_trbs++; ret = prepare_ring(xhci, xhci->cmd_ring, EP_STATE_RUNNING, reserved_trbs, GFP_ATOMIC); if (ret < 0) { xhci_err(xhci, "ERR: No room for command on command ring\n"); if (command_must_succeed) xhci_err(xhci, "ERR: Reserved TRB counting for " "unfailable commands failed.\n"); return ret; } queue_trb(xhci, xhci->cmd_ring, false, field1, field2, field3, field4 | xhci->cmd_ring->cycle_state); return 0; } /* Queue a slot enable or disable request on the command ring */ int xhci_queue_slot_control(struct xhci_hcd *xhci, u32 trb_type, u32 slot_id) { return queue_command(xhci, 0, 0, 0, TRB_TYPE(trb_type) | SLOT_ID_FOR_TRB(slot_id), false); } /* Queue an address device command TRB */ int xhci_queue_address_device(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_ADDR_DEV) | SLOT_ID_FOR_TRB(slot_id), false); } int xhci_queue_vendor_command(struct xhci_hcd *xhci, u32 field1, u32 field2, u32 field3, u32 field4) { return queue_command(xhci, field1, field2, field3, field4, false); } /* Queue a reset device command TRB */ int xhci_queue_reset_device(struct xhci_hcd *xhci, u32 slot_id) { return queue_command(xhci, 0, 0, 0, TRB_TYPE(TRB_RESET_DEV) | SLOT_ID_FOR_TRB(slot_id), false); } /* Queue a configure endpoint command TRB */ int xhci_queue_configure_endpoint(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id, bool command_must_succeed) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_CONFIG_EP) | SLOT_ID_FOR_TRB(slot_id), command_must_succeed); } /* Queue an evaluate context command TRB */ int xhci_queue_evaluate_context(struct xhci_hcd *xhci, dma_addr_t in_ctx_ptr, u32 slot_id) { return queue_command(xhci, lower_32_bits(in_ctx_ptr), upper_32_bits(in_ctx_ptr), 0, TRB_TYPE(TRB_EVAL_CONTEXT) | SLOT_ID_FOR_TRB(slot_id), false); } /* * Suspend is set to indicate "Stop Endpoint Command" is being issued to stop * activity on an endpoint that is about to be suspended. */ int xhci_queue_stop_endpoint(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, int suspend) { u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 type = TRB_TYPE(TRB_STOP_RING); u32 trb_suspend = SUSPEND_PORT_FOR_TRB(suspend); return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type | trb_suspend, false); } /* Set Transfer Ring Dequeue Pointer command. * This should not be used for endpoints that have streams enabled. */ static int queue_set_tr_deq(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index, unsigned int stream_id, struct xhci_segment *deq_seg, union xhci_trb *deq_ptr, u32 cycle_state) { dma_addr_t addr; u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 trb_stream_id = STREAM_ID_FOR_TRB(stream_id); u32 type = TRB_TYPE(TRB_SET_DEQ); struct xhci_virt_ep *ep; addr = xhci_trb_virt_to_dma(deq_seg, deq_ptr); if (addr == 0) { xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n"); xhci_warn(xhci, "WARN deq seg = %p, deq pt = %p\n", deq_seg, deq_ptr); return 0; } ep = &xhci->devs[slot_id]->eps[ep_index]; if ((ep->ep_state & SET_DEQ_PENDING)) { xhci_warn(xhci, "WARN Cannot submit Set TR Deq Ptr\n"); xhci_warn(xhci, "A Set TR Deq Ptr command is pending.\n"); return 0; } ep->queued_deq_seg = deq_seg; ep->queued_deq_ptr = deq_ptr; return queue_command(xhci, lower_32_bits(addr) | cycle_state, upper_32_bits(addr), trb_stream_id, trb_slot_id | trb_ep_index | type, false); } int xhci_queue_reset_ep(struct xhci_hcd *xhci, int slot_id, unsigned int ep_index) { u32 trb_slot_id = SLOT_ID_FOR_TRB(slot_id); u32 trb_ep_index = EP_ID_FOR_TRB(ep_index); u32 type = TRB_TYPE(TRB_RESET_EP); return queue_command(xhci, 0, 0, 0, trb_slot_id | trb_ep_index | type, false); }
Java
/* * Copyright (c) 2009-2013, 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. * */ #include <linux/module.h> #include <linux/kernel.h> #include <linux/sched.h> #include <linux/time.h> #include <linux/init.h> #include <linux/interrupt.h> #include <linux/spinlock.h> #include <linux/hrtimer.h> #include <linux/clk.h> #include <mach/hardware.h> #include <mach/iommu_domains.h> #include <mach/iommu.h> #include <linux/iommu.h> #include <linux/io.h> #include <linux/debugfs.h> #include <linux/fb.h> #include <linux/msm_mdp.h> #include <linux/file.h> #include <linux/android_pmem.h> #include <linux/major.h> #include <asm/system.h> #include <asm/mach-types.h> #include <linux/semaphore.h> #include <linux/uaccess.h> #include <linux/mutex.h> #include <linux/msm_kgsl.h> #include "mdp.h" #include "msm_fb.h" #include "mdp4.h" #define VERSION_KEY_MASK 0xFFFFFF00 struct mdp4_overlay_ctrl { struct mdp4_overlay_pipe plist[OVERLAY_PIPE_MAX]; struct mdp4_overlay_pipe *stage[MDP4_MIXER_MAX][MDP4_MIXER_STAGE_MAX]; struct mdp4_overlay_pipe *baselayer[MDP4_MIXER_MAX]; struct blend_cfg blend[MDP4_MIXER_MAX][MDP4_MIXER_STAGE_MAX]; uint32 mixer_cfg[MDP4_MIXER_MAX]; uint32 flush[MDP4_MIXER_MAX]; struct iommu_free_list iommu_free[MDP4_MIXER_MAX]; struct iommu_free_list iommu_free_prev[MDP4_MIXER_MAX]; uint32 dmap_cfg[5]; uint32 cs_controller; uint32 panel_3d; uint32 panel_mode; uint32 mixer0_played; uint32 mixer1_played; uint32 mixer2_played; } mdp4_overlay_db = { .cs_controller = CS_CONTROLLER_0, .plist = { { .pipe_type = OVERLAY_TYPE_RGB, .pipe_num = OVERLAY_PIPE_RGB1, .pipe_ndx = 1, }, { .pipe_type = OVERLAY_TYPE_RGB, .pipe_num = OVERLAY_PIPE_RGB2, .pipe_ndx = 2, }, { .pipe_type = OVERLAY_TYPE_VIDEO, .pipe_num = OVERLAY_PIPE_VG1, .pipe_ndx = 3, }, { .pipe_type = OVERLAY_TYPE_VIDEO, .pipe_num = OVERLAY_PIPE_VG2, .pipe_ndx = 4, }, { .pipe_type = OVERLAY_TYPE_BF, .pipe_num = OVERLAY_PIPE_RGB3, .pipe_ndx = 5, .mixer_num = MDP4_MIXER0, }, { .pipe_type = OVERLAY_TYPE_BF, .pipe_num = OVERLAY_PIPE_VG3, .pipe_ndx = 6, .mixer_num = MDP4_MIXER1, }, { .pipe_type = OVERLAY_TYPE_BF, .pipe_num = OVERLAY_PIPE_VG4, .pipe_ndx = 7, .mixer_num = MDP4_MIXER2, }, }, }; static DEFINE_MUTEX(iommu_mutex); static DEFINE_MUTEX(perf_mutex); static struct mdp4_overlay_ctrl *ctrl = &mdp4_overlay_db; struct mdp4_overlay_perf { u32 mdp_clk_rate; u32 use_ov_blt[MDP4_MIXER_MAX]; u64 mdp_ov_ab_bw[MDP4_MIXER_MAX]; u64 mdp_ov_ib_bw[MDP4_MIXER_MAX]; u32 mdp_ab_bw; u32 mdp_ib_bw; }; static struct mdp4_overlay_perf perf_request; static struct mdp4_overlay_perf perf_current; void mdp4_overlay_free_base_pipe(struct msm_fb_data_type *mfd) { if (!hdmi_prim_display && mfd->index == 0) { if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_free_base_pipe(mfd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_free_base_pipe(mfd); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_free_base_pipe(mfd); } else if (hdmi_prim_display || mfd->index == 1) { mdp4_dtv_free_base_pipe(mfd); } } static struct ion_client *display_iclient; static int mdp4_map_sec_resource(struct msm_fb_data_type *mfd) { int ret = 0; if (!mfd) { pr_err("%s: mfd is invalid\n", __func__); return -ENODEV; } pr_debug("%s %d mfd->index=%d,mapped=%d\n", __func__, __LINE__, mfd->index, mfd->sec_mapped); if (mfd->sec_mapped) return 0; ret = mdp_enable_iommu_clocks(); if (ret) { pr_err("IOMMU clock enabled failed while open"); return ret; } ret = msm_ion_secure_heap(ION_HEAP(ION_CP_MM_HEAP_ID)); if (ret) pr_err("ION heap secure failed heap id %d ret %d\n", ION_CP_MM_HEAP_ID, ret); else mfd->sec_mapped = 1; mdp_disable_iommu_clocks(); return ret; } int mdp4_unmap_sec_resource(struct msm_fb_data_type *mfd) { int ret = 0; int i, sec_cnt = 0; struct mdp4_overlay_pipe *pipe; if (!mfd) { pr_err("%s: mfd is invalid\n", __func__); return -ENODEV; } if (mfd->sec_mapped == 0) return 0; for (i = 0; i < OVERLAY_PIPE_MAX; i++) { pipe = &ctrl->plist[i]; if ((pipe->mixer_num == mfd->index) && pipe->flags & MDP_SECURE_OVERLAY_SESSION) sec_cnt++; } if (sec_cnt) return 0; pr_debug("%s %d mfd->index=%d,mapped=%d\n", __func__, __LINE__, mfd->index, mfd->sec_mapped); ret = mdp_enable_iommu_clocks(); if (ret) { pr_err("IOMMU clock enabled failed while close\n"); return ret; } msm_ion_unsecure_heap(ION_HEAP(ION_CP_MM_HEAP_ID)); mfd->sec_mapped = 0; mdp_disable_iommu_clocks(); return ret; } /* * mdp4_overlay_iommu_unmap_freelist() * mdp4_overlay_iommu_2freelist() * mdp4_overlay_iommu_pipe_free() * above three functiosns need to be called from same thread and * in order so that no mutex are needed. */ void mdp4_overlay_iommu_unmap_freelist(int mixer) { int i; struct ion_handle *ihdl; struct iommu_free_list *flist, *pflist; if (mixer >= MDP4_MIXER_MAX) return; mutex_lock(&iommu_mutex); pflist = &ctrl->iommu_free_prev[mixer]; flist = &ctrl->iommu_free[mixer]; pr_debug("%s: mixer=%d fndx=%d %d\n", __func__, mixer, pflist->fndx, flist->fndx); if (pflist->fndx == 0) { goto flist_to_pflist; } for (i = 0; i < IOMMU_FREE_LIST_MAX; i++) { ihdl = pflist->ihdl[i]; if (ihdl == NULL) continue; pr_debug("%s: mixer=%d i=%d ihdl=0x%p\n", __func__, mixer, i, ihdl); ion_unmap_iommu(display_iclient, ihdl, DISPLAY_READ_DOMAIN, GEN_POOL); mdp4_stat.iommu_unmap++; pr_debug("%s: map=%d unmap=%d drop=%d\n", __func__, (int)mdp4_stat.iommu_map, (int)mdp4_stat.iommu_unmap, (int)mdp4_stat.iommu_drop); ion_free(display_iclient, ihdl); } flist_to_pflist: /* move flist to pflist*/ memcpy(pflist, flist, sizeof(*pflist)); memset(flist, 0, sizeof(*flist)); mutex_unlock(&iommu_mutex); } void mdp4_overlay_iommu_2freelist(int mixer, struct ion_handle *ihdl) { struct iommu_free_list *flist; flist = &ctrl->iommu_free[mixer]; if (flist->fndx >= IOMMU_FREE_LIST_MAX) { pr_err("%s: Error, mixer=%d iommu fndx=%d\n", __func__, mixer, flist->fndx); mdp4_stat.iommu_drop++; return; } pr_debug("%s: add mixer=%d fndx=%d ihdl=0x%p\n", __func__, mixer, flist->fndx, ihdl); flist->ihdl[flist->fndx++] = ihdl; } void mdp4_overlay_iommu_pipe_free(int ndx, int all) { struct mdp4_overlay_pipe *pipe; struct mdp4_iommu_pipe_info *iom; int plane, mixer; pipe = mdp4_overlay_ndx2pipe(ndx); if (pipe == NULL) return; if (pipe->flags & MDP_MEMORY_ID_TYPE_FB) { pipe->flags &= ~MDP_MEMORY_ID_TYPE_FB; if (pipe->put0_need) { fput_light(pipe->srcp0_file, pipe->put0_need); pipe->put0_need = 0; } if (pipe->put1_need) { fput_light(pipe->srcp1_file, pipe->put1_need); pipe->put1_need = 0; } if (pipe->put2_need) { fput_light(pipe->srcp2_file, pipe->put2_need); pipe->put2_need = 0; } pr_debug("%s: ndx=%d flags=%x put=%d\n", __func__, pipe->pipe_ndx, pipe->flags, pipe->put0_need); return; } mutex_lock(&iommu_mutex); mixer = pipe->mixer_num; iom = &pipe->iommu; pr_debug("%s: mixer=%d ndx=%d all=%d\n", __func__, mixer, pipe->pipe_ndx, all); for (plane = 0; plane < MDP4_MAX_PLANE; plane++) { if (iom->prev_ihdl[plane]) { mdp4_overlay_iommu_2freelist(mixer, iom->prev_ihdl[plane]); iom->prev_ihdl[plane] = NULL; } if (all && iom->ihdl[plane]) { mdp4_overlay_iommu_2freelist(mixer, iom->ihdl[plane]); iom->ihdl[plane] = NULL; } } mutex_unlock(&iommu_mutex); } int mdp4_overlay_iommu_map_buf(int mem_id, struct mdp4_overlay_pipe *pipe, unsigned int plane, unsigned long *start, unsigned long *len, struct ion_handle **srcp_ihdl) { struct mdp4_iommu_pipe_info *iom; if (!display_iclient) return -EINVAL; *srcp_ihdl = ion_import_dma_buf(display_iclient, mem_id); if (IS_ERR_OR_NULL(*srcp_ihdl)) { pr_err("ion_import_dma_buf() failed\n"); return PTR_ERR(*srcp_ihdl); } pr_debug("%s(): ion_hdl %p, ion_buf %d\n", __func__, *srcp_ihdl, ion_share_dma_buf(display_iclient, *srcp_ihdl)); pr_debug("mixer %u, pipe %u, plane %u\n", pipe->mixer_num, pipe->pipe_ndx, plane); if (ion_map_iommu(display_iclient, *srcp_ihdl, DISPLAY_READ_DOMAIN, GEN_POOL, SZ_4K, 0, start, len, 0, 0)) { ion_free(display_iclient, *srcp_ihdl); pr_err("ion_map_iommu() failed\n"); return -EINVAL; } mutex_lock(&iommu_mutex); iom = &pipe->iommu; if (iom->prev_ihdl[plane]) { mdp4_overlay_iommu_2freelist(pipe->mixer_num, iom->prev_ihdl[plane]); mdp4_stat.iommu_drop++; pr_err("%s: dropped, ndx=%d plane=%d\n", __func__, pipe->pipe_ndx, plane); } iom->prev_ihdl[plane] = iom->ihdl[plane]; iom->ihdl[plane] = *srcp_ihdl; mdp4_stat.iommu_map++; pr_debug("%s: ndx=%d plane=%d prev=0x%p cur=0x%p start=0x%lx len=%lx\n", __func__, pipe->pipe_ndx, plane, iom->prev_ihdl[plane], iom->ihdl[plane], *start, *len); mutex_unlock(&iommu_mutex); return 0; } static struct mdp4_iommu_pipe_info mdp_iommu[MDP4_MIXER_MAX][OVERLAY_PIPE_MAX]; void mdp4_iommu_unmap(struct mdp4_overlay_pipe *pipe) { struct mdp4_iommu_pipe_info *iom_pipe_info; unsigned char i, j; if (!display_iclient) return; for (j = 0; j < OVERLAY_PIPE_MAX; j++) { iom_pipe_info = &mdp_iommu[pipe->mixer_num][j]; for (i = 0; i < MDP4_MAX_PLANE; i++) { if (iom_pipe_info->prev_ihdl[i]) { pr_debug("%s(): mixer %u, pipe %u, plane %u, " "prev_ihdl %p\n", __func__, pipe->mixer_num, j + 1, i, iom_pipe_info->prev_ihdl[i]); ion_unmap_iommu(display_iclient, iom_pipe_info->prev_ihdl[i], DISPLAY_READ_DOMAIN, GEN_POOL); ion_free(display_iclient, iom_pipe_info->prev_ihdl[i]); iom_pipe_info->prev_ihdl[i] = NULL; } if (iom_pipe_info->mark_unmap) { if (iom_pipe_info->ihdl[i]) { pr_debug("%s(): MARK, mixer %u, pipe %u, plane %u, " "ihdl %p\n", __func__, pipe->mixer_num, j + 1, i, iom_pipe_info->ihdl[i]); ion_unmap_iommu(display_iclient, iom_pipe_info->ihdl[i], DISPLAY_READ_DOMAIN, GEN_POOL); ion_free(display_iclient, iom_pipe_info->ihdl[i]); iom_pipe_info->ihdl[i] = NULL; } } } iom_pipe_info->mark_unmap = 0; } } #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) static int panel_rotate_180 = 1; #endif int mdp4_overlay_mixer_play(int mixer_num) { if (mixer_num == MDP4_MIXER2) return ctrl->mixer2_played; else if (mixer_num == MDP4_MIXER1) return ctrl->mixer1_played; else return ctrl->mixer0_played; } void mdp4_overlay_panel_3d(int mixer_num, uint32 panel_3d) { ctrl->panel_3d = panel_3d; } void mdp4_overlay_panel_mode(int mixer_num, uint32 mode) { ctrl->panel_mode |= mode; } void mdp4_overlay_panel_mode_unset(int mixer_num, uint32 mode) { ctrl->panel_mode &= ~mode; } uint32 mdp4_overlay_panel_list(void) { return ctrl->panel_mode; } int mdp4_overlay_borderfill_supported(void) { return (mdp_rev >= MDP_REV_42); } void mdp4_overlay_dmae_cfg(struct msm_fb_data_type *mfd, int atv) { uint32 dmae_cfg_reg; if (atv) dmae_cfg_reg = DMA_DEFLKR_EN; else dmae_cfg_reg = 0; if (mfd->fb_imgType == MDP_BGR_565) dmae_cfg_reg |= DMA_PACK_PATTERN_BGR; else dmae_cfg_reg |= DMA_PACK_PATTERN_RGB; if (mfd->panel_info.bpp == 18) { dmae_cfg_reg |= DMA_DSTC0G_6BITS | /* 666 18BPP */ DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS; } else if (mfd->panel_info.bpp == 16) { dmae_cfg_reg |= DMA_DSTC0G_6BITS | /* 565 16BPP */ DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS; } else { dmae_cfg_reg |= DMA_DSTC0G_8BITS | /* 888 16BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* dma2 config register */ MDP_OUTP(MDP_BASE + 0xb0000, dmae_cfg_reg); if (atv) { MDP_OUTP(MDP_BASE + 0xb0070, 0xeb0010); MDP_OUTP(MDP_BASE + 0xb0074, 0xf00010); MDP_OUTP(MDP_BASE + 0xb0078, 0xf00010); MDP_OUTP(MDP_BASE + 0xb3000, 0x80); MDP_OUTP(MDP_BASE + 0xb3010, 0x1800040); MDP_OUTP(MDP_BASE + 0xb3014, 0x1000080); MDP_OUTP(MDP_BASE + 0xb4004, 0x67686970); } else { mdp_vid_quant_set(); } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } #ifdef CONFIG_FB_MSM_HDMI_3D void unfill_black_screen(void) { return; } #else void unfill_black_screen(void) { uint32 temp_src_format; mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* * VG2 Constant Color */ temp_src_format = inpdw(MDP_BASE + 0x30050); MDP_OUTP(MDP_BASE + 0x30050, temp_src_format&(~BIT(22))); /* * MDP_OVERLAY_REG_FLUSH */ MDP_OUTP(MDP_BASE + 0x18000, BIT(3)); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); return; } #endif #ifdef CONFIG_FB_MSM_HDMI_3D void fill_black_screen(void) { return; } #else void fill_black_screen(void) { /*Black color*/ uint32 color = 0x00000000; uint32 temp_src_format; mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* * VG2 Constant Color */ MDP_OUTP(MDP_BASE + 0x31008, color); /* * MDP_VG2_SRC_FORMAT */ temp_src_format = inpdw(MDP_BASE + 0x30050); MDP_OUTP(MDP_BASE + 0x30050, temp_src_format | BIT(22)); /* * MDP_OVERLAY_REG_FLUSH */ MDP_OUTP(MDP_BASE + 0x18000, BIT(3)); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); return; } #endif void mdp4_overlay_dmae_xy(struct mdp4_overlay_pipe *pipe) { mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); MDP_OUTP(MDP_BASE + 0xb0004, (pipe->src_height << 16 | pipe->src_width)); if (pipe->dma_blt_addr) { uint32 off, bpp; #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif off = 0; if (pipe->ov_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; MDP_OUTP(MDP_BASE + 0xb0008, pipe->dma_blt_addr + off); /* RGB888, output of overlay blending */ MDP_OUTP(MDP_BASE + 0xb000c, pipe->src_width * bpp); } else { /* dma_e source */ MDP_OUTP(MDP_BASE + 0xb0008, pipe->srcp0_addr); MDP_OUTP(MDP_BASE + 0xb000c, pipe->srcp0_ystride); } /* dma_e dest */ MDP_OUTP(MDP_BASE + 0xb0010, (pipe->dst_y << 16 | pipe->dst_x)); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } void mdp4_overlay_dmap_cfg(struct msm_fb_data_type *mfd, int lcdc) { uint32 dma2_cfg_reg; uint32 mask, curr; dma2_cfg_reg = DMA_DITHER_EN; #ifdef BLT_RGB565 /* RGB888 is 0 */ dma2_cfg_reg |= DMA_BUF_FORMAT_RGB565; /* blt only */ #endif if (mfd->fb_imgType == MDP_BGR_565) dma2_cfg_reg |= DMA_PACK_PATTERN_BGR; else dma2_cfg_reg |= DMA_PACK_PATTERN_RGB; if ((mfd->panel_info.type == MIPI_CMD_PANEL) || (mfd->panel_info.type == MIPI_VIDEO_PANEL)) { dma2_cfg_reg |= DMA_DSTC0G_8BITS | /* 888 24BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } else if (mfd->panel_info.bpp == 18) { dma2_cfg_reg |= DMA_DSTC0G_6BITS | /* 666 18BPP */ DMA_DSTC1B_6BITS | DMA_DSTC2R_6BITS; } else if (mfd->panel_info.bpp == 16) { dma2_cfg_reg |= DMA_DSTC0G_6BITS | /* 565 16BPP */ DMA_DSTC1B_5BITS | DMA_DSTC2R_5BITS; } else { dma2_cfg_reg |= DMA_DSTC0G_8BITS | /* 888 24BPP */ DMA_DSTC1B_8BITS | DMA_DSTC2R_8BITS; } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); #ifndef CONFIG_FB_MSM_LCDC_CHIMEI_WXGA_PANEL if (lcdc) dma2_cfg_reg |= DMA_PACK_ALIGN_MSB; #endif /* dma2 config register */ curr = inpdw(MDP_BASE + 0x90000); mask = 0x0FFFFFFF; dma2_cfg_reg = (dma2_cfg_reg & mask) | (curr & ~mask); MDP_OUTP(MDP_BASE + 0x90000, dma2_cfg_reg); ctrl->dmap_cfg[0] = dma2_cfg_reg; mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } /* * mdp4_overlay_dmap_xy: called form baselayer only */ void mdp4_overlay_dmap_xy(struct mdp4_overlay_pipe *pipe) { uint32 off, bpp; if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); if (pipe->dma_blt_addr) { #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif off = 0; if (pipe->dmap_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; ctrl->dmap_cfg[2] = pipe->dma_blt_addr + off; MDP_OUTP(MDP_BASE + 0x90008, pipe->dma_blt_addr + off); /* RGB888, output of overlay blending */ MDP_OUTP(MDP_BASE + 0x9000c, pipe->src_width * bpp); ctrl->dmap_cfg[3] = pipe->src_width * bpp; } else { MDP_OUTP(MDP_BASE + 0x90008, pipe->srcp0_addr); ctrl->dmap_cfg[2] = pipe->srcp0_addr; MDP_OUTP(MDP_BASE + 0x9000c, pipe->srcp0_ystride); ctrl->dmap_cfg[3] = pipe->srcp0_ystride; } /* dma_p source */ MDP_OUTP(MDP_BASE + 0x90004, (pipe->src_height << 16 | pipe->src_width)); ctrl->dmap_cfg[1] = (pipe->src_height << 16 | pipe->src_width); /* dma_p dest */ MDP_OUTP(MDP_BASE + 0x90010, (pipe->dst_y << 16 | pipe->dst_x)); ctrl->dmap_cfg[4] = (pipe->dst_y << 16 | pipe->dst_x); if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } static void mdp4_overlay_dmap_reconfig(void) { MDP_OUTP(MDP_BASE + 0x90000, ctrl->dmap_cfg[0]); MDP_OUTP(MDP_BASE + 0x90004, ctrl->dmap_cfg[1]); MDP_OUTP(MDP_BASE + 0x90008, ctrl->dmap_cfg[2]); MDP_OUTP(MDP_BASE + 0x9000c, ctrl->dmap_cfg[3]); MDP_OUTP(MDP_BASE + 0x90010, ctrl->dmap_cfg[4]); } #define MDP4_VG_PHASE_STEP_DEFAULT 0x20000000 #define MDP4_VG_PHASE_STEP_SHIFT 29 static int mdp4_leading_0(uint32 num) { uint32 bit = 0x80000000; int i; for (i = 0; i < 32; i++) { if (bit & num) return i; bit >>= 1; } return i; } static uint32 mdp4_scale_phase_step(int f_num, uint32 src, uint32 dst) { uint32 val, s; int n; n = mdp4_leading_0(src); if (n > f_num) n = f_num; s = src << n; /* maximum to reduce lose of resolution */ val = s / dst; if (n < f_num) { n = f_num - n; val <<= n; val |= ((s % dst) << n) / dst; } return val; } static void mdp4_scale_setup(struct mdp4_overlay_pipe *pipe) { pipe->phasex_step = MDP4_VG_PHASE_STEP_DEFAULT; pipe->phasey_step = MDP4_VG_PHASE_STEP_DEFAULT; if (pipe->dst_h && pipe->src_h != pipe->dst_h) { u32 upscale_max; upscale_max = (mdp_rev >= MDP_REV_41) ? MDP4_REV41_OR_LATER_UP_SCALING_MAX : MDP4_REV40_UP_SCALING_MAX; if (pipe->dst_h > pipe->src_h * upscale_max) return; pipe->op_mode |= MDP4_OP_SCALEY_EN; if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) { if (pipe->flags & MDP_BACKEND_COMPOSITION && pipe->alpha_enable && pipe->dst_h > pipe->src_h) pipe->op_mode |= MDP4_OP_SCALEY_PIXEL_RPT; else if (pipe->dst_h <= (pipe->src_h / 4)) pipe->op_mode |= MDP4_OP_SCALEY_MN_PHASE; else pipe->op_mode |= MDP4_OP_SCALEY_FIR; } else { /* RGB pipe */ pipe->op_mode |= MDP4_OP_SCALE_RGB_ENHANCED | MDP4_OP_SCALE_RGB_BILINEAR | MDP4_OP_SCALE_ALPHA_BILINEAR; } pipe->phasey_step = mdp4_scale_phase_step(29, pipe->src_h, pipe->dst_h); } if (pipe->dst_w && pipe->src_w != pipe->dst_w) { u32 upscale_max; upscale_max = (mdp_rev >= MDP_REV_41) ? MDP4_REV41_OR_LATER_UP_SCALING_MAX : MDP4_REV40_UP_SCALING_MAX; if (pipe->dst_w > pipe->src_w * upscale_max) return; pipe->op_mode |= MDP4_OP_SCALEX_EN; if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) { if (pipe->flags & MDP_BACKEND_COMPOSITION && pipe->alpha_enable && pipe->dst_w > pipe->src_w) pipe->op_mode |= MDP4_OP_SCALEX_PIXEL_RPT; else if (pipe->dst_w <= (pipe->src_w / 4)) pipe->op_mode |= MDP4_OP_SCALEX_MN_PHASE; else pipe->op_mode |= MDP4_OP_SCALEX_FIR; } else { /* RGB pipe */ pipe->op_mode |= MDP4_OP_SCALE_RGB_ENHANCED | MDP4_OP_SCALE_RGB_BILINEAR | MDP4_OP_SCALE_ALPHA_BILINEAR; } pipe->phasex_step = mdp4_scale_phase_step(29, pipe->src_w, pipe->dst_w); } } void mdp4_overlay_solidfill_init(struct mdp4_overlay_pipe *pipe) { char *base; uint32 src_size, src_xy, dst_size, dst_xy; uint32 format; uint32 off; int i; src_size = ((pipe->src_h << 16) | pipe->src_w); src_xy = ((pipe->src_y << 16) | pipe->src_x); dst_size = ((pipe->dst_h << 16) | pipe->dst_w); dst_xy = ((pipe->dst_y << 16) | pipe->dst_x); base = MDP_BASE + MDP4_VIDEO_BASE; off = MDP4_VIDEO_OFF; /* 0x10000 */ mdp_clk_ctrl(1); for(i = 0; i < 4; i++) { /* 4 pipes */ format = inpdw(base + 0x50); format |= MDP4_FORMAT_SOLID_FILL; outpdw(base + 0x0000, src_size);/* MDP_RGB_SRC_SIZE */ outpdw(base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ outpdw(base + 0x0008, dst_size);/* MDP_RGB_DST_SIZE */ outpdw(base + 0x000c, dst_xy); /* MDP_RGB_DST_XY */ outpdw(base + 0x0050, format);/* MDP_RGB_SRC_FORMAT */ outpdw(base + 0x1008, 0x0);/* Black */ base += off; } /* * keep it at primary * will be picked up at first commit */ ctrl->flush[MDP4_MIXER0] = 0x3c; /* all pipes */ mdp_clk_ctrl(0); } void mdp4_overlay_rgb_setup(struct mdp4_overlay_pipe *pipe) { char *rgb_base; uint32 src_size, src_xy, dst_size, dst_xy; uint32 format, pattern; uint32 curr, mask; uint32 offset = 0; int pnum; pnum = pipe->pipe_num - OVERLAY_PIPE_RGB1; /* start from 0 */ rgb_base = MDP_BASE + MDP4_RGB_BASE; rgb_base += (MDP4_RGB_OFF * pnum); src_size = ((pipe->src_h << 16) | pipe->src_w); src_xy = ((pipe->src_y << 16) | pipe->src_x); dst_size = ((pipe->dst_h << 16) | pipe->dst_w); dst_xy = ((pipe->dst_y << 16) | pipe->dst_x); if ((pipe->src_x + pipe->src_w) > 0x7FF) { offset += pipe->src_x * pipe->bpp; src_xy &= 0xFFFF0000; } if ((pipe->src_y + pipe->src_h) > 0x7FF) { offset += pipe->src_y * pipe->src_width * pipe->bpp; src_xy &= 0x0000FFFF; } format = mdp4_overlay_format(pipe); pattern = mdp4_overlay_unpack_pattern(pipe); #ifdef MDP4_IGC_LUT_ENABLE pipe->op_mode |= MDP4_OP_IGC_LUT_EN; #endif mdp4_scale_setup(pipe); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* Ensure proper covert matrix loaded when color space swaps */ curr = inpdw(rgb_base + 0x0058); /* Don't touch bits you don't want to configure*/ mask = 0xFFFEFFFF; pipe->op_mode = (pipe->op_mode & mask) | (curr & ~mask); #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) //2012-11-20 taewonee.kim@lge.com : QCT pre patch for the inverted clone image [START] if((pipe->mfd->panel_info.type != DTV_PANEL)&&(pipe->mfd->panel_info.type != WRITEBACK_PANEL)) //2012-11-20 taewonee.kim@lge.com : QCT pre patch for the inverted clone image [END] { if (panel_rotate_180 && (pipe->pipe_num == OVERLAY_PIPE_RGB1 || pipe->pipe_num == OVERLAY_PIPE_RGB2)) { uint32 op_mode = pipe->op_mode | MDP4_OP_FLIP_UD | MDP4_OP_SCALEY_EN; if (pipe->ext_flag & MDP_FLIP_UD) op_mode &= ~MDP4_OP_FLIP_UD; pipe->op_mode = op_mode; } if ((pipe->op_mode & MDP4_OP_FLIP_UD) && pipe->mfd) dst_xy = (((pipe->mfd->panel_info.yres - pipe->dst_y - pipe->dst_h) << 16) | pipe->dst_x); } if (!pipe->mfd) pr_err("rgb mfd is not set\n"); #endif outpdw(rgb_base + 0x0000, src_size); /* MDP_RGB_SRC_SIZE */ outpdw(rgb_base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ outpdw(rgb_base + 0x0008, dst_size); /* MDP_RGB_DST_SIZE */ outpdw(rgb_base + 0x000c, dst_xy); /* MDP_RGB_DST_XY */ outpdw(rgb_base + 0x0010, pipe->srcp0_addr + offset); outpdw(rgb_base + 0x0040, pipe->srcp0_ystride); outpdw(rgb_base + 0x0050, format);/* MDP_RGB_SRC_FORMAT */ outpdw(rgb_base + 0x0054, pattern);/* MDP_RGB_SRC_UNPACK_PATTERN */ if (format & MDP4_FORMAT_SOLID_FILL) { u32 op_mode = pipe->op_mode; op_mode &= ~(MDP4_OP_FLIP_LR + MDP4_OP_SCALEX_EN); op_mode &= ~(MDP4_OP_FLIP_UD + MDP4_OP_SCALEY_EN); outpdw(rgb_base + 0x0058, op_mode);/* MDP_RGB_OP_MODE */ } else { if (pipe->op_mode & MDP4_OP_FLIP_LR && mdp_rev >= MDP_REV_42) { /* Enable x-scaling bit to enable LR flip */ /* for MDP > 4.2 targets */ pipe->op_mode |= 0x01; } outpdw(rgb_base + 0x0058, pipe->op_mode);/* MDP_RGB_OP_MODE */ } outpdw(rgb_base + 0x005c, pipe->phasex_step); outpdw(rgb_base + 0x0060, pipe->phasey_step); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mdp4_stat.pipe[pipe->pipe_num]++; } static void mdp4_overlay_vg_get_src_offset(struct mdp4_overlay_pipe *pipe, char *vg_base, uint32 *luma_off, uint32 *chroma_off) { uint32 src_xy; *luma_off = 0; *chroma_off = 0; if (pipe->src_x && (pipe->frame_format == MDP4_FRAME_FORMAT_LINEAR)) { src_xy = (pipe->src_y << 16) | pipe->src_x; src_xy &= 0xffff0000; outpdw(vg_base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ switch (pipe->src_format) { case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CB_CR_H2V2: *luma_off = pipe->src_x; *chroma_off = pipe->src_x/2; break; case MDP_Y_CBCR_H2V2_TILE: case MDP_Y_CRCB_H2V2_TILE: case MDP_Y_CBCR_H2V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: case MDP_Y_CRCB_H2V1: case MDP_Y_CBCR_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: *luma_off = pipe->src_x + (pipe->src_y * pipe->srcp0_ystride); *chroma_off = pipe->src_x + (pipe->src_y * pipe->srcp1_ystride); break; case MDP_YCBYCR_H2V1: case MDP_YCRYCB_H2V1: if (pipe->src_x & 0x1) pipe->src_x += 1; *luma_off += pipe->src_x * 2; break; case MDP_ARGB_8888: case MDP_RGBA_8888: case MDP_BGRA_8888: case MDP_RGBX_8888: case MDP_RGB_565: case MDP_BGR_565: case MDP_XRGB_8888: case MDP_RGB_888: case MDP_YCBCR_H1V1: case MDP_YCRCB_H1V1: *luma_off = pipe->src_x * pipe->bpp; break; default: pr_err("%s: fmt %u not supported for adjustment\n", __func__, pipe->src_format); break; } } } void mdp4_overlay_vg_setup(struct mdp4_overlay_pipe *pipe) { char *vg_base; uint32 frame_size, src_size, src_xy, dst_size, dst_xy; uint32 format, pattern, luma_offset, chroma_offset; /* 2012-11-29 wonhee.jeong@lge.com this code add to mdp tunning when start DMB in G, GK (apq8064) [S]*/ /* This source code confirmed by QCT*/ uint32 mask, curr, addr; /* 2012-11-29 wonhee.jeong@lge.com this code add to mdp tunning when start DMB in G, GK (apq8064) [E]*/ int pnum, ptype, i; uint32_t block; pnum = pipe->pipe_num - OVERLAY_PIPE_VG1; /* start from 0 */ vg_base = MDP_BASE + MDP4_VIDEO_BASE; vg_base += (MDP4_VIDEO_OFF * pnum); frame_size = ((pipe->src_height << 16) | pipe->src_width); src_size = ((pipe->src_h << 16) | pipe->src_w); src_xy = ((pipe->src_y << 16) | pipe->src_x); dst_size = ((pipe->dst_h << 16) | pipe->dst_w); dst_xy = ((pipe->dst_y << 16) | pipe->dst_x); ptype = mdp4_overlay_format2type(pipe->src_format); format = mdp4_overlay_format(pipe); pattern = mdp4_overlay_unpack_pattern(pipe); /* CSC Post Processing enabled? */ if (pipe->flags & MDP_OVERLAY_PP_CFG_EN) { if (pipe->pp_cfg.config_ops & MDP_OVERLAY_PP_CSC_CFG) { if (pipe->pp_cfg.csc_cfg.flags & MDP_CSC_FLAG_ENABLE) pipe->op_mode |= MDP4_OP_CSC_EN; if (pipe->pp_cfg.csc_cfg.flags & MDP_CSC_FLAG_YUV_IN) pipe->op_mode |= MDP4_OP_SRC_DATA_YCBCR; if (pipe->pp_cfg.csc_cfg.flags & MDP_CSC_FLAG_YUV_OUT) pipe->op_mode |= MDP4_OP_DST_DATA_YCBCR; mdp4_csc_write(&pipe->pp_cfg.csc_cfg, (uint32_t) (vg_base + MDP4_VIDEO_CSC_OFF)); if (pipe->pipe_num == OVERLAY_PIPE_VG1) block = MDP_BLOCK_VG_1; else block = MDP_BLOCK_VG_2; for (i = 0; i < CSC_MAX_BLOCKS; i++) { if (block == csc_cfg_matrix[i].block) { memcpy(&csc_cfg_matrix[i].csc_data, &(pipe->pp_cfg.csc_cfg), sizeof(struct mdp_csc_cfg)); break; } } } if (pipe->pp_cfg.config_ops & MDP_OVERLAY_PP_QSEED_CFG) { mdp4_qseed_access_cfg(&pipe->pp_cfg.qseed_cfg[0], (uint32_t) vg_base); mdp4_qseed_access_cfg(&pipe->pp_cfg.qseed_cfg[1], (uint32_t) vg_base); } } /* not RGB use VG pipe, pure VG pipe */ if (ptype != OVERLAY_TYPE_RGB) pipe->op_mode |= (MDP4_OP_CSC_EN | MDP4_OP_SRC_DATA_YCBCR); #ifdef MDP4_IGC_LUT_ENABLE pipe->op_mode |= MDP4_OP_IGC_LUT_EN; #endif mdp4_scale_setup(pipe); luma_offset = 0; chroma_offset = 0; if (ptype == OVERLAY_TYPE_RGB) { if ((pipe->src_y + pipe->src_h) > 0x7FF) { luma_offset = pipe->src_y * pipe->src_width * pipe->bpp; src_xy &= 0x0000FFFF; } if ((pipe->src_x + pipe->src_w) > 0x7FF) { luma_offset += pipe->src_x * pipe->bpp; src_xy &= 0xFFFF0000; } } #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) //2012-11-20 taewonee.kim@lge.com : QCT pre patch for the inverted clone image [START] if((pipe->mfd->panel_info.type != DTV_PANEL) && (pipe->mfd->panel_info.type != WRITEBACK_PANEL)) //2012-11-20 taewonee.kim@lge.com : QCT pre patch for the inverted clone image [END] { if (panel_rotate_180) { uint32 op_mode = pipe->op_mode | MDP4_OP_FLIP_UD; if (pipe->ext_flag & MDP_FLIP_UD) op_mode &= ~MDP4_OP_FLIP_UD; pipe->op_mode = op_mode; } if ((pipe->op_mode & MDP4_OP_FLIP_UD) && pipe->mfd) { dst_xy = (((pipe->mfd->panel_info.yres - pipe->dst_y - pipe->dst_h) << 16) | pipe->dst_x); outpdw(MDP_BASE + 0xE0044, 0xe0fff); } } if (!pipe->mfd) pr_err("vg mfd is not set\n"); #endif mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); outpdw(vg_base + 0x0000, src_size); /* MDP_RGB_SRC_SIZE */ outpdw(vg_base + 0x0004, src_xy); /* MDP_RGB_SRC_XY */ outpdw(vg_base + 0x0008, dst_size); /* MDP_RGB_DST_SIZE */ outpdw(vg_base + 0x000c, dst_xy); /* MDP_RGB_DST_XY */ if (pipe->frame_format != MDP4_FRAME_FORMAT_LINEAR) { struct mdp4_overlay_pipe *real_pipe; u32 psize, csize; /* * video tile frame size register is NOT double buffered. * when this register updated, it kicks in immediatly * During transition from smaller resolution to higher * resolution it may have possibility that mdp still fetch * from smaller resolution buffer with new higher resolution * frame size. This will cause iommu page fault. */ real_pipe = mdp4_overlay_ndx2pipe(pipe->pipe_ndx); psize = real_pipe->prev_src_height * real_pipe->prev_src_width; csize = pipe->src_height * pipe->src_width; if (psize && (csize > psize)) { frame_size = (real_pipe->prev_src_height << 16 | real_pipe->prev_src_width); } outpdw(vg_base + 0x0048, frame_size); /* TILE frame size */ real_pipe->prev_src_height = pipe->src_height; real_pipe->prev_src_width = pipe->src_width; } /* * Adjust src X offset to avoid MDP from overfetching pixels * present before the offset. This is required for video * frames coming with unused green pixels along the left margin */ /* not RGB use VG pipe, pure VG pipe */ if (ptype != OVERLAY_TYPE_RGB) { mdp4_overlay_vg_get_src_offset(pipe, vg_base, &luma_offset, &chroma_offset); } /* 2012-11-29 wonhee.jeong@lge.com this code add to mdp tunning when start DMB in G, GK (apq8064) [S]*/ /* This source code confirmed by QCT*/ /* Ensure proper covert matrix loaded when color space swaps */ curr = inpdw(vg_base + 0x0058); mask = 0x600; if ((curr & mask) != (pipe->op_mode & mask)) { addr = ((uint32_t)vg_base) + 0x4000; if (ptype != OVERLAY_TYPE_RGB) mdp4_csc_write(&(mdp_csc_convert[1]), addr); else mdp4_csc_write(&(mdp_csc_convert[0]), addr); mask = 0xFFFCFFFF; } else { /* Don't touch bits you don't want to configure*/ mask = 0xFFFCF1FF; } pipe->op_mode = (pipe->op_mode & mask) | (curr & ~mask); /* 2012-11-29 wonhee.jeong@lge.com this code add to mdp tunning when start DMB in G, GK (apq8064) [E]*/ /* luma component plane */ outpdw(vg_base + 0x0010, pipe->srcp0_addr + luma_offset); /* chroma component plane or planar color 1 */ outpdw(vg_base + 0x0014, pipe->srcp1_addr + chroma_offset); /* planar color 2 */ outpdw(vg_base + 0x0018, pipe->srcp2_addr + chroma_offset); outpdw(vg_base + 0x0040, pipe->srcp1_ystride << 16 | pipe->srcp0_ystride); outpdw(vg_base + 0x0044, pipe->srcp3_ystride << 16 | pipe->srcp2_ystride); outpdw(vg_base + 0x0050, format); /* MDP_RGB_SRC_FORMAT */ outpdw(vg_base + 0x0054, pattern); /* MDP_RGB_SRC_UNPACK_PATTERN */ if (format & MDP4_FORMAT_SOLID_FILL) { u32 op_mode = pipe->op_mode; op_mode &= ~(MDP4_OP_FLIP_LR + MDP4_OP_SCALEX_EN); op_mode &= ~(MDP4_OP_FLIP_UD + MDP4_OP_SCALEY_EN); outpdw(vg_base + 0x0058, op_mode);/* MDP_RGB_OP_MODE */ } else outpdw(vg_base + 0x0058, pipe->op_mode);/* MDP_RGB_OP_MODE */ outpdw(vg_base + 0x005c, pipe->phasex_step); outpdw(vg_base + 0x0060, pipe->phasey_step); if (pipe->op_mode & MDP4_OP_DITHER_EN) { outpdw(vg_base + 0x0068, pipe->r_bit << 4 | pipe->b_bit << 2 | pipe->g_bit); } if (mdp_rev > MDP_REV_41) { /* mdp chip select controller */ mask = 0; if (pipe->pipe_num == OVERLAY_PIPE_VG1) mask = 0x020; /* bit 5 */ else if (pipe->pipe_num == OVERLAY_PIPE_VG2) mask = 0x02000; /* bit 13 */ if (mask) { if (pipe->op_mode & MDP4_OP_SCALEY_MN_PHASE) ctrl->cs_controller &= ~mask; else ctrl->cs_controller |= mask; /* NOT double buffered */ outpdw(MDP_BASE + 0x00c0, ctrl->cs_controller); } } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mdp4_stat.pipe[pipe->pipe_num]++; } int mdp4_overlay_format2type(uint32 format) { switch (format) { case MDP_RGB_565: case MDP_RGB_888: case MDP_BGR_565: case MDP_XRGB_8888: case MDP_ARGB_8888: case MDP_RGBA_8888: case MDP_BGRA_8888: case MDP_RGBX_8888: return OVERLAY_TYPE_RGB; case MDP_YCBYCR_H2V1: case MDP_YCRYCB_H2V1: case MDP_Y_CRCB_H2V1: case MDP_Y_CBCR_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CBCR_H2V2: case MDP_Y_CBCR_H2V2_TILE: case MDP_Y_CRCB_H2V2_TILE: case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CB_CR_H2V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: case MDP_YCRCB_H1V1: case MDP_YCBCR_H1V1: return OVERLAY_TYPE_VIDEO; case MDP_RGB_BORDERFILL: return OVERLAY_TYPE_BF; default: mdp4_stat.err_format++; return -ERANGE; } } #define C3_ALPHA 3 /* alpha */ #define C2_R_Cr 2 /* R/Cr */ #define C1_B_Cb 1 /* B/Cb */ #define C0_G_Y 0 /* G/luma */ #define YUV_444_MAX_WIDTH 1280 /* Max width for YUV 444*/ int mdp4_overlay_format2pipe(struct mdp4_overlay_pipe *pipe) { switch (pipe->src_format) { case MDP_RGB_565: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 0; pipe->r_bit = 1; /* R, 5 bits */ pipe->b_bit = 1; /* B, 5 bits */ pipe->g_bit = 2; /* G, 6 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element2 = C2_R_Cr; /* R */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C1_B_Cb; /* B */ pipe->bpp = 2; /* 2 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_RGB_888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element2 = C1_B_Cb; /* B */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C2_R_Cr; /* R */ pipe->bpp = 3; /* 3 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_BGR_565: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 0; pipe->r_bit = 1; /* R, 5 bits */ pipe->b_bit = 1; /* B, 5 bits */ pipe->g_bit = 2; /* G, 6 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element2 = C1_B_Cb; /* B */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C2_R_Cr; /* R */ pipe->bpp = 2; /* 2 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_XRGB_8888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C1_B_Cb; /* B */ pipe->element2 = C0_G_Y; /* G */ pipe->element1 = C2_R_Cr; /* R */ pipe->element0 = C3_ALPHA; /* alpha */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_ARGB_8888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 1; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C1_B_Cb; /* B */ pipe->element2 = C0_G_Y; /* G */ pipe->element1 = C2_R_Cr; /* R */ pipe->element0 = C3_ALPHA; /* alpha */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_RGBA_8888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 1; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C3_ALPHA; /* alpha */ pipe->element2 = C1_B_Cb; /* B */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C2_R_Cr; /* R */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_RGBX_8888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 3; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C3_ALPHA; /* alpha */ pipe->element2 = C1_B_Cb; /* B */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C2_R_Cr; /* R */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_BGRA_8888: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 3; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 1; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; pipe->element3 = C3_ALPHA; /* alpha */ pipe->element2 = C2_R_Cr; /* R */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C1_B_Cb; /* B */ pipe->bpp = 4; /* 4 bpp */ pipe->chroma_sample = MDP4_CHROMA_RGB; break; case MDP_YCBYCR_H2V1: case MDP_YCRYCB_H2V1: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 0; /* alpha, 4 bits */ pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 3; if (pipe->src_format == MDP_YCRYCB_H2V1) { pipe->element3 = C0_G_Y; /* G */ pipe->element2 = C2_R_Cr; /* R */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C1_B_Cb; /* B */ } else if (pipe->src_format == MDP_YCBYCR_H2V1) { pipe->element3 = C0_G_Y; /* G */ pipe->element2 = C1_B_Cb; /* B */ pipe->element1 = C0_G_Y; /* G */ pipe->element0 = C2_R_Cr; /* R */ } pipe->bpp = 2; /* 2 bpp */ pipe->chroma_sample = MDP4_CHROMA_H2V1; break; case MDP_Y_CRCB_H2V1: case MDP_Y_CBCR_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CBCR_H2V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_PSEUDO_PLANAR; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 1; /* 2 */ if (pipe->src_format == MDP_Y_CRCB_H2V1) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; pipe->chroma_sample = MDP4_CHROMA_H2V1; } else if (pipe->src_format == MDP_Y_CRCB_H1V1) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; if (pipe->src_width > YUV_444_MAX_WIDTH) pipe->chroma_sample = MDP4_CHROMA_H1V2; else pipe->chroma_sample = MDP4_CHROMA_RGB; } else if (pipe->src_format == MDP_Y_CBCR_H2V1) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; pipe->chroma_sample = MDP4_CHROMA_H2V1; } else if (pipe->src_format == MDP_Y_CBCR_H1V1) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; if (pipe->src_width > YUV_444_MAX_WIDTH) pipe->chroma_sample = MDP4_CHROMA_H1V2; else pipe->chroma_sample = MDP4_CHROMA_RGB; } else if (pipe->src_format == MDP_Y_CRCB_H1V2) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; pipe->chroma_sample = MDP4_CHROMA_H1V2; } else if (pipe->src_format == MDP_Y_CBCR_H1V2) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; pipe->chroma_sample = MDP4_CHROMA_H1V2; } else if (pipe->src_format == MDP_Y_CRCB_H2V2) { pipe->element1 = C1_B_Cb; pipe->element0 = C2_R_Cr; pipe->chroma_sample = MDP4_CHROMA_420; } else if (pipe->src_format == MDP_Y_CBCR_H2V2) { pipe->element1 = C2_R_Cr; pipe->element0 = C1_B_Cb; pipe->chroma_sample = MDP4_CHROMA_420; } pipe->bpp = 2; /* 2 bpp */ break; case MDP_Y_CBCR_H2V2_TILE: case MDP_Y_CRCB_H2V2_TILE: pipe->frame_format = MDP4_FRAME_FORMAT_VIDEO_SUPERTILE; pipe->fetch_plane = OVERLAY_PLANE_PSEUDO_PLANAR; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 1; /* 2 */ if (pipe->src_format == MDP_Y_CRCB_H2V2_TILE) { pipe->element1 = C1_B_Cb; /* B */ pipe->element0 = C2_R_Cr; /* R */ pipe->chroma_sample = MDP4_CHROMA_420; } else if (pipe->src_format == MDP_Y_CBCR_H2V2_TILE) { pipe->element1 = C2_R_Cr; /* R */ pipe->element0 = C1_B_Cb; /* B */ pipe->chroma_sample = MDP4_CHROMA_420; } pipe->bpp = 2; /* 2 bpp */ break; case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CB_CR_H2V2: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_PLANAR; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->chroma_sample = MDP4_CHROMA_420; pipe->bpp = 2; /* 2 bpp */ break; case MDP_YCBCR_H1V1: case MDP_YCRCB_H1V1: pipe->frame_format = MDP4_FRAME_FORMAT_LINEAR; pipe->fetch_plane = OVERLAY_PLANE_INTERLEAVED; pipe->a_bit = 0; pipe->r_bit = 3; /* R, 8 bits */ pipe->b_bit = 3; /* B, 8 bits */ pipe->g_bit = 3; /* G, 8 bits */ pipe->alpha_enable = 0; pipe->unpack_tight = 1; pipe->unpack_align_msb = 0; pipe->unpack_count = 2; pipe->element0 = C0_G_Y; /* G */ if (pipe->src_format == MDP_YCRCB_H1V1) { pipe->element1 = C2_R_Cr; /* R */ pipe->element2 = C1_B_Cb; /* B */ } else { pipe->element1 = C1_B_Cb; /* B */ pipe->element2 = C2_R_Cr; /* R */ } pipe->bpp = 3; /* 3 bpp */ case MDP_RGB_BORDERFILL: pipe->alpha_enable = 0; pipe->alpha = 0; break; default: /* not likely */ mdp4_stat.err_format++; return -ERANGE; } return 0; } /* * color_key_convert: output with 12 bits color key */ static uint32 color_key_convert(int start, int num, uint32 color) { uint32 data; data = (color >> start) & ((1 << num) - 1); /* convert to 8 bits */ if (num == 5) data = ((data << 3) | (data >> 2)); else if (num == 6) data = ((data << 2) | (data >> 4)); /* convert 8 bits to 12 bits */ data = (data << 4) | (data >> 4); return data; } void transp_color_key(int format, uint32 transp, uint32 *c0, uint32 *c1, uint32 *c2) { int b_start, g_start, r_start; int b_num, g_num, r_num; switch (format) { case MDP_RGB_565: b_start = 0; g_start = 5; r_start = 11; r_num = 5; g_num = 6; b_num = 5; break; case MDP_RGB_888: case MDP_XRGB_8888: case MDP_ARGB_8888: case MDP_BGRA_8888: b_start = 0; g_start = 8; r_start = 16; r_num = 8; g_num = 8; b_num = 8; break; case MDP_RGBA_8888: case MDP_RGBX_8888: b_start = 16; g_start = 8; r_start = 0; r_num = 8; g_num = 8; b_num = 8; break; case MDP_BGR_565: b_start = 11; g_start = 5; r_start = 0; r_num = 5; g_num = 6; b_num = 5; break; case MDP_Y_CB_CR_H2V2: case MDP_Y_CBCR_H2V2: case MDP_Y_CBCR_H2V1: case MDP_YCBCR_H1V1: b_start = 8; g_start = 16; r_start = 0; r_num = 8; g_num = 8; b_num = 8; break; case MDP_Y_CR_CB_H2V2: case MDP_Y_CR_CB_GH2V2: case MDP_Y_CRCB_H2V2: case MDP_Y_CRCB_H2V1: case MDP_Y_CRCB_H1V2: case MDP_Y_CBCR_H1V2: case MDP_Y_CRCB_H1V1: case MDP_Y_CBCR_H1V1: case MDP_YCRCB_H1V1: b_start = 0; g_start = 16; r_start = 8; r_num = 8; g_num = 8; b_num = 8; break; default: b_start = 0; g_start = 8; r_start = 16; r_num = 8; g_num = 8; b_num = 8; break; } *c0 = color_key_convert(g_start, g_num, transp); *c1 = color_key_convert(b_start, b_num, transp); *c2 = color_key_convert(r_start, r_num, transp); } uint32 mdp4_overlay_format(struct mdp4_overlay_pipe *pipe) { uint32 format; format = 0; if (pipe->solid_fill) format |= MDP4_FORMAT_SOLID_FILL; if (pipe->unpack_align_msb) format |= MDP4_FORMAT_UNPACK_ALIGN_MSB; if (pipe->unpack_tight) format |= MDP4_FORMAT_UNPACK_TIGHT; if (pipe->alpha_enable) format |= MDP4_FORMAT_ALPHA_ENABLE; if (pipe->flags & MDP_SOURCE_ROTATED_90) format |= MDP4_FORMAT_90_ROTATED; format |= (pipe->unpack_count << 13); format |= ((pipe->bpp - 1) << 9); format |= (pipe->a_bit << 6); format |= (pipe->r_bit << 4); format |= (pipe->b_bit << 2); format |= pipe->g_bit; format |= (pipe->frame_format << 29); /* video/graphic */ format |= (pipe->fetch_plane << 19); format |= (pipe->chroma_site << 28); format |= (pipe->chroma_sample << 26); return format; } uint32 mdp4_overlay_unpack_pattern(struct mdp4_overlay_pipe *pipe) { return (pipe->element3 << 24) | (pipe->element2 << 16) | (pipe->element1 << 8) | pipe->element0; } /* * mdp4_overlayproc_cfg: only be called from base layer */ void mdp4_overlayproc_cfg(struct mdp4_overlay_pipe *pipe) { uint32 data, intf; char *overlay_base; uint32 curr; intf = 0; if (pipe->mixer_num == MDP4_MIXER2) overlay_base = MDP_BASE + MDP4_OVERLAYPROC2_BASE; else if (pipe->mixer_num == MDP4_MIXER1) { overlay_base = MDP_BASE + MDP4_OVERLAYPROC1_BASE;/* 0x18000 */ intf = inpdw(MDP_BASE + 0x0038); /* MDP_DISP_INTF_SEL */ intf >>= 4; intf &= 0x03; } else overlay_base = MDP_BASE + MDP4_OVERLAYPROC0_BASE;/* 0x10000 */ if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); /* * BLT support both primary and external external */ if (pipe->ov_blt_addr) { int off, bpp; #ifdef BLT_RGB565 bpp = 2; /* overlay ouput is RGB565 */ #else bpp = 3; /* overlay ouput is RGB888 */ #endif data = pipe->src_height; data <<= 16; data |= pipe->src_width; outpdw(overlay_base + 0x0008, data); /* ROI, height + width */ if (pipe->mixer_num == MDP4_MIXER0 || pipe->mixer_num == MDP4_MIXER1) { off = 0; if (pipe->ov_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; outpdw(overlay_base + 0x000c, pipe->ov_blt_addr + off); /* overlay ouput is RGB888 */ outpdw(overlay_base + 0x0010, pipe->src_width * bpp); outpdw(overlay_base + 0x001c, pipe->ov_blt_addr + off); /* MDDI - BLT + on demand */ outpdw(overlay_base + 0x0004, 0x08); curr = inpdw(overlay_base + 0x0014); curr &= 0x4; #ifdef BLT_RGB565 outpdw(overlay_base + 0x0014, curr | 0x1); /* RGB565 */ #else outpdw(overlay_base + 0x0014, curr | 0x0); /* RGB888 */ #endif } else if (pipe->mixer_num == MDP4_MIXER2) { if (ctrl->panel_mode & MDP4_PANEL_WRITEBACK) { off = 0; bpp = 1; if (pipe->ov_cnt & 0x01) off = pipe->src_height * pipe->src_width * bpp; outpdw(overlay_base + 0x000c, pipe->ov_blt_addr + off); /* overlay ouput is RGB888 */ outpdw(overlay_base + 0x0010, ((pipe->src_width << 16) | pipe->src_width)); outpdw(overlay_base + 0x001c, pipe->ov_blt_addr + off); off = pipe->src_height * pipe->src_width; /* align chroma to 2k address */ off = (off + 2047) & ~2047; /* UV plane adress */ outpdw(overlay_base + 0x0020, pipe->ov_blt_addr + off); /* MDDI - BLT + on demand */ outpdw(overlay_base + 0x0004, 0x08); /* pseudo planar + writeback */ curr = inpdw(overlay_base + 0x0014); curr &= 0x4; outpdw(overlay_base + 0x0014, curr | 0x012); /* rgb->yuv */ outpdw(overlay_base + 0x0200, 0x05); } } } else { data = pipe->src_height; data <<= 16; data |= pipe->src_width; outpdw(overlay_base + 0x0008, data); /* ROI, height + width */ outpdw(overlay_base + 0x000c, pipe->srcp0_addr); outpdw(overlay_base + 0x0010, pipe->srcp0_ystride); outpdw(overlay_base + 0x0004, 0x01); /* directout */ } if (pipe->mixer_num == MDP4_MIXER1) { if (intf == TV_INTF) { curr = inpdw(overlay_base + 0x0014); curr &= 0x4; outpdw(overlay_base + 0x0014, 0x02); /* yuv422 */ /* overlay1 CSC config */ outpdw(overlay_base + 0x0200, 0x05); /* rgb->yuv */ } } #ifdef MDP4_IGC_LUT_ENABLE curr = inpdw(overlay_base + 0x0014); curr &= ~0x4; outpdw(overlay_base + 0x0014, curr | 0x4); /* GC_LUT_EN, 888 */ #endif if (!in_interrupt()) mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } int mdp4_overlay_pipe_staged(struct mdp4_overlay_pipe *pipe) { uint32 data, mask; int mixer; mixer = pipe->mixer_num; data = ctrl->mixer_cfg[mixer]; mask = 0x0f; mask <<= (4 * pipe->pipe_num); data &= mask; return data; } int mdp4_mixer_info(int mixer_num, struct mdp_mixer_info *info) { int ndx, cnt; struct mdp4_overlay_pipe *pipe; if (mixer_num > MDP4_MIXER_MAX) return -ENODEV; cnt = 0; ndx = MDP4_MIXER_STAGE_BASE; for ( ; ndx < MDP4_MIXER_STAGE_MAX; ndx++) { pipe = &ctrl->plist[ndx]; if (pipe == NULL) continue; if (!pipe->pipe_used) continue; info->z_order = pipe->mixer_stage - MDP4_MIXER_STAGE0; /* z_order == -1, means base layer */ info->ptype = pipe->pipe_type; info->pnum = pipe->pipe_num; info->pndx = pipe->pipe_ndx; info->mixer_num = pipe->mixer_num; info++; cnt++; } return cnt; } void mdp4_mixer_reset(int mixer) { uint32 data, data1, mask; int i, ndx, min, max, bit; mdp_clk_ctrl(1); /* MDP_LAYERMIXER_IN_CFG, shard by both mixer 0 and 1 */ data = inpdw(MDP_BASE + 0x10100); data1 = data; if (mixer == 0) { min = 1; max = 8; bit = 0x03; /* mixer0, dmap */ } else { min = 9; max = 0xf; bit = 0x0C; /* mixer1, dmae */ } mask = 0x0f; for (i = 0 ; i < 8 ; i++) { ndx = data & mask; ndx >>= (i * 4); if (ndx >= min && ndx <= max) data1 &= ~mask; /* unstage pipe from mixer */ mask <<= 4; } pr_debug("%s: => MIXER_RESET, data1=%x data=%x bit=%x\n", __func__, data1, data, bit); /* unstage pipes of mixer to be reset */ outpdw(MDP_BASE + 0x10100, data1); /* MDP_LAYERMIXER_IN_CFG */ outpdw(MDP_BASE + 0x18000, 0); mdp4_sw_reset(bit); /* reset mixer */ /* 0 => mixer0, dmap */ /* restore origianl stage */ outpdw(MDP_BASE + 0x10100, data); /* MDP_LAYERMIXER_IN_CFG */ outpdw(MDP_BASE + 0x18000, 0); mdp4_vg_csc_restore(); mdp4_overlay_dmap_reconfig(); mdp_clk_ctrl(0); } void mdp4_mixer_stage_commit(int mixer) { struct mdp4_overlay_pipe *pipe; int i, num; u32 data, stage; int off; unsigned long flags; data = 0; for (i = MDP4_MIXER_STAGE_BASE; i < MDP4_MIXER_STAGE_MAX; i++) { pipe = ctrl->stage[mixer][i]; if (pipe == NULL) continue; pr_debug("%s: mixer=%d ndx=%d stage=%d\n", __func__, mixer, pipe->pipe_ndx, i); stage = pipe->mixer_stage; if (mixer >= MDP4_MIXER1) stage += 8; stage <<= (4 * pipe->pipe_num); data |= stage; } /* * stage_commit may be called from overlay_unset * for command panel, mdp clocks may be off at this time. * so mdp clock enabled is necessary */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); mdp_clk_ctrl(1); if (data) mdp4_mixer_blend_setup(mixer); off = 0; if (data != ctrl->mixer_cfg[mixer]) { ctrl->mixer_cfg[mixer] = data; if (mixer >= MDP4_MIXER2) { /* MDP_LAYERMIXER2_IN_CFG */ off = 0x100f0; } else { /* mixer 0 or 1 */ num = mixer + 1; num &= 0x01; data |= ctrl->mixer_cfg[num]; off = 0x10100; } pr_debug("%s: mixer=%d data=%x flush=%x pid=%d\n", __func__, mixer, data, ctrl->flush[mixer], current->pid); } local_irq_save(flags); if (off) outpdw(MDP_BASE + off, data); if (ctrl->flush[mixer]) { outpdw(MDP_BASE + 0x18000, ctrl->flush[mixer]); ctrl->flush[mixer] = 0; } local_irq_restore(flags); mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); mdp_clk_ctrl(0); } void mdp4_mixer_stage_up(struct mdp4_overlay_pipe *pipe, int commit) { struct mdp4_overlay_pipe *pp; int i, mixer; mixer = pipe->mixer_num; for (i = MDP4_MIXER_STAGE_BASE; i < MDP4_MIXER_STAGE_MAX; i++) { pp = ctrl->stage[mixer][i]; if (pp && pp->pipe_ndx == pipe->pipe_ndx) { ctrl->stage[mixer][i] = NULL; break; } } ctrl->stage[mixer][pipe->mixer_stage] = pipe; /* keep it */ if (commit) mdp4_mixer_stage_commit(mixer); } void mdp4_mixer_stage_down(struct mdp4_overlay_pipe *pipe, int commit) { struct mdp4_overlay_pipe *pp; int i, mixer; mixer = pipe->mixer_num; for (i = MDP4_MIXER_STAGE_BASE; i < MDP4_MIXER_STAGE_MAX; i++) { pp = ctrl->stage[mixer][i]; if (pp && pp->pipe_ndx == pipe->pipe_ndx) ctrl->stage[mixer][i] = NULL; /* clear it */ } if (commit) mdp4_mixer_stage_commit(mixer); } /* * mixer0: rgb3: border color at register 0x15004, 0x15008 * mixer1: vg3: border color at register 0x1D004, 0x1D008 * mixer2: xxx: border color at register 0x8D004, 0x8D008 */ void mdp4_overlay_borderfill_stage_up(struct mdp4_overlay_pipe *pipe) { struct mdp4_overlay_pipe *bspipe; int ptype, pnum, pndx, mixer; int format, alpha_enable, alpha; struct mdp4_iommu_pipe_info iom; if (pipe->pipe_type != OVERLAY_TYPE_BF) return; mixer = pipe->mixer_num; if (ctrl->baselayer[mixer]) return; bspipe = ctrl->stage[mixer][MDP4_MIXER_STAGE_BASE]; if (bspipe == NULL) { pr_err("%s: no base layer at mixer=%d\n", __func__, mixer); return; } /* * bspipe is clone here * get real pipe */ bspipe = mdp4_overlay_ndx2pipe(bspipe->pipe_ndx); if (bspipe == NULL) { pr_err("%s: mdp4_overlay_ndx2pipe returned null pipe ndx\n", __func__); return; } /* save original base layer */ ctrl->baselayer[mixer] = bspipe; iom = pipe->iommu; pipe->alpha = 0; /* make sure bf pipe has alpha 0 */ ptype = pipe->pipe_type; pnum = pipe->pipe_num; pndx = pipe->pipe_ndx; format = pipe->src_format; alpha_enable = pipe->alpha_enable; alpha = pipe->alpha; *pipe = *bspipe; /* keep base layer configuration */ pipe->pipe_type = ptype; pipe->pipe_num = pnum; pipe->pipe_ndx = pndx; pipe->src_format = format; pipe->alpha_enable = alpha_enable; pipe->alpha = alpha; pipe->iommu = iom; /* free original base layer pipe to be sued as normal pipe */ bspipe->pipe_used = 0; if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_base_swap(0, pipe); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_base_swap(0, pipe); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_base_swap(0, pipe); else if (ctrl->panel_mode & MDP4_PANEL_DTV) mdp4_dtv_base_swap(0, pipe); mdp4_overlay_reg_flush(bspipe, 1); /* borderfill pipe as base layer */ mdp4_mixer_stage_up(pipe, 0); } void mdp4_overlay_borderfill_stage_down(struct mdp4_overlay_pipe *pipe) { struct mdp4_overlay_pipe *bspipe; int ptype, pnum, pndx, mixer; int format, alpha_enable, alpha; struct mdp4_iommu_pipe_info iom; if (pipe->pipe_type != OVERLAY_TYPE_BF) return; mixer = pipe->mixer_num; /* retrieve original base layer */ bspipe = ctrl->baselayer[mixer]; if (bspipe == NULL) { pr_err("%s: no base layer at mixer=%d\n", __func__, mixer); return; } iom = bspipe->iommu; ptype = bspipe->pipe_type; pnum = bspipe->pipe_num; pndx = bspipe->pipe_ndx; format = bspipe->src_format; alpha_enable = bspipe->alpha_enable; alpha = bspipe->alpha; *bspipe = *pipe; /* restore base layer configuration */ bspipe->pipe_type = ptype; bspipe->pipe_num = pnum; bspipe->pipe_ndx = pndx; bspipe->src_format = format; bspipe->alpha_enable = alpha_enable; bspipe->alpha = alpha; bspipe->iommu = iom; bspipe->pipe_used++; /* mark base layer pipe used */ ctrl->baselayer[mixer] = NULL; /* free borderfill pipe */ pipe->pipe_used = 0; if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_base_swap(0, bspipe); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_base_swap(0, bspipe); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_base_swap(0, bspipe); else if (ctrl->panel_mode & MDP4_PANEL_DTV) mdp4_dtv_base_swap(0, bspipe); /* free borderfill pipe */ mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_down(pipe, 0); /* commit will happen for bspipe up */ mdp4_overlay_pipe_free(pipe, 0); /* stage up base layer */ mdp4_overlay_reg_flush(bspipe, 1); /* restore original base layer */ mdp4_mixer_stage_up(bspipe, 1); } static struct mdp4_overlay_pipe *mdp4_background_layer(int mixer, struct mdp4_overlay_pipe *sp) { struct mdp4_overlay_pipe *pp; struct mdp4_overlay_pipe *kp; int i; kp = ctrl->stage[mixer][MDP4_MIXER_STAGE_BASE]; for (i = MDP4_MIXER_STAGE_BASE; i < MDP4_MIXER_STAGE_MAX; i++) { pp = ctrl->stage[mixer][i]; if (pp == NULL) continue; if (pp == sp) break; if ((pp->dst_x <= sp->dst_x) && ((pp->dst_x + pp->dst_w) >= (sp->dst_x + sp->dst_w))) { if ((pp->dst_y <= sp->dst_y) && ((pp->dst_y + pp->dst_h) >= (sp->dst_y + sp->dst_h))) { kp = pp; } } } return kp; } static void mdp4_overlay_bg_solidfill(struct blend_cfg *blend) { struct mdp4_overlay_pipe *pipe; char *base; u32 op_mode, format; int pnum, ptype; pipe = blend->solidfill_pipe; if (pipe == NULL) return; if (pipe->pipe_type == OVERLAY_TYPE_BF) return; ptype = mdp4_overlay_format2type(pipe->src_format); if (ptype == OVERLAY_TYPE_RGB) { pnum = pipe->pipe_num - OVERLAY_PIPE_RGB1; base = MDP_BASE + MDP4_RGB_BASE; base += MDP4_RGB_OFF * pnum; } else { pnum = pipe->pipe_num - OVERLAY_PIPE_VG1; base = MDP_BASE + MDP4_VIDEO_BASE; base += MDP4_VIDEO_OFF * pnum; } format = inpdw(base + 0x50); if (blend->solidfill) { format |= MDP4_FORMAT_SOLID_FILL; /* * If solid fill is enabled, flip and scale * have to be disabled. otherwise, h/w * underruns. */ op_mode = inpdw(base + 0x0058); op_mode &= ~(MDP4_OP_FLIP_LR + MDP4_OP_SCALEX_EN); op_mode &= ~(MDP4_OP_FLIP_UD + MDP4_OP_SCALEY_EN); outpdw(base + 0x0058, op_mode); outpdw(base + 0x1008, 0); /* black */ /* * Set src size and dst size same to avoid underruns */ outpdw(base + 0x0000, inpdw(base + 0x0008)); } else { u32 src_size = ((pipe->src_h << 16) | pipe->src_w); outpdw(base + 0x0000, src_size); format &= ~MDP4_FORMAT_SOLID_FILL; blend->solidfill_pipe = NULL; } outpdw(base + 0x50, format); mdp4_overlay_reg_flush(pipe, 0); } void mdp4_mixer_blend_cfg(int mixer) { int i, off; unsigned char *overlay_base; struct blend_cfg *blend; if (mixer == MDP4_MIXER2) overlay_base = MDP_BASE + MDP4_OVERLAYPROC2_BASE; else if (mixer == MDP4_MIXER1) overlay_base = MDP_BASE + MDP4_OVERLAYPROC1_BASE; else overlay_base = MDP_BASE + MDP4_OVERLAYPROC0_BASE; blend = &ctrl->blend[mixer][MDP4_MIXER_STAGE_BASE]; blend++; /* stage0 */ for (i = MDP4_MIXER_STAGE0; i < MDP4_MIXER_STAGE_MAX; i++) { off = 20 * i; off = 0x20 * (i - MDP4_MIXER_STAGE0); if (i == MDP4_MIXER_STAGE3) off -= 4; outpdw(overlay_base + off + 0x104, blend->op); blend++; } } static void mdp4_set_blend_by_op(struct mdp4_overlay_pipe *s_pipe, struct mdp4_overlay_pipe *d_pipe, int alpha_drop, struct blend_cfg *blend) { int d_alpha, s_alpha; u32 op; d_alpha = d_pipe->alpha_enable; s_alpha = s_pipe->alpha_enable; /* base on fg's alpha */ blend->fg_alpha = s_pipe->alpha; blend->bg_alpha = 0x0ff - s_pipe->alpha; blend->op = MDP4_BLEND_FG_ALPHA_FG_CONST | MDP4_BLEND_BG_ALPHA_BG_CONST; blend->co3_sel = 1; /* use fg alpha */ op = s_pipe->blend_op; if (op == BLEND_OP_OPAQUE) { blend->bg_alpha = 0; blend->fg_alpha = 0xff; } else if ((op == BLEND_OP_PREMULTIPLIED) && (!alpha_drop) && s_alpha) { blend->op = MDP4_BLEND_FG_ALPHA_FG_CONST | MDP4_BLEND_BG_INV_ALPHA | MDP4_BLEND_BG_ALPHA_FG_PIXEL; if (blend->fg_alpha != 0xff) { blend->bg_alpha = blend->fg_alpha; blend->op |= MDP4_BLEND_BG_MOD_ALPHA; } } else if (!alpha_drop && s_alpha) { blend->op = MDP4_BLEND_FG_ALPHA_FG_PIXEL | MDP4_BLEND_BG_INV_ALPHA | MDP4_BLEND_BG_ALPHA_FG_PIXEL; if (blend->fg_alpha != 0xff) { blend->bg_alpha = blend->fg_alpha; blend->op |= MDP4_BLEND_FG_MOD_ALPHA | MDP4_BLEND_BG_MOD_ALPHA; } } if (!s_alpha && d_alpha) blend->co3_sel = 0; pr_debug("%s: op %d bg alpha %d, fg alpha %d blend: %x\n", __func__, op, blend->bg_alpha, blend->fg_alpha, blend->op); } static void mdp4_set_blend_by_fmt(struct mdp4_overlay_pipe *s_pipe, struct mdp4_overlay_pipe *d_pipe, int alpha_drop, struct blend_cfg *blend) { int ptype, d_alpha, s_alpha; d_alpha = d_pipe->alpha_enable; s_alpha = s_pipe->alpha_enable; /* base on fg's alpha */ blend->bg_alpha = 0x0ff - s_pipe->alpha; blend->fg_alpha = s_pipe->alpha; blend->co3_sel = 1; /* use fg alpha */ if (s_pipe->is_fg) { if (s_pipe->alpha == 0xff) { blend->solidfill = 1; blend->solidfill_pipe = d_pipe; } } else if (s_alpha) { if (!alpha_drop) { blend->op = MDP4_BLEND_BG_ALPHA_FG_PIXEL; if (!(s_pipe->flags & MDP_BLEND_FG_PREMULT)) blend->op |= MDP4_BLEND_FG_ALPHA_FG_PIXEL; } else blend->op = MDP4_BLEND_BG_ALPHA_FG_CONST; blend->op |= MDP4_BLEND_BG_INV_ALPHA; } else if (d_alpha) { ptype = mdp4_overlay_format2type(s_pipe->src_format); if (ptype == OVERLAY_TYPE_VIDEO && (!(s_pipe->flags & MDP_BACKEND_COMPOSITION))) { blend->op = (MDP4_BLEND_FG_ALPHA_BG_PIXEL | MDP4_BLEND_FG_INV_ALPHA); if (!(s_pipe->flags & MDP_BLEND_FG_PREMULT)) blend->op |= MDP4_BLEND_BG_ALPHA_BG_PIXEL; blend->co3_sel = 0; /* use bg alpha */ } else { /* s_pipe is rgb without alpha */ blend->op = (MDP4_BLEND_FG_ALPHA_FG_CONST | MDP4_BLEND_BG_ALPHA_BG_CONST); blend->bg_alpha = 0; } } } /* * D(i+1) = Ks * S + Kd * D(i) */ void mdp4_mixer_blend_setup(int mixer) { struct mdp4_overlay_pipe *d_pipe; struct mdp4_overlay_pipe *s_pipe; struct blend_cfg *blend; int i, off, alpha_drop; unsigned char *overlay_base; uint32 c0, c1, c2; d_pipe = ctrl->stage[mixer][MDP4_MIXER_STAGE_BASE]; if (d_pipe == NULL) { pr_err("%s: Error: no bg_pipe at mixer=%d\n", __func__, mixer); return; } blend = &ctrl->blend[mixer][MDP4_MIXER_STAGE0]; for (i = MDP4_MIXER_STAGE0; i < MDP4_MIXER_STAGE_MAX; i++) { blend->solidfill = 0; blend->op = (MDP4_BLEND_FG_ALPHA_FG_CONST | MDP4_BLEND_BG_ALPHA_BG_CONST); s_pipe = ctrl->stage[mixer][i]; if (s_pipe == NULL) { blend++; d_pipe = NULL; continue; } alpha_drop = 0; /* per stage */ /* alpha channel is lost on VG pipe when using QSEED or M/N */ if (s_pipe->pipe_type == OVERLAY_TYPE_VIDEO && s_pipe->alpha_enable && ((s_pipe->op_mode & MDP4_OP_SCALEY_EN) || (s_pipe->op_mode & MDP4_OP_SCALEX_EN)) && !(s_pipe->op_mode & (MDP4_OP_SCALEX_PIXEL_RPT | MDP4_OP_SCALEY_PIXEL_RPT))) alpha_drop = 1; d_pipe = mdp4_background_layer(mixer, s_pipe); pr_debug("%s: stage=%d: bg: ndx=%d da=%d dalpha=%x " "fg: ndx=%d sa=%d salpha=%x is_fg=%d alpha_drop=%d\n", __func__, i-2, d_pipe->pipe_ndx, d_pipe->alpha_enable, d_pipe->alpha, s_pipe->pipe_ndx, s_pipe->alpha_enable, s_pipe->alpha, s_pipe->is_fg, alpha_drop); if ((s_pipe->blend_op == BLEND_OP_NOT_DEFINED) || (s_pipe->blend_op >= BLEND_OP_MAX)) mdp4_set_blend_by_fmt(s_pipe, d_pipe, alpha_drop, blend); else mdp4_set_blend_by_op(s_pipe, d_pipe, alpha_drop, blend); if (s_pipe->transp != MDP_TRANSP_NOP) { if (s_pipe->is_fg) { transp_color_key(s_pipe->src_format, s_pipe->transp, &c0, &c1, &c2); /* Fg blocked */ blend->op |= MDP4_BLEND_FG_TRANSP_EN; /* lower limit */ blend->transp_low0 = (c1 << 16 | c0); blend->transp_low1 = c2; /* upper limit */ blend->transp_high0 = (c1 << 16 | c0); blend->transp_high1 = c2; } else { transp_color_key(d_pipe->src_format, s_pipe->transp, &c0, &c1, &c2); /* Fg blocked */ blend->op |= MDP4_BLEND_BG_TRANSP_EN; blend--; /* one stage back */ /* lower limit */ blend->transp_low0 = (c1 << 16 | c0); blend->transp_low1 = c2; /* upper limit */ blend->transp_high0 = (c1 << 16 | c0); blend->transp_high1 = c2; blend++; /* back to original stage */ } } blend++; } /* mixer numer, /dev/fb0, /dev/fb1, /dev/fb2 */ if (mixer == MDP4_MIXER2) overlay_base = MDP_BASE + MDP4_OVERLAYPROC2_BASE;/* 0x88000 */ else if (mixer == MDP4_MIXER1) overlay_base = MDP_BASE + MDP4_OVERLAYPROC1_BASE;/* 0x18000 */ else overlay_base = MDP_BASE + MDP4_OVERLAYPROC0_BASE;/* 0x10000 */ mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_ON, FALSE); blend = &ctrl->blend[mixer][MDP4_MIXER_STAGE_BASE]; /* lower limit */ outpdw(overlay_base + 0x180, blend->transp_low0); outpdw(overlay_base + 0x184, blend->transp_low1); /* upper limit */ outpdw(overlay_base + 0x188, blend->transp_high0); outpdw(overlay_base + 0x18c, blend->transp_high1); blend++; /* stage0 */ for (i = MDP4_MIXER_STAGE0; i < MDP4_MIXER_STAGE_MAX; i++) { off = 20 * i; off = 0x20 * (i - MDP4_MIXER_STAGE0); if (i == MDP4_MIXER_STAGE3) off -= 4; if (blend->solidfill_pipe) mdp4_overlay_bg_solidfill(blend); outpdw(overlay_base + off + 0x108, blend->fg_alpha); outpdw(overlay_base + off + 0x10c, blend->bg_alpha); if (mdp_rev >= MDP_REV_42) outpdw(overlay_base + off + 0x104, blend->op); outpdw(overlay_base + (off << 5) + 0x1004, blend->co3_sel); outpdw(overlay_base + off + 0x110, blend->transp_low0);/* low */ outpdw(overlay_base + off + 0x114, blend->transp_low1);/* low */ /* upper limit */ outpdw(overlay_base + off + 0x118, blend->transp_high0); outpdw(overlay_base + off + 0x11c, blend->transp_high1); blend++; } mdp_pipe_ctrl(MDP_CMD_BLOCK, MDP_BLOCK_POWER_OFF, FALSE); } void mdp4_overlay_reg_flush(struct mdp4_overlay_pipe *pipe, int all) { int mixer; uint32 *reg; mixer = pipe->mixer_num; reg = &ctrl->flush[mixer]; *reg |= (1 << (2 + pipe->pipe_num)); if (all) { if (mixer == MDP4_MIXER0) *reg |= 0x01; else *reg |= 0x02; } } void mdp4_overlay_flush_piggyback(int m0, int m1) { u32 data; data = ctrl->flush[m0] | ctrl->flush[m1]; ctrl->flush[m0] = data; } void mdp4_overlay_reg_flush_reset(struct mdp4_overlay_pipe *pipe) { int mixer; mixer = pipe->mixer_num; ctrl->flush[mixer] = 0; } struct mdp4_overlay_pipe *mdp4_overlay_stage_pipe(int mixer, int stage) { return ctrl->stage[mixer][stage]; } struct mdp4_overlay_pipe *mdp4_overlay_ndx2pipe(int ndx) { struct mdp4_overlay_pipe *pipe; if (ndx <= 0 || ndx > OVERLAY_PIPE_MAX) return NULL; pipe = &ctrl->plist[ndx - 1]; /* ndx start from 1 */ if (pipe->pipe_used == 0) return NULL; return pipe; } struct mdp4_overlay_pipe *mdp4_overlay_pipe_alloc(int ptype, int mixer) { int i; struct mdp4_overlay_pipe *pipe; if (ptype == OVERLAY_TYPE_BF) { if (!mdp4_overlay_borderfill_supported()) return NULL; } for (i = 0; i < OVERLAY_PIPE_MAX; i++) { pipe = &ctrl->plist[i]; if (pipe->pipe_type == ptype || (ptype == OVERLAY_TYPE_RGB && pipe->pipe_type == OVERLAY_TYPE_VIDEO)) { if ((ptype == OVERLAY_TYPE_BF && mixer != pipe->mixer_num) || (ptype != OVERLAY_TYPE_BF && pipe->pipe_used != 0)) { continue; } else if (ptype == OVERLAY_TYPE_BF) { //borderfill pipe mdp4_overlay_borderfill_stage_down(pipe); } init_completion(&pipe->comp); init_completion(&pipe->dmas_comp); pr_debug("%s: pipe=%x ndx=%d num=%d\n", __func__, (int)pipe, pipe->pipe_ndx, pipe->pipe_num); return pipe; } } pr_err("%s: ptype=%d FAILED\n", __func__, ptype); return NULL; } void mdp4_overlay_pipe_free(struct mdp4_overlay_pipe *pipe, int all) { uint32 ptype, num, ndx, mixer; struct mdp4_iommu_pipe_info iom; struct mdp4_overlay_pipe *orgpipe; pr_debug("%s: pipe=%x ndx=%d\n", __func__, (int)pipe, pipe->pipe_ndx); ptype = pipe->pipe_type; num = pipe->pipe_num; ndx = pipe->pipe_ndx; mixer = pipe->mixer_num; /* No need for borderfill pipe */ if (pipe->pipe_type != OVERLAY_TYPE_BF) mdp4_overlay_iommu_pipe_free(pipe->pipe_ndx, all); iom = pipe->iommu; memset(pipe, 0, sizeof(*pipe)); pipe->pipe_type = ptype; pipe->pipe_num = num; pipe->pipe_ndx = ndx; pipe->mixer_num = mixer; pipe->iommu = iom; /*Clear real pipe attributes as well */ orgpipe = mdp4_overlay_ndx2pipe(pipe->pipe_ndx); if (orgpipe != NULL) orgpipe->pipe_used = 0; } static int mdp4_overlay_req2pipe(struct mdp_overlay *req, int mixer, struct mdp4_overlay_pipe **ppipe, struct msm_fb_data_type *mfd) { struct mdp4_overlay_pipe *pipe; int ret, ptype; u32 upscale_max; upscale_max = (mdp_rev >= MDP_REV_41) ? MDP4_REV41_OR_LATER_UP_SCALING_MAX : MDP4_REV40_UP_SCALING_MAX; if (mfd == NULL) { pr_err("%s: mfd == NULL, -ENODEV\n", __func__); return -ENODEV; } if (mixer >= MDP4_MIXER_MAX) { pr_err("%s: mixer out of range!\n", __func__); mdp4_stat.err_mixer++; return -ERANGE; } if (req->z_order < 0 || req->z_order > 3) { pr_err("%s: z_order=%d out of range!\n", __func__, req->z_order); mdp4_stat.err_zorder++; return -ERANGE; } if (req->src_rect.h > 0xFFF || req->src_rect.h < 2) { pr_err("%s: src_h is out of range: 0X%x!\n", __func__, req->src_rect.h); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.w > 0xFFF || req->src_rect.w < 2) { pr_err("%s: src_w is out of range: 0X%x!\n", __func__, req->src_rect.w); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.x > 0xFFF) { pr_err("%s: src_x is out of range: 0X%x!\n", __func__, req->src_rect.x); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.y > 0xFFF) { pr_err("%s: src_y is out of range: 0X%x!\n", __func__, req->src_rect.y); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.h > 0xFFF || req->dst_rect.h < 2) { pr_err("%s: dst_h is out of range: 0X%x!\n", __func__, req->dst_rect.h); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.w > 0xFFF || req->dst_rect.w < 2) { pr_err("%s: dst_w is out of range: 0X%x!\n", __func__, req->dst_rect.w); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.x > 0xFFF) { pr_err("%s: dst_x is out of range: 0X%x!\n", __func__, req->dst_rect.x); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.y > 0xFFF) { pr_err("%s: dst_y is out of range: 0X%x!\n", __func__, req->dst_rect.y); mdp4_stat.err_size++; return -EINVAL; } if (req->src_rect.h == 0 || req->src_rect.w == 0) { pr_err("%s: src img of zero size!\n", __func__); mdp4_stat.err_size++; return -EINVAL; } if (req->dst_rect.h > (req->src_rect.h * upscale_max)) { mdp4_stat.err_scale++; pr_err("%s: scale up, too much (h)!\n", __func__); return -ERANGE; } if (req->src_rect.h > (req->dst_rect.h * 8)) { /* too little */ mdp4_stat.err_scale++; pr_err("%s: scale down, too little (h)!\n", __func__); return -ERANGE; } if (req->dst_rect.w > (req->src_rect.w * upscale_max)) { mdp4_stat.err_scale++; pr_err("%s: scale up, too much (w)!\n", __func__); return -ERANGE; } if (req->src_rect.w > (req->dst_rect.w * 8)) { /* too little */ mdp4_stat.err_scale++; pr_err("%s: scale down, too little (w)!\n", __func__); return -ERANGE; } if (mdp_hw_revision == MDP4_REVISION_V1) { /* non integer down saceling ratio smaller than 1/4 * is not supportted */ if (req->src_rect.h > (req->dst_rect.h * 4)) { if (req->src_rect.h % req->dst_rect.h) { mdp4_stat.err_scale++; pr_err("%s: need integer (h)!\n", __func__); return -ERANGE; } } if (req->src_rect.w > (req->dst_rect.w * 4)) { if (req->src_rect.w % req->dst_rect.w) { mdp4_stat.err_scale++; pr_err("%s: need integer (w)!\n", __func__); return -ERANGE; } } } if (((req->src_rect.x + req->src_rect.w) > req->src.width) || ((req->src_rect.y + req->src_rect.h) > req->src.height)) { mdp4_stat.err_size++; pr_err("%s invalid src rectangle\n", __func__); return -ERANGE; } if (ctrl->panel_3d != MDP4_3D_SIDE_BY_SIDE) { int xres; int yres; xres = mfd->panel_info.xres; yres = mfd->panel_info.yres; if (((req->dst_rect.x + req->dst_rect.w) > xres) || ((req->dst_rect.y + req->dst_rect.h) > yres)) { mdp4_stat.err_size++; pr_err("%s invalid dst rectangle (%dx%d) vs (%dx%d)\n", __func__,(req->dst_rect.x + req->dst_rect.w),(req->dst_rect.y + req->dst_rect.h),xres,yres); return -ERANGE; } } ptype = mdp4_overlay_format2type(req->src.format); if (ptype < 0) { pr_err("%s: mdp4_overlay_format2type!\n", __func__); return ptype; } if (req->flags & MDP_OV_PIPE_SHARE) ptype = OVERLAY_TYPE_VIDEO; /* VG pipe supports both RGB+YUV */ if (req->id == MSMFB_NEW_REQUEST) /* new request */ pipe = mdp4_overlay_pipe_alloc(ptype, mixer); else pipe = mdp4_overlay_ndx2pipe(req->id); if (pipe == NULL) { pr_err("%s: pipe == NULL!\n", __func__); return -ENOMEM; } #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) pipe->mfd = mfd; #endif if (!display_iclient && !IS_ERR_OR_NULL(mfd->iclient)) { display_iclient = mfd->iclient; pr_debug("%s(): display_iclient %p\n", __func__, display_iclient); } pipe->src_format = req->src.format; ret = mdp4_overlay_format2pipe(pipe); if (ret < 0) { pr_err("%s: mdp4_overlay_format2pipe!\n", __func__); return ret; } /* * base layer == 1, reserved for frame buffer * zorder 0 == stage 0 == 2 * zorder 1 == stage 1 == 3 * zorder 2 == stage 2 == 4 */ if (req->id == MSMFB_NEW_REQUEST) { /* new request */ if (mdp4_overlay_pipe_staged(pipe)) { pr_err("%s: ndx=%d still staged\n", __func__, pipe->pipe_ndx); return -EPERM; } pipe->pipe_used++; pipe->mixer_num = mixer; pr_debug("%s: zorder=%d pipe ndx=%d num=%d\n", __func__, req->z_order, pipe->pipe_ndx, pipe->pipe_num); } pipe->mixer_stage = req->z_order + MDP4_MIXER_STAGE0; pipe->src_width = req->src.width & 0x1fff; /* source img width */ pipe->src_height = req->src.height & 0x1fff; /* source img height */ pipe->src_h = req->src_rect.h & 0x07ff; pipe->src_w = req->src_rect.w & 0x07ff; pipe->src_y = req->src_rect.y & 0x07ff; pipe->src_x = req->src_rect.x & 0x07ff; pipe->dst_h = req->dst_rect.h & 0x07ff; pipe->dst_w = req->dst_rect.w & 0x07ff; pipe->dst_y = req->dst_rect.y & 0x07ff; pipe->dst_x = req->dst_rect.x & 0x07ff; pipe->op_mode = 0; #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) pipe->ext_flag = req->flags; #endif if (req->flags & MDP_FLIP_LR) pipe->op_mode |= MDP4_OP_FLIP_LR; if (req->flags & MDP_FLIP_UD) pipe->op_mode |= MDP4_OP_FLIP_UD; if (req->flags & MDP_DITHER) pipe->op_mode |= MDP4_OP_DITHER_EN; if (req->flags & MDP_DEINTERLACE) pipe->op_mode |= MDP4_OP_DEINT_EN; if (req->flags & MDP_DEINTERLACE_ODD) pipe->op_mode |= MDP4_OP_DEINT_ODD_REF; pipe->is_fg = req->is_fg;/* control alpha and color key */ pipe->alpha = req->alpha & 0x0ff; pipe->blend_op = req->blend_op; pipe->transp = req->transp_mask; pipe->flags = req->flags; *ppipe = pipe; return 0; } static int mdp4_calc_pipe_mdp_clk(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { u32 pclk; u32 xscale, yscale; u32 hsync = 0; u32 shift = 16; u64 rst; int ptype; int ret = -EINVAL; if (!pipe) { pr_err("%s: pipe is null!\n", __func__); return ret; } if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } pr_debug("%s: pipe sets: panel res(x,y)=(%d,%d)\n", __func__, mfd->panel_info.xres, mfd->panel_info.yres); pr_debug("%s: src(w,h)(%d,%d),src(x,y)(%d,%d)\n", __func__, pipe->src_w, pipe->src_h, pipe->src_x, pipe->src_y); pr_debug("%s: dst(w,h)(%d,%d),dst(x,y)(%d,%d)\n", __func__, pipe->dst_w, pipe->dst_h, pipe->dst_x, pipe->dst_y); pclk = (mfd->panel_info.type == MIPI_VIDEO_PANEL || mfd->panel_info.type == MIPI_CMD_PANEL) ? mfd->panel_info.mipi.dsi_pclk_rate : mfd->panel_info.clk_rate; if (mfd->panel_info.type == LVDS_PANEL && mfd->panel_info.lvds.channel_mode == LVDS_DUAL_CHANNEL_MODE) pclk = pclk << 1; if (!pclk) { pipe->req_clk = mdp_max_clk; pr_err("%s panel pixel clk is zero!\n", __func__); return ret; } pr_debug("%s: mdp panel pixel clk is %d.\n", __func__, pclk); if (!pipe->dst_h) { pr_err("%s: pipe dst_h is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (!pipe->src_h) { pr_err("%s: pipe src_h is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (!pipe->dst_w) { pr_err("%s: pipe dst_w is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (!pipe->dst_h) { pr_err("%s: pipe dst_h is zero!\n", __func__); pipe->req_clk = mdp_max_clk; return ret; } if (pipe->mixer_num == MDP4_MIXER0) { if (pipe->blt_forced) return 0; ptype = mdp4_overlay_format2type(pipe->src_format); if (ptype == OVERLAY_TYPE_VIDEO) { if ((pipe->src_h >= 720) && (pipe->src_w >= 1080)) { pipe->req_clk = (u32) mdp_max_clk + 100; pipe->blt_forced++; return 0; } else if ((pipe->src_h >= 1080) && (pipe->src_w >= 720)) { pipe->req_clk = (u32) mdp_max_clk + 100; pipe->blt_forced++; return 0; } } } /* * For the scaling cases, make more margin by removing porch * values and adding extra 20%. */ if ((pipe->src_h != pipe->dst_h) || (pipe->src_w != pipe->dst_w)) { hsync = mfd->panel_info.xres; hsync *= 100; hsync /= 120; pr_debug("%s: panel hsync is %d. with scaling\n", __func__, hsync); } else { hsync = mfd->panel_info.lcdc.h_back_porch + mfd->panel_info.lcdc.h_front_porch + mfd->panel_info.lcdc.h_pulse_width + mfd->panel_info.xres; pr_debug("%s: panel hsync is %d.\n", __func__, hsync); } if (!hsync) { pipe->req_clk = mdp_max_clk; pr_err("%s: panel hsync is zero!\n", __func__); return 0; } xscale = mfd->panel_info.xres; xscale += pipe->src_w; if (xscale < pipe->dst_w) { pipe->req_clk = mdp_max_clk; pr_err("%s: xres+src_w cannot be less than dst_w!\n", __func__); return ret; } xscale -= pipe->dst_w; xscale <<= shift; xscale /= hsync; pr_debug("%s: the right %d shifted xscale is %d.\n", __func__, shift, xscale); if (pipe->src_h > pipe->dst_h) { yscale = pipe->src_h; yscale <<= shift; yscale /= pipe->dst_h; } else { /* upscale */ yscale = pipe->dst_h; yscale <<= shift; yscale /= pipe->src_h; } yscale *= pipe->src_w; yscale /= hsync; pr_debug("%s: the right %d shifted yscale is %d.\n", __func__, shift, yscale); rst = pclk; if (yscale > xscale) rst *= yscale; else rst *= xscale; rst >>= shift; /* * There is one special case for the panels that have low * v_back_porch (<=4), mdp clk should be fast enough to buffer * 4 lines input during back porch time if scaling is * required(FIR). */ if ((mfd->panel_info.lcdc.v_back_porch <= 4) && (pipe->src_h != pipe->dst_h) && (mfd->panel_info.lcdc.v_back_porch)) { u32 clk = 0; clk = 4 * (pclk >> shift) / mfd->panel_info.lcdc.v_back_porch; clk <<= shift; pr_debug("%s: mdp clk rate %d based on low vbp %d\n", __func__, clk, mfd->panel_info.lcdc.v_back_porch); rst = (rst > clk) ? rst : clk; } /* * If the calculated mdp clk is less than panel pixel clk, * most likely due to upscaling, mdp clk rate will be set to * greater than pclk. Now the driver uses 1.15 as the * factor. Ideally this factor is passed from board file. */ if (rst < pclk) { rst = ((pclk >> shift) * 23 / 20) << shift; pr_debug("%s calculated mdp clk is less than pclk.\n", __func__); } /* * Interlaced videos require the max mdp clk but cannot * be explained by mdp clk equation. */ if (pipe->flags & MDP_DEINTERLACE) { rst = (rst > mdp_max_clk) ? rst : mdp_max_clk; pr_info("%s deinterlace requires max mdp clk.\n", __func__); } pipe->req_clk = (u32) rst; pr_debug("%s: required mdp clk %d mixer %d pipe ndx %d\n", __func__, pipe->req_clk, pipe->mixer_num, pipe->pipe_ndx); return 0; } static int mdp4_calc_pipe_mdp_bw(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { u32 fps; int ret = -EINVAL; u32 quota; u32 shift = 16; if (!pipe) { pr_err("%s: pipe is null!\n", __func__); return ret; } if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } fps = mdp_get_panel_framerate(mfd); quota = pipe->src_w * pipe->src_h * fps * pipe->bpp; quota >>= shift; pipe->bw_ab_quota = quota * mdp_bw_ab_factor / 100; pipe->bw_ib_quota = quota * mdp_bw_ib_factor / 100; pr_debug("%s max_bw=%llu ab_factor=%d ib_factor=%d\n", __func__, mdp_max_bw, mdp_bw_ab_factor, mdp_bw_ib_factor); /* down scaling factor for ib */ if ((!pipe->dst_h) && (!pipe->src_h) && (pipe->src_h > pipe->dst_h)) { u64 ib = quota; ib *= pipe->src_h; ib /= pipe->dst_h; pipe->bw_ib_quota = max(ib, pipe->bw_ib_quota); pr_debug("%s: src_h=%d dst_h=%d mdp ib %llu, ib_quota=%llu\n", __func__, pipe->src_h, pipe->dst_h, ib<<shift, pipe->bw_ib_quota<<shift); } pipe->bw_ab_quota <<= shift; pipe->bw_ib_quota <<= shift; pr_debug("%s: pipe ndx=%d src(h,w)(%d, %d) fps=%d bpp=%d\n", __func__, pipe->pipe_ndx, pipe->src_h, pipe->src_w, fps, pipe->bpp); pr_debug("%s: ab_quota=%llu ib_quota=%llu\n", __func__, pipe->bw_ab_quota, pipe->bw_ib_quota); return 0; } int mdp4_calc_blt_mdp_bw(struct msm_fb_data_type *mfd, struct mdp4_overlay_pipe *pipe) { struct mdp4_overlay_perf *perf_req = &perf_request; u32 fps; int bpp; int ret = -EINVAL; u32 quota; u32 shift = 16; if (!pipe) { pr_err("%s: pipe is null!\n", __func__); return ret; } if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } mutex_lock(&perf_mutex); bpp = BLT_BPP; fps = mdp_get_panel_framerate(mfd); /* read and write bw*/ quota = pipe->dst_w * pipe->dst_h * fps * bpp * 2; quota >>= shift; perf_req->mdp_ov_ab_bw[pipe->mixer_num] = quota * mdp_bw_ab_factor / 100; perf_req->mdp_ov_ib_bw[pipe->mixer_num] = quota * mdp_bw_ib_factor / 100; perf_req->mdp_ov_ab_bw[pipe->mixer_num] <<= shift; perf_req->mdp_ov_ib_bw[pipe->mixer_num] <<= shift; pr_debug("%s: pipe ndx=%d dst(h,w)(%d, %d) fps=%d bpp=%d\n", __func__, pipe->pipe_ndx, pipe->dst_h, pipe->dst_w, fps, bpp); pr_debug("%s: overlay=%d ab_bw=%llu ib_bw=%llu\n", __func__, pipe->mixer_num, perf_req->mdp_ov_ab_bw[pipe->mixer_num], perf_req->mdp_ov_ib_bw[pipe->mixer_num]); mutex_unlock(&perf_mutex); return 0; } int mdp4_overlay_mdp_perf_req(struct msm_fb_data_type *mfd) { u32 worst_mdp_clk = 0; int i; struct mdp4_overlay_perf *perf_req = &perf_request; struct mdp4_overlay_pipe *pipe; u32 cnt = 0; int ret = -EINVAL; u64 ab_quota_total = 0, ib_quota_total = 0; if (!mfd) { pr_err("%s: mfd is null!\n", __func__); return ret; } mutex_lock(&perf_mutex); pipe = ctrl->plist; for (i = 0; i < MDP4_MIXER_MAX; i++) perf_req->use_ov_blt[i] = 0; for (i = 0; i < OVERLAY_PIPE_MAX; i++, pipe++) { if (!pipe) { mutex_unlock(&perf_mutex); return ret; } if (!pipe->pipe_used) continue; cnt++; if (worst_mdp_clk < pipe->req_clk) worst_mdp_clk = pipe->req_clk; if (pipe->req_clk > mdp_max_clk) perf_req->use_ov_blt[pipe->mixer_num] = 1; if (pipe->mixer_num == MDP4_MIXER2) perf_req->use_ov_blt[MDP4_MIXER2] = 1; if (pipe->pipe_type != OVERLAY_TYPE_BF) { ab_quota_total += pipe->bw_ab_quota; ib_quota_total += pipe->bw_ib_quota; } if (mfd->mdp_rev == MDP_REV_41) { /* * writeback (blt) mode to provide work around * for dsi cmd mode interface hardware bug. */ if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { if (pipe->dst_x != 0) perf_req->use_ov_blt[MDP4_MIXER0] = 1; } if ((mfd->panel_info.xres > 1280) && (mfd->panel_info.type != DTV_PANEL)) { perf_req->use_ov_blt[MDP4_MIXER0] = 1; } } } perf_req->mdp_clk_rate = min(worst_mdp_clk, mdp_max_clk); perf_req->mdp_clk_rate = mdp_clk_round_rate(perf_req->mdp_clk_rate); for (i = 0; i < MDP4_MIXER_MAX; i++) { if (perf_req->use_ov_blt[i]) { ab_quota_total += perf_req->mdp_ov_ab_bw[i]; ib_quota_total += perf_req->mdp_ov_ib_bw[i]; } } perf_req->mdp_ab_bw = roundup(ab_quota_total, MDP_BUS_SCALE_AB_STEP); perf_req->mdp_ib_bw = roundup(ib_quota_total, MDP_BUS_SCALE_AB_STEP); pr_debug("%s %d: ab_quota_total=(%llu, %d) ib_quota_total=(%llu, %d)\n", __func__, __LINE__, ab_quota_total, perf_req->mdp_ab_bw, ib_quota_total, perf_req->mdp_ib_bw); if (ab_quota_total > mdp_max_bw) pr_warn("%s: req ab bw=%llu is larger than max bw=%llu", __func__, ab_quota_total, mdp_max_bw); if (ib_quota_total > mdp_max_bw) pr_warn("%s: req ib bw=%llu is larger than max bw=%llu", __func__, ib_quota_total, mdp_max_bw); pr_debug("%s %d: pid %d cnt %d clk %d ov0_blt %d, ov1_blt %d\n", __func__, __LINE__, current->pid, cnt, perf_req->mdp_clk_rate, perf_req->use_ov_blt[0], perf_req->use_ov_blt[1]); mutex_unlock(&perf_mutex); return 0; } int mdp4_overlay_mdp_pipe_req(struct mdp4_overlay_pipe *pipe, struct msm_fb_data_type *mfd) { int ret = 0; if (mdp4_calc_pipe_mdp_clk(mfd, pipe)) { pr_err("%s unable to calc mdp pipe clk rate ret=%d\n", __func__, ret); ret = -EINVAL; } if (mdp4_calc_pipe_mdp_bw(mfd, pipe)) { pr_err("%s unable to calc mdp pipe bandwidth ret=%d\n", __func__, ret); ret = -EINVAL; } return ret; } void mdp4_overlay_mdp_perf_upd(struct msm_fb_data_type *mfd, int flag) { struct mdp4_overlay_perf *perf_req = &perf_request; struct mdp4_overlay_perf *perf_cur = &perf_current; pr_debug("%s %d: req mdp clk %d, cur mdp clk %d flag %d\n", __func__, __LINE__, perf_req->mdp_clk_rate, perf_cur->mdp_clk_rate, flag); mutex_lock(&perf_mutex); if (!mdp4_extn_disp) perf_cur->use_ov_blt[1] = 0; if (flag) { if (perf_req->mdp_clk_rate > perf_cur->mdp_clk_rate) { mdp_set_core_clk(perf_req->mdp_clk_rate); pr_info("%s mdp clk is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_clk_rate, perf_req->mdp_clk_rate); perf_cur->mdp_clk_rate = perf_req->mdp_clk_rate; } if ((perf_req->mdp_ab_bw > perf_cur->mdp_ab_bw) || (perf_req->mdp_ib_bw > perf_cur->mdp_ib_bw)) { mdp_bus_scale_update_request (perf_req->mdp_ab_bw, perf_req->mdp_ib_bw); pr_debug("%s mdp ab_bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ab_bw, perf_req->mdp_ab_bw); pr_debug("%s mdp ib_bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ib_bw, perf_req->mdp_ib_bw); perf_cur->mdp_ab_bw = perf_req->mdp_ab_bw; perf_cur->mdp_ib_bw = perf_req->mdp_ib_bw; } if ((mfd->panel_info.pdest == DISPLAY_1 && perf_req->use_ov_blt[0] && !perf_cur->use_ov_blt[0]) || dbg_force_ov0_blt) { if (mfd->panel_info.type == LCDC_PANEL || mfd->panel_info.type == LVDS_PANEL) mdp4_lcdc_overlay_blt_start(mfd); else if (mfd->panel_info.type == MIPI_VIDEO_PANEL) mdp4_dsi_video_blt_start(mfd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_blt_start(mfd); pr_debug("%s mixer0 start blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[0], perf_req->use_ov_blt[0]); perf_cur->use_ov_blt[0] = perf_req->use_ov_blt[0]; } if ((mfd->panel_info.pdest == DISPLAY_2 && perf_req->use_ov_blt[1] && !perf_cur->use_ov_blt[1]) || dbg_force_ov1_blt) { mdp4_dtv_overlay_blt_start(mfd); pr_debug("%s mixer1 start blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[1], perf_req->use_ov_blt[1]); perf_cur->use_ov_blt[1] = perf_req->use_ov_blt[1]; } } else { if (perf_req->mdp_clk_rate < perf_cur->mdp_clk_rate) { pr_info("%s mdp clk is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_clk_rate, perf_req->mdp_clk_rate); mdp_set_core_clk(perf_req->mdp_clk_rate); perf_cur->mdp_clk_rate = perf_req->mdp_clk_rate; } if (perf_req->mdp_ab_bw < perf_cur->mdp_ab_bw || perf_req->mdp_ib_bw < perf_cur->mdp_ib_bw) { mdp_bus_scale_update_request (perf_req->mdp_ab_bw, perf_req->mdp_ib_bw); pr_debug("%s mdp ab bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ab_bw, perf_req->mdp_ab_bw); pr_debug("%s mdp ib bw is changed [%d] from %d to %d\n", __func__, flag, perf_cur->mdp_ib_bw, perf_req->mdp_ib_bw); perf_cur->mdp_ab_bw = perf_req->mdp_ab_bw; perf_cur->mdp_ib_bw = perf_req->mdp_ib_bw; } if ((mfd->panel_info.pdest == DISPLAY_1 && !perf_req->use_ov_blt[0] && perf_cur->use_ov_blt[0]) || dbg_force_ov0_blt) { if (mfd->panel_info.type == LCDC_PANEL || mfd->panel_info.type == LVDS_PANEL) mdp4_lcdc_overlay_blt_stop(mfd); else if (mfd->panel_info.type == MIPI_VIDEO_PANEL) mdp4_dsi_video_blt_stop(mfd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_blt_stop(mfd); pr_debug("%s mixer0 stop blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[0], perf_req->use_ov_blt[0]); perf_cur->use_ov_blt[0] = perf_req->use_ov_blt[0]; } if ((mfd->panel_info.pdest == DISPLAY_2 && !perf_req->use_ov_blt[1] && perf_cur->use_ov_blt[1]) || dbg_force_ov1_blt) { mdp4_dtv_overlay_blt_stop(mfd); pr_debug("%s mixer1 stop blt [%d] from %d to %d.\n", __func__, flag, perf_cur->use_ov_blt[1], perf_req->use_ov_blt[1]); perf_cur->use_ov_blt[1] = perf_req->use_ov_blt[1]; } } mutex_unlock(&perf_mutex); return; } static int get_img(struct msmfb_data *img, struct fb_info *info, struct mdp4_overlay_pipe *pipe, unsigned int plane, unsigned long *start, unsigned long *len, struct file **srcp_file, int *p_need, struct ion_handle **srcp_ihdl) { struct file *file; int put_needed, ret = 0, fb_num; #ifdef CONFIG_ANDROID_PMEM unsigned long vstart; #endif *p_need = 0; if (img->flags & MDP_BLIT_SRC_GEM) { *srcp_file = NULL; return kgsl_gem_obj_addr(img->memory_id, (int) img->priv, start, len); } if (img->flags & MDP_MEMORY_ID_TYPE_FB) { file = fget_light(img->memory_id, &put_needed); if (file == NULL) return -EINVAL; pipe->flags |= MDP_MEMORY_ID_TYPE_FB; if (MAJOR(file->f_dentry->d_inode->i_rdev) == FB_MAJOR) { fb_num = MINOR(file->f_dentry->d_inode->i_rdev); if (get_fb_phys_info(start, len, fb_num, DISPLAY_SUBSYSTEM_ID)) { ret = -1; } else { *srcp_file = file; *p_need = put_needed; } } else ret = -1; if (ret) fput_light(file, put_needed); return ret; } #ifdef CONFIG_MSM_MULTIMEDIA_USE_ION return mdp4_overlay_iommu_map_buf(img->memory_id, pipe, plane, start, len, srcp_ihdl); #endif #ifdef CONFIG_ANDROID_PMEM if (!get_pmem_file(img->memory_id, start, &vstart, len, srcp_file)) return 0; else return -EINVAL; #endif } #ifdef CONFIG_FB_MSM_MIPI_DSI int mdp4_overlay_3d_sbys(struct fb_info *info, struct msmfb_overlay_3d *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; int ret = -EPERM; if (mutex_lock_interruptible(&mfd->dma->ov_mutex)) return -EINTR; if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { mdp4_dsi_cmd_3d_sbys(mfd, req); ret = 0; } else if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) { mdp4_dsi_video_3d_sbys(mfd, req); ret = 0; } mutex_unlock(&mfd->dma->ov_mutex); return ret; } #else int mdp4_overlay_3d_sbys(struct fb_info *info, struct msmfb_overlay_3d *req) { /* do nothing */ return -EPERM; } #endif int mdp4_overlay_blt(struct fb_info *info, struct msmfb_overlay_blt *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; if (mfd == NULL) return -ENODEV; if (mutex_lock_interruptible(&mfd->dma->ov_mutex)) return -EINTR; if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_overlay_blt(mfd, req); else if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_overlay_blt(mfd, req); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_overlay_blt(mfd, req); else if (ctrl->panel_mode & MDP4_PANEL_MDDI) mdp4_mddi_overlay_blt(mfd, req); mutex_unlock(&mfd->dma->ov_mutex); return 0; } int mdp4_overlay_get(struct fb_info *info, struct mdp_overlay *req) { struct mdp4_overlay_pipe *pipe; pipe = mdp4_overlay_ndx2pipe(req->id); if (pipe == NULL) return -ENODEV; *req = pipe->req_data; if (mdp4_overlay_borderfill_supported()) req->flags |= MDP_BORDERFILL_SUPPORTED; return 0; } int mdp4_overlay_set(struct fb_info *info, struct mdp_overlay *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; int ret, mixer; struct mdp4_overlay_pipe *pipe; if (mfd == NULL) { pr_err("%s: mfd == NULL, -ENODEV\n", __func__); return -ENODEV; } if (info->node != 0 || mfd->cont_splash_done) /* primary */ if (!mfd->panel_power_on) /* suspended */ return -EPERM; if (req->src.format == MDP_FB_FORMAT) req->src.format = mfd->fb_imgType; if (mutex_lock_interruptible(&mfd->dma->ov_mutex)) { pr_err("%s: mutex_lock_interruptible, -EINTR\n", __func__); return -EINTR; } mixer = mfd->panel_info.pdest; /* DISPLAY_1 or DISPLAY_2 */ ret = mdp4_overlay_req2pipe(req, mixer, &pipe, mfd); if (ret < 0) { mutex_unlock(&mfd->dma->ov_mutex); pr_err("%s: mdp4_overlay_req2pipe, ret=%d\n", __func__, ret); return ret; } #if (CONFIG_MACH_LGE) mdp4_calc_pipe_mdp_clk(mfd, pipe); if(pipe->mixer_num == MDP4_MIXER0 && pipe->req_clk > mdp_max_clk && OVERLAY_TYPE_RGB == mdp4_overlay_format2type(pipe->src_format)) { pr_err("%s UI blt case, can't compose with MDP directly.\n", __func__); if(req->id == MSMFB_NEW_REQUEST) { mdp4_overlay_pipe_free(pipe,0); } mutex_unlock(&mfd->dma->ov_mutex); return -EINVAL; } #endif if (pipe->flags & MDP_SECURE_OVERLAY_SESSION) { mdp4_map_sec_resource(mfd); } /* return id back to user */ req->id = pipe->pipe_ndx; /* pipe_ndx start from 1 */ pipe->req_data = *req; /* keep original req */ if (!IS_ERR_OR_NULL(mfd->iclient)) { pr_debug("pipe->flags 0x%x\n", pipe->flags); if (pipe->flags & MDP_SECURE_OVERLAY_SESSION) { mfd->mem_hid &= ~BIT(ION_IOMMU_HEAP_ID); mfd->mem_hid |= ION_SECURE; } else { mfd->mem_hid |= BIT(ION_IOMMU_HEAP_ID); mfd->mem_hid &= ~ION_SECURE; } } mdp4_stat.overlay_set[pipe->mixer_num]++; if (pipe->flags & MDP_OVERLAY_PP_CFG_EN) { if (pipe->pipe_num <= OVERLAY_PIPE_VG2) memcpy(&pipe->pp_cfg, &req->overlay_pp_cfg, sizeof(struct mdp_overlay_pp_params)); else pr_debug("%s: RGB Pipes don't support CSC/QSEED\n", __func__); } mdp4_overlay_mdp_pipe_req(pipe, mfd); #if (CONFIG_MACH_LGE) #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_WXGA_PT) || defined(CONFIG_FB_MSM_MIPI_HITACHI_VIDEO_HD_PT) if(pipe->mixer_num == MDP4_MIXER0 && OVERLAY_TYPE_VIDEO == mdp4_overlay_format2type(pipe->src_format)) { pr_debug("%s video blt mode off, req_clk is max now.\n", __func__); pipe->req_clk = mdp_max_clk; } #else if(pipe->mixer_num == MDP4_MIXER0 && pipe->req_clk > mdp_max_clk && OVERLAY_TYPE_VIDEO == mdp4_overlay_format2type(pipe->src_format)) { pr_debug("%s video blt mode off, req_clk is max now.\n", __func__); pipe->req_clk = mdp_max_clk; } #endif #endif mutex_unlock(&mfd->dma->ov_mutex); return 0; } int mdp4_overlay_unset_mixer(int mixer) { struct mdp4_overlay_pipe *pipe; int i, cnt = 0; /* free pipe besides base layer pipe */ for (i = MDP4_MIXER_STAGE3; i > MDP4_MIXER_STAGE_BASE; i--) { pipe = ctrl->stage[mixer][i]; if (pipe == NULL) continue; pipe->flags &= ~MDP_OV_PLAY_NOWAIT; mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_down(pipe, 1); mdp4_overlay_pipe_free(pipe, 1); cnt++; } return cnt; } int mdp4_overlay_unset(struct fb_info *info, int ndx) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct mdp4_overlay_pipe *pipe; if (mfd == NULL) return -ENODEV; if (mutex_lock_interruptible(&mfd->dma->ov_mutex)) return -EINTR; pipe = mdp4_overlay_ndx2pipe(ndx); if (pipe == NULL) { mutex_unlock(&mfd->dma->ov_mutex); return -ENODEV; } if (pipe->pipe_type == OVERLAY_TYPE_BF) { mdp4_overlay_borderfill_stage_down(pipe); mutex_unlock(&mfd->dma->ov_mutex); return 0; } if (pipe->mixer_num == MDP4_MIXER2) ctrl->mixer2_played = 0; else if (pipe->mixer_num == MDP4_MIXER1) ctrl->mixer1_played = 0; else { /* mixer 0 */ ctrl->mixer0_played = 0; if (ctrl->panel_mode & MDP4_PANEL_MDDI) { if (mfd->panel_power_on) mdp4_mddi_blt_dmap_busy_wait(mfd); } } mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_down(pipe, 0); if (pipe->blt_forced) { if (pipe->flags & MDP_SECURE_OVERLAY_SESSION) { pipe->blt_forced = 0; pipe->req_clk = 0; mdp4_overlay_mdp_perf_req(mfd); } } if (pipe->mixer_num == MDP4_MIXER0) { if (ctrl->panel_mode & MDP4_PANEL_MDDI) { if (mfd->panel_power_on) mdp4_mddi_overlay_restore(); } } else { /* mixer1, DTV, ATV */ if (ctrl->panel_mode & MDP4_PANEL_DTV) mdp4_overlay_dtv_unset(mfd, pipe); } mdp4_stat.overlay_unset[pipe->mixer_num]++; mdp4_overlay_pipe_free(pipe, 0); mutex_unlock(&mfd->dma->ov_mutex); return 0; } int mdp4_overlay_wait4vsync(struct fb_info *info) { if (!hdmi_prim_display && info->node == 0) { if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_wait4vsync(0); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_wait4vsync(0); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_wait4vsync(0); } else if (hdmi_prim_display || info->node == 1) { mdp4_dtv_wait4vsync(0); } return 0; } int mdp4_overlay_vsync_ctrl(struct fb_info *info, int enable) { int cmd; if (enable) cmd = 1; else cmd = 0; if (!hdmi_prim_display && info->node == 0) { if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) mdp4_dsi_video_vsync_ctrl(info, cmd); else if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) mdp4_dsi_cmd_vsync_ctrl(info, cmd); else if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_lcdc_vsync_ctrl(info, cmd); } else if (hdmi_prim_display || info->node == 1) mdp4_dtv_vsync_ctrl(info, cmd); return 0; } struct tile_desc { uint32 width; /* tile's width */ uint32 height; /* tile's height */ uint32 row_tile_w; /* tiles per row's width */ uint32 row_tile_h; /* tiles per row's height */ }; void tile_samsung(struct tile_desc *tp) { /* * each row of samsung tile consists of two tiles in height * and two tiles in width which means width should align to * 64 x 2 bytes and height should align to 32 x 2 bytes. * video decoder generate two tiles in width and one tile * in height which ends up height align to 32 X 1 bytes. */ tp->width = 64; /* 64 bytes */ tp->row_tile_w = 2; /* 2 tiles per row's width */ tp->height = 32; /* 32 bytes */ tp->row_tile_h = 1; /* 1 tiles per row's height */ } uint32 tile_mem_size(struct mdp4_overlay_pipe *pipe, struct tile_desc *tp) { uint32 tile_w, tile_h; uint32 row_num_w, row_num_h; tile_w = tp->width * tp->row_tile_w; tile_h = tp->height * tp->row_tile_h; row_num_w = (pipe->src_width + tile_w - 1) / tile_w; row_num_h = (pipe->src_height + tile_h - 1) / tile_h; return ((row_num_w * row_num_h * tile_w * tile_h) + 8191) & ~8191; } int mdp4_overlay_play_wait(struct fb_info *info, struct msmfb_overlay_data *req) { return 0; } /* * mdp4_overlay_dma_commit: called from dma_done isr * No mutex/sleep allowed */ void mdp4_overlay_dma_commit(int mixer) { /* * non double buffer register update here * perf level, new clock rate should be done here */ } /* * mdp4_overlay_vsync_commit: called from tasklet context * No mutex/sleep allowed */ void mdp4_overlay_vsync_commit(struct mdp4_overlay_pipe *pipe) { if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) mdp4_overlay_vg_setup(pipe); /* video/graphic pipe */ else mdp4_overlay_rgb_setup(pipe); /* rgb pipe */ pr_debug("%s: pipe=%x ndx=%d num=%d used=%d\n", __func__, (int) pipe, pipe->pipe_ndx, pipe->pipe_num, pipe->pipe_used); mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_up(pipe, 0); } int mdp4_overlay_play(struct fb_info *info, struct msmfb_overlay_data *req) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; struct msmfb_data *img; struct mdp4_overlay_pipe *pipe; ulong start, addr; ulong len = 0; struct ion_handle *srcp0_ihdl = NULL; struct ion_handle *srcp1_ihdl = NULL, *srcp2_ihdl = NULL; uint32_t overlay_version = 0; int ret = 0; if (mfd == NULL) return -ENODEV; pipe = mdp4_overlay_ndx2pipe(req->id); if (pipe == NULL) { mdp4_stat.err_play++; return -ENODEV; } if (pipe->pipe_type == OVERLAY_TYPE_BF) { mdp4_overlay_borderfill_stage_up(pipe); mdp4_mixer_stage_commit(pipe->mixer_num); return 0; } mutex_lock(&mfd->dma->ov_mutex); img = &req->data; get_img(img, info, pipe, 0, &start, &len, &pipe->srcp0_file, &pipe->put0_need, &srcp0_ihdl); if (len == 0) { pr_err("%s: pmem Error\n", __func__); ret = -1; goto end; } addr = start + img->offset; pipe->srcp0_addr = addr; pipe->srcp0_ystride = pipe->src_width * pipe->bpp; pr_debug("%s: mixer=%d ndx=%x addr=%x flags=%x pid=%d\n", __func__, pipe->mixer_num, pipe->pipe_ndx, (int)addr, pipe->flags, current->pid); if ((req->version_key & VERSION_KEY_MASK) == 0xF9E8D700) overlay_version = (req->version_key & ~VERSION_KEY_MASK); if (pipe->fetch_plane == OVERLAY_PLANE_PSEUDO_PLANAR) { if (overlay_version > 0) { img = &req->plane1_data; get_img(img, info, pipe, 1, &start, &len, &pipe->srcp1_file, &pipe->put1_need, &srcp1_ihdl); if (len == 0) { pr_err("%s: Error to get plane1\n", __func__); ret = -EINVAL; goto end; } pipe->srcp1_addr = start + img->offset; } else if (pipe->frame_format == MDP4_FRAME_FORMAT_VIDEO_SUPERTILE) { struct tile_desc tile; tile_samsung(&tile); pipe->srcp1_addr = addr + tile_mem_size(pipe, &tile); } else { pipe->srcp1_addr = addr + (pipe->src_width * pipe->src_height); } pipe->srcp0_ystride = pipe->src_width; if ((pipe->src_format == MDP_Y_CRCB_H1V1) || (pipe->src_format == MDP_Y_CBCR_H1V1) || (pipe->src_format == MDP_Y_CRCB_H1V2) || (pipe->src_format == MDP_Y_CBCR_H1V2)) { if (pipe->src_width > YUV_444_MAX_WIDTH) pipe->srcp1_ystride = pipe->src_width << 2; else pipe->srcp1_ystride = pipe->src_width << 1; } else pipe->srcp1_ystride = pipe->src_width; } else if (pipe->fetch_plane == OVERLAY_PLANE_PLANAR) { if (overlay_version > 0) { img = &req->plane1_data; get_img(img, info, pipe, 1, &start, &len, &pipe->srcp1_file, &pipe->put1_need, &srcp1_ihdl); if (len == 0) { pr_err("%s: Error to get plane1\n", __func__); ret = -EINVAL; goto end; } pipe->srcp1_addr = start + img->offset; img = &req->plane2_data; get_img(img, info, pipe, 2, &start, &len, &pipe->srcp2_file, &pipe->put2_need, &srcp2_ihdl); if (len == 0) { pr_err("%s: Error to get plane2\n", __func__); ret = -EINVAL; goto end; } pipe->srcp2_addr = start + img->offset; } else { if (pipe->src_format == MDP_Y_CR_CB_GH2V2) { addr += (ALIGN(pipe->src_width, 16) * pipe->src_height); pipe->srcp1_addr = addr; addr += ((ALIGN((pipe->src_width / 2), 16)) * (pipe->src_height / 2)); pipe->srcp2_addr = addr; } else { addr += (pipe->src_width * pipe->src_height); pipe->srcp1_addr = addr; addr += ((pipe->src_width / 2) * (pipe->src_height / 2)); pipe->srcp2_addr = addr; } } /* mdp planar format expects Cb in srcp1 and Cr in p2 */ if ((pipe->src_format == MDP_Y_CR_CB_H2V2) || (pipe->src_format == MDP_Y_CR_CB_GH2V2)) swap(pipe->srcp1_addr, pipe->srcp2_addr); if (pipe->src_format == MDP_Y_CR_CB_GH2V2) { pipe->srcp0_ystride = ALIGN(pipe->src_width, 16); pipe->srcp1_ystride = ALIGN(pipe->src_width / 2, 16); pipe->srcp2_ystride = ALIGN(pipe->src_width / 2, 16); } else { pipe->srcp0_ystride = pipe->src_width; pipe->srcp1_ystride = pipe->src_width / 2; pipe->srcp2_ystride = pipe->src_width / 2; } } mdp4_overlay_mdp_perf_req(mfd); #if defined(CONFIG_FB_MSM_MIPI_LGIT_VIDEO_FHD_INVERSE_PT) pipe->mfd = mfd; #endif if (pipe->mixer_num == MDP4_MIXER0) { if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { /* cndx = 0 */ mdp4_dsi_cmd_pipe_queue(0, pipe); } else if (ctrl->panel_mode & MDP4_PANEL_DSI_VIDEO) { /* cndx = 0 */ mdp4_dsi_video_pipe_queue(0, pipe); } else if (ctrl->panel_mode & MDP4_PANEL_LCDC) { /* cndx = 0 */ mdp4_lcdc_pipe_queue(0, pipe); } } else if (pipe->mixer_num == MDP4_MIXER1) { if (ctrl->panel_mode & MDP4_PANEL_DTV) mdp4_dtv_pipe_queue(0, pipe);/* cndx = 0 */ } else if (pipe->mixer_num == MDP4_MIXER2) { ctrl->mixer2_played++; if (ctrl->panel_mode & MDP4_PANEL_WRITEBACK) mdp4_wfd_pipe_queue(0, pipe);/* cndx = 0 */ } if (!(pipe->flags & MDP_OV_PLAY_NOWAIT)) mdp4_iommu_unmap(pipe); mdp4_stat.overlay_play[pipe->mixer_num]++; end: mutex_unlock(&mfd->dma->ov_mutex); return ret; } int mdp4_overlay_commit(struct fb_info *info) { int ret = 0, release_busy = true; struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; int mixer; if (mfd == NULL) { ret = -ENODEV; goto mdp4_overlay_commit_exit; } if (!mfd->panel_power_on) { ret = -EINVAL; goto mdp4_overlay_commit_exit; } mixer = mfd->panel_info.pdest; /* DISPLAY_1 or DISPLAY_2 */ if (mixer >= MDP4_MIXER_MAX) return -EPERM; mutex_lock(&mfd->dma->ov_mutex); msm_fb_wait_for_fence(mfd); switch (mfd->panel.type) { case MIPI_CMD_PANEL: mdp4_dsi_cmd_pipe_commit(0, 1, &release_busy); break; case MIPI_VIDEO_PANEL: mdp4_dsi_video_pipe_commit(0, 1); break; case LCDC_PANEL: mdp4_lcdc_pipe_commit(0, 1); break; case DTV_PANEL: mdp4_dtv_pipe_commit(0, 1); break; case WRITEBACK_PANEL: mdp4_wfd_pipe_commit(mfd, 0, 1); break; default: pr_err("Panel Not Supported for Commit"); ret = -EINVAL; break; } msm_fb_signal_timeline(mfd); mdp4_unmap_sec_resource(mfd); if (release_busy) mutex_unlock(&mfd->dma->ov_mutex); mdp4_overlay_commit_exit: if (release_busy) msm_fb_release_busy(mfd); return ret; } void mdp4_overlay_commit_finish(struct fb_info *info) { struct msm_fb_data_type *mfd = (struct msm_fb_data_type *)info->par; mdp4_overlay_mdp_perf_upd(mfd, 0); } struct msm_iommu_ctx { char *name; int domain; }; static struct msm_iommu_ctx msm_iommu_ctx_names[] = { /* Display read*/ { .name = "mdp_port0_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display read*/ { .name = "mdp_port0_cb1", .domain = DISPLAY_READ_DOMAIN, }, /* Display write */ { .name = "mdp_port1_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display write */ { .name = "mdp_port1_cb1", .domain = DISPLAY_READ_DOMAIN, }, }; static struct msm_iommu_ctx msm_iommu_split_ctx_names[] = { /* Display read*/ { .name = "mdp_port0_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display read*/ { .name = "mdp_port0_cb1", .domain = DISPLAY_WRITE_DOMAIN, }, /* Display write */ { .name = "mdp_port1_cb0", .domain = DISPLAY_READ_DOMAIN, }, /* Display write */ { .name = "mdp_port1_cb1", .domain = DISPLAY_WRITE_DOMAIN, }, }; void mdp4_iommu_attach(void) { static int done; struct msm_iommu_ctx *ctx_names; struct iommu_domain *domain; int i, arr_size; if (!done) { if (mdp_iommu_split_domain) { ctx_names = msm_iommu_split_ctx_names; arr_size = ARRAY_SIZE(msm_iommu_split_ctx_names); } else { ctx_names = msm_iommu_ctx_names; arr_size = ARRAY_SIZE(msm_iommu_ctx_names); } for (i = 0; i < arr_size; i++) { int domain_idx; struct device *ctx = msm_iommu_get_ctx( ctx_names[i].name); if (!ctx) continue; domain_idx = ctx_names[i].domain; domain = msm_get_iommu_domain(domain_idx); if (!domain) continue; if (iommu_attach_device(domain, ctx)) { WARN(1, "%s: could not attach domain %d to context %s." " iommu programming will not occur.\n", __func__, domain_idx, ctx_names[i].name); continue; } } done = 1; } } int mdp4_v4l2_overlay_set(struct fb_info *info, struct mdp_overlay *req, struct mdp4_overlay_pipe **ppipe) { struct mdp4_overlay_pipe *pipe; int err; struct msm_fb_data_type *mfb = info->par; req->z_order = 0; req->id = MSMFB_NEW_REQUEST; req->is_fg = false; req->alpha = 0xff; err = mdp4_overlay_req2pipe(req, MDP4_MIXER0, &pipe, mfb); if (err < 0) { pr_err("%s:Could not allocate MDP overlay pipe\n", __func__); return err; } mdp4_mixer_blend_setup(pipe->mixer_num); *ppipe = pipe; return 0; } void mdp4_v4l2_overlay_clear(struct mdp4_overlay_pipe *pipe) { mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_down(pipe, 1); mdp4_overlay_pipe_free(pipe, 1); } int mdp4_v4l2_overlay_play(struct fb_info *info, struct mdp4_overlay_pipe *pipe, unsigned long srcp0_addr, unsigned long srcp1_addr, unsigned long srcp2_addr) { struct msm_fb_data_type *mfd = info->par; int err; if (mutex_lock_interruptible(&mfd->dma->ov_mutex)) return -EINTR; switch (pipe->src_format) { case MDP_Y_CR_CB_H2V2: /* YUV420 */ pipe->srcp0_addr = srcp0_addr; pipe->srcp0_ystride = pipe->src_width; /* * For YUV420, the luma plane is 1 byte per pixel times * num of pixels in the image Also, the planes are * switched in MDP, srcp2 is actually first chroma plane */ pipe->srcp2_addr = srcp1_addr ? srcp1_addr : pipe->srcp0_addr + (pipe->src_width * pipe->src_height); pipe->srcp2_ystride = pipe->src_width/2; /* * The chroma planes are half the size of the luma * planes */ pipe->srcp1_addr = srcp2_addr ? srcp2_addr : pipe->srcp2_addr + (pipe->src_width * pipe->src_height / 4); pipe->srcp1_ystride = pipe->src_width/2; break; case MDP_Y_CRCB_H2V2: /* NV12 */ pipe->srcp0_addr = srcp0_addr; pipe->srcp0_ystride = pipe->src_width; pipe->srcp1_addr = srcp1_addr ? srcp1_addr : pipe->srcp0_addr + (pipe->src_width * pipe->src_height); pipe->srcp1_ystride = pipe->src_width; break; default: pr_err("%s: format (%u) is not supported\n", __func__, pipe->src_format); err = -EINVAL; goto done; } pr_debug("%s: pipe ndx=%d stage=%d format=%x\n", __func__, pipe->pipe_ndx, pipe->mixer_stage, pipe->src_format); if (pipe->pipe_type == OVERLAY_TYPE_VIDEO) mdp4_overlay_vg_setup(pipe); else mdp4_overlay_rgb_setup(pipe); if (ctrl->panel_mode & MDP4_PANEL_LCDC) mdp4_overlay_reg_flush(pipe, 1); mdp4_mixer_stage_up(pipe, 0); /* mixer stage commit commits this */ mdp4_mixer_stage_commit(pipe->mixer_num); #ifdef V4L2_VSYNC /* * TODO: incorporate v4l2 into vsycn driven mechanism */ if (ctrl->panel_mode & MDP4_PANEL_LCDC) { mdp4_overlay_lcdc_vsync_push(mfd, pipe); } else { #ifdef CONFIG_FB_MSM_MIPI_DSI if (ctrl->panel_mode & MDP4_PANEL_DSI_CMD) { mdp4_dsi_cmd_dma_busy_wait(mfd); mdp4_dsi_cmd_kickoff_video(mfd, pipe); } #else if (ctrl->panel_mode & MDP4_PANEL_MDDI) { mdp4_mddi_dma_busy_wait(mfd); mdp4_mddi_kickoff_video(mfd, pipe); } #endif } #endif done: mutex_unlock(&mfd->dma->ov_mutex); return err; } int mdp4_overlay_reset() { memset(&perf_request, 0, sizeof(perf_request)); memset(&perf_current, 0, sizeof(perf_current)); return 0; }
Java
<?php /* +--------------------------------------------------------------------+ | CiviCRM version 4.6 | +--------------------------------------------------------------------+ | Copyright CiviCRM LLC (c) 2004-2015 | +--------------------------------------------------------------------+ | This file is a part of CiviCRM. | | | | CiviCRM is free software; you can copy, modify, and distribute it | | under the terms of the GNU Affero General Public License | | Version 3, 19 November 2007 and the CiviCRM Licensing Exception. | | | | CiviCRM 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 Affero General Public License for more details. | | | | You should have received a copy of the GNU Affero General Public | | License and the CiviCRM Licensing Exception along | | with this program; if not, contact CiviCRM LLC | | at info[AT]civicrm[DOT]org. If you have questions about the | | GNU Affero General Public License or the licensing of CiviCRM, | | see the CiviCRM license FAQ at http://civicrm.org/licensing | +--------------------------------------------------------------------+ */ /** * @package CRM * @copyright CiviCRM LLC (c) 2004-2015 * * Generated from xml/schema/CRM/Contribute/Premium.xml * DO NOT EDIT. Generated by CRM_Core_CodeGen */ require_once 'CRM/Core/DAO.php'; require_once 'CRM/Utils/Type.php'; class CRM_Contribute_DAO_Premium extends CRM_Core_DAO { /** * static instance to hold the table name * * @var string */ static $_tableName = 'civicrm_premiums'; /** * static instance to hold the field values * * @var array */ static $_fields = null; /** * static instance to hold the keys used in $_fields for each field. * * @var array */ static $_fieldKeys = null; /** * static instance to hold the FK relationships * * @var string */ static $_links = null; /** * static instance to hold the values that can * be imported * * @var array */ static $_import = null; /** * static instance to hold the values that can * be exported * * @var array */ static $_export = null; /** * static value to see if we should log any modifications to * this table in the civicrm_log table * * @var boolean */ static $_log = true; /** * * @var int unsigned */ public $id; /** * Joins these premium settings to another object. Always civicrm_contribution_page for now. * * @var string */ public $entity_table; /** * * @var int unsigned */ public $entity_id; /** * Is the Premiums feature enabled for this page? * * @var boolean */ public $premiums_active; /** * Title for Premiums section. * * @var string */ public $premiums_intro_title; /** * Displayed in <div> at top of Premiums section of page. Text and HTML allowed. * * @var text */ public $premiums_intro_text; /** * This email address is included in receipts if it is populated and a premium has been selected. * * @var string */ public $premiums_contact_email; /** * This phone number is included in receipts if it is populated and a premium has been selected. * * @var string */ public $premiums_contact_phone; /** * Boolean. Should we automatically display minimum contribution amount text after the premium descriptions. * * @var boolean */ public $premiums_display_min_contribution; /** * Label displayed for No Thank-you option in premiums block (e.g. No thank you) * * @var string */ public $premiums_nothankyou_label; /** * * @var int unsigned */ public $premiums_nothankyou_position; /** * class constructor * * @return civicrm_premiums */ function __construct() { $this->__table = 'civicrm_premiums'; parent::__construct(); } /** * Returns foreign keys and entity references * * @return array * [CRM_Core_Reference_Interface] */ static function getReferenceColumns() { if (!self::$_links) { self::$_links = static ::createReferenceColumns(__CLASS__); self::$_links[] = new CRM_Core_Reference_Dynamic(self::getTableName() , 'entity_id', NULL, 'id', 'entity_table'); } return self::$_links; } /** * Returns all the column names of this table * * @return array */ static function &fields() { if (!(self::$_fields)) { self::$_fields = array( 'id' => array( 'name' => 'id', 'type' => CRM_Utils_Type::T_INT, 'title' => ts('Premium ID') , 'required' => true, ) , 'entity_table' => array( 'name' => 'entity_table', 'type' => CRM_Utils_Type::T_STRING, 'title' => ts('Premium Entity') , 'description' => 'Joins these premium settings to another object. Always civicrm_contribution_page for now.', 'required' => true, 'maxlength' => 64, 'size' => CRM_Utils_Type::BIG, ) , 'entity_id' => array( 'name' => 'entity_id', 'type' => CRM_Utils_Type::T_INT, 'title' => ts('Premium entity ID') , 'required' => true, ) , 'premiums_active' => array( 'name' => 'premiums_active', 'type' => CRM_Utils_Type::T_BOOLEAN, 'title' => ts('Is Premium Active?') , 'description' => 'Is the Premiums feature enabled for this page?', 'required' => true, ) , 'premiums_intro_title' => array( 'name' => 'premiums_intro_title', 'type' => CRM_Utils_Type::T_STRING, 'title' => ts('Title for Premiums section') , 'description' => 'Title for Premiums section.', 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, ) , 'premiums_intro_text' => array( 'name' => 'premiums_intro_text', 'type' => CRM_Utils_Type::T_TEXT, 'title' => ts('Premium Introductory Text') , 'description' => 'Displayed in <div> at top of Premiums section of page. Text and HTML allowed.', ) , 'premiums_contact_email' => array( 'name' => 'premiums_contact_email', 'type' => CRM_Utils_Type::T_STRING, 'title' => ts('Premium Contact Email') , 'description' => 'This email address is included in receipts if it is populated and a premium has been selected.', 'maxlength' => 100, 'size' => CRM_Utils_Type::HUGE, ) , 'premiums_contact_phone' => array( 'name' => 'premiums_contact_phone', 'type' => CRM_Utils_Type::T_STRING, 'title' => ts('Premiums Contact Phone') , 'description' => 'This phone number is included in receipts if it is populated and a premium has been selected.', 'maxlength' => 50, 'size' => CRM_Utils_Type::BIG, ) , 'premiums_display_min_contribution' => array( 'name' => 'premiums_display_min_contribution', 'type' => CRM_Utils_Type::T_BOOLEAN, 'title' => ts('Display Minimum Contribution?') , 'description' => 'Boolean. Should we automatically display minimum contribution amount text after the premium descriptions.', 'required' => true, ) , 'premiums_nothankyou_label' => array( 'name' => 'premiums_nothankyou_label', 'type' => CRM_Utils_Type::T_STRING, 'title' => ts('No Thank-you Text') , 'description' => 'Label displayed for No Thank-you option in premiums block (e.g. No thank you)', 'maxlength' => 255, 'size' => CRM_Utils_Type::HUGE, ) , 'premiums_nothankyou_position' => array( 'name' => 'premiums_nothankyou_position', 'type' => CRM_Utils_Type::T_INT, 'title' => ts('No Thank-you Position') , 'default' => '1', ) , ); } return self::$_fields; } /** * Returns an array containing, for each field, the arary key used for that * field in self::$_fields. * * @return array */ static function &fieldKeys() { if (!(self::$_fieldKeys)) { self::$_fieldKeys = array( 'id' => 'id', 'entity_table' => 'entity_table', 'entity_id' => 'entity_id', 'premiums_active' => 'premiums_active', 'premiums_intro_title' => 'premiums_intro_title', 'premiums_intro_text' => 'premiums_intro_text', 'premiums_contact_email' => 'premiums_contact_email', 'premiums_contact_phone' => 'premiums_contact_phone', 'premiums_display_min_contribution' => 'premiums_display_min_contribution', 'premiums_nothankyou_label' => 'premiums_nothankyou_label', 'premiums_nothankyou_position' => 'premiums_nothankyou_position', ); } return self::$_fieldKeys; } /** * Returns the names of this table * * @return string */ static function getTableName() { return CRM_Core_DAO::getLocaleTableName(self::$_tableName); } /** * Returns if this table needs to be logged * * @return boolean */ function getLog() { return self::$_log; } /** * Returns the list of fields that can be imported * * @param bool $prefix * * @return array */ static function &import($prefix = false) { if (!(self::$_import)) { self::$_import = array(); $fields = self::fields(); foreach($fields as $name => $field) { if (CRM_Utils_Array::value('import', $field)) { if ($prefix) { self::$_import['premiums'] = & $fields[$name]; } else { self::$_import[$name] = & $fields[$name]; } } } } return self::$_import; } /** * Returns the list of fields that can be exported * * @param bool $prefix * * @return array */ static function &export($prefix = false) { if (!(self::$_export)) { self::$_export = array(); $fields = self::fields(); foreach($fields as $name => $field) { if (CRM_Utils_Array::value('export', $field)) { if ($prefix) { self::$_export['premiums'] = & $fields[$name]; } else { self::$_export[$name] = & $fields[$name]; } } } } return self::$_export; } }
Java