code
stringlengths
3
1.05M
repo_name
stringlengths
4
116
path
stringlengths
4
991
language
stringclasses
9 values
license
stringclasses
15 values
size
int32
3
1.05M
/* * Copyright (C) 2011 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY APPLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "DFGExitProfile.h" #if ENABLE(DFG_JIT) #include <wtf/PassOwnPtr.h> namespace JSC { namespace DFG { ExitProfile::ExitProfile() { } ExitProfile::~ExitProfile() { } bool ExitProfile::add(const ConcurrentJITLocker&, const FrequentExitSite& site) { ASSERT(site.jitType() != ExitFromAnything); // If we've never seen any frequent exits then create the list and put this site // into it. if (!m_frequentExitSites) { m_frequentExitSites = adoptPtr(new Vector<FrequentExitSite>()); m_frequentExitSites->append(site); return true; } // Don't add it if it's already there. This is O(n), but that's OK, because we // know that the total number of places where code exits tends to not be large, // and this code is only used when recompilation is triggered. for (unsigned i = 0; i < m_frequentExitSites->size(); ++i) { if (m_frequentExitSites->at(i) == site) return false; } m_frequentExitSites->append(site); return true; } Vector<FrequentExitSite> ExitProfile::exitSitesFor(unsigned bytecodeIndex) { Vector<FrequentExitSite> result; if (!m_frequentExitSites) return result; for (unsigned i = 0; i < m_frequentExitSites->size(); ++i) { if (m_frequentExitSites->at(i).bytecodeOffset() == bytecodeIndex) result.append(m_frequentExitSites->at(i)); } return result; } bool ExitProfile::hasExitSite(const ConcurrentJITLocker&, const FrequentExitSite& site) const { if (!m_frequentExitSites) return false; for (unsigned i = m_frequentExitSites->size(); i--;) { if (site.subsumes(m_frequentExitSites->at(i))) return true; } return false; } QueryableExitProfile::QueryableExitProfile() { } QueryableExitProfile::~QueryableExitProfile() { } void QueryableExitProfile::initialize(const ConcurrentJITLocker&, const ExitProfile& profile) { if (!profile.m_frequentExitSites) return; for (unsigned i = 0; i < profile.m_frequentExitSites->size(); ++i) m_frequentExitSites.add(profile.m_frequentExitSites->at(i)); } } } // namespace JSC::DFG #endif
loveyoupeng/rt
modules/web/src/main/native/Source/JavaScriptCore/bytecode/DFGExitProfile.cpp
C++
gpl-2.0
3,542
/** * Copyright (c) 2001-2002. Department of Family Medicine, McMaster University. All Rights Reserved. * This software is published under the GPL GNU General Public License. * 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. * * This software was written for the * Department of Family Medicine * McMaster University * Hamilton * Ontario, Canada */ package oscar.eform.actions; import java.io.File; import java.util.ArrayList; import javax.activation.MimetypesFileTypeMap; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionMapping; import org.apache.struts.actions.DownloadAction; import org.oscarehr.util.MiscUtils; import oscar.OscarProperties; /** * eform_image * @author jay *and Paul */ public class DisplayImageAction extends DownloadAction{ /** Creates a new instance of DisplayImageAction */ public DisplayImageAction() { } protected StreamInfo getStreamInfo(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { String fileName = request.getParameter("imagefile"); //if (fileName.indexOf('/') != -1) return null; //prevents navigating away from the page. String home_dir = OscarProperties.getInstance().getProperty("eform_image"); response.setHeader("Content-disposition","inline; filename=" + fileName); File file = null; try{ File directory = new File(home_dir); if(!directory.exists()){ throw new Exception("Directory: "+home_dir+ " does not exist"); } file = new File(directory,fileName); //String canonicalPath = file.getParentFile().getCanonicalPath(); //absolute path of the retrieved file if (!directory.equals(file.getParentFile())) { MiscUtils.getLogger().debug("SECURITY WARNING: Illegal file path detected, client attempted to navigate away from the file directory"); throw new Exception("Could not open file " + fileName + ". Check the file path"); } }catch(Exception e){ MiscUtils.getLogger().error("Error", e); throw new Exception("Could not open file "+home_dir+fileName +" does "+home_dir+ " exist ?",e); } //gets content type from image extension String contentType = new MimetypesFileTypeMap().getContentType(file); /** * For encoding file types not included in the mimetypes file * You need to look at mimetypes file to check if the file type you are using is included * */ try{ if(extension(file.getName()).equalsIgnoreCase("png")){ // for PNG contentType = "image/png"; }else if(extension(file.getName()).equalsIgnoreCase("jpeg")|| extension(file.getName()).equalsIgnoreCase("jpe")|| extension(file.getName()).equalsIgnoreCase("jpg")){ //for JPEG,JPG,JPE contentType = "image/jpeg"; }else if(extension(file.getName()).equalsIgnoreCase("bmp")){ // for BMP contentType = "image/bmp"; }else if(extension(file.getName()).equalsIgnoreCase("cod")){ // for COD contentType = "image/cis-cod"; }else if(extension(file.getName()).equalsIgnoreCase("ief")){ // for IEF contentType = "image/ief"; }else if(extension(file.getName()).equalsIgnoreCase("jfif")){ // for JFIF contentType = "image/pipeg"; }else if(extension(file.getName()).equalsIgnoreCase("svg")){ // for SVG contentType = "image/svg+xml"; }else if(extension(file.getName()).equalsIgnoreCase("tiff")|| extension(file.getName()).equalsIgnoreCase("tif")){ // for TIFF or TIF contentType = "image/tiff"; }else if(extension(file.getName()).equalsIgnoreCase("pbm")){ // for PBM contentType = "image/x-portable-bitmap"; }else if(extension(file.getName()).equalsIgnoreCase("pnm")){ // for PNM contentType = "image/x-portable-anymap"; }else if(extension(file.getName()).equalsIgnoreCase("pgm")){ // for PGM contentType = "image/x-portable-greymap"; }else if(extension(file.getName()).equalsIgnoreCase("ppm")){ // for PPM contentType = "image/x-portable-pixmap"; }else if(extension(file.getName()).equalsIgnoreCase("xbm")){ // for XBM contentType = "image/x-xbitmap"; }else if(extension(file.getName()).equalsIgnoreCase("xpm")){ // for XPM contentType = "image/x-xpixmap"; }else if(extension(file.getName()).equalsIgnoreCase("xwd")){ // for XWD contentType = "image/x-xwindowdump"; }else if(extension(file.getName()).equalsIgnoreCase("rgb")){ // for RGB contentType = "image/x-rgb"; }else if(extension(file.getName()).equalsIgnoreCase("ico")){ // for ICO contentType = "image/x-icon"; }else if(extension(file.getName()).equalsIgnoreCase("cmx")){ // for CMX contentType = "image/x-cmx"; }else if(extension(file.getName()).equalsIgnoreCase("ras")){ // for RAS contentType = "image/x-cmu-raster"; }else if(extension(file.getName()).equalsIgnoreCase("gif")){ // for GIF contentType = "image/gif"; }else if(extension(file.getName()).equalsIgnoreCase("js")){ // for GIF contentType = "text/javascript"; }else if(extension(file.getName()).equalsIgnoreCase("css")){ // for GIF contentType = "text/css"; }else if(extension(file.getName()).equalsIgnoreCase("rtl") || extension(file.getName()).equalsIgnoreCase("html") || extension(file.getName()).equalsIgnoreCase("htm")){ // for HTML contentType = "text/html"; }else{ throw new Exception("please check the file type or update mimetypes.default file to include the "+"."+extension(file.getName())); } }catch(Exception e){MiscUtils.getLogger().error("Error", e); throw new Exception("Could not open file "+file.getName()+" wrong file extension, ",e); } return new FileStreamInfo(contentType, file); } /** * * @String <filename e.g example.jpeg> * This method used to get file extension from a given filename * @return String <file extension> * */ public String extension(String f) { int dot = f.lastIndexOf("."); return f.substring(dot + 1); } public static File getImageFile(String imageFileName) throws Exception { String home_dir = OscarProperties.getInstance().getProperty("eform_image"); File file = null; try{ File directory = new File(home_dir); if(!directory.exists()){ throw new Exception("Directory: "+home_dir+ " does not exist"); } file = new File(directory,imageFileName); //String canonicalPath = file.getParentFile().getCanonicalPath(); //absolute path of the retrieved file if (!directory.equals(file.getParentFile())) { MiscUtils.getLogger().debug("SECURITY WARNING: Illegal file path detected, client attempted to navigate away from the file directory"); throw new Exception("Could not open file " + imageFileName + ". Check the file path"); } return file; }catch(Exception e){ MiscUtils.getLogger().error("Error", e); throw new Exception("Could not open file "+home_dir+imageFileName +" does "+home_dir+ " exist ?",e); } } /** * * Process only files under dir * This method used to list images for eform generator * */ public String[] visitAllFiles(File dir) { String[] children=null; if (dir.isDirectory()) { children = dir.list(); for (int i=0; i<children.length; i++) { visitAllFiles(new File(dir, children[i])); } } return children; } public static String[] getRichTextLetterTemplates(File dir) { ArrayList<String> results = getFiles(dir, ".*(rtl)$", null); return results.toArray(new String[0]); } public static ArrayList<String> getFiles(File dir, String ext, ArrayList<String> files) { if (files == null) { files = new ArrayList<String>(); } if (dir.isDirectory()) { for (String fileName : dir.list()) { if (fileName.toLowerCase().matches(ext)) { files.add(fileName); } } } return files; } }
vvanherk/oscar_emr
src/main/java/oscar/eform/actions/DisplayImageAction.java
Java
gpl-2.0
9,846
<?php /** * Sample implementation of the Custom Header feature * http://codex.wordpress.org/Custom_Headers * * You can add an optional custom header image to header.php like so ... <?php $header_image = get_header_image(); if ( ! empty( $header_image ) ) { ?> <a href="<?php echo esc_url( home_url( '/' ) ); ?>" title="<?php echo esc_attr( get_bloginfo( 'name', 'display' ) ); ?>" rel="home"> <img src="<?php header_image(); ?>" width="<?php echo get_custom_header()->width; ?>" height="<?php echo get_custom_header()->height; ?>" alt="" /> </a> <?php } // if ( ! empty( $header_image ) ) ?> * * @package wpjobboard_theme */ /** * Setup the WordPress core custom header feature. * * Use add_theme_support to register support for WordPress 3.4+ * as well as provide backward compatibility for previous versions. * Use feature detection of wp_get_theme() which was introduced * in WordPress 3.4. * * @todo Rework this function to remove WordPress 3.4 support when WordPress 3.6 is released. * * @uses wpjobboard_theme_header_style() * @uses wpjobboard_theme_admin_header_style() * @uses wpjobboard_theme_admin_header_image() * * @package wpjobboard_theme */ function wpjobboard_theme_custom_header_setup() { $args = array( 'default-image' => '', 'default-text-color' => '000', 'width' => 1000, 'height' => 250, 'flex-height' => true, 'wp-head-callback' => 'wpjobboard_theme_header_style', 'admin-head-callback' => 'wpjobboard_theme_admin_header_style', 'admin-preview-callback' => 'wpjobboard_theme_admin_header_image', ); $args = apply_filters('wpjobboard_theme_custom_header_args', $args); if (function_exists('wp_get_theme')) { add_theme_support('custom-header', $args); } else { // Compat: Versions of WordPress prior to 3.4. define('HEADER_TEXTCOLOR', $args['default-text-color']); define('HEADER_IMAGE', $args['default-image']); define('HEADER_IMAGE_WIDTH', $args['width']); define('HEADER_IMAGE_HEIGHT', $args['height']); add_custom_image_header($args['wp-head-callback'], $args['admin-head-callback'], $args['admin-preview-callback']); } } add_action('after_setup_theme', 'wpjobboard_theme_custom_header_setup'); /** * Shiv for get_custom_header(). * * get_custom_header() was introduced to WordPress * in version 3.4. To provide backward compatibility * with previous versions, we will define our own version * of this function. * * @todo Remove this function when WordPress 3.6 is released. * @return stdClass All properties represent attributes of the curent header image. * * @package wpjobboard_theme */ if (!function_exists('get_custom_header')) { function get_custom_header() { return (object) array( 'url' => get_header_image(), 'thumbnail_url' => get_header_image(), 'width' => HEADER_IMAGE_WIDTH, 'height' => HEADER_IMAGE_HEIGHT, ); } } if (!function_exists('wpjobboard_theme_header_style')) : /** * Styles the header image and text displayed on the blog * * @see wpjobboard_theme_custom_header_setup(). */ function wpjobboard_theme_header_style() { // If no custom options for text are set, let's bail // get_header_textcolor() options: HEADER_TEXTCOLOR is default, hide text (returns 'blank') or any hex value if (HEADER_TEXTCOLOR == get_header_textcolor()) return; // If we get this far, we have custom styles. Let's do this. ?> <style type="text/css"> <?php // Has the text been hidden? if ('blank' == get_header_textcolor()) : ?> .site-title, .site-description { position: absolute !important; clip: rect(1px 1px 1px 1px); /* IE6, IE7 */ clip: rect(1px, 1px, 1px, 1px); } <?php // If the user has set a custom color for the text use that else : ?> .site-title a, .site-description { color: #<?php echo get_header_textcolor(); ?>; } <?php endif; ?> </style> <?php } endif; // wpjobboard_theme_header_style if (!function_exists('wpjobboard_theme_admin_header_style')) : /** * Styles the header image displayed on the Appearance > Header admin panel. * * @see wpjobboard_theme_custom_header_setup(). */ function wpjobboard_theme_admin_header_style() { ?> <style type="text/css"> .appearance_page_custom-header #headimg { border: none; } #headimg h1, #desc { } #headimg h1 { } #headimg h1 a { } #desc { } #headimg img { } </style> <?php } endif; // wpjobboard_theme_admin_header_style if (!function_exists('wpjobboard_theme_admin_header_image')) : /** * Custom header image markup displayed on the Appearance > Header admin panel. * * @see wpjobboard_theme_custom_header_setup(). */ function wpjobboard_theme_admin_header_image() { ?> <div id="headimg"> <?php if ('blank' == get_header_textcolor() || '' == get_header_textcolor()) $style = ' style="display:none;"'; else $style = ' style="color:#' . get_header_textcolor() . ';"'; ?> <h1 class="displaying-header-text"><a id="name"<?php echo $style; ?> onclick="return false;" href="<?php echo esc_url(home_url('/')); ?>"><?php bloginfo('name'); ?></a></h1> <div class="displaying-header-text" id="desc"<?php echo $style; ?>><?php bloginfo('description'); ?></div> <?php $header_image = get_header_image(); if (!empty($header_image)) : ?> <img src="<?php echo esc_url($header_image); ?>" alt="" /> <?php endif; ?> </div> <?php } endif; // wpjobboard_theme_admin_header_image
ashchat404/wordpress
wp-content/themes/tsf/inc/custom-header.php
PHP
gpl-2.0
6,290
<?php /* vim: set expandtab sw=4 ts=4 sts=4: */ /** * Functionality for the navigation tree * * @package PhpMyAdmin-Navigation */ if (! defined('PHPMYADMIN')) { exit; } require_once 'libraries/navigation/Nodes/Node_DatabaseChild.class.php'; /** * Represents a view node in the navigation tree * * @package PhpMyAdmin-Navigation */ class Node_View extends Node_DatabaseChild { /** * Initialises the class * * @param string $name An identifier for the new node * @param int $type Type of node, may be one of CONTAINER or OBJECT * @param bool $is_group Whether this object has been created * while grouping nodes * * @return Node_View */ public function __construct($name, $type = Node::OBJECT, $is_group = false) { parent::__construct($name, $type, $is_group); $this->icon = PMA_Util::getImage('b_props.png', __('View')); $this->links = array( 'text' => 'sql.php?server=' . $GLOBALS['server'] . '&amp;db=%2$s&amp;table=%1$s&amp;pos=0' . '&amp;token=' . $_SESSION[' PMA_token '], 'icon' => 'tbl_structure.php?server=' . $GLOBALS['server'] . '&amp;db=%2$s&amp;table=%1$s' . '&amp;token=' . $_SESSION[' PMA_token '] ); $this->classes = 'view'; } /** * Returns the type of the item represented by the node. * * @return string type of the item */ protected function getItemType() { return 'view'; } }
saisai/phpmyadmin
libraries/navigation/Nodes/Node_View.class.php
PHP
gpl-2.0
1,597
/* * Digital Media Server, for streaming digital media to UPnP AV or DLNA * compatible devices based on PS3 Media Server and Universal Media Server. * Copyright (C) 2016 Digital Media Server developers. * * 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 3 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, see http://www.gnu.org/licenses/. */ package net.pms.formats.audio; public class MPC extends AudioBase { @Override public Identifier getIdentifier() { return Identifier.MPC; } @Override public String[] getSupportedExtensions() { return new String[] { "mpc", "mp+", "mpp", }; } }
DigitalMediaServer/DigitalMediaServer
src/main/java/net/pms/formats/audio/MPC.java
Java
gpl-2.0
1,121
<?php /* +---------------------------------------------------------------------------+ | Revive Adserver | | http://www.revive-adserver.com | | | | Copyright: See the COPYRIGHT.txt file. | | License: GPLv2 or later, see the LICENSE.txt file. | +---------------------------------------------------------------------------+ */ require_once(MAX_PATH.'/lib/OA/Upgrade/Migration.php'); class Migration_542 extends Migration { function Migration_542() { //$this->__construct(); $this->aTaskList_constructive[] = 'beforeAddField__campaigns__as_reject_reason'; $this->aTaskList_constructive[] = 'afterAddField__campaigns__as_reject_reason'; $this->aObjectMap['campaigns']['as_reject_reason'] = array('fromTable'=>'campaigns', 'fromField'=>'as_reject_reason'); } function beforeAddField__campaigns__as_reject_reason() { return $this->beforeAddField('campaigns', 'as_reject_reason'); } function afterAddField__campaigns__as_reject_reason() { return $this->afterAddField('campaigns', 'as_reject_reason'); } } ?>
adqio/revive-adserver
etc/changes/migration_tables_core_542.php
PHP
gpl-2.0
1,282
<?php namespace Elgg\I18n; /** * WARNING: API IN FLUX. DO NOT USE DIRECTLY. * * @access private * * @since 1.10.0 */ class Translator { /** * Global Elgg configuration * * @var \stdClass */ private $CONFIG; /** * Initializes new translator */ public function __construct() { global $CONFIG; $this->CONFIG = $CONFIG; $this->defaultPath = dirname(dirname(dirname(dirname(__DIR__)))) . "/languages/"; } /** * Given a message key, returns an appropriately translated full-text string * * @param string $message_key The short message code * @param array $args An array of arguments to pass through vsprintf(). * @param string $language Optionally, the standard language code * (defaults to site/user default, then English) * * @return string Either the translated string, the English string, * or the original language string. */ function translate($message_key, $args = array(), $language = "") { static $CURRENT_LANGUAGE; // old param order is deprecated if (!is_array($args)) { elgg_deprecated_notice( 'As of Elgg 1.8, the 2nd arg to elgg_echo() is an array of string replacements and the 3rd arg is the language.', 1.8 ); $language = $args; $args = array(); } if (!isset($GLOBALS['_ELGG']->translations)) { // this means we probably had an exception before translations were initialized $this->registerTranslations($this->defaultPath); } if (!$CURRENT_LANGUAGE) { $CURRENT_LANGUAGE = $this->getLanguage(); } if (!$language) { $language = $CURRENT_LANGUAGE; } if (!isset($GLOBALS['_ELGG']->translations[$language])) { // The language being requested is not the same as the language of the // logged in user, so we will have to load it separately. (Most likely // we're sending a notification and the recipient is using a different // language than the logged in user.) _elgg_load_translations_for_language($language); } if (isset($GLOBALS['_ELGG']->translations[$language][$message_key])) { $string = $GLOBALS['_ELGG']->translations[$language][$message_key]; } else if (isset($GLOBALS['_ELGG']->translations["en"][$message_key])) { $string = $GLOBALS['_ELGG']->translations["en"][$message_key]; _elgg_services()->logger->notice(sprintf('Missing %s translation for "%s" language key', $language, $message_key)); } else { $string = $message_key; _elgg_services()->logger->notice(sprintf('Missing English translation for "%s" language key', $message_key)); } // only pass through if we have arguments to allow backward compatibility // with manual sprintf() calls. if ($args) { $string = vsprintf($string, $args); } return $string; } /** * Add a translation. * * Translations are arrays in the Zend Translation array format, eg: * * $english = array('message1' => 'message1', 'message2' => 'message2'); * $german = array('message1' => 'Nachricht1','message2' => 'Nachricht2'); * * @param string $country_code Standard country code (eg 'en', 'nl', 'es') * @param array $language_array Formatted array of strings * * @return bool Depending on success */ function addTranslation($country_code, $language_array) { if (!isset($GLOBALS['_ELGG']->translations)) { $GLOBALS['_ELGG']->translations = array(); } $country_code = strtolower($country_code); $country_code = trim($country_code); if (is_array($language_array) && $country_code != "") { if (sizeof($language_array) > 0) { if (!isset($GLOBALS['_ELGG']->translations[$country_code])) { $GLOBALS['_ELGG']->translations[$country_code] = $language_array; } else { $GLOBALS['_ELGG']->translations[$country_code] = $language_array + $GLOBALS['_ELGG']->translations[$country_code]; } } return true; } return false; } /** * Detect the current language being used by the current site or logged in user. * * @return string The language code for the site/user or "en" if not set */ function getCurrentLanguage() { $language = $this->getLanguage(); if (!$language) { $language = 'en'; } return $language; } /** * Gets the current language in use by the system or user. * * @return string The language code (eg "en") or false if not set */ function getLanguage() { $url_lang = _elgg_services()->input->get('hl'); if ($url_lang) { return $url_lang; } $user = _elgg_services()->session->getLoggedInUser(); $language = false; if (($user) && ($user->language)) { $language = $user->language; } if ((!$language) && (isset($this->CONFIG->language)) && ($this->CONFIG->language)) { $language = $this->CONFIG->language; } if ($language) { return $language; } return false; } /** * @access private */ function loadTranslations() { if ($this->CONFIG->system_cache_enabled) { $loaded = true; $languages = array_unique(array('en', $this->getCurrentLanguage())); foreach ($languages as $language) { $data = elgg_load_system_cache("$language.lang"); if ($data) { $this->addTranslation($language, unserialize($data)); } else { $loaded = false; } } if ($loaded) { $GLOBALS['_ELGG']->i18n_loaded_from_cache = true; // this is here to force $GLOBALS['_ELGG']->language_paths[$this->defaultPath] = true; return; } } // load core translations from languages directory $this->registerTranslations($this->defaultPath); } /** * Registers translations in a directory assuming the standard plugin layout. * * @param string $path Without the trailing slash. * * @return bool Success */ function registerPluginTranslations($path) { $languages_path = rtrim($path, "\\/") . "/languages"; // don't need to have translations if (!is_dir($languages_path)) { return true; } return $this->registerTranslations($languages_path); } /** * When given a full path, finds translation files and loads them * * @param string $path Full path * @param bool $load_all If true all languages are loaded, if * false only the current language + en are loaded * * @return bool success */ function registerTranslations($path, $load_all = false) { $path = sanitise_filepath($path); // Make a note of this path just incase we need to register this language later if (!isset($GLOBALS['_ELGG']->language_paths)) { $GLOBALS['_ELGG']->language_paths = array(); } $GLOBALS['_ELGG']->language_paths[$path] = true; // Get the current language based on site defaults and user preference $current_language = $this->getCurrentLanguage(); _elgg_services()->logger->info("Translations loaded from: $path"); // only load these files unless $load_all is true. $load_language_files = array( 'en.php', "$current_language.php" ); $load_language_files = array_unique($load_language_files); $handle = opendir($path); if (!$handle) { _elgg_services()->logger->error("Could not open language path: $path"); return false; } $return = true; while (false !== ($language = readdir($handle))) { // ignore bad files if (substr($language, 0, 1) == '.' || substr($language, -4) !== '.php') { continue; } if (in_array($language, $load_language_files) || $load_all) { $result = include_once($path . $language); if ($result === false) { $return = false; continue; } elseif (is_array($result)) { $this->addTranslation(basename($language, '.php'), $result); } } } return $return; } /** * Reload all translations from all registered paths. * * This is only called by functions which need to know all possible translations. * * @todo Better on demand loading based on language_paths array * * @return void */ function reloadAllTranslations() { static $LANG_RELOAD_ALL_RUN; if ($LANG_RELOAD_ALL_RUN) { return; } if ($GLOBALS['_ELGG']->i18n_loaded_from_cache) { $cache = elgg_get_system_cache(); $cache_dir = $cache->getVariable("cache_path"); $filenames = elgg_get_file_list($cache_dir, array(), array(), array(".lang")); foreach ($filenames as $filename) { // Look for files matching for example 'en.lang', 'cmn.lang' or 'pt_br.lang'. // Note that this regex is just for the system cache. The original language // files are allowed to have uppercase letters (e.g. pt_BR.php). if (preg_match('/(([a-z]{2,3})(_[a-z]{2})?)\.lang$/', $filename, $matches)) { $language = $matches[1]; $data = elgg_load_system_cache("$language.lang"); if ($data) { $this->addTranslation($language, unserialize($data)); } } } } else { foreach ($GLOBALS['_ELGG']->language_paths as $path => $dummy) { $this->registerTranslations($path, true); } } $LANG_RELOAD_ALL_RUN = true; } /** * Return an array of installed translations as an associative * array "two letter code" => "native language name". * * @return array */ function getInstalledTranslations() { // Ensure that all possible translations are loaded $this->reloadAllTranslations(); $installed = array(); $admin_logged_in = _elgg_services()->session->isAdminLoggedIn(); foreach ($GLOBALS['_ELGG']->translations as $k => $v) { $installed[$k] = $this->translate($k, array(), $k); if ($admin_logged_in && ($k != 'en')) { $completeness = $this->getLanguageCompleteness($k); if ($completeness < 100) { $installed[$k] .= " (" . $completeness . "% " . $this->translate('complete') . ")"; } } } return $installed; } /** * Return the level of completeness for a given language code (compared to english) * * @param string $language Language * * @return int */ function getLanguageCompleteness($language) { // Ensure that all possible translations are loaded $this->reloadAllTranslations(); $language = sanitise_string($language); $en = count($GLOBALS['_ELGG']->translations['en']); $missing = $this->getMissingLanguageKeys($language); if ($missing) { $missing = count($missing); } else { $missing = 0; } //$lang = count($GLOBALS['_ELGG']->translations[$language]); $lang = $en - $missing; return round(($lang / $en) * 100, 2); } /** * Return the translation keys missing from a given language, * or those that are identical to the english version. * * @param string $language The language * * @return mixed */ function getMissingLanguageKeys($language) { // Ensure that all possible translations are loaded $this->reloadAllTranslations(); $missing = array(); foreach ($GLOBALS['_ELGG']->translations['en'] as $k => $v) { if ((!isset($GLOBALS['_ELGG']->translations[$language][$k])) || ($GLOBALS['_ELGG']->translations[$language][$k] == $GLOBALS['_ELGG']->translations['en'][$k])) { $missing[] = $k; } } if (count($missing)) { return $missing; } return false; } /** * Check if a give language key exists * * @param string $key The translation key * @param string $language The specific language to check * * @return bool * @since 1.11 */ function languageKeyExists($key, $language = 'en') { if (empty($key)) { return false; } if (($language !== 'en') && !array_key_exists($language, $GLOBALS['_ELGG']->translations)) { // Ensure that all possible translations are loaded $this->reloadAllTranslations(); } if (!array_key_exists($language, $GLOBALS['_ELGG']->translations)) { return false; } return array_key_exists($key, $GLOBALS['_ELGG']->translations[$language]); } /** * Returns an array of language codes. * * @return array */ function getAllLanguageCodes() { return array( "aa", // "Afar" "ab", // "Abkhazian" "af", // "Afrikaans" "am", // "Amharic" "ar", // "Arabic" "as", // "Assamese" "ay", // "Aymara" "az", // "Azerbaijani" "ba", // "Bashkir" "be", // "Byelorussian" "bg", // "Bulgarian" "bh", // "Bihari" "bi", // "Bislama" "bn", // "Bengali; Bangla" "bo", // "Tibetan" "br", // "Breton" "ca", // "Catalan" "cmn", // "Mandarin Chinese" // ISO 639-3 "co", // "Corsican" "cs", // "Czech" "cy", // "Welsh" "da", // "Danish" "de", // "German" "dz", // "Bhutani" "el", // "Greek" "en", // "English" "eo", // "Esperanto" "es", // "Spanish" "et", // "Estonian" "eu", // "Basque" "fa", // "Persian" "fi", // "Finnish" "fj", // "Fiji" "fo", // "Faeroese" "fr", // "French" "fy", // "Frisian" "ga", // "Irish" "gd", // "Scots / Gaelic" "gl", // "Galician" "gn", // "Guarani" "gu", // "Gujarati" "he", // "Hebrew" "ha", // "Hausa" "hi", // "Hindi" "hr", // "Croatian" "hu", // "Hungarian" "hy", // "Armenian" "ia", // "Interlingua" "id", // "Indonesian" "ie", // "Interlingue" "ik", // "Inupiak" "is", // "Icelandic" "it", // "Italian" "iu", // "Inuktitut" "iw", // "Hebrew (obsolete)" "ja", // "Japanese" "ji", // "Yiddish (obsolete)" "jw", // "Javanese" "ka", // "Georgian" "kk", // "Kazakh" "kl", // "Greenlandic" "km", // "Cambodian" "kn", // "Kannada" "ko", // "Korean" "ks", // "Kashmiri" "ku", // "Kurdish" "ky", // "Kirghiz" "la", // "Latin" "ln", // "Lingala" "lo", // "Laothian" "lt", // "Lithuanian" "lv", // "Latvian/Lettish" "mg", // "Malagasy" "mi", // "Maori" "mk", // "Macedonian" "ml", // "Malayalam" "mn", // "Mongolian" "mo", // "Moldavian" "mr", // "Marathi" "ms", // "Malay" "mt", // "Maltese" "my", // "Burmese" "na", // "Nauru" "ne", // "Nepali" "nl", // "Dutch" "no", // "Norwegian" "oc", // "Occitan" "om", // "(Afan) Oromo" "or", // "Oriya" "pa", // "Punjabi" "pl", // "Polish" "ps", // "Pashto / Pushto" "pt", // "Portuguese" "pt_br", // 'Brazilian Portuguese' "qu", // "Quechua" "rm", // "Rhaeto-Romance" "rn", // "Kirundi" "ro", // "Romanian" "ru", // "Russian" "rw", // "Kinyarwanda" "sa", // "Sanskrit" "sd", // "Sindhi" "sg", // "Sangro" "sh", // "Serbo-Croatian" "si", // "Singhalese" "sk", // "Slovak" "sl", // "Slovenian" "sm", // "Samoan" "sn", // "Shona" "so", // "Somali" "sq", // "Albanian" "sr", // "Serbian" "ss", // "Siswati" "st", // "Sesotho" "su", // "Sundanese" "sv", // "Swedish" "sw", // "Swahili" "ta", // "Tamil" "te", // "Tegulu" "tg", // "Tajik" "th", // "Thai" "ti", // "Tigrinya" "tk", // "Turkmen" "tl", // "Tagalog" "tn", // "Setswana" "to", // "Tonga" "tr", // "Turkish" "ts", // "Tsonga" "tt", // "Tatar" "tw", // "Twi" "ug", // "Uigur" "uk", // "Ukrainian" "ur", // "Urdu" "uz", // "Uzbek" "vi", // "Vietnamese" "vo", // "Volapuk" "wo", // "Wolof" "xh", // "Xhosa" "yi", // "Yiddish" "yo", // "Yoruba" "za", // "Zuang" "zh", // "Chinese" "zu", // "Zulu" ); } }
printerpam/Elgg
engine/classes/Elgg/I18n/Translator.php
PHP
gpl-2.0
15,087
<?php /** * This file is part of http://github.com/LukeBeer/BroadworksOCIP * * (c) 2013-2015 Luke Berezynskyj <eat.lemons@gmail.com> */ namespace BroadworksOCIP\api\Rel_17_sp4_1_197_OCISchemaAS\OCISchemaDataTypes; use BroadworksOCIP\Builder\Types\SimpleType; use BroadworksOCIP\Builder\Restrictions\Enumeration; /** * Choices for extended file resource usage. */ class ExtendedFileResourceSelection extends SimpleType { public $elementName = "ExtendedFileResourceSelection"; public function __construct($value) { $this->setElementValue($value); $this->addRestriction(new Enumeration([ 'File', 'URL', 'Default' ])); } }
paericksen/broadworks-ocip
src/BroadworksOCIP/api/Rel_17_sp4_1_197_OCISchemaAS/OCISchemaDataTypes/ExtendedFileResourceSelection.php
PHP
gpl-2.0
703
/** * Copyright (C) 2015 Frank Steiler <frank@steilerdev.de> * * 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, see <http://www.gnu.org/licenses/>. */ package de.steilerdev.whatToStudy.Exception; /** * This class is a application specific exception, always thrown and handled if an application specific error occurs. * In general other exceptions are tried to be wrapped inside this exception, so the program only needs to handle these kind of exceptions. */ public class WhatToStudyException extends Exception { /** * Constructs a new exception with {@code null} as its detail message. The cause is not initialized, and may * subsequently be initialized by a call to {@link #initCause}. */ public WhatToStudyException() { super(); } /** * Constructs a new exception with the specified detail message. The cause is not initialized, and may subsequently * be initialized by a call to {@link #initCause}. * * @param message the detail message. The detail message is saved for later retrieval by the {@link #getMessage()} * method. */ public WhatToStudyException(String message) { super(message); } /** * Constructs a new exception with the specified detail message and cause. <p>Note that the detail message * associated with {@code cause} is <i>not</i> automatically incorporated in this exception's detail message. * * @param message the detail message (which is saved for later retrieval by the {@link #getMessage()} method). * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). (A * <tt>null</tt> value is permitted, and indicates that the cause is nonexistent or unknown.) * @since 1.4 */ public WhatToStudyException(String message, Throwable cause) { super(message, cause); } /** * Constructs a new exception with the specified cause and a detail message of <tt>(cause==null ? null : * cause.toString())</tt> (which typically contains the class and detail message of <tt>cause</tt>). This * constructor is useful for exceptions that are little more than wrappers for other throwables (for example, {@link * java.security.PrivilegedActionException}). * * @param cause the cause (which is saved for later retrieval by the {@link #getCause()} method). (A <tt>null</tt> * value is permitted, and indicates that the cause is nonexistent or unknown.) * @since 1.4 */ public WhatToStudyException(Throwable cause) { super(cause); } /** * Constructs a new exception with the specified detail message, cause, suppression enabled or disabled, and * writable stack trace enabled or disabled. * * @param message the detail message. * @param cause the cause. (A {@code null} value is permitted, and indicates that the cause is * nonexistent or unknown.) * @param enableSuppression whether or not suppression is enabled or disabled * @param writableStackTrace whether or not the stack trace should be writable * @since 1.7 */ protected WhatToStudyException(String message, Throwable cause, boolean enableSuppression, boolean writableStackTrace) { super(message, cause, enableSuppression, writableStackTrace); } }
steilerDev/WhatToStudy
Source/src/de/steilerdev/whatToStudy/Exception/WhatToStudyException.java
Java
gpl-2.0
4,019
<?php /* * @version $Id$ ------------------------------------------------------------------------- GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2015-2016 Teclib'. http://glpi-project.org based on GLPI - Gestionnaire Libre de Parc Informatique Copyright (C) 2003-2014 by the INDEPNET Development Team. ------------------------------------------------------------------------- LICENSE This file is part of GLPI. GLPI is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. GLPI is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with GLPI. If not, see <http://www.gnu.org/licenses/>. -------------------------------------------------------------------------- */ /** @file * @brief */ class RuleDictionnaryMonitorModel extends RuleDictionnaryDropdown { /** * Constructor **/ function __construct() { parent::__construct('RuleDictionnaryMonitorModel'); } /** * @see Rule::getCriterias() **/ function getCriterias() { static $criterias = array(); if (count($criterias)) { return $criterias; } $criterias['name']['field'] = 'name'; $criterias['name']['name'] = __('Model'); $criterias['name']['table'] = 'glpi_monitormodels'; $criterias['manufacturer']['field'] = 'name'; $criterias['manufacturer']['name'] = __('Manufacturer'); $criterias['manufacturer']['table'] = 'glpi_manufacturers'; return $criterias; } /** * @see Rule::getActions() **/ function getActions() { $actions = array(); $actions['name']['name'] = __('Model'); $actions['name']['force_actions'] = array('append_regex_result', 'assign','regex_result'); return $actions; } }
TECLIB/glpi
inc/ruledictionnarymonitormodel.class.php
PHP
gpl-2.0
2,216
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed'); /** * Employee Model * Check if user is staff, perform basic moderation actions * @package Models */ class Employee_model extends CI_Model { /** * Allow loggedin user access if session var * * @return bool * */ public function allow_access() { // check sess vars $staff = $this->php_session->get('employee'); if ($staff == 0) { return false; } else { return true; } } /** * Check if user is staff * * @param string $username The user's username * @return bool If the user is staff or not * */ public function is_staff($username) { // query db to check if user is employee $this->db->select('employee') ->from('users') ->where('username', $username); $result = $this->db->get()->row_array(); // return 0 or 1 switch($result['employee']) { case 1: return true; case 0: return false; } } /** * Get all users * * @return array, user's data * */ public function get_users() { // query db to list usernames and stuff $this->db->select('name, username, official, employee, avatar, points, email, id') ->from('users'); return $this->db->get()->result_array(); } /** * Delete user * * @return boolean, status of deletion * */ public function delete($id) { // query db if (is_numeric($id)) { $this->db->select('employee') ->from('users') ->where('id', $id); $arr = $this->db->get()->row_array(); $status = $arr['employee']; if($status == 1) { return false; } else { $this->db->delete('users', array('id'=>$id)); return true; } } } public function delete_f($id) { if (is_numeric($id)) { return $this->db->delete('users', array('id'=>$id)); } else { return false; } } public function delete_post($id) { return $this->db->delete('debates', array('id'=>$id)); } public function official($id) { if (is_numeric($id)) { $this->db->where('id', $id); $st = 1; $this->db->update('users', array('official'=>$st)); } } public function staff($id) { if (is_numeric($id)) { $this->db->where('id', $id); $st = 1; $this->db->update('users', array('employee'=>$st)); } } } ?>
unfinite/Alphasquare
src/application/models/employee_model.php
PHP
gpl-2.0
2,577
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You 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. */ package org.apache.mahout.cf.taste.hadoop.item; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.Path; import org.apache.hadoop.mapreduce.Reducer; import org.apache.mahout.cf.taste.hadoop.MutableRecommendedItem; import org.apache.mahout.cf.taste.hadoop.RecommendedItemsWritable; import org.apache.mahout.cf.taste.hadoop.TasteHadoopUtils; import org.apache.mahout.cf.taste.hadoop.TopItemsQueue; import org.apache.mahout.cf.taste.impl.common.FastIDSet; import org.apache.mahout.cf.taste.recommender.RecommendedItem; import org.apache.mahout.common.HadoopUtil; import org.apache.mahout.common.iterator.FileLineIterable; import org.apache.mahout.math.RandomAccessSparseVector; import org.apache.mahout.math.VarLongWritable; import org.apache.mahout.math.Vector; import org.apache.mahout.math.Vector.Element; import org.apache.mahout.math.function.Functions; import org.apache.mahout.math.map.OpenIntLongHashMap; import java.io.IOException; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * <p>computes prediction values for each user</p> * * <pre> * u = a user * i = an item not yet rated by u * N = all items similar to i (where similarity is usually computed by pairwisely comparing the item-vectors * of the user-item matrix) * * Prediction(u,i) = sum(all n from N: similarity(i,n) * rating(u,n)) / sum(all n from N: abs(similarity(i,n))) * </pre> */ public final class AggregateAndRecommendReducer extends Reducer<VarLongWritable,PrefAndSimilarityColumnWritable,VarLongWritable,RecommendedItemsWritable> { private static final Logger log = LoggerFactory.getLogger(AggregateAndRecommendReducer.class); static final String ITEMID_INDEX_PATH = "itemIDIndexPath"; static final String NUM_RECOMMENDATIONS = "numRecommendations"; static final int DEFAULT_NUM_RECOMMENDATIONS = 10; static final String ITEMS_FILE = "itemsFile"; private boolean booleanData; private int recommendationsPerUser; private FastIDSet itemsToRecommendFor; private OpenIntLongHashMap indexItemIDMap; private final RecommendedItemsWritable recommendedItems = new RecommendedItemsWritable(); private static final float BOOLEAN_PREF_VALUE = 1.0f; @Override protected void setup(Context context) throws IOException { Configuration conf = context.getConfiguration(); recommendationsPerUser = conf.getInt(NUM_RECOMMENDATIONS, DEFAULT_NUM_RECOMMENDATIONS); booleanData = conf.getBoolean(RecommenderJob.BOOLEAN_DATA, false); indexItemIDMap = TasteHadoopUtils.readIDIndexMap(conf.get(ITEMID_INDEX_PATH), conf); String itemFilePathString = conf.get(ITEMS_FILE); if (itemFilePathString != null) { itemsToRecommendFor = new FastIDSet(); for (String line : new FileLineIterable(HadoopUtil.openStream(new Path(itemFilePathString), conf))) { try { itemsToRecommendFor.add(Long.parseLong(line)); } catch (NumberFormatException nfe) { log.warn("itemsFile line ignored: {}", line); } } } } @Override protected void reduce(VarLongWritable userID, Iterable<PrefAndSimilarityColumnWritable> values, Context context) throws IOException, InterruptedException { if (booleanData) { reduceBooleanData(userID, values, context); } else { reduceNonBooleanData(userID, values, context); } } private void reduceBooleanData(VarLongWritable userID, Iterable<PrefAndSimilarityColumnWritable> values, Context context) throws IOException, InterruptedException { /* having boolean data, each estimated preference can only be 1, * however we can't use this to rank the recommended items, * so we use the sum of similarities for that. */ Iterator<PrefAndSimilarityColumnWritable> columns = values.iterator(); Vector predictions = columns.next().getSimilarityColumn(); while (columns.hasNext()) { predictions.assign(columns.next().getSimilarityColumn(), Functions.PLUS); } writeRecommendedItems(userID, predictions, context); } private void reduceNonBooleanData(VarLongWritable userID, Iterable<PrefAndSimilarityColumnWritable> values, Context context) throws IOException, InterruptedException { /* each entry here is the sum in the numerator of the prediction formula */ Vector numerators = null; /* each entry here is the sum in the denominator of the prediction formula */ Vector denominators = null; /* each entry here is the number of similar items used in the prediction formula */ Vector numberOfSimilarItemsUsed = new RandomAccessSparseVector(Integer.MAX_VALUE, 100); for (PrefAndSimilarityColumnWritable prefAndSimilarityColumn : values) { Vector simColumn = prefAndSimilarityColumn.getSimilarityColumn(); float prefValue = prefAndSimilarityColumn.getPrefValue(); /* count the number of items used for each prediction */ for (Element e : simColumn.nonZeroes()) { int itemIDIndex = e.index(); numberOfSimilarItemsUsed.setQuick(itemIDIndex, numberOfSimilarItemsUsed.getQuick(itemIDIndex) + 1); } if (denominators == null) { denominators = simColumn.clone(); } else { denominators.assign(simColumn, Functions.PLUS_ABS); } if (numerators == null) { numerators = simColumn.clone(); if (prefValue != BOOLEAN_PREF_VALUE) { numerators.assign(Functions.MULT, prefValue); } } else { if (prefValue != BOOLEAN_PREF_VALUE) { simColumn.assign(Functions.MULT, prefValue); } numerators.assign(simColumn, Functions.PLUS); } } if (numerators == null) { return; } Vector recommendationVector = new RandomAccessSparseVector(Integer.MAX_VALUE, 100); for (Element element : numerators.nonZeroes()) { int itemIDIndex = element.index(); /* preference estimations must be based on at least 2 datapoints */ if (numberOfSimilarItemsUsed.getQuick(itemIDIndex) > 1) { /* compute normalized prediction */ double prediction = element.get() / denominators.getQuick(itemIDIndex); recommendationVector.setQuick(itemIDIndex, prediction); } } writeRecommendedItems(userID, recommendationVector, context); } /** * find the top entries in recommendationVector, map them to the real itemIDs and write back the result */ private void writeRecommendedItems(VarLongWritable userID, Vector recommendationVector, Context context) throws IOException, InterruptedException { TopItemsQueue topKItems = new TopItemsQueue(recommendationsPerUser); for (Element element : recommendationVector.nonZeroes()) { int index = element.index(); long itemID; if (indexItemIDMap != null && !indexItemIDMap.isEmpty()) { itemID = indexItemIDMap.get(index); } else { //we don't have any mappings, so just use the original itemID = index; } if (itemsToRecommendFor == null || itemsToRecommendFor.contains(itemID)) { float value = (float) element.get(); if (!Float.isNaN(value)) { MutableRecommendedItem topItem = topKItems.top(); if (value > topItem.getValue()) { topItem.set(itemID, value); topKItems.updateTop(); } } } } List<RecommendedItem> topItems = topKItems.getTopItems(); if (!topItems.isEmpty()) { recommendedItems.set(topItems); context.write(userID, recommendedItems); } } }
bharcode/MachineLearning
CustomMahout/core/src/main/java/org/apache/mahout/cf/taste/hadoop/item/AggregateAndRecommendReducer.java
Java
gpl-2.0
8,512
<?php /** * Page Template * * Loaded automatically by index.php?main_page=order_status.<br /> * Displays information related to a single specific order * * @package templateSystem * @copyright Copyright 2003-2015 Zen Cart Development Team * @copyright Portions Copyright 2003 osCommerce * @copyright Portions copyright COWOA authors see https://www.zen-cart.com/downloads.php?do=file&id=1115 * @license http://www.zen-cart.com/license/2_0.txt GNU Public License V2.0 * @version $Id: New in V1.6.0 $ */ ?> <!-- TPL_ORDER_STATUS_DEFAULT.PHP --> <div class="centerColumn" id="accountHistInfo"> <h1 id="orderHistoryHeading"><?php echo HEADING_TITLE; ?></h1> <br /> <?php if (isset($_POST['action']) && $_POST['action'] == "process" && ($errorInvalidID || $errorInvalidEmail || $errorNoMatch)) { ?> <div class="messageStackWarning larger"> <?php if($errorInvalidID) echo ERROR_INVALID_ORDER; if($errorInvalidEmail) echo ERROR_INVALID_EMAIL; if($errorNoMatch) echo ERROR_NO_MATCH; ?> </div> <?php } ?> <?php if (isset($order)) { ?> <table border="0" width="100%" cellspacing="0" cellpadding="0" summary="Itemized listing of previous order, includes number ordered, items and prices"> <h2 id="orderHistoryDetailedOrder"><?php echo SUB_HEADING_TITLE . ORDER_HEADING_DIVIDER . sprintf(HEADING_ORDER_NUMBER, $_POST['order_id']); ?></h2> <div class="forward"><?php echo HEADING_ORDER_DATE . ' ' . zen_date_long($order->info['date_purchased']); ?></div> <br class="clearBoth" /> <tr class="tableHeading"> <th scope="col" id="myAccountQuantity"><?php echo HEADING_QUANTITY; ?></th> <th scope="col" id="myAccountProducts"><?php echo HEADING_PRODUCTS; ?></th> <?php if (sizeof($order->info['tax_groups']) > 1) { ?> <th scope="col" id="myAccountTax"><?php echo HEADING_TAX; ?></th> <?php } ?> <th scope="col" id="myAccountTotal"><?php echo HEADING_TOTAL; ?></th> </tr> <?php for ($i=0, $n=sizeof($order->products); $i<$n; $i++) { ?> <tr> <td class="accountQuantityDisplay"><?php echo $order->products[$i]['qty'] . QUANTITY_SUFFIX; ?></td> <td class="accountProductDisplay"><?php echo $order->products[$i]['name']; if ( (isset($order->products[$i]['attributes'])) && (sizeof($order->products[$i]['attributes']) > 0) ) { echo '<ul class="orderAttribsList">'; for ($j=0, $n2=sizeof($order->products[$i]['attributes']); $j<$n2; $j++) { echo '<li>' . $order->products[$i]['attributes'][$j]['option'] . TEXT_OPTION_DIVIDER . nl2br($order->products[$i]['attributes'][$j]['value']) . '</li>'; } echo '</ul>'; } ?> </td> <?php if (sizeof($order->info['tax_groups']) > 1) { ?> <td class="accountTaxDisplay"><?php echo zen_display_tax_value($order->products[$i]['tax']) . '%' ?></td> <?php } ?> <td class="accountTotalDisplay"><?php echo $currencies->format(zen_add_tax($order->products[$i]['final_price'], $order->products[$i]['tax']) * $order->products[$i]['qty'], true, $order->info['currency'], $order->info['currency_value']) . ($order->products[$i]['onetime_charges'] != 0 ? '<br />' . $currencies->format(zen_add_tax($order->products[$i]['onetime_charges'], $order->products[$i]['tax']), true, $order->info['currency'], $order->info['currency_value']) : '') ?></td> </tr> <?php } ?> </table> <hr /> <div id="orderTotals"> <?php for ($i=0, $n=sizeof($order->totals); $i<$n; $i++) { ?> <div class="amount larger forward"><?php echo $order->totals[$i]['text'] ?></div> <div class="lineTitle larger forward"><?php echo $order->totals[$i]['title'] ?></div> <br class="clearBoth" /> <?php } ?> </div> <?php /** * Used to display any downloads associated with the cutomers account */ if (DOWNLOAD_ENABLED == 'true') require($template->get_template_dir('tpl_modules_downloads.php',DIR_WS_TEMPLATE, $current_page_base,'templates'). '/tpl_modules_downloads.php'); ?> <?php /** * Used to loop thru and display order status information */ if (sizeof($statusArray)) { ?> <table border="0" width="100%" cellspacing="0" cellpadding="0" id="myAccountOrdersStatus" summary="Table contains the date, order status and any comments regarding the order"> <caption><h2 id="orderHistoryStatus"><?php echo HEADING_ORDER_HISTORY; ?></h2></caption> <tr class="tableHeading"> <th scope="col" id="myAccountStatusDate"><?php echo TABLE_HEADING_STATUS_DATE; ?></th> <th scope="col" id="myAccountStatus"><?php echo TABLE_HEADING_STATUS_ORDER_STATUS; ?></th> <th scope="col" id="myAccountStatusComments"><?php echo TABLE_HEADING_STATUS_COMMENTS; ?></th> </tr> <?php foreach ($statusArray as $statuses) { ?> <tr> <td><?php echo zen_date_short($statuses['date_added']); ?></td> <td><?php echo $statuses['orders_status_name']; ?></td> <td><?php echo (empty($statuses['comments']) ? '&nbsp;' : nl2br(zen_output_string_protected($statuses['comments']))); ?></td> </tr> <?php } ?> </table> <?php } ?> <hr /> <div id="myAccountShipInfo" class="floatingBox back"> <?php if (zen_not_null($order->info['shipping_method'])) { ?> <h4><?php echo HEADING_SHIPPING_METHOD; ?></h4> <div><?php echo $order->info['shipping_method']; ?></div> <?php } else { // temporary just remove these 4 lines ?> <div>WARNING: Missing Shipping Information</div> <?php } ?> </div> <div id="myAccountPaymentInfo" class="floatingBox forward"> <h4><?php echo HEADING_PAYMENT_METHOD; ?></h4> <div><?php echo $order->info['payment_method']; ?></div> </div> <br class="clearBoth" /> <br /> <?php } ?> <?php echo zen_draw_form('order_status', zen_href_link(FILENAME_ORDER_STATUS, '', 'SSL'), 'post') . zen_draw_hidden_field('action', 'process'); ?> <fieldset> <legend><?php echo HEADING_TITLE; ?></legend> <?php echo TEXT_LOOKUP_INSTRUCTIONS; ?> <br /><br /> <label class="inputLabel"><?php echo ENTRY_ORDER_NUMBER; ?></label> <?php echo zen_draw_input_field('order_id', (int)$_GET['order_id'], 'size="10" id="order_id" required autofocus', 'number'); ?> <br /> <br /> <label class="inputLabel"><?php echo ENTRY_EMAIL; ?></label> <?php echo zen_draw_input_field('query_email_address', '', 'size="35" id="query_email_address" required', 'email'); ?> <br /> <div class="buttonRow forward"><?php echo zen_image_submit(BUTTON_IMAGE_CONTINUE, BUTTON_CONTINUE_ALT); ?></div> </fieldset> </form> </div>
drbyte/zc-v1-series
includes/templates/template_default/templates/tpl_order_status_default.php
PHP
gpl-2.0
6,773
/* * Copyright (c) 2011, 2016, Oracle and/or its affiliates. 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ #include "common.h" #include <UIAutomation.h> #include "GlassApplication.h" #include "ViewContainer.h" #include "GlassView.h" #include "KeyTable.h" #include "Utils.h" #include "GlassDnD.h" #include "GlassInputTextInfo.h" #include "ManipulationEvents.h" #include "BaseWnd.h" #include "com_sun_glass_events_ViewEvent.h" #include "com_sun_glass_events_KeyEvent.h" #include "com_sun_glass_events_MouseEvent.h" #include "com_sun_glass_events_DndEvent.h" #include "com_sun_glass_events_TouchEvent.h" static UINT LangToCodePage(LANGID idLang) { WCHAR strCodePage[8]; // use the LANGID to create a LCID LCID idLocale = MAKELCID(idLang, SORT_DEFAULT); // get the ANSI code page associated with this locale if (::GetLocaleInfo(idLocale, LOCALE_IDEFAULTANSICODEPAGE, strCodePage, sizeof(strCodePage) / sizeof(WCHAR)) > 0) { return _wtoi(strCodePage); } else { return ::GetACP(); } } namespace { bool IsTouchEvent() { // Read this link if you wonder why we need to hard code the mask and signature: // http://msdn.microsoft.com/en-us/library/windows/desktop/ms703320(v=vs.85).aspx //"The lower 8 bits returned from GetMessageExtraInfo are variable. // Of those bits, 7 (the lower 7, masked by 0x7F) are used to represent the cursor ID, // zero for the mouse or a variable value for the pen ID. // Additionally, in Windows Vista, the eighth bit, masked by 0x80, is used to // differentiate touch input from pen input (0 = pen, 1 = touch)." UINT SIGNATURE = 0xFF515780; UINT MASK = 0xFFFFFF80; UINT v = (UINT) GetMessageExtraInfo(); return ((v & MASK) == SIGNATURE); } } // namespace ViewContainer::ViewContainer() : m_view(NULL), m_bTrackingMouse(FALSE), m_manipProc(NULL), m_inertiaProc(NULL), m_manipEventSink(NULL), m_gestureSupportCls(NULL), m_lastMouseMovePosition(-1), m_mouseButtonDownCounter(0), m_deadKeyWParam(0) { m_kbLayout = ::GetKeyboardLayout(0); m_idLang = LOWORD(m_kbLayout); m_codePage = LangToCodePage(m_idLang); m_lastTouchInputCount = 0; } jobject ViewContainer::GetView() { return GetGlassView() != NULL ? GetGlassView()->GetView() : NULL; } void ViewContainer::InitDropTarget(HWND hwnd) { if (!hwnd) { return; } m_spDropTarget = std::auto_ptr<IDropTarget>(new GlassDropTarget(this, hwnd)); } void ViewContainer::ReleaseDropTarget() { m_spDropTarget = std::auto_ptr<IDropTarget>(); } void ViewContainer::InitManipProcessor(HWND hwnd) { if (IS_WIN7) { ::RegisterTouchWindow(hwnd, TWF_WANTPALM); HRESULT hr = ::CoCreateInstance(CLSID_ManipulationProcessor, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (VOID**)(&m_manipProc) ); if (SUCCEEDED(hr)) { ::CoCreateInstance(CLSID_InertiaProcessor, NULL, CLSCTX_INPROC_SERVER, IID_IUnknown, (VOID**)(&m_inertiaProc) ); m_manipEventSink = new ManipulationEventSinkWithInertia(m_manipProc, m_inertiaProc, this, hwnd); } const DWORD_PTR dwHwndTabletProperty = TABLET_DISABLE_PENTAPFEEDBACK | TABLET_DISABLE_PENBARRELFEEDBACK | TABLET_DISABLE_FLICKS; ::SetProp(hwnd, MICROSOFT_TABLETPENSERVICE_PROPERTY, reinterpret_cast<HANDLE>(dwHwndTabletProperty)); if (!m_gestureSupportCls) { JNIEnv *env = GetEnv(); const jclass cls = GlassApplication::ClassForName(env, "com.sun.glass.ui.win.WinGestureSupport"); m_gestureSupportCls = (jclass)env->NewGlobalRef(cls); env->DeleteLocalRef(cls); ASSERT(m_gestureSupportCls); } } } void ViewContainer::ReleaseManipProcessor() { if (IS_WIN7) { if (m_manipProc) { m_manipProc->Release(); m_manipProc = NULL; } if (m_inertiaProc) { m_inertiaProc->Release(); m_inertiaProc = NULL; } if (m_manipEventSink) { m_manipEventSink->Release(); m_manipEventSink = NULL; } } if (m_gestureSupportCls) { JNIEnv *env = GetEnv(); env->DeleteGlobalRef(m_gestureSupportCls); m_gestureSupportCls = 0; } } void ViewContainer::HandleViewInputLangChange(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } m_kbLayout = reinterpret_cast<HKL>(lParam); m_idLang = LOWORD(m_kbLayout); m_codePage = LangToCodePage(m_idLang); m_deadKeyWParam = 0; } void ViewContainer::NotifyViewMoved(HWND hwnd) { if (!hwnd || !GetGlassView()) { return; } JNIEnv* env = GetEnv(); env->CallVoidMethod(GetView(), javaIDs.View.notifyView, com_sun_glass_events_ViewEvent_MOVE); CheckAndClearException(env); } void ViewContainer::NotifyViewSize(HWND hwnd) { if (!hwnd || !GetGlassView()) { return; } RECT r; if (::GetClientRect(hwnd, &r)) { JNIEnv* env = GetEnv(); env->CallVoidMethod(GetView(), javaIDs.View.notifyResize, r.right-r.left, r.bottom - r.top); CheckAndClearException(env); } } void ViewContainer::HandleViewPaintEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } RECT r; if (!::GetUpdateRect(hwnd, &r, FALSE)) { return; } JNIEnv* env = GetEnv(); env->CallVoidMethod(GetView(), javaIDs.View.notifyRepaint, r.left, r.top, r.right-r.left, r.bottom-r.top); CheckAndClearException(env); } LRESULT ViewContainer::HandleViewGetAccessible(HWND hwnd, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return NULL; } /* WM_GETOBJECT is sent to request different object types, * always test the type to avoid unnecessary work. */ LRESULT lr = NULL; if (static_cast<long>(lParam) == static_cast<long>(UiaRootObjectId)) { /* The client is requesting UI Automation. */ JNIEnv* env = GetEnv(); if (!env) return NULL; jlong pProvider = env->CallLongMethod(GetView(), javaIDs.View.getAccessible); CheckAndClearException(env); /* It is possible WM_GETOBJECT is sent before the toolkit is ready to * create the accessible object (getAccessible returns NULL). * On Windows 7, calling UiaReturnRawElementProvider() with a NULL provider * returns an invalid LRESULT which stops further WM_GETOBJECT to be sent, * effectively disabling accessibility for the window. */ if (pProvider) { lr = UiaReturnRawElementProvider(hwnd, wParam, lParam, reinterpret_cast<IRawElementProviderSimple*>(pProvider)); } } else if (static_cast<long>(lParam) == static_cast<long>(OBJID_CLIENT)) { /* By default JAWS does not send WM_GETOBJECT with UiaRootObjectId till * a focus event is raised by UiaRaiseAutomationEvent(). * In some systems (i.e. touch monitors), OBJID_CLIENT are sent when * no screen reader is active. Test for SPI_GETSCREENREADER and * UiaClientsAreListening() to avoid initializing accessibility * unnecessarily. */ UINT screenReader = 0; ::SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); if (screenReader && UiaClientsAreListening()) { JNIEnv* env = GetEnv(); if (env) { /* Calling getAccessible() initializes accessibility which * eventually raises the focus events required to indicate to * JAWS to use UIA for this window. * * Note: do not return the accessible object for OBJID_CLIENT, * that would create an UIA-MSAA bridge. That problem with the * bridge is that it does not respect * ProviderOptions_UseComThreading. */ env->CallLongMethod(GetView(), javaIDs.View.getAccessible); CheckAndClearException(env); } } } return lr; } void ViewContainer::HandleViewSizeEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (wParam == SIZE_MINIMIZED) { return; } NotifyViewSize(hwnd); } void ViewContainer::HandleViewMenuEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } if ((HWND)wParam != hwnd) { return; } jboolean isKeyboardTrigger = lParam == (LPARAM)-1; if (isKeyboardTrigger) { lParam = ::GetMessagePos (); } POINT pt; int absX = pt.x = GET_X_LPARAM(lParam); int absY = pt.y = GET_Y_LPARAM(lParam); ::ScreenToClient (hwnd, &pt); if (!isKeyboardTrigger) { RECT rect; ::GetClientRect(hwnd, &rect); if (!::PtInRect(&rect, pt)) { return; } } // unmirror the x coordinate LONG style = ::GetWindowLong(hwnd, GWL_EXSTYLE); if (style & WS_EX_LAYOUTRTL) { RECT rect = {0}; ::GetClientRect(hwnd, &rect); pt.x = max(0, rect.right - rect.left) - pt.x; } JNIEnv* env = GetEnv(); env->CallVoidMethod(GetView(), javaIDs.View.notifyMenu, pt.x, pt.y, absX, absY, isKeyboardTrigger); CheckAndClearException(env); } void ViewContainer::HandleViewKeyEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } static const BYTE KEY_STATE_DOWN = 0x80; UINT wKey = static_cast<UINT>(wParam); UINT flags = HIWORD(lParam); jint jKeyCode = WindowsKeyToJavaKey(wKey); if (flags & (1 << 8)) { // this is an extended key (e.g. Right ALT == AltGr) switch (jKeyCode) { case com_sun_glass_events_KeyEvent_VK_ALT: jKeyCode = com_sun_glass_events_KeyEvent_VK_ALT_GRAPH; break; } } BYTE kbState[256]; if (!::GetKeyboardState(kbState)) { return; } jint jModifiers = GetModifiers(); if (jModifiers & com_sun_glass_events_KeyEvent_MODIFIER_CONTROL) { kbState[VK_CONTROL] &= ~KEY_STATE_DOWN; } WORD mbChar; UINT scancode = ::MapVirtualKeyEx(wKey, 0, m_kbLayout); // Depress modifiers to map a Unicode char to a key code kbState[VK_CONTROL] &= ~0x80; kbState[VK_SHIFT] &= ~0x80; kbState[VK_MENU] &= ~0x80; int converted = ::ToAsciiEx(wKey, scancode, kbState, &mbChar, 0, m_kbLayout); wchar_t wChar[4] = {0}; int unicodeConverted = ::ToUnicodeEx(wKey, scancode, kbState, wChar, 4, 0, m_kbLayout); // Some virtual codes require special handling switch (wKey) { case 0x00BA:// VK_OEM_1 case 0x00BB:// VK_OEM_PLUS case 0x00BC:// VK_OEM_COMMA case 0x00BD:// VK_OEM_MINUS case 0x00BE:// VK_OEM_PERIOD case 0x00BF:// VK_OEM_2 case 0x00C0:// VK_OEM_3 case 0x00DB:// VK_OEM_4 case 0x00DC:// VK_OEM_5 case 0x00DD:// VK_OEM_6 case 0x00DE:// VK_OEM_7 case 0x00DF:// VK_OEM_8 case 0x00E2:// VK_OEM_102 if (unicodeConverted < 0) { // Dead key switch (wChar[0]) { case L'`': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_GRAVE; break; case L'\'': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_ACUTE; break; case 0x00B4: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_ACUTE; break; case L'^': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_CIRCUMFLEX; break; case L'~': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_TILDE; break; case 0x02DC: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_TILDE; break; case 0x00AF: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_MACRON; break; case 0x02D8: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_BREVE; break; case 0x02D9: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_ABOVEDOT; break; case L'"': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_DIAERESIS; break; case 0x00A8: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_DIAERESIS; break; case 0x02DA: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_ABOVERING; break; case 0x02DD: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_DOUBLEACUTE; break; case 0x02C7: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_CARON; break; // aka hacek case L',': jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_CEDILLA; break; case 0x00B8: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_CEDILLA; break; case 0x02DB: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_OGONEK; break; case 0x037A: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_IOTA; break; // ASCII ??? case 0x309B: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_VOICED_SOUND; break; case 0x309C: jKeyCode = com_sun_glass_events_KeyEvent_VK_DEAD_SEMIVOICED_SOUND; break; default: jKeyCode = com_sun_glass_events_KeyEvent_VK_UNDEFINED; break; }; } else if (unicodeConverted == 1) { switch (wChar[0]) { case L'!': jKeyCode = com_sun_glass_events_KeyEvent_VK_EXCLAMATION; break; case L'"': jKeyCode = com_sun_glass_events_KeyEvent_VK_DOUBLE_QUOTE; break; case L'#': jKeyCode = com_sun_glass_events_KeyEvent_VK_NUMBER_SIGN; break; case L'$': jKeyCode = com_sun_glass_events_KeyEvent_VK_DOLLAR; break; case L'&': jKeyCode = com_sun_glass_events_KeyEvent_VK_AMPERSAND; break; case L'\'': jKeyCode = com_sun_glass_events_KeyEvent_VK_QUOTE; break; case L'(': jKeyCode = com_sun_glass_events_KeyEvent_VK_LEFT_PARENTHESIS; break; case L')': jKeyCode = com_sun_glass_events_KeyEvent_VK_RIGHT_PARENTHESIS; break; case L'*': jKeyCode = com_sun_glass_events_KeyEvent_VK_ASTERISK; break; case L'+': jKeyCode = com_sun_glass_events_KeyEvent_VK_PLUS; break; case L',': jKeyCode = com_sun_glass_events_KeyEvent_VK_COMMA; break; case L'-': jKeyCode = com_sun_glass_events_KeyEvent_VK_MINUS; break; case L'.': jKeyCode = com_sun_glass_events_KeyEvent_VK_PERIOD; break; case L'/': jKeyCode = com_sun_glass_events_KeyEvent_VK_SLASH; break; case L':': jKeyCode = com_sun_glass_events_KeyEvent_VK_COLON; break; case L';': jKeyCode = com_sun_glass_events_KeyEvent_VK_SEMICOLON; break; case L'<': jKeyCode = com_sun_glass_events_KeyEvent_VK_LESS; break; case L'=': jKeyCode = com_sun_glass_events_KeyEvent_VK_EQUALS; break; case L'>': jKeyCode = com_sun_glass_events_KeyEvent_VK_GREATER; break; case L'@': jKeyCode = com_sun_glass_events_KeyEvent_VK_AT; break; case L'[': jKeyCode = com_sun_glass_events_KeyEvent_VK_OPEN_BRACKET; break; case L'\\': jKeyCode = com_sun_glass_events_KeyEvent_VK_BACK_SLASH; break; case L']': jKeyCode = com_sun_glass_events_KeyEvent_VK_CLOSE_BRACKET; break; case L'^': jKeyCode = com_sun_glass_events_KeyEvent_VK_CIRCUMFLEX; break; case L'_': jKeyCode = com_sun_glass_events_KeyEvent_VK_UNDERSCORE; break; case L'`': jKeyCode = com_sun_glass_events_KeyEvent_VK_BACK_QUOTE; break; case L'{': jKeyCode = com_sun_glass_events_KeyEvent_VK_BRACELEFT; break; case L'}': jKeyCode = com_sun_glass_events_KeyEvent_VK_BRACERIGHT; break; case 0x00A1: jKeyCode = com_sun_glass_events_KeyEvent_VK_INV_EXCLAMATION; break; case 0x20A0: jKeyCode = com_sun_glass_events_KeyEvent_VK_EURO_SIGN; break; default: jKeyCode = com_sun_glass_events_KeyEvent_VK_UNDEFINED; break; } } else if (unicodeConverted == 0 || unicodeConverted > 1) { jKeyCode = com_sun_glass_events_KeyEvent_VK_UNDEFINED; } break; }; int keyCharCount = 0; jchar keyChars[4]; const bool isAutoRepeat = (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN) && (lParam & (1 << 30)); if (converted < 0) { // Dead key return; } else if (converted == 0) { // No translation available keyCharCount = 0; // This includes SHIFT, CONTROL, ALT, etc. // RT-17062: suppress auto-repeated events for modifier keys if (isAutoRepeat) { switch (jKeyCode) { case com_sun_glass_events_KeyEvent_VK_SHIFT: case com_sun_glass_events_KeyEvent_VK_CONTROL: case com_sun_glass_events_KeyEvent_VK_ALT: case com_sun_glass_events_KeyEvent_VK_ALT_GRAPH: case com_sun_glass_events_KeyEvent_VK_WINDOWS: return; } } } else { // Handle some special cases if ((wKey == VK_BACK) || (wKey == VK_ESCAPE)) { keyCharCount = 0; } else { keyCharCount = ::MultiByteToWideChar(m_codePage, MB_PRECOMPOSED, (LPCSTR)&mbChar, 2, (LPWSTR)keyChars, 4 * sizeof(jchar)) - 1; if (keyCharCount <= 0) { return; } } } JNIEnv* env = GetEnv(); jcharArray jKeyChars = env->NewCharArray(keyCharCount); if (jKeyChars) { if (keyCharCount) { env->SetCharArrayRegion(jKeyChars, 0, keyCharCount, keyChars); CheckAndClearException(env); } if (jKeyCode == com_sun_glass_events_KeyEvent_VK_PRINTSCREEN && (msg == WM_KEYUP || msg == WM_SYSKEYUP)) { // MS Windows doesn't send WM_KEYDOWN for the PrintScreen key, // so we synthesize one env->CallVoidMethod(GetView(), javaIDs.View.notifyKey, com_sun_glass_events_KeyEvent_PRESS, jKeyCode, jKeyChars, jModifiers); CheckAndClearException(env); } if (GetGlassView()) { env->CallVoidMethod(GetView(), javaIDs.View.notifyKey, (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN) ? com_sun_glass_events_KeyEvent_PRESS : com_sun_glass_events_KeyEvent_RELEASE, jKeyCode, jKeyChars, jModifiers); CheckAndClearException(env); } // MS Windows doesn't send WM_CHAR for the Delete key, // so we synthesize one if (jKeyCode == com_sun_glass_events_KeyEvent_VK_DELETE && (msg == WM_KEYDOWN || msg == WM_SYSKEYDOWN) && GetGlassView()) { // 0x7F == U+007F - a Unicode character for DELETE SendViewTypedEvent(1, (jchar)0x7F); } env->DeleteLocalRef(jKeyChars); } } void ViewContainer::SendViewTypedEvent(int repCount, jchar wChar) { if (!GetGlassView()) { return; } JNIEnv* env = GetEnv(); jcharArray jKeyChars = env->NewCharArray(repCount); if (jKeyChars) { jchar* nKeyChars = env->GetCharArrayElements(jKeyChars, NULL); if (nKeyChars) { for (int i = 0; i < repCount; i++) { nKeyChars[i] = wChar; } env->ReleaseCharArrayElements(jKeyChars, nKeyChars, 0); env->CallVoidMethod(GetView(), javaIDs.View.notifyKey, com_sun_glass_events_KeyEvent_TYPED, com_sun_glass_events_KeyEvent_VK_UNDEFINED, jKeyChars, GetModifiers()); CheckAndClearException(env); } env->DeleteLocalRef(jKeyChars); } } void ViewContainer::HandleViewDeadKeyEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } if (!m_deadKeyWParam) { // HandleViewKeyEvent() calls ::ToAsciiEx and ::ToUnicodeEx which clear // the dead key status from the keyboard layout. We store the current dead // key here to use it when processing WM_CHAR in order to get the // actual character typed. m_deadKeyWParam = wParam; } else { // There already was another dead key pressed previously. Clear it // and send two separate TYPED events instead to emulate native behavior. SendViewTypedEvent(1, (jchar)m_deadKeyWParam); SendViewTypedEvent(1, (jchar)wParam); m_deadKeyWParam = 0; } // Since we handle dead keys ourselves, reset the keyboard dead key status (if any) static BYTE kbState[256]; ::GetKeyboardState(kbState); WORD ignored; ::ToAsciiEx(VK_SPACE, ::MapVirtualKey(VK_SPACE, 0), kbState, &ignored, 0, m_kbLayout); } void ViewContainer::HandleViewTypedEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return; } int repCount = LOWORD(lParam); jchar wChar; if (!m_deadKeyWParam) { wChar = (jchar)wParam; } else { // The character is composed together with the dead key, which // may be translated into one or more combining characters. const size_t COMP_SIZE = 5; wchar_t comp[COMP_SIZE] = { (wchar_t)wParam }; // Some dead keys need additional translation: // http://www.fileformat.info/info/unicode/block/combining_diacritical_marks/images.htm // Also see awt_Component.cpp for the original dead keys table if (LOBYTE(m_idLang) == LANG_GREEK) { switch (m_deadKeyWParam) { case L']': comp[1] = 0x300; break; // varia case L';': comp[1] = 0x301; break; // oxia (wrong? generates tonos, not oxia) case L'-': comp[1] = 0x304; break; // macron case L'_': comp[1] = 0x306; break; // vrachy case L':': comp[1] = 0x308; break; // dialytika case L'"': comp[1] = 0x314; break; // dasia case 0x0384: comp[1] = 0x341; break; // tonos case L'[': comp[1] = 0x342; break; // perispomeni case L'\'': comp[1] = 0x343; break; // psili case L'~': comp[1] = 0x344; break; // dialytika oxia case L'{': comp[1] = 0x345; break; // ypogegrammeni case L'`': comp[1] = 0x308; comp[2] = 0x300; break; // dialytika varia case L'\\': comp[1] = 0x313; comp[2] = 0x300; break; // psili varia case L'/': comp[1] = 0x313; comp[2] = 0x301; break; // psili oxia case L'=': comp[1] = 0x313; comp[2] = 0x342; break; // psili perispomeni case L'|': comp[1] = 0x314; comp[2] = 0x300; break; // dasia varia case L'?': comp[1] = 0x314; comp[2] = 0x301; break; // dasia oxia case L'+': comp[1] = 0x314; comp[2] = 0x342; break; // dasia perispomeni // AltGr dead chars don't work. Maybe kbd isn't reset properly? // case 0x1fc1: comp[1] = 0x308; comp[2] = 0x342; break; // dialytika perispomeni // case 0x1fde: comp[1] = 0x314; comp[2] = 0x301; comp[3] = 0x345; break; // dasia oxia ypogegrammeni default: comp[1] = static_cast<wchar_t>(m_deadKeyWParam); break; } } else if (HIWORD(m_kbLayout) == 0xF0B1 && LOBYTE(m_idLang) == LANG_LATVIAN) { // The Latvian (Standard) keyboard, available in Win 8.1 and later. switch (m_deadKeyWParam) { case L'\'': case L'"': // Note: " is Shift-' and automatically capitalizes the typed // character in native Win 8.1 apps. We don't do this, so the user // needs to keep the Shift key down. This is probably the common use // case anyway. switch (wParam) { case L'A': case L'a': case L'E': case L'e': case L'I': case L'i': case L'U': case L'u': comp[1] = 0x304; break; // macron case L'C': case L'c': case L'S': case L's': case L'Z': case L'z': comp[1] = 0x30c; break; // caron case L'G': case L'g': case L'K': case L'k': case L'L': case L'l': case L'N': case L'n': comp[1] = 0x327; break; // cedilla default: comp[1] = static_cast<wchar_t>(m_deadKeyWParam); break; } break; default: comp[1] = static_cast<wchar_t>(m_deadKeyWParam); break; } } else { switch (m_deadKeyWParam) { case L'`': comp[1] = 0x300; break; case L'\'': comp[1] = 0x301; break; case 0x00B4: comp[1] = 0x301; break; case L'^': comp[1] = 0x302; break; case L'~': comp[1] = 0x303; break; case 0x02DC: comp[1] = 0x303; break; case 0x00AF: comp[1] = 0x304; break; case 0x02D8: comp[1] = 0x306; break; case 0x02D9: comp[1] = 0x307; break; case L'"': comp[1] = 0x308; break; case 0x00A8: comp[1] = 0x308; break; case 0x00B0: comp[1] = 0x30A; break; case 0x02DA: comp[1] = 0x30A; break; case 0x02DD: comp[1] = 0x30B; break; case 0x02C7: comp[1] = 0x30C; break; case L',': comp[1] = 0x327; break; case 0x00B8: comp[1] = 0x327; break; case 0x02DB: comp[1] = 0x328; break; default: comp[1] = static_cast<wchar_t>(m_deadKeyWParam); break; } } int compSize = 3; for (int i = 1; i < COMP_SIZE; i++) { if (comp[i] == L'\0') { compSize = i + 1; break; } } wchar_t out[3]; int res = ::FoldString(MAP_PRECOMPOSED, (LPWSTR)comp, compSize, (LPWSTR)out, 3); if (res > 0) { wChar = (jchar)out[0]; if (res == 3) { // The character cannot be accented, so we send a TYPED event // for the dead key itself first. SendViewTypedEvent(1, (jchar)m_deadKeyWParam); } } else { // Folding failed. Use the untranslated original character then wChar = (jchar)wParam; } // Clear the dead key m_deadKeyWParam = 0; } SendViewTypedEvent(repCount, wChar); } BOOL ViewContainer::HandleViewMouseEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { if (!GetGlassView()) { return FALSE; } int type = 0; int button = com_sun_glass_events_MouseEvent_BUTTON_NONE; POINT pt; // client coords jdouble wheelRotation = 0.0; if (msg == WM_MOUSELEAVE) { type = com_sun_glass_events_MouseEvent_EXIT; // get the coords (the message does not contain them) lParam = ::GetMessagePos(); pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam); // this is screen coords, convert to client ::ScreenToClient(hwnd, &pt); // Windows has finished tracking mouse pointer already m_bTrackingMouse = FALSE; m_lastMouseMovePosition = -1; } else { // for all other messages lParam contains cursor coords pt.x = GET_X_LPARAM(lParam); pt.y = GET_Y_LPARAM(lParam); switch (msg) { case WM_MOUSEMOVE: if (lParam == m_lastMouseMovePosition) { // Avoid sending synthetic MOVE/DRAG events if // the pointer hasn't moved actually. // Just consume the messages. return TRUE; } else { m_lastMouseMovePosition = lParam; } // See RT-11305 regarding the GetCapture() check if ((wParam & (MK_LBUTTON | MK_RBUTTON | MK_MBUTTON)) != 0 && ::GetCapture() == hwnd) { type = com_sun_glass_events_MouseEvent_DRAG; } else { type = com_sun_glass_events_MouseEvent_MOVE; } // Due to RT-11305 we should report the pressed button for both // MOVE and DRAG. This also enables one to filter out these // events in client code in case they're undesired. if (wParam & MK_RBUTTON) { button = com_sun_glass_events_MouseEvent_BUTTON_RIGHT; } else if (wParam & MK_LBUTTON) { button = com_sun_glass_events_MouseEvent_BUTTON_LEFT; } else if (wParam & MK_MBUTTON) { button = com_sun_glass_events_MouseEvent_BUTTON_OTHER; } break; case WM_LBUTTONDOWN: type = com_sun_glass_events_MouseEvent_DOWN; button = com_sun_glass_events_MouseEvent_BUTTON_LEFT; break; case WM_LBUTTONUP: type = com_sun_glass_events_MouseEvent_UP; button = com_sun_glass_events_MouseEvent_BUTTON_LEFT; break; case WM_RBUTTONDOWN: type = com_sun_glass_events_MouseEvent_DOWN; button = com_sun_glass_events_MouseEvent_BUTTON_RIGHT; break; case WM_RBUTTONUP: type = com_sun_glass_events_MouseEvent_UP; button = com_sun_glass_events_MouseEvent_BUTTON_RIGHT; break; case WM_MBUTTONDOWN: type = com_sun_glass_events_MouseEvent_DOWN; button = com_sun_glass_events_MouseEvent_BUTTON_OTHER; break; case WM_MBUTTONUP: type = com_sun_glass_events_MouseEvent_UP; button = com_sun_glass_events_MouseEvent_BUTTON_OTHER; break; case WM_MOUSEWHEEL: case WM_MOUSEHWHEEL: { // MS Windows always sends WHEEL events to the focused window. // Redirect the message to a Glass window under the mouse // cursor instead to match Mac behavior HWND hwndUnderCursor = ::ChildWindowFromPointEx( ::GetDesktopWindow(), pt, CWP_SKIPDISABLED | CWP_SKIPINVISIBLE); if (hwndUnderCursor && hwndUnderCursor != hwnd) { DWORD hWndUnderCursorProcess; ::GetWindowThreadProcessId(hwndUnderCursor, &hWndUnderCursorProcess); if (::GetCurrentProcessId() == hWndUnderCursorProcess) { return (BOOL)::SendMessage(hwndUnderCursor, msg, wParam, lParam); } } // if there's none, proceed as usual type = com_sun_glass_events_MouseEvent_WHEEL; wheelRotation = (jdouble)GET_WHEEL_DELTA_WPARAM(wParam) / WHEEL_DELTA; } break; } } switch (type) { case 0: // not handled return FALSE; case com_sun_glass_events_MouseEvent_DOWN: m_mouseButtonDownCounter++; if (::GetCapture() != hwnd) { ::SetCapture(hwnd); } break; case com_sun_glass_events_MouseEvent_UP: if (m_mouseButtonDownCounter) { m_mouseButtonDownCounter--; } //else { internal inconsistency; quite unimportant though } if (::GetCapture() == hwnd && !m_mouseButtonDownCounter) { ::ReleaseCapture(); } break; } // get screen coords POINT ptAbs = pt; if (type == com_sun_glass_events_MouseEvent_WHEEL) { ::ScreenToClient(hwnd, &pt); } else { ::ClientToScreen(hwnd, &ptAbs); } // unmirror the x coordinate LONG style = ::GetWindowLong(hwnd, GWL_EXSTYLE); if (style & WS_EX_LAYOUTRTL) { RECT rect = {0}; ::GetClientRect(hwnd, &rect); pt.x = max(0, rect.right - rect.left) - pt.x; } jint jModifiers = GetModifiers(); const jboolean isSynthesized = jboolean(IsTouchEvent()); JNIEnv *env = GetEnv(); if (!m_bTrackingMouse && type != com_sun_glass_events_MouseEvent_EXIT) { TRACKMOUSEEVENT trackData; trackData.cbSize = sizeof(trackData); trackData.dwFlags = TME_LEAVE; trackData.hwndTrack = hwnd; trackData.dwHoverTime = HOVER_DEFAULT; if (::TrackMouseEvent(&trackData)) { // Mouse tracking will be canceled automatically upon receiving WM_MOUSELEAVE m_bTrackingMouse = TRUE; } // Note that (ViewContainer*)this != (BaseWnd*)this. We could use // dynamic_case<>() instead, but it would fail later if 'this' is // already deleted. So we use FromHandle() which is safe. const BaseWnd *origWnd = BaseWnd::FromHandle(hwnd); env->CallVoidMethod(GetView(), javaIDs.View.notifyMouse, com_sun_glass_events_MouseEvent_ENTER, com_sun_glass_events_MouseEvent_BUTTON_NONE, pt.x, pt.y, ptAbs.x, ptAbs.y, jModifiers, JNI_FALSE, isSynthesized); CheckAndClearException(env); // At this point 'this' might have already been deleted if the app // closed the window while processing the ENTER event. Hence the check: if (!::IsWindow(hwnd) || BaseWnd::FromHandle(hwnd) != origWnd || !GetGlassView()) { return TRUE; } } switch (type) { case com_sun_glass_events_MouseEvent_DOWN: GlassDropSource::SetDragButton(button); break; case com_sun_glass_events_MouseEvent_UP: GlassDropSource::SetDragButton(0); break; } if (type == com_sun_glass_events_MouseEvent_WHEEL) { jdouble dx, dy; if (msg == WM_MOUSEHWHEEL) { // native horizontal scroll // Negate the value to be more "natural" dx = -wheelRotation; dy = 0.0; } else if (msg == WM_MOUSEWHEEL && LOWORD(wParam) & MK_SHIFT) { // Do not negate the emulated horizontal scroll amount dx = wheelRotation; dy = 0.0; } else { // vertical scroll dx = 0.0; dy = wheelRotation; } jint ls, cs; UINT val = 0; ::SystemParametersInfo(SPI_GETWHEELSCROLLLINES, 0, &val, 0); ls = (jint)val; val = 0; ::SystemParametersInfo(SPI_GETWHEELSCROLLCHARS, 0, &val, 0); cs = (jint)val; env->CallVoidMethod(GetView(), javaIDs.View.notifyScroll, pt.x, pt.y, ptAbs.x, ptAbs.y, dx, dy, jModifiers, ls, cs, 3, 3, (jdouble)40.0, (jdouble)40.0); } else { env->CallVoidMethod(GetView(), javaIDs.View.notifyMouse, type, button, pt.x, pt.y, ptAbs.x, ptAbs.y, jModifiers, type == com_sun_glass_events_MouseEvent_UP && button == com_sun_glass_events_MouseEvent_BUTTON_RIGHT, isSynthesized); } CheckAndClearException(env); return TRUE; } void ViewContainer::NotifyCaptureChanged(HWND hwnd, HWND to) { m_mouseButtonDownCounter = 0; } void ViewContainer::ResetMouseTracking(HWND hwnd) { if (!m_bTrackingMouse) { return; } // We don't expect WM_MOUSELEAVE anymore, so we cancel mouse tracking manually TRACKMOUSEEVENT trackData; trackData.cbSize = sizeof(trackData); trackData.dwFlags = TME_LEAVE | TME_CANCEL; trackData.hwndTrack = hwnd; trackData.dwHoverTime = HOVER_DEFAULT; ::TrackMouseEvent(&trackData); m_bTrackingMouse = FALSE; if (!GetGlassView()) { return; } POINT ptAbs; ::GetCursorPos(&ptAbs); POINT pt = ptAbs; ::ScreenToClient(hwnd, &pt); // unmirror the x coordinate LONG style = ::GetWindowLong(hwnd, GWL_EXSTYLE); if (style & WS_EX_LAYOUTRTL) { RECT rect = {0}; ::GetClientRect(hwnd, &rect); pt.x = max(0, rect.right - rect.left) - pt.x; } JNIEnv *env = GetEnv(); env->CallVoidMethod(GetView(), javaIDs.View.notifyMouse, com_sun_glass_events_MouseEvent_EXIT, 0, pt.x, pt.y, ptAbs.x, ptAbs.y, GetModifiers(), JNI_FALSE, JNI_FALSE); CheckAndClearException(env); } BOOL ViewContainer::HandleViewInputMethodEvent(HWND hwnd, UINT msg, WPARAM wParam, LPARAM lParam) { GlassView* gv = GetGlassView(); if (!gv) { return FALSE; } switch (msg) { case WM_IME_ENDCOMPOSITION: SendInputMethodEvent(NULL, 0, NULL, 0, NULL, NULL, 0, 0, 0); case WM_IME_STARTCOMPOSITION: return gv->IsInputMethodEventEnabled(); case WM_IME_COMPOSITION: if (gv->IsInputMethodEventEnabled()) { WmImeComposition(hwnd, wParam, lParam); return TRUE; } break; case WM_IME_NOTIFY: if (gv->IsInputMethodEventEnabled()) { WmImeNotify(hwnd, wParam, lParam); } break; default: return FALSE; } return FALSE; } void ViewContainer::WmImeComposition(HWND hwnd, WPARAM wParam, LPARAM lParam) { BOOL ret = FALSE; JNIEnv *env = GetEnv(); int* bndClauseW = NULL; int* bndAttrW = NULL; BYTE* valAttrW = NULL; int cClauseW = 0; GlassInputTextInfo textInfo = GlassInputTextInfo(this); HIMC hIMC = ImmGetContext(hwnd); ASSERT(hIMC!=0); try { textInfo.GetContextData(hIMC, lParam); jstring jtextString = textInfo.GetText(); if ((lParam & GCS_RESULTSTR && jtextString != NULL) || (lParam & GCS_COMPSTR)) { int cursorPosW = textInfo.GetCursorPosition(); int cAttrW = textInfo.GetAttributeInfo(bndAttrW, valAttrW); cClauseW = textInfo.GetClauseInfo(bndClauseW); SendInputMethodEvent(jtextString, cClauseW, bndClauseW, cAttrW, bndAttrW, valAttrW, textInfo.GetCommittedTextLength(), cursorPosW, cursorPosW); } ImmReleaseContext(hwnd, hIMC); } catch (...) { // since GetClauseInfo and GetAttributeInfo could throw exception, we have to release // the pointer here. delete [] bndClauseW; delete [] bndAttrW; delete [] valAttrW; ImmReleaseContext(hwnd, hIMC); throw; } /* Free the storage allocated. Since jtextString won't be passed from threads * to threads, we just use the local ref and it will be deleted within the destructor * of GlassInputTextInfo object. */ delete [] bndClauseW; delete [] bndAttrW; delete [] valAttrW; CheckAndClearException(env); } void ViewContainer::WmImeNotify(HWND hwnd, WPARAM wParam, LPARAM lParam) { if (wParam == IMN_OPENCANDIDATE || wParam == IMN_CHANGECANDIDATE) { JNIEnv *env = GetEnv(); POINT curPos; UINT bits = 1; HIMC hIMC = ImmGetContext(hwnd); CANDIDATEFORM cf; GetCandidatePos(&curPos); ::ScreenToClient(hwnd, &curPos); for (int iCandType=0; iCandType<32; iCandType++, bits<<=1) { if (lParam & bits) { cf.dwIndex = iCandType; cf.dwStyle = CFS_CANDIDATEPOS; // The constant offset is needed because Windows is moving the IM window cf.ptCurrentPos.x = curPos.x - 6; cf.ptCurrentPos.y = curPos.y - 15; ::ImmSetCandidateWindow(hIMC, &cf); } } ImmReleaseContext(hwnd, hIMC); } } // // generate and post InputMethodEvent // void ViewContainer::SendInputMethodEvent(jstring text, int cClause, int* rgClauseBoundary, int cAttrBlock, int* rgAttrBoundary, BYTE *rgAttrValue, int commitedTextLength, int caretPos, int visiblePos) { JNIEnv *env = GetEnv(); // assumption for array type casting ASSERT(sizeof(int)==sizeof(jint)); ASSERT(sizeof(BYTE)==sizeof(jbyte)); // caluse information jintArray clauseBoundary = NULL; if (cClause && rgClauseBoundary) { // convert clause boundary offset array to java array clauseBoundary = env->NewIntArray(cClause+1); if (clauseBoundary) { env->SetIntArrayRegion(clauseBoundary, 0, cClause+1, (jint *)rgClauseBoundary); CheckAndClearException(env); } } // attribute information jintArray attrBoundary = NULL; jbyteArray attrValue = NULL; if (cAttrBlock && rgAttrBoundary && rgAttrValue) { // convert attribute boundary offset array to java array attrBoundary = env->NewIntArray(cAttrBlock+1); if (attrBoundary) { env->SetIntArrayRegion(attrBoundary, 0, cAttrBlock+1, (jint *)rgAttrBoundary); CheckAndClearException(env); } // convert attribute value byte array to java array attrValue = env->NewByteArray(cAttrBlock); if (attrValue) { env->SetByteArrayRegion(attrValue, 0, cAttrBlock, (jbyte *)rgAttrValue); CheckAndClearException(env); } } env->CallBooleanMethod(GetView(), javaIDs.View.notifyInputMethod, text, clauseBoundary, attrBoundary, attrValue, commitedTextLength, caretPos, visiblePos); CheckAndClearException(env); if (clauseBoundary) { env->DeleteLocalRef(clauseBoundary); } if (attrBoundary) { env->DeleteLocalRef(attrBoundary); } if (attrValue) { env->DeleteLocalRef(attrValue); } } // Gets the candidate position void ViewContainer::GetCandidatePos(LPPOINT curPos) { JNIEnv *env = GetEnv(); double* nativePos; jdoubleArray pos = (jdoubleArray)env->CallObjectMethod(GetView(), javaIDs.View.notifyInputMethodCandidatePosRequest, 0); nativePos = env->GetDoubleArrayElements(pos, NULL); if (nativePos) { curPos->x = (int)nativePos[0]; curPos->y = (int)nativePos[1]; env->ReleaseDoubleArrayElements(pos, nativePos, 0); } } namespace { class AutoTouchInputHandle { HTOUCHINPUT m_h; private: AutoTouchInputHandle(const AutoTouchInputHandle&); AutoTouchInputHandle& operator=(const AutoTouchInputHandle&); public: explicit AutoTouchInputHandle(LPARAM lParam): m_h((HTOUCHINPUT)lParam) { } ~AutoTouchInputHandle() { if (m_h) { ::CloseTouchInputHandle(m_h); } } operator HTOUCHINPUT() const { return m_h; } }; static BOOL debugTouch = false; static char * touchEventName(unsigned int dwFlags) { if (dwFlags & TOUCHEVENTF_MOVE) { return "MOVE"; } if (dwFlags & TOUCHEVENTF_DOWN) { return "PRESS"; } if (dwFlags & TOUCHEVENTF_UP) { return "RELEASE"; } return "UNKOWN"; } void NotifyTouchInput( HWND hWnd, jobject view, jclass gestureSupportCls, const TOUCHINPUT* ti, unsigned count) { JNIEnv *env = GetEnv(); // TBD: set to 'true' if source device is a touch screen // and to 'false' if source device is a touch pad. // So far assume source device on Windows is always a touch screen. const bool isDirect = true; jint modifiers = GetModifiers(); env->CallStaticObjectMethod(gestureSupportCls, javaIDs.Gestures.notifyBeginTouchEventMID, view, modifiers, jboolean(isDirect), jint(count)); CheckAndClearException(env); for (; count; --count, ++ti) { jlong touchID = jlong(ti->dwID); jint eventID = 0; if (ti->dwFlags & TOUCHEVENTF_MOVE) { eventID = com_sun_glass_events_TouchEvent_TOUCH_MOVED; } if (ti->dwFlags & TOUCHEVENTF_DOWN) { eventID = com_sun_glass_events_TouchEvent_TOUCH_PRESSED; } if (ti->dwFlags & TOUCHEVENTF_UP) { eventID = com_sun_glass_events_TouchEvent_TOUCH_RELEASED; } POINT screen; POINT client; client.x = screen.x = LONG(ti->x / 100); client.y = screen.y = LONG(ti->y / 100); ScreenToClient(hWnd, &client); // unmirror the x coordinate LONG style = ::GetWindowLong(hWnd, GWL_EXSTYLE); if (style & WS_EX_LAYOUTRTL) { RECT rect = {0}; ::GetClientRect(hWnd, &rect); client.x = max(0, rect.right - rect.left) - client.x; } env->CallStaticObjectMethod(gestureSupportCls, javaIDs.Gestures.notifyNextTouchEventMID, view, eventID, touchID, jint(client.x), jint(client.y), jint(screen.x), jint(screen.y)); CheckAndClearException(env); } env->CallStaticObjectMethod( gestureSupportCls, javaIDs.Gestures.notifyEndTouchEventMID, view); CheckAndClearException(env); } void NotifyManipulationProcessor( IManipulationProcessor& manipProc, const TOUCHINPUT* ti, unsigned count) { for (; count; --count, ++ti) { if (ti->dwFlags & TOUCHEVENTF_DOWN) { manipProc.ProcessDownWithTime(ti->dwID, FLOAT(ti->x), FLOAT(ti->y), ti->dwTime); } if (ti->dwFlags & TOUCHEVENTF_MOVE) { manipProc.ProcessMoveWithTime(ti->dwID, FLOAT(ti->x), FLOAT(ti->y), ti->dwTime); } if (ti->dwFlags & TOUCHEVENTF_UP) { manipProc.ProcessUpWithTime(ti->dwID, FLOAT(ti->x), FLOAT(ti->y), ti->dwTime); } } } } // namespace unsigned int ViewContainer::HandleViewTouchEvent( HWND hWnd, UINT msg, WPARAM wParam, LPARAM lParam) { const UINT newCount = static_cast<UINT>(LOWORD(wParam)); TOUCHINPUT * tempTouchInputBuf; unsigned int bufsz = newCount > 10 ? newCount : 10; if (m_thisTouchInputBuf.size() < bufsz) { m_thisTouchInputBuf.resize(bufsz); } if (newCount > 0) { tempTouchInputBuf = new TOUCHINPUT[newCount]; do { AutoTouchInputHandle inputInfo(lParam); if (!::GetTouchInputInfo(inputInfo, newCount, tempTouchInputBuf, sizeof(TOUCHINPUT))) { delete [] tempTouchInputBuf; return 0; } } while(0); // scope for 'inputInfo' } // Fix up the touch point stream. Some drivers seem to lose touch events, // dropping PRESS, MOVE, UP, so we need to add them back in. unsigned int activeCount = 0; unsigned int pointsCount = 0; // check first for any "lost" touches // these need to get added to the send list of points for (unsigned int i = 0 ; i < m_lastTouchInputCount; i++) { if (!(m_lastTouchInputBuf[i].dwFlags & TOUCHEVENTF_UP)) { // looking for a dwID that is // not present in the new batch // was not UP in the old batch bool found = false; for (unsigned int j = 0; j < newCount; j++) { if (m_lastTouchInputBuf[i].dwID == tempTouchInputBuf[j].dwID) { found = true; //break; } } if (!found) { // We have a old event but not a new one, so release it m_thisTouchInputBuf[pointsCount].dwFlags = TOUCHEVENTF_UP; m_thisTouchInputBuf[pointsCount].dwID = m_lastTouchInputBuf[i].dwID; m_thisTouchInputBuf[pointsCount].x = m_lastTouchInputBuf[i].x; m_thisTouchInputBuf[pointsCount].y = m_lastTouchInputBuf[i].y; if (newCount > 0) { //use the time of the first new element for our inserted event m_thisTouchInputBuf[pointsCount].dwTime = tempTouchInputBuf[0].dwTime; } else { m_thisTouchInputBuf[pointsCount].dwTime = m_lastTouchInputBuf[i].dwTime; } m_thisTouchInputBuf[pointsCount].dwMask = m_lastTouchInputBuf[i].dwMask; if (debugTouch) { printf("TOUCH FIX UP %d, %s\n", m_lastTouchInputBuf[i].dwID, touchEventName(m_lastTouchInputBuf[i].dwFlags)); } pointsCount++; } } } if (pointsCount + newCount > m_thisTouchInputBuf.size()) { bufsz = pointsCount + newCount; m_thisTouchInputBuf.resize(bufsz); } // now fold in the current touch points for (unsigned int i = 0 ; i < newCount; i++) { bool found = false; for (unsigned int j = 0 ; j < m_lastTouchInputCount; j++) { if (m_lastTouchInputBuf[j].dwID == tempTouchInputBuf[i].dwID) { found = true; break; } } m_thisTouchInputBuf[pointsCount].dwFlags = tempTouchInputBuf[i].dwFlags; m_thisTouchInputBuf[pointsCount].dwID = tempTouchInputBuf[i].dwID; m_thisTouchInputBuf[pointsCount].dwTime = tempTouchInputBuf[i].dwTime; m_thisTouchInputBuf[pointsCount].dwMask = tempTouchInputBuf[i].dwMask; m_thisTouchInputBuf[pointsCount].x = tempTouchInputBuf[i].x; m_thisTouchInputBuf[pointsCount].y = tempTouchInputBuf[i].y; if (m_thisTouchInputBuf[pointsCount].dwFlags & TOUCHEVENTF_DOWN) { pointsCount++; activeCount ++; } else if (m_thisTouchInputBuf[pointsCount].dwFlags & TOUCHEVENTF_MOVE) { if (!found) { if (debugTouch) { printf("TOUCH FIX MV->DOWN %d, %s\n", m_thisTouchInputBuf[pointsCount].dwID, touchEventName(m_thisTouchInputBuf[pointsCount].dwFlags)); } m_thisTouchInputBuf[pointsCount].dwFlags = TOUCHEVENTF_DOWN; } pointsCount++; activeCount ++; } else if (m_thisTouchInputBuf[pointsCount].dwFlags & TOUCHEVENTF_UP) { if (found) { pointsCount++; } else { // UP without a previous DOWN, ignore it } } } if (debugTouch) { printf("Touch Sequence %d/%d win=%d view=%d %d,%d,%d\n",pointsCount,activeCount, hWnd, GetView(), m_lastTouchInputCount, newCount, pointsCount); for (unsigned int i = 0 ; i < m_lastTouchInputCount; i++) { printf(" old %d, %s\n", m_lastTouchInputBuf[i].dwID, touchEventName(m_lastTouchInputBuf[i].dwFlags)); } for (unsigned int i = 0 ; i < newCount; i++) { printf(" in %d, %s\n", tempTouchInputBuf[i].dwID, touchEventName(tempTouchInputBuf[i].dwFlags)); } for (unsigned int i = 0 ; i < pointsCount; i++) { printf(" this %d, %d\n", m_thisTouchInputBuf[i].dwID, m_thisTouchInputBuf[i].dwFlags & 0x07); } printf(" ---\n"); fflush(stdout); } if (pointsCount > 0) { NotifyTouchInput(hWnd, GetView(), m_gestureSupportCls, &m_thisTouchInputBuf[0], pointsCount); if (m_manipProc) { NotifyManipulationProcessor(*m_manipProc, &m_thisTouchInputBuf[0], pointsCount); } std::swap(m_lastTouchInputBuf, m_thisTouchInputBuf); m_lastTouchInputCount = pointsCount; } if ( newCount > 0) { delete [] tempTouchInputBuf; } return activeCount; } void ViewContainer::HandleViewTimerEvent(HWND hwnd, UINT_PTR timerID) { if (IDT_GLASS_INERTIAPROCESSOR == timerID) { BOOL completed = FALSE; HRESULT hr = m_inertiaProc->Process(&completed); if (SUCCEEDED(hr) && completed) { StopTouchInputInertia(hwnd); JNIEnv *env = GetEnv(); env->CallStaticVoidMethod(m_gestureSupportCls, javaIDs.Gestures.inertiaGestureFinishedMID, GetView()); CheckAndClearException(env); } } } void ViewContainer::NotifyGesturePerformed(HWND hWnd, bool isDirect, bool isInertia, FLOAT x, FLOAT y, FLOAT deltaX, FLOAT deltaY, FLOAT scaleDelta, FLOAT expansionDelta, FLOAT rotationDelta, FLOAT cumulativeDeltaX, FLOAT cumulativeDeltaY, FLOAT cumulativeScale, FLOAT cumulativeExpansion, FLOAT cumulativeRotation) { JNIEnv *env = GetEnv(); POINT screen; screen.x = LONG((x + 0.5) / 100); screen.y = LONG((y + 0.5) / 100); POINT client; client.x = screen.x; client.y = screen.y; ScreenToClient(hWnd, &client); // unmirror the x coordinate LONG style = ::GetWindowLong(hWnd, GWL_EXSTYLE); if (style & WS_EX_LAYOUTRTL) { RECT rect = {0}; ::GetClientRect(hWnd, &rect); client.x = max(0, rect.right - rect.left) - client.x; } jint modifiers = GetModifiers(); env->CallStaticVoidMethod(m_gestureSupportCls, javaIDs.Gestures.gesturePerformedMID, GetView(), modifiers, jboolean(isDirect), jboolean(isInertia), jint(client.x), jint(client.y), jint(screen.x), jint(screen.y), deltaX / 100, deltaY / 100, cumulativeDeltaX / 100, cumulativeDeltaY / 100, cumulativeScale, cumulativeExpansion / 100, cumulativeRotation); CheckAndClearException(env); } void ViewContainer::StartTouchInputInertia(HWND hwnd) { // TBD: check errors // // Collect initial inertia data // FLOAT vX, vY; m_manipProc->GetVelocityX(&vX); m_manipProc->GetVelocityY(&vY); const FLOAT VELOCITY_THRESHOLD = 10.0f; if (fabs(vX) < VELOCITY_THRESHOLD && fabs(vY) < VELOCITY_THRESHOLD) { return; } // TBD: check errors POINT origin; GetCursorPos(&origin); // // Setup inertia. // m_inertiaProc->Reset(); m_inertiaProc->put_DesiredDeceleration(0.23f); // Set initial origins. m_inertiaProc->put_InitialOriginX(origin.x * 100.0f); m_inertiaProc->put_InitialOriginY(origin.y * 100.0f); // Set initial velocities. m_inertiaProc->put_InitialVelocityX(vX); m_inertiaProc->put_InitialVelocityY(vY); // TBD: check errors ::SetTimer(hwnd, IDT_GLASS_INERTIAPROCESSOR, 16, NULL); } void ViewContainer::StopTouchInputInertia(HWND hwnd) { // TBD: check errors ::KillTimer(hwnd, IDT_GLASS_INERTIAPROCESSOR); } extern "C" { JNIEXPORT void JNICALL Java_com_sun_glass_ui_win_WinGestureSupport__1initIDs( JNIEnv *env, jclass cls) { javaIDs.Gestures.gesturePerformedMID = env->GetStaticMethodID(cls, "gesturePerformed", "(Lcom/sun/glass/ui/View;IZZIIIIFFFFFFF)V"); CheckAndClearException(env); javaIDs.Gestures.inertiaGestureFinishedMID = env->GetStaticMethodID(cls, "inertiaGestureFinished", "(Lcom/sun/glass/ui/View;)V"); CheckAndClearException(env); javaIDs.Gestures.notifyBeginTouchEventMID = env->GetStaticMethodID(cls, "notifyBeginTouchEvent", "(Lcom/sun/glass/ui/View;IZI)V"); CheckAndClearException(env); javaIDs.Gestures.notifyNextTouchEventMID = env->GetStaticMethodID(cls, "notifyNextTouchEvent", "(Lcom/sun/glass/ui/View;IJIIII)V"); CheckAndClearException(env); javaIDs.Gestures.notifyEndTouchEventMID = env->GetStaticMethodID(cls, "notifyEndTouchEvent", "(Lcom/sun/glass/ui/View;)V"); CheckAndClearException(env); } } // extern "C"
teamfx/openjfx-9-dev-rt
modules/javafx.graphics/src/main/native-glass/win/ViewContainer.cpp
C++
gpl-2.0
58,952
<?php $params = array_merge( require(__DIR__ . '/../../common/config/params.php'), require(__DIR__ . '/../../common/config/params-local.php'), require(__DIR__ . '/params.php'), require(__DIR__ . '/params-local.php') ); return [ 'id' => 'app-frontend', 'basePath' => dirname(__DIR__), 'bootstrap' => ['log'], 'controllerNamespace' => 'frontend\controllers', 'components' => [ 'user' => [ 'identityClass' => 'common\models\User', 'enableAutoLogin' => true, ], 'log' => [ 'traceLevel' => YII_DEBUG ? 3 : 0, 'targets' => [ [ 'class' => 'yii\log\FileTarget', 'levels' => ['error', 'warning'], ], ], ], 'errorHandler' => [ 'errorAction' => 'site/error', ], 'i18n' => [ 'translations' => [ 'app*' => [ 'class' => 'yii\i18n\PhpMessageSource', 'basePath' => '@frontend/messages', 'sourceLanguage' => 'en', 'fileMap' => [ 'app' => 'app.php', 'app/tag' => 'tag.php', 'app/poll' => 'poll.php', 'app/user' => 'user.php', 'app/form' => 'form.php', 'app/content' => 'content.php', ], ], ], ], ], 'params' => $params, ];
cangsalak/Yii2-CMS
frontend/config/main.php
PHP
gpl-2.0
1,425
<div class="metabox-holder indeed"> <div class="stuffbox"> <div class="ism-top-message"><b>"Share Bar"</b> - is a special Social Icons Display on the top of the page when the visitor scroll down.</div> </div> <div class="stuffbox"> <h3> <label style="font-size:16px;"> AddOn Status </label> </h3> <div class="inside"> <div class="submit" style="float:left; width:80%;"> This AddOn is not installed into your system. To use this section you need to install and activate the "Social Share Bar Display" AddOn. </div> <div class="submit" style="float:left; width:20%; text-align:center;"> </div> <div class="clear"></div> </div> </div> <div class="stuffbox"> <h3> <label style="font-size:16px;"> AddOn Details </label> </h3> <div class="inside"> <div class="ism_not_item"> <?php if($_GET['tab'] == 'isb'){ $url = 'http://codecanyon.net/item/social-share-on-images-addon-wordpress/9719076'; $html = file_get_contents($url); $get1 = explode( '<div class="item-preview">' , $html ); $get2 = explode( '</div>' , $get1[1] ); preg_match_all('/<img.*?>/', $get2[0], $out); if(isset($out) && count($out) > 0){ foreach($out as $value){ echo '<div class="top-preview">'.$value[0].'</div>'; } } $get3 = explode( '<div class="user-html">' , $html ); $get4 = explode( '</div>' , $get3[1] ); preg_match_all('/<img.*?>/', $get4[0], $images); if(isset($images) && count($images) > 0){ foreach($images as $img){ foreach($img as $value){ if (strpos($value,'preview') === false && strpos($value,'button') === false) echo $value; } } } } ?> </div> <div class="clear"></div> </div> </div> </div> </div>
srwiser/ssctube
wp-content/plugins/indeed-social-media_v5.1/admin/tabs/isb.php
PHP
gpl-2.0
1,740
<?php function getSentNotificationNum() { return intval(file_get_contents('http://localhost:55555/')); } ?>
marco-c/wp-web-push
tests/test-utils.php
PHP
gpl-2.0
112
/** * @fileoverview * Tool '서식' Source, * */ TrexConfig.addTool( "tabletemplate", { sync: _FALSE, status: _TRUE, rows: 5, cols: 9, options: [ { label: 'image', data: 1 , klass: 'tx-tabletemplate-1' }, { label: 'image', data: 2 , klass: 'tx-tabletemplate-2' }, { label: 'image', data: 3 , klass: 'tx-tabletemplate-3' }, { label: 'image', data: 4 , klass: 'tx-tabletemplate-4' }, { label: 'image', data: 5 , klass: 'tx-tabletemplate-5' }, { label: 'image', data: 6 , klass: 'tx-tabletemplate-6' }, { label: 'image', data: 7 , klass: 'tx-tabletemplate-7' }, { label: 'image', data: 8 , klass: 'tx-tabletemplate-8' }, { label: 'image', data: 9 , klass: 'tx-tabletemplate-9' }, { label: 'image', data: 10 , klass: 'tx-tabletemplate-10' }, { label: 'image', data: 11 , klass: 'tx-tabletemplate-11' }, { label: 'image', data: 12 , klass: 'tx-tabletemplate-12' }, { label: 'image', data: 13 , klass: 'tx-tabletemplate-13' }, { label: 'image', data: 14 , klass: 'tx-tabletemplate-14' }, { label: 'image', data: 15 , klass: 'tx-tabletemplate-15' }, { label: 'image', data: 16 , klass: 'tx-tabletemplate-16' }, { label: 'image', data: 17 , klass: 'tx-tabletemplate-17' }, { label: 'image', data: 18 , klass: 'tx-tabletemplate-18' }, { label: 'image', data: 19 , klass: 'tx-tabletemplate-19' }, { label: 'image', data: 20 , klass: 'tx-tabletemplate-20' }, { label: 'image', data: 21 , klass: 'tx-tabletemplate-21' }, { label: 'image', data: 22 , klass: 'tx-tabletemplate-22' }, { label: 'image', data: 23 , klass: 'tx-tabletemplate-23' }, { label: 'image', data: 24 , klass: 'tx-tabletemplate-24' }, { label: 'image', data: 25 , klass: 'tx-tabletemplate-25' }, { label: 'image', data: 26 , klass: 'tx-tabletemplate-26' }, { label: 'image', data: 27 , klass: 'tx-tabletemplate-27' }, { label: 'image', data: 28 , klass: 'tx-tabletemplate-28' }, { label: 'image', data: 29 , klass: 'tx-tabletemplate-29' }, { label: 'image', data: 30 , klass: 'tx-tabletemplate-30' }, { label: 'image', data: 31 , klass: 'tx-tabletemplate-31' }, { label: 'image', data: 32 , klass: 'tx-tabletemplate-32' }, { label: 'image', data: 33 , klass: 'tx-tabletemplate-33' }, { label: 'image', data: 34 , klass: 'tx-tabletemplate-34' }, { label: 'image', data: 35 , klass: 'tx-tabletemplate-35' }, { label: 'image', data: 36 , klass: 'tx-tabletemplate-36' }, { label: 'image', data: 37 , klass: 'tx-tabletemplate-37' }, { label: 'image', data: 38 , klass: 'tx-tabletemplate-38' }, { label: 'image', data: 39 , klass: 'tx-tabletemplate-39' }, { label: 'image', data: 40 , klass: 'tx-tabletemplate-40' }, { label: 'image', data: 41 , klass: 'tx-tabletemplate-41' }, { label: 'image', data: 42 , klass: 'tx-tabletemplate-42' }, { label: 'image', data: 43 , klass: 'tx-tabletemplate-43' }, { label: 'image', data: 44 , klass: 'tx-tabletemplate-44' }, { label: 'image', data: 45 , klass: 'tx-tabletemplate-45' } ] } ); Trex.Tool.Tabletemplate = Trex.Class.create({ $const: { __Identity: 'tabletemplate' }, $extend: Trex.Tool, oninitialized: function(config) { var _tool = this; var _canvas = this.canvas; var _map = {}; config.options.each(function(option) { _map[option.data] = { type: option.type }; }); var _toolHandler = function(data) { if(!_map[data]) { return; } var _table = _NULL; _canvas.execute(function(processor) { if (processor.table) { _table = processor.findNode('table'); processor.table.setTemplateStyle(_table, data); } }); }; /* button & menu weave */ this.weave.bind(this)( /* button */ new Trex.Button(this.buttonCfg), /* menu */ new Trex.Menu.List(this.menuCfg), /* handler */ _toolHandler ); } });
zaljayo/TestProject
lib_editor/js/trex/tool/tabletemplate.js
JavaScript
gpl-2.0
3,877
#include "GitRevision.h" #include "CompilerDefs.h" #include "revision_data.h" char const* GitRevision::GetHash() { return _HASH; } char const* GitRevision::GetDate() { return _DATE; } char const* GitRevision::GetBranch() { return _BRANCH; } char const* GitRevision::GetSourceDirectory() { return _SOURCE_DIRECTORY; } char const* GitRevision::GetMySQLExecutable() { return _MYSQL_EXECUTABLE; } char const* GitRevision::GetFullDatabase() { return _FULL_DATABASE; } char const* GitRevision::GetHotfixesDatabase() { return _HOTFIXES_DATABASE; } #define _PACKAGENAME "TrinityCore" char const* GitRevision::GetFullVersion() { #if PLATFORM == PLATFORM_WINDOWS # ifdef _WIN64 return _PACKAGENAME " rev. " VER_PRODUCTVERSION_STR " (Win64, " _BUILD_DIRECTIVE ")"; # else return _PACKAGENAME " rev. " VER_PRODUCTVERSION_STR " (Win32, " _BUILD_DIRECTIVE ")"; # endif #else return _PACKAGENAME " rev. " VER_PRODUCTVERSION_STR " (Unix, " _BUILD_DIRECTIVE ")"; #endif } char const* GitRevision::GetCompanyNameStr() { return VER_COMPANYNAME_STR; } char const* GitRevision::GetLegalCopyrightStr() { return VER_LEGALCOPYRIGHT_STR; } char const* GitRevision::GetFileVersionStr() { return VER_FILEVERSION_STR; } char const* GitRevision::GetProductVersionStr() { return VER_PRODUCTVERSION_STR; }
pizcogirl/TrinityCore
src/server/shared/GitRevision.cpp
C++
gpl-2.0
1,344
<?php namespace TYPO3\CMS\Core\Resource\Driver; /** * This file is part of the TYPO3 CMS project. * * It is free software; you can redistribute it and/or modify it under * the terms of the GNU General Public License, either version 2 * of the License, or any later version. * * For the full copyright and license information, please read the * LICENSE.txt file that was distributed with this source code. * * The TYPO3 project - inspiring people to share! */ /** * Class AbstractHierarchicalFilesystemDriver */ abstract class AbstractHierarchicalFilesystemDriver extends AbstractDriver { /** * Wrapper for \TYPO3\CMS\Core\Utility\GeneralUtility::validPathStr() * * @param string $theFile Filepath to evaluate * @return boolean TRUE if no '/', '..' or '\' is in the $theFile * @see \TYPO3\CMS\Core\Utility\GeneralUtility::validPathStr() */ protected function isPathValid($theFile) { return \TYPO3\CMS\Core\Utility\GeneralUtility::validPathStr($theFile); } /** * Makes sure the Path given as parameter is valid * * @param string $filePath The file path (including the file name!) * @return string * @throws \TYPO3\CMS\Core\Resource\Exception\InvalidPathException */ protected function canonicalizeAndCheckFilePath($filePath) { $filePath = \TYPO3\CMS\Core\Utility\PathUtility::getCanonicalPath($filePath); // filePath must be valid // Special case is required by vfsStream in Unit Test context if (!$this->isPathValid($filePath) && substr($filePath, 0, 6) !== 'vfs://') { throw new \TYPO3\CMS\Core\Resource\Exception\InvalidPathException('File ' . $filePath . ' is not valid (".." and "//" is not allowed in path).', 1320286857); } return $filePath; } /** * Makes sure the Path given as parameter is valid * * @param string $fileIdentifier The file path (including the file name!) * @return string * @throws \TYPO3\CMS\Core\Resource\Exception\InvalidPathException */ protected function canonicalizeAndCheckFileIdentifier($fileIdentifier) { if ($fileIdentifier !== '') { $fileIdentifier = $this->canonicalizeAndCheckFilePath($fileIdentifier); $fileIdentifier = '/' . ltrim($fileIdentifier, '/'); if (!$this->isCaseSensitiveFileSystem()) { $fileIdentifier = strtolower($fileIdentifier); } } return $fileIdentifier; } /** * Makes sure the Path given as parameter is valid * * @param string $folderPath The file path (including the file name!) * @return string */ protected function canonicalizeAndCheckFolderIdentifier($folderPath) { if ($folderPath === '/') { $canonicalizedIdentifier = $folderPath; } else { $canonicalizedIdentifier = rtrim($this->canonicalizeAndCheckFileIdentifier($folderPath), '/') . '/'; } return $canonicalizedIdentifier; } /** * Returns the identifier of the folder the file resides in * * @param string $fileIdentifier * @return mixed */ public function getParentFolderIdentifierOfIdentifier($fileIdentifier) { $fileIdentifier = $this->canonicalizeAndCheckFileIdentifier($fileIdentifier); return \TYPO3\CMS\Core\Utility\PathUtility::dirname($fileIdentifier) . '/'; } }
demonege/sutogo
typo3/sysext/core/Classes/Resource/Driver/AbstractHierarchicalFilesystemDriver.php
PHP
gpl-2.0
3,140
/** -*- c++ -*- * Copyright (C) 2008 Doug Judd (Zvents, Inc.) * * This file is part of Hypertable. * * Hypertable is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * as published by the Free Software Foundation; version 2 of the * License, or any later version. * * Hypertable 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 "Common/Compat.h" #include <cassert> #include <cstdio> #include <cstring> #include <boost/progress.hpp> #include <boost/timer.hpp> #include <boost/thread/xtime.hpp> extern "C" { #include <time.h> } #include "AsyncComm/DispatchHandlerSynchronizer.h" #include "Common/Error.h" #include "Common/FileUtils.h" #include "Hypertable/Lib/HqlHelpText.h" #include "Hypertable/Lib/HqlParser.h" #include "Hypertable/Lib/Key.h" #include "Hypertable/Lib/LoadDataSource.h" #include "Hypertable/Lib/RangeState.h" #include "Hypertable/Lib/ScanBlock.h" #include "Hypertable/Lib/ScanSpec.h" #include "Hypertable/Lib/TestSource.h" #include "RangeServerCommandInterpreter.h" #define BUFFER_SIZE 65536 using namespace std; using namespace Hypertable; using namespace Hql; using namespace Serialization; namespace { void process_event(EventPtr &event_ptr) { int32_t error; const uint8_t *decode_ptr = event_ptr->payload + 4; size_t decode_remain = event_ptr->payload_len - 4; uint32_t offset, len; if (decode_remain == 0) cout << "success" << endl; else { while (decode_remain) { try { error = decode_i32(&decode_ptr, &decode_remain); offset = decode_i32(&decode_ptr, &decode_remain); len = decode_i32(&decode_ptr, &decode_remain); } catch (Exception &e) { HT_ERROR_OUT << e << HT_END; break; } cout << "rejected: offset=" << offset << " span=" << len << " " << Error::get_text(error) << endl; } } } } RangeServerCommandInterpreter::RangeServerCommandInterpreter(Comm *comm, Hyperspace::SessionPtr &hyperspace_ptr, const sockaddr_in addr, RangeServerClientPtr &range_server_ptr) : m_comm(comm), m_hyperspace_ptr(hyperspace_ptr), m_addr(addr), m_range_server_ptr(range_server_ptr), m_cur_scanner_id(-1) { HqlHelpText::install_range_server_client_text(); return; } void RangeServerCommandInterpreter::execute_line(const String &line) { TableIdentifier *table = 0; RangeSpec range; TableInfo *table_info; String schema_str; String out_str; SchemaPtr schema_ptr; Hql::ParserState state; Hql::Parser parser(state); parse_info<> info; DispatchHandlerSynchronizer sync_handler; ScanBlock scanblock; int32_t scanner_id; EventPtr event_ptr; info = parse(line.c_str(), parser, space_p); if (info.full) { // if table name specified, get associated objects if (state.table_name != "") { table_info = m_table_map[state.table_name]; if (table_info == 0) { table_info = new TableInfo(state.table_name); table_info->load(m_hyperspace_ptr); m_table_map[state.table_name] = table_info; } table = table_info->get_table_identifier(); table_info->get_schema_ptr(schema_ptr); } // if end row is "??", transform it to 0xff 0xff if (state.range_end_row == "??") state.range_end_row = Key::END_ROW_MARKER; if (state.command == COMMAND_LOAD_RANGE) { RangeState range_state; cout << "TableName = " << state.table_name << endl; cout << "StartRow = " << state.range_start_row << endl; cout << "EndRow = " << state.range_end_row << endl; range.start_row = state.range_start_row.c_str(); range.end_row = state.range_end_row.c_str(); range_state.soft_limit = 200000000LL; m_range_server_ptr->load_range(m_addr, *table, range, 0, range_state, 0); } else if (state.command == COMMAND_UPDATE) { TestSource *tsource = 0; if (!FileUtils::exists(state.input_file.c_str())) HT_THROW(Error::FILE_NOT_FOUND, String("Input file '") + state.input_file + "' does not exist"); tsource = new TestSource(state.input_file, schema_ptr.get()); uint8_t *send_buf = 0; size_t send_buf_len = 0; DynamicBuffer buf(BUFFER_SIZE); SerializedKey key; ByteString value; size_t key_len, value_len; uint32_t send_count = 0; bool outstanding = false; while (true) { while (tsource->next(key, value)) { key_len = key.length(); value_len = value.length(); buf.ensure(key_len + value_len); buf.add_unchecked(key.ptr, key_len); buf.add_unchecked(value.ptr, value_len); if (buf.fill() > BUFFER_SIZE) break; } /** * Sort the keys */ if (buf.fill()) { std::vector<SerializedKey> keys; const uint8_t *ptr; size_t len; key.ptr = ptr = buf.base; while (ptr < buf.ptr) { keys.push_back(key); key.next(); key.next(); ptr = key.ptr; } std::sort(keys.begin(), keys.end()); send_buf = new uint8_t [buf.fill()]; uint8_t *sendp = send_buf; for (size_t i=0; i<keys.size(); i++) { key = keys[i]; key.next(); key.next(); len = key.ptr - keys[i].ptr; memcpy(sendp, keys[i].ptr, len); sendp += len; } send_buf_len = sendp - send_buf; buf.clear(); send_count = keys.size(); } else { send_buf_len = 0; send_count = 0; } if (outstanding) { if (!sync_handler.wait_for_reply(event_ptr)) HT_THROW(Protocol::response_code(event_ptr), (Protocol::string_format_message(event_ptr))); process_event(event_ptr); } outstanding = false; if (send_buf_len > 0) { StaticBuffer mybuf(send_buf, send_buf_len); m_range_server_ptr->update(m_addr, *table, send_count, mybuf, 0, &sync_handler); outstanding = true; } else break; } if (outstanding) { if (!sync_handler.wait_for_reply(event_ptr)) HT_THROW(Protocol::response_code(event_ptr), (Protocol::string_format_message(event_ptr))); process_event(event_ptr); } } else if (state.command == COMMAND_CREATE_SCANNER) { range.start_row = state.range_start_row.c_str(); range.end_row = state.range_end_row.c_str(); m_range_server_ptr->create_scanner(m_addr, *table, range, state.scan.builder.get(), scanblock); m_cur_scanner_id = scanblock.get_scanner_id(); SerializedKey key; ByteString value; while (scanblock.next(key, value)) display_scan_data(key, value, schema_ptr); if (scanblock.eos()) m_cur_scanner_id = -1; } else if (state.command == COMMAND_FETCH_SCANBLOCK) { if (state.scanner_id == -1) { if (m_cur_scanner_id == -1) HT_THROW(Error::RANGESERVER_INVALID_SCANNER_ID, "No currently open scanner"); scanner_id = m_cur_scanner_id; m_cur_scanner_id = -1; } else scanner_id = state.scanner_id; /** */ m_range_server_ptr->fetch_scanblock(m_addr, scanner_id, scanblock); SerializedKey key; ByteString value; while (scanblock.next(key, value)) display_scan_data(key, value, schema_ptr); if (scanblock.eos()) m_cur_scanner_id = -1; } else if (state.command == COMMAND_DESTROY_SCANNER) { if (state.scanner_id == -1) { if (m_cur_scanner_id == -1) return; scanner_id = m_cur_scanner_id; m_cur_scanner_id = -1; } else scanner_id = state.scanner_id; m_range_server_ptr->destroy_scanner(m_addr, scanner_id); } else if (state.command == COMMAND_DROP_RANGE) { range.start_row = state.range_start_row.c_str(); range.end_row = state.range_end_row.c_str(); m_range_server_ptr->drop_range(m_addr, *table, range, &sync_handler); if (!sync_handler.wait_for_reply(event_ptr)) HT_THROW(Protocol::response_code(event_ptr), (Protocol::string_format_message(event_ptr))); } else if (state.command == COMMAND_REPLAY_BEGIN) { // fix me!! added metadata boolean m_range_server_ptr->replay_begin(m_addr, false, &sync_handler); if (!sync_handler.wait_for_reply(event_ptr)) HT_THROW(Protocol::response_code(event_ptr), (Protocol::string_format_message(event_ptr))); } else if (state.command == COMMAND_REPLAY_LOG) { cout << "Not implemented." << endl; } else if (state.command == COMMAND_DUMP) { m_range_server_ptr->dump(m_addr, state.output_file, state.nokeys); cout << "success" << endl; } else if (state.command == COMMAND_REPLAY_COMMIT) { m_range_server_ptr->replay_commit(m_addr, &sync_handler); if (!sync_handler.wait_for_reply(event_ptr)) HT_THROW(Protocol::response_code(event_ptr), (Protocol::string_format_message(event_ptr))); } else if (state.command == COMMAND_HELP) { const char **text = HqlHelpText::get(state.str); if (text) { for (size_t i=0; text[i]; i++) cout << text[i] << endl; } else cout << endl << "no help for '" << state.str << "'" << endl << endl; } else if (state.command == COMMAND_CLOSE) { m_range_server_ptr->close(m_addr); } else if (state.command == COMMAND_SHUTDOWN) { m_range_server_ptr->close(m_addr); m_range_server_ptr->shutdown(m_addr); } else HT_THROW(Error::HQL_PARSE_ERROR, "unsupported command"); } else HT_THROW(Error::HQL_PARSE_ERROR, String("parse error at: ") + info.stop); } /** * */ void RangeServerCommandInterpreter::display_scan_data(const SerializedKey &serkey, const ByteString &value, SchemaPtr &schema_ptr) { Key key(serkey); Schema::ColumnFamily *cf; if (key.flag == FLAG_DELETE_ROW) { cout << key.timestamp << " " << key.row << " DELETE" << endl; } else if (key.flag == FLAG_DELETE_COLUMN_FAMILY) { cf = schema_ptr->get_column_family(key.column_family_code); cout << key.timestamp << " " << key.row << " " << cf->name << " DELETE" << endl; } else { if (key.column_family_code > 0) { cf = schema_ptr->get_column_family(key.column_family_code); if (key.flag == FLAG_DELETE_CELL) cout << key.timestamp << " " << key.row << " " << cf->name << ":" << key.column_qualifier << " DELETE" << endl; else { cout << key.timestamp << " " << key.row << " " << cf->name << ":" << key.column_qualifier; cout << endl; } } else { cerr << "Bad column family (" << (int)key.column_family_code << ") for row key " << key.row; cerr << endl; } } }
tempbottle/hypertable
src/cc/Tools/rsclient/RangeServerCommandInterpreter.cc
C++
gpl-2.0
11,721
/* $Id$ */ /*************************************************************************** * (C) Copyright 2003-2010 - Stendhal * *************************************************************************** *************************************************************************** * * * 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. * * * ***************************************************************************/ package games.stendhal.client.gui.j2d.entity; // // import games.stendhal.client.entity.IEntity; import games.stendhal.client.sprite.Sprite; import games.stendhal.client.sprite.SpriteStore; import java.util.HashMap; import java.util.Map; import org.apache.log4j.Logger; /** * The 2D view of an animated entity. * * @param <T> entity type */ abstract class StateEntity2DView<T extends IEntity> extends Entity2DView<T> { /** * Log4J. */ private static final Logger logger = Logger .getLogger(StateEntity2DView.class); /** * Map of named sprites. */ protected Map<Object, Sprite> sprites = new HashMap<Object, Sprite>(); // // StateEntity2DView // /** * Build animations. * * @param entity the entity to build animations for */ private void buildAnimations(T entity) { buildSprites(entity, sprites); } /** * Populate named state sprites. * * @param entity The entity to build sprites for * @param map * The map to populate. */ protected abstract void buildSprites(T entity, final Map<Object, Sprite> map); /** * Get a keyed state sprite. * * @param state * The state. * * @return The appropriate sprite for the given state. */ protected Sprite getSprite(final Object state) { return sprites.get(state); } /** * Get the current model state. * * @param entity * @return The model state. */ protected abstract Object getState(T entity); /** * Get the current animated sprite. * * @param entity * @return The appropriate sprite for the current state. */ private Sprite getStateSprite(T entity) { final Object state = getState(entity); final Sprite sprite = getSprite(state); if (sprite == null) { logger.debug("No sprite found for: " + state); return SpriteStore.get().getFailsafe(); } return sprite; } // // Entity2DView // /** * Build the visual representation of this entity. This builds all the * animation sprites and sets the default frame. */ @Override protected void buildRepresentation(T entity) { buildAnimations(entity); setSprite(getStateSprite(entity)); } /** * Update sprite state of the entity. * * @param entity */ protected void proceedChangedState(T entity) { setSprite(getStateSprite(entity)); } }
acsid/stendhal
src/games/stendhal/client/gui/j2d/entity/StateEntity2DView.java
Java
gpl-2.0
3,163
/*---------------------------------------------------------------------------*\ ========= | \\ / F ield | OpenFOAM: The Open Source CFD Toolbox \\ / O peration | \\ / A nd | Copyright held by original author \\/ M anipulation | ------------------------------------------------------------------------------- License This file is part of OpenFOAM. OpenFOAM 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. OpenFOAM 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 OpenFOAM; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA \*---------------------------------------------------------------------------*/ #include "meshTriangulation.H" #include "polyMesh.H" #include "faceTriangulation.H" // * * * * * * * * * * * * * Private Member Functions * * * * * * * * * * * // bool Foam::meshTriangulation::isInternalFace ( const primitiveMesh& mesh, const boolList& includedCell, const label faceI ) { if (mesh.isInternalFace(faceI)) { label own = mesh.faceOwner()[faceI]; label nei = mesh.faceNeighbour()[faceI]; if (includedCell[own] && includedCell[nei]) { // Neighbouring cell will get included in subset // as well so face is internal. return true; } else { return false; } } else { return false; } } void Foam::meshTriangulation::getFaces ( const primitiveMesh& mesh, const boolList& includedCell, boolList& faceIsCut, label& nFaces, label& nInternalFaces ) { // All faces to be triangulated. faceIsCut.setSize(mesh.nFaces()); faceIsCut = false; nFaces = 0; nInternalFaces = 0; forAll(includedCell, cellI) { // Include faces of cut cells only. if (includedCell[cellI]) { const labelList& cFaces = mesh.cells()[cellI]; forAll(cFaces, i) { label faceI = cFaces[i]; if (!faceIsCut[faceI]) { // First visit of face. nFaces++; faceIsCut[faceI] = true; // See if would become internal or external face if (isInternalFace(mesh, includedCell, faceI)) { nInternalFaces++; } } } } } Pout<< "Subset consists of " << nFaces << " faces out of " << mesh.nFaces() << " of which " << nInternalFaces << " are internal" << endl; } void Foam::meshTriangulation::insertTriangles ( const triFaceList& faceTris, const label faceI, const label regionI, const bool reverse, List<labelledTri>& triangles, label& triI ) { // Copy triangles. Optionally reverse them forAll(faceTris, i) { const triFace& f = faceTris[i]; labelledTri& tri = triangles[triI]; if (reverse) { tri[0] = f[0]; tri[2] = f[1]; tri[1] = f[2]; } else { tri[0] = f[0]; tri[1] = f[1]; tri[2] = f[2]; } tri.region() = regionI; faceMap_[triI] = faceI; triI++; } } // * * * * * * * * * * * * * * * * Constructors * * * * * * * * * * * * * * // // Null constructor Foam::meshTriangulation::meshTriangulation() : triSurface(), nInternalFaces_(0), faceMap_() {} // Construct from faces of cells Foam::meshTriangulation::meshTriangulation ( const polyMesh& mesh, const label internalFacesPatch, const boolList& includedCell, const bool faceCentreDecomposition ) : triSurface(), nInternalFaces_(0), faceMap_() { const faceList& faces = mesh.faces(); const pointField& points = mesh.points(); const polyBoundaryMesh& patches = mesh.boundaryMesh(); // All faces to be triangulated. boolList faceIsCut; label nFaces, nInternalFaces; getFaces ( mesh, includedCell, faceIsCut, nFaces, nInternalFaces ); // Find upper limit for number of triangles // (can be less if triangulation fails) label nTotTri = 0; if (faceCentreDecomposition) { forAll(faceIsCut, faceI) { if (faceIsCut[faceI]) { nTotTri += faces[faceI].size(); } } } else { forAll(faceIsCut, faceI) { if (faceIsCut[faceI]) { nTotTri += faces[faceI].nTriangles(points); } } } Pout<< "nTotTri : " << nTotTri << endl; // Storage for new and old points (only for faceCentre decomposition; // for triangulation uses only existing points) pointField newPoints; if (faceCentreDecomposition) { newPoints.setSize(mesh.nPoints() + faces.size()); forAll(mesh.points(), pointI) { newPoints[pointI] = mesh.points()[pointI]; } // Face centres forAll(faces, faceI) { newPoints[mesh.nPoints() + faceI] = mesh.faceCentres()[faceI]; } } // Storage for all triangles List<labelledTri> triangles(nTotTri); faceMap_.setSize(nTotTri); label triI = 0; if (faceCentreDecomposition) { // Decomposition around face centre // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Triangulate internal faces forAll(faceIsCut, faceI) { if (faceIsCut[faceI] && isInternalFace(mesh, includedCell, faceI)) { // Face was internal to the mesh and will be 'internal' to // the surface. // Triangulate face const face& f = faces[faceI]; forAll(f, fp) { faceMap_[triI] = faceI; triangles[triI++] = labelledTri ( f[fp], f.nextLabel(fp), mesh.nPoints() + faceI, // face centre internalFacesPatch ); } } } nInternalFaces_ = triI; // Triangulate external faces forAll(faceIsCut, faceI) { if (faceIsCut[faceI] && !isInternalFace(mesh, includedCell, faceI)) { // Face will become outside of the surface. label patchI = -1; bool reverse = false; if (mesh.isInternalFace(faceI)) { patchI = internalFacesPatch; // Check orientation. Check which side of the face gets // included (note: only one side is). if (includedCell[mesh.faceOwner()[faceI]]) { reverse = false; } else { reverse = true; } } else { // Face was already outside so orientation ok. patchI = patches.whichPatch(faceI); reverse = false; } // Triangulate face const face& f = faces[faceI]; if (reverse) { forAll(f, fp) { faceMap_[triI] = faceI; triangles[triI++] = labelledTri ( f.nextLabel(fp), f[fp], mesh.nPoints() + faceI, // face centre patchI ); } } else { forAll(f, fp) { faceMap_[triI] = faceI; triangles[triI++] = labelledTri ( f[fp], f.nextLabel(fp), mesh.nPoints() + faceI, // face centre patchI ); } } } } } else { // Triangulation using existing vertices // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ // Triangulate internal faces forAll(faceIsCut, faceI) { if (faceIsCut[faceI] && isInternalFace(mesh, includedCell, faceI)) { // Face was internal to the mesh and will be 'internal' to // the surface. // Triangulate face. Fall back to naive triangulation if failed. faceTriangulation faceTris(points, faces[faceI], true); if (faceTris.empty()) { WarningIn("meshTriangulation::meshTriangulation") << "Could not find triangulation for face " << faceI << " vertices " << faces[faceI] << " coords " << IndirectList<point>(points, faces[faceI])() << endl; } else { // Copy triangles. Make them internalFacesPatch insertTriangles ( faceTris, faceI, internalFacesPatch, false, // no reverse triangles, triI ); } } } nInternalFaces_ = triI; // Triangulate external faces forAll(faceIsCut, faceI) { if (faceIsCut[faceI] && !isInternalFace(mesh, includedCell, faceI)) { // Face will become outside of the surface. label patchI = -1; bool reverse = false; if (mesh.isInternalFace(faceI)) { patchI = internalFacesPatch; // Check orientation. Check which side of the face gets // included (note: only one side is). if (includedCell[mesh.faceOwner()[faceI]]) { reverse = false; } else { reverse = true; } } else { // Face was already outside so orientation ok. patchI = patches.whichPatch(faceI); reverse = false; } // Triangulate face faceTriangulation faceTris(points, faces[faceI], true); if (faceTris.empty()) { WarningIn("meshTriangulation::meshTriangulation") << "Could not find triangulation for face " << faceI << " vertices " << faces[faceI] << " coords " << IndirectList<point>(points, faces[faceI])() << endl; } else { // Copy triangles. Optionally reverse them insertTriangles ( faceTris, faceI, patchI, reverse, // whether to reverse triangles, triI ); } } } } // Shrink if nessecary (because of invalid triangulations) triangles.setSize(triI); faceMap_.setSize(triI); Pout<< "nInternalFaces_:" << nInternalFaces_ << endl; Pout<< "triangles:" << triangles.size() << endl; geometricSurfacePatchList surfPatches(patches.size()); forAll(patches, patchI) { surfPatches[patchI] = geometricSurfacePatch ( patches[patchI].physicalType(), patches[patchI].name(), patchI ); } // Create globally numbered tri surface if (faceCentreDecomposition) { // Use newPoints (mesh points + face centres) triSurface globalSurf(triangles, surfPatches, newPoints); // Create locally numbered tri surface triSurface::operator= ( triSurface ( globalSurf.localFaces(), surfPatches, globalSurf.localPoints() ) ); } else { // Use mesh points triSurface globalSurf(triangles, surfPatches, mesh.points()); // Create locally numbered tri surface triSurface::operator= ( triSurface ( globalSurf.localFaces(), surfPatches, globalSurf.localPoints() ) ); } } // ************************************************************************* //
CFDEMproject/OpenFOAM-1.6-ext
src/triSurface/meshTriangulation/meshTriangulation.C
C++
gpl-2.0
14,053
/* * Copyright (c) 2008, Oracle and/or its affiliates. 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. Oracle designates this * particular file as subject to the "Classpath" exception as provided * by Oracle 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.sun.beans.decoder; /** * This class is intended to handle &lt;int&gt; element. * This element specifies {@code int} values. * The class {@link Integer} is used as wrapper for these values. * The result value is created from text of the body of this element. * The body parsing is described in the class {@link StringElementHandler}. * For example:<pre> * &lt;int&gt;-1&lt;/int&gt;</pre> * is shortcut to<pre> * &lt;method name="decode" class="java.lang.Integer"&gt; * &lt;string&gt;-1&lt;/string&gt; * &lt;/method&gt;</pre> * which is equivalent to {@code Integer.decode("-1")} in Java code. * <p>The following attribute is supported: * <dl> * <dt>id * <dd>the identifier of the variable that is intended to store the result * </dl> * * @since 1.7 * * @author Sergey A. Malenkov */ final class IntElementHandler extends StringElementHandler { /** * Creates {@code int} value from * the text of the body of this element. * * @param argument the text of the body * @return evaluated {@code int} value */ @Override public Object getValue(String argument) { return Integer.decode(argument); } }
openjdk/jdk7u
jdk/src/share/classes/com/sun/beans/decoder/IntElementHandler.java
Java
gpl-2.0
2,393
/* * Copyright (c) 2014, Oracle and/or its affiliates. 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. * * 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 Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA * or visit www.oracle.com if you need additional information or have any * questions. */ package com.oracle.graal.phases.util; import jdk.internal.jvmci.meta.*; import com.oracle.graal.phases.*; /** * Lazily computed debug value name composed of a prefix and a {@linkplain JavaMethod#getName() * method name}. */ public class MethodDebugValueName extends LazyName { final String prefix; final JavaMethod method; public MethodDebugValueName(String prefix, JavaMethod method) { this.prefix = prefix; this.method = method; } @Override public String createString() { return prefix + "[" + method.getName() + "]"; } }
mur47x111/GraalVM
graal/com.oracle.graal.phases/src/com/oracle/graal/phases/util/MethodDebugValueName.java
Java
gpl-2.0
1,635
<?php include 'common.php'; include 'header.php'; include 'menu.php'; Typecho_Widget::widget('Widget_Contents_Page_Edit')->to($page); ?> <div class="main"> <div class="body container"> <?php include 'page-title.php'; ?> <div class="row typecho-page-main typecho-post-area" role="form"> <form action="<?php $security->index('/action/contents-page-edit'); ?>" method="post" name="write_page"> <div class="col-mb-12 col-tb-9" role="main"> <?php if ($page->draft): ?> <?php if ($page->draft['cid'] != $page->cid): ?> <?php $pageModifyDate = new Typecho_Date($page->draft['modified']); ?> <cite class="edit-draft-notice"><?php _e('当前正在编辑的是保存于%s的草稿, 你可以<a href="%s">删除它</a>', $pageModifyDate->word(), $security->getIndex('/action/contents-page-edit?do=deleteDraft&cid=' . $page->cid)); ?></cite> <?php else: ?> <cite class="edit-draft-notice"><?php _e('当前正在编辑的是未发布的草稿'); ?></cite> <?php endif; ?> <input name="draft" type="hidden" value="<?php echo $page->draft['cid'] ?>" /> <?php endif; ?> <p class="title"> <label for="title" class="sr-only"><?php _e('标题'); ?></label> <input type="text" id="title" name="title" autocomplete="off" value="<?php $page->title(); ?>" placeholder="<?php _e('标题'); ?>" class="w-100 text title" /> </p> <?php $permalink = Typecho_Common::url($options->routingTable['page']['url'], $options->index); list ($scheme, $permalink) = explode(':', $permalink, 2); $permalink = ltrim($permalink, '/'); $permalink = preg_replace("/\[([_a-z0-9-]+)[^\]]*\]/i", "{\\1}", $permalink); if ($page->have()) { $permalink = str_replace('{cid}', $page->cid, $permalink); } $input = '<input type="text" id="slug" name="slug" autocomplete="off" value="' . htmlspecialchars($page->slug) . '" class="mono" />'; ?> <p class="mono url-slug"> <label for="slug" class="sr-only"><?php _e('网址缩略名'); ?></label> <?php echo preg_replace("/\{slug\}/i", $input, $permalink); ?> </p> <p> <label for="text" class="sr-only"><?php _e('页面内容'); ?></label> <textarea style="height: <?php $options->editorSize(); ?>px" autocomplete="off" id="text" name="text" class="w-100 mono"><?php echo htmlspecialchars($page->text); ?></textarea> </p> <?php include 'custom-fields.php'; ?> <p class="submit clearfix"> <span class="left"> <button type="button" id="btn-cancel-preview" class="btn"><i class="i-caret-left"></i> <?php _e('取消预览'); ?></button> </span> <span class="right"> <input type="hidden" name="cid" value="<?php $page->cid(); ?>" /> <button type="button" id="btn-preview" class="btn"><i class="i-exlink"></i> <?php _e('预览页面'); ?></button> <button type="submit" name="do" value="save" id="btn-save" class="btn"><?php _e('保存草稿'); ?></button> <button type="submit" name="do" value="publish" class="btn primary" id="btn-submit"><?php _e('发布页面'); ?></button> <?php if ($options->markdown && (!$page->have() || $page->isMarkdown)): ?> <input type="hidden" name="markdown" value="1" /> <?php endif; ?> </span> </p> <?php Typecho_Plugin::factory('admin/write-page.php')->content($page); ?> </div> <div id="edit-secondary" class="col-mb-12 col-tb-3" role="complementary"> <ul class="typecho-option-tabs clearfix"> <li class="active w-50"><a href="#tab-advance"><?php _e('选项'); ?></a></li> <li class="w-50"><a href="#tab-files" id="tab-files-btn"><?php _e('附件'); ?></a></li> </ul> <div id="tab-advance" class="tab-content"> <section class="typecho-post-option" role="application"> <label for="date" class="typecho-label"><?php _e('发布日期'); ?></label> <p><input class="typecho-date w-100" type="text" name="date" id="date" value="<?php $page->have() ? $page->date('Y-m-d H:i') : ''; ?>" /></p> </section> <section class="typecho-post-option"> <label for="order" class="typecho-label"><?php _e('页面顺序'); ?></label> <p><input type="text" id="order" name="order" value="<?php $page->order(); ?>" class="w-100" /></p> <p class="description"><?php _e('为你的自定义页面设定一个序列值以后, 能够使得它们按此值从小到大排列'); ?></p> </section> <section class="typecho-post-option"> <label for="template" class="typecho-label"><?php _e('自定义模板'); ?></label> <p> <select name="template" id="template"> <option value=""><?php _e('不选择'); ?></option> <?php $templates = $page->getTemplates(); foreach ($templates as $template => $name): ?> <option value="<?php echo $template; ?>"<?php if($template == $page->template): ?> selected="true"<?php endif; ?>><?php echo $name; ?></option> <?php endforeach; ?> </select> </p> <p class="description"><?php _e('如果你为此页面选择了一个自定义模板, 系统将按照你选择的模板文件展现它'); ?></p> </section> <?php Typecho_Plugin::factory('admin/write-page.php')->option($page); ?> <button type="button" id="advance-panel-btn" class="btn btn-xs"><?php _e('高级选项'); ?> <i class="i-caret-down"></i></button> <div id="advance-panel"> <section class="typecho-post-option visibility-option"> <label for="visibility" class="typecho-label"><?php _e('公开度'); ?></label> <p> <select id="visibility" name="visibility"> <option value="publish"<?php if ($page->status == 'publish' || !$page->status): ?> selected<?php endif; ?>><?php _e('公开'); ?></option> <option value="hidden"<?php if ($page->status == 'hidden'): ?> selected<?php endif; ?>><?php _e('隐藏'); ?></option> </select> </p> </section> <section class="typecho-post-option allow-option"> <label class="typecho-label"><?php _e('权限控制'); ?></label> <ul> <li><input id="allowComment" name="allowComment" type="checkbox" value="1" <?php if($page->allow('comment')): ?>checked="true"<?php endif; ?> /> <label for="allowComment"><?php _e('允许评论'); ?></label></li> <li><input id="allowPing" name="allowPing" type="checkbox" value="1" <?php if($page->allow('ping')): ?>checked="true"<?php endif; ?> /> <label for="allowPing"><?php _e('允许被引用'); ?></label></li> <li><input id="allowFeed" name="allowFeed" type="checkbox" value="1" <?php if($page->allow('feed')): ?>checked="true"<?php endif; ?> /> <label for="allowFeed"><?php _e('允许在聚合中出现'); ?></label></li> </ul> </section> <?php Typecho_Plugin::factory('admin/write-page.php')->advanceOption($page); ?> </div> <?php if($page->have()): ?> <?php $modified = new Typecho_Date($page->modified); ?> <section class="typecho-post-option"> <p class="description"> <br>&mdash;<br> <?php _e('本页面由 <a href="%s">%s</a> 创建', Typecho_Common::url('manage-pages.php?uid=' . $page->author->uid, $options->adminUrl), $page->author->screenName); ?><br> <?php _e('最后更新于 %s', $modified->word()); ?> </p> </section> <?php endif; ?> </div><!-- end #tab-advance --> <div id="tab-files" class="tab-content hidden"> <?php include 'file-upload.php'; ?> </div><!-- end #tab-files --> </div> </form> </div> </div> </div> <?php include 'copyright.php'; include 'common-js.php'; include 'form-js.php'; include 'write-js.php'; Typecho_Plugin::factory('admin/write-page.php')->trigger($plugged)->richEditor($page); if (!$plugged) { include 'editor-js.php'; } include 'file-upload-js.php'; include 'custom-fields-js.php'; Typecho_Plugin::factory('admin/write-page.php')->bottom($page); include 'footer.php'; ?>
engine-go/pizida
admin/write-page.php
PHP
gpl-2.0
10,482
<?php /** * @file * Tests for ssh.drush.inc * * @group commands */ class siteSshCase extends Drush_CommandTestCase { /** * Test drush ssh --simulate. No additional bash passed. */ public function testInteractive() { if ($this->is_windows()) { $this->markTestSkipped('ssh command not currently available on Windows.'); } $options = array( 'simulate' => NULL, ); $this->drush('ssh', array(), $options, 'user@server/path/to/drupal#sitename', NULL, self::EXIT_SUCCESS, '2>&1'); $output = $this->getOutput(); $expected = sprintf('Calling proc_open(ssh -o PasswordAuthentication=no -t %s@%s %s);', self::escapeshellarg('user'), self::escapeshellarg('server'), "'cd /path/to/drupal && bash -l'"); $this->assertEquals($expected, $output); } /** * Test drush ssh --simulate 'date'. * @todo Run over a site list. drush_sitealias_get_record() currently cannot * handle a site list comprised of longhand site specifications. */ public function testNonInteractive() { $options = array( 'cd' => '0', 'simulate' => NULL, ); $this->drush('ssh', array('date'), $options, 'user@server/path/to/drupal#sitename', NULL, self::EXIT_SUCCESS, '2>&1'); $output = $this->getOutput(); $expected = sprintf('Calling proc_open(ssh -o PasswordAuthentication=no %s@%s %s);', self::escapeshellarg('user'), self::escapeshellarg('server'), self::escapeshellarg('date')); $this->assertEquals($expected, $output); } /** * Test drush ssh with multiple arguments (preferred form). */ public function testSshMultipleArgs() { $options = array( 'cd' => '0', 'simulate' => NULL, ); $this->drush('ssh', array('ls', '/path1', '/path2'), $options, 'user@server/path/to/drupal#sitename', NULL, self::EXIT_SUCCESS, '2>&1'); $output = $this->getOutput(); $expected = sprintf('Calling proc_open(ssh -o PasswordAuthentication=no %s@%s \'ls /path1 /path2\');', self::escapeshellarg('user'), self::escapeshellarg('server')); $this->assertEquals($expected, $output); } /** * Test drush ssh with multiple arguments (legacy form). */ public function testSshMultipleArgsLegacy() { $options = array( 'cd' => '0', 'simulate' => NULL, ); $this->drush('ssh', array('ls /path1 /path2'), $options, 'user@server/path/to/drupal#sitename', NULL, self::EXIT_SUCCESS, '2>&1'); $output = $this->getOutput(); $expected = sprintf('Calling proc_open(ssh -o PasswordAuthentication=no %s@%s \'ls /path1 /path2\');', self::escapeshellarg('user'), self::escapeshellarg('server')); $this->assertEquals($expected, $output); } }
junsuwhy/tungfilm
vendor/drush/drush/tests/siteSshTest.php
PHP
gpl-2.0
2,659
package org.bouncycastle.asn1; import java.io.IOException; public interface ASN1SequenceParser extends DEREncodable, InMemoryRepresentable { DEREncodable readObject() throws IOException; }
Z-Shang/onscripter-gbk
svn/onscripter-read-only/src/org/bouncycastle/asn1/ASN1SequenceParser.java
Java
gpl-2.0
207
<?php /** * @version $Id$ * * @author Valérie Isaksen * @package VirtueMart * @copyright Copyright (C) iStraxx - All rights reserved. * @license istraxx_license.txt Proprietary License. This code belongs to istraxx UG (haftungsbeschränkt) * You are not allowed to distribute or sell this code. * You are not allowed to modify this code */ defined('JPATH_BASE') or die(); /** * Renders a label element */ class JElementKlarnaLabel extends JElement { /** * Element name * * @access protected * @var string */ var $_name = 'KlarnaLabel'; function fetchElement($name, $value, &$node, $control_name) { $class = ( $node->attributes('class') ? 'class="'.$node->attributes('class').'"' : 'class="text_area"' ); return '<label for="'.$name.'"'.$class.'>'.$value.'</label>'; } }
Jasonudoo/platform
administrator/components/com_virtuemart_allinone/plugins/vmpayment/klarna/klarna/elements/klarnalabel.php
PHP
gpl-2.0
800
/* * Copyright (C) 2008-2018 TrinityCore <https://www.trinitycore.org/> * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) 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, see <http://www.gnu.org/licenses/>. */ #include "GuildPackets.h" void WorldPackets::Guild::QueryGuildInfo::Read() { _worldPacket >> GuildGuid; _worldPacket >> PlayerGuid; } WorldPackets::Guild::QueryGuildInfoResponse::QueryGuildInfoResponse() : ServerPacket(SMSG_QUERY_GUILD_INFO_RESPONSE) { } WorldPacket const* WorldPackets::Guild::QueryGuildInfoResponse::Write() { _worldPacket << GuildGuid; _worldPacket.WriteBit(Info.is_initialized()); _worldPacket.FlushBits(); if (Info) { _worldPacket << Info->GuildGUID; _worldPacket << uint32(Info->VirtualRealmAddress); _worldPacket << uint32(Info->Ranks.size()); _worldPacket << uint32(Info->EmblemStyle); _worldPacket << uint32(Info->EmblemColor); _worldPacket << uint32(Info->BorderStyle); _worldPacket << uint32(Info->BorderColor); _worldPacket << uint32(Info->BackgroundColor); _worldPacket.WriteBits(Info->GuildName.size(), 7); _worldPacket.FlushBits(); for (GuildInfo::GuildInfoRank const& rank : Info->Ranks) { _worldPacket << uint32(rank.RankID); _worldPacket << uint32(rank.RankOrder); _worldPacket.WriteBits(rank.RankName.size(), 7); _worldPacket.FlushBits(); _worldPacket.WriteString(rank.RankName); } _worldPacket.WriteString(Info->GuildName); } return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildRoster::Write() { _worldPacket << NumAccounts; _worldPacket.AppendPackedTime(CreateDate); _worldPacket << GuildFlags; _worldPacket << uint32(MemberData.size()); _worldPacket.WriteBits(WelcomeText.length(), 10); _worldPacket.WriteBits(InfoText.length(), 11); _worldPacket.FlushBits(); for (GuildRosterMemberData const& member : MemberData) _worldPacket << member; _worldPacket.WriteString(WelcomeText); _worldPacket.WriteString(InfoText); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildRosterUpdate::Write() { _worldPacket << uint32(MemberData.size()); for (GuildRosterMemberData const& member : MemberData) _worldPacket << member; return &_worldPacket; } void WorldPackets::Guild::GuildUpdateMotdText::Read() { uint32 textLen = _worldPacket.ReadBits(10); MotdText = _worldPacket.ReadString(textLen); } WorldPacket const* WorldPackets::Guild::GuildCommandResult::Write() { _worldPacket << Result; _worldPacket << Command; _worldPacket.WriteBits(Name.length(), 8); _worldPacket.FlushBits(); _worldPacket.WriteString(Name); return &_worldPacket; } void WorldPackets::Guild::DeclineGuildInvites::Read() { Allow = _worldPacket.ReadBit(); } void WorldPackets::Guild::GuildInviteByName::Read() { uint32 nameLen = _worldPacket.ReadBits(9); Name = _worldPacket.ReadString(nameLen); } WorldPacket const* WorldPackets::Guild::GuildInvite::Write() { _worldPacket.WriteBits(InviterName.length(), 6); _worldPacket.WriteBits(GuildName.length(), 7); _worldPacket.WriteBits(OldGuildName.length(), 7); _worldPacket.FlushBits(); _worldPacket << InviterVirtualRealmAddress; _worldPacket << GuildVirtualRealmAddress; _worldPacket << GuildGUID; _worldPacket << OldGuildVirtualRealmAddress; _worldPacket << OldGuildGUID; _worldPacket << EmblemStyle; _worldPacket << EmblemColor; _worldPacket << BorderStyle; _worldPacket << BorderColor; _worldPacket << Background; _worldPacket << AchievementPoints; _worldPacket.WriteString(InviterName); _worldPacket.WriteString(GuildName); _worldPacket.WriteString(OldGuildName); return &_worldPacket; } ByteBuffer& operator<<(ByteBuffer& data, WorldPackets::Guild::GuildRosterProfessionData const& rosterProfessionData) { data << rosterProfessionData.DbID; data << rosterProfessionData.Rank; data << rosterProfessionData.Step; return data; } ByteBuffer& operator<<(ByteBuffer& data, WorldPackets::Guild::GuildRosterMemberData const& rosterMemberData) { data << rosterMemberData.Guid; data << rosterMemberData.RankID; data << rosterMemberData.AreaID; data << rosterMemberData.PersonalAchievementPoints; data << rosterMemberData.GuildReputation; data << rosterMemberData.LastSave; for (uint8 i = 0; i < 2; i++) data << rosterMemberData.Profession[i]; data << rosterMemberData.VirtualRealmAddress; data << rosterMemberData.Status; data << rosterMemberData.Level; data << rosterMemberData.ClassID; data << rosterMemberData.Gender; data.WriteBits(rosterMemberData.Name.length(), 6); data.WriteBits(rosterMemberData.Note.length(), 8); data.WriteBits(rosterMemberData.OfficerNote.length(), 8); data.WriteBit(rosterMemberData.Authenticated); data.WriteBit(rosterMemberData.SorEligible); data.FlushBits(); data.WriteString(rosterMemberData.Name); data.WriteString(rosterMemberData.Note); data.WriteString(rosterMemberData.OfficerNote); return data; } WorldPacket const* WorldPackets::Guild::GuildEventPresenceChange::Write() { _worldPacket << Guid; _worldPacket << VirtualRealmAddress; _worldPacket.WriteBits(Name.length(), 6); _worldPacket.WriteBit(LoggedOn); _worldPacket.WriteBit(Mobile); _worldPacket.FlushBits(); _worldPacket.WriteString(Name); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventMotd::Write() { _worldPacket.WriteBits(MotdText.length(), 10); _worldPacket.FlushBits(); _worldPacket.WriteString(MotdText); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventPlayerJoined::Write() { _worldPacket << Guid; _worldPacket << VirtualRealmAddress; _worldPacket.WriteBits(Name.length(), 6); _worldPacket.FlushBits(); _worldPacket.WriteString(Name); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventRankChanged::Write() { _worldPacket << RankID; return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventBankMoneyChanged::Write() { _worldPacket << Money; return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventLogQueryResults::Write() { _worldPacket.reserve(4 + Entry.size() * 38); _worldPacket << uint32(Entry.size()); for (GuildEventEntry const& entry : Entry) { _worldPacket << entry.PlayerGUID; _worldPacket << entry.OtherGUID; _worldPacket << entry.TransactionType; _worldPacket << entry.RankID; _worldPacket << entry.TransactionDate; } return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventPlayerLeft::Write() { _worldPacket.WriteBit(Removed); _worldPacket.WriteBits(LeaverName.length(), 6); _worldPacket.FlushBits(); if (Removed) { _worldPacket.WriteBits(RemoverName.length(), 6); _worldPacket.FlushBits(); _worldPacket << RemoverGUID; _worldPacket << RemoverVirtualRealmAddress; _worldPacket.WriteString(RemoverName); } _worldPacket << LeaverGUID; _worldPacket << LeaverVirtualRealmAddress; _worldPacket.WriteString(LeaverName); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildPermissionsQueryResults::Write() { _worldPacket << RankID; _worldPacket << WithdrawGoldLimit; _worldPacket << Flags; _worldPacket << NumTabs; _worldPacket << uint32(Tab.size()); for (GuildRankTabPermissions const& tab : Tab) { _worldPacket << tab.Flags; _worldPacket << tab.WithdrawItemLimit; } return &_worldPacket; } void WorldPackets::Guild::GuildSetRankPermissions::Read() { _worldPacket >> RankID; _worldPacket >> RankOrder; _worldPacket >> Flags; _worldPacket >> OldFlags; _worldPacket >> WithdrawGoldLimit; for (uint8 i = 0; i < GUILD_BANK_MAX_TABS; i++) { _worldPacket >> TabFlags[i]; _worldPacket >> TabWithdrawItemLimit[i]; } _worldPacket.ResetBitPos(); uint32 rankNameLen = _worldPacket.ReadBits(7); RankName = _worldPacket.ReadString(rankNameLen); } WorldPacket const* WorldPackets::Guild::GuildEventNewLeader::Write() { _worldPacket.WriteBit(SelfPromoted); _worldPacket.WriteBits(NewLeaderName.length(), 6); _worldPacket.WriteBits(OldLeaderName.length(), 6); _worldPacket.FlushBits(); _worldPacket << OldLeaderGUID; _worldPacket << OldLeaderVirtualRealmAddress; _worldPacket << NewLeaderGUID; _worldPacket << NewLeaderVirtualRealmAddress; _worldPacket.WriteString(NewLeaderName); _worldPacket.WriteString(OldLeaderName); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventTabModified::Write() { _worldPacket << Tab; _worldPacket.WriteBits(Name.length(), 7); _worldPacket.WriteBits(Icon.length(), 9); _worldPacket.FlushBits(); _worldPacket.WriteString(Name); _worldPacket.WriteString(Icon); return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildEventTabTextChanged::Write() { _worldPacket << Tab; return &_worldPacket; } ByteBuffer& operator<<(ByteBuffer& data, WorldPackets::Guild::GuildRankData const& rankData) { data << rankData.RankID; data << rankData.RankOrder; data << rankData.Flags; data << rankData.WithdrawGoldLimit; for (uint8 i = 0; i < GUILD_BANK_MAX_TABS; i++) { data << rankData.TabFlags[i]; data << rankData.TabWithdrawItemLimit[i]; } data.WriteBits(rankData.RankName.length(), 7); data.FlushBits(); data.WriteString(rankData.RankName); return data; } void WorldPackets::Guild::GuildAddRank::Read() { uint32 nameLen = _worldPacket.ReadBits(7); _worldPacket.ResetBitPos(); _worldPacket >> RankOrder; Name = _worldPacket.ReadString(nameLen); } void WorldPackets::Guild::GuildAssignMemberRank::Read() { _worldPacket >> Member; _worldPacket >> RankOrder; } void WorldPackets::Guild::GuildDeleteRank::Read() { _worldPacket >> RankOrder; } void WorldPackets::Guild::GuildGetRanks::Read() { _worldPacket >> GuildGUID; } WorldPacket const* WorldPackets::Guild::GuildRanks::Write() { _worldPacket << uint32(Ranks.size()); for (GuildRankData const& rank : Ranks) _worldPacket << rank; return &_worldPacket; } WorldPacket const* WorldPackets::Guild::GuildSendRankChange::Write() { _worldPacket << Officer; _worldPacket << Other; _worldPacket << RankID; _worldPacket.WriteBit(Promote); _worldPacket.FlushBits(); return &_worldPacket; } void WorldPackets::Guild::GuildShiftRank::Read() { _worldPacket >> RankOrder; ShiftUp = _worldPacket.ReadBit(); } void WorldPackets::Guild::GuildUpdateInfoText::Read() { uint32 textLen = _worldPacket.ReadBits(11); InfoText = _worldPacket.ReadString(textLen); } void WorldPackets::Guild::GuildSetMemberNote::Read() { _worldPacket >> NoteeGUID; uint32 noteLen = _worldPacket.ReadBits(8); IsPublic = _worldPacket.ReadBit(); Note = _worldPacket.ReadString(noteLen); } WorldPacket const* WorldPackets::Guild::GuildMemberUpdateNote::Write() { _worldPacket.reserve(16 + 2 + Note.size()); _worldPacket << Member; _worldPacket.WriteBits(Note.length(), 8); _worldPacket.WriteBit(IsPublic); _worldPacket.FlushBits(); _worldPacket.WriteString(Note); return &_worldPacket; } void WorldPackets::Guild::GuildDemoteMember::Read() { _worldPacket >> Demotee; } void WorldPackets::Guild::GuildPromoteMember::Read() { _worldPacket >> Promotee; } void WorldPackets::Guild::GuildOfficerRemoveMember::Read() { _worldPacket >> Removee; } void WorldPackets::Guild::GuildChangeNameRequest::Read() { uint32 nameLen = _worldPacket.ReadBits(7); NewName = _worldPacket.ReadString(nameLen); } WorldPacket const* WorldPackets::Guild::GuildFlaggedForRename::Write() { _worldPacket.WriteBit(FlagSet); return &_worldPacket; } void WorldPackets::Guild::RequestGuildPartyState::Read() { _worldPacket >> GuildGUID; } WorldPacket const* WorldPackets::Guild::GuildPartyState::Write() { _worldPacket.WriteBit(InGuildParty); _worldPacket.FlushBits(); _worldPacket << NumMembers; _worldPacket << NumRequired; _worldPacket << GuildXPEarnedMult; return &_worldPacket; } ByteBuffer& operator<<(ByteBuffer& data, WorldPackets::Guild::GuildRewardItem const& rewardItem) { data << rewardItem.ItemID; data << rewardItem.Unk4; data << uint32(rewardItem.AchievementsRequired.size()); data << rewardItem.RaceMask; data << rewardItem.MinGuildLevel; data << rewardItem.MinGuildRep; data << rewardItem.Cost; for (uint8 i = 0; i < rewardItem.AchievementsRequired.size(); i++) data << rewardItem.AchievementsRequired[i]; return data; } void WorldPackets::Guild::RequestGuildRewardsList::Read() { _worldPacket >> CurrentVersion; } WorldPacket const* WorldPackets::Guild::GuildRewardList::Write() { _worldPacket << Version; _worldPacket << uint32(RewardItems.size()); for (GuildRewardItem const& item : RewardItems) _worldPacket << item; return &_worldPacket; } void WorldPackets::Guild::GuildBankActivate::Read() { _worldPacket >> Banker; FullUpdate = _worldPacket.ReadBit(); } void WorldPackets::Guild::GuildBankBuyTab::Read() { _worldPacket >> Banker; _worldPacket >> BankTab; } void WorldPackets::Guild::GuildBankUpdateTab::Read() { _worldPacket >> Banker; _worldPacket >> BankTab; _worldPacket.ResetBitPos(); uint32 nameLen = _worldPacket.ReadBits(7); uint32 iconLen = _worldPacket.ReadBits(9); Name = _worldPacket.ReadString(nameLen); Icon = _worldPacket.ReadString(iconLen); } void WorldPackets::Guild::GuildBankDepositMoney::Read() { _worldPacket >> Banker; _worldPacket >> Money; } void WorldPackets::Guild::GuildBankQueryTab::Read() { _worldPacket >> Banker; _worldPacket >> Tab; FullUpdate = _worldPacket.ReadBit(); } WorldPacket const* WorldPackets::Guild::GuildBankRemainingWithdrawMoney::Write() { _worldPacket << RemainingWithdrawMoney; return &_worldPacket; } void WorldPackets::Guild::GuildBankWithdrawMoney::Read() { _worldPacket >> Banker; _worldPacket >> Money; } WorldPacket const* WorldPackets::Guild::GuildBankQueryResults::Write() { _worldPacket << Money; _worldPacket << Tab; _worldPacket << WithdrawalsRemaining; _worldPacket << uint32(TabInfo.size()); _worldPacket << uint32(ItemInfo.size()); _worldPacket.WriteBit(FullUpdate); _worldPacket.FlushBits(); for (GuildBankTabInfo const& tab : TabInfo) { _worldPacket << tab.TabIndex; _worldPacket.WriteBits(tab.Name.length(), 7); _worldPacket.WriteBits(tab.Icon.length(), 9); _worldPacket.FlushBits(); _worldPacket.WriteString(tab.Name); _worldPacket.WriteString(tab.Icon); } for (GuildBankItemInfo const& item : ItemInfo) { _worldPacket << item.Slot; _worldPacket << item.Count; _worldPacket << item.EnchantmentID; _worldPacket << item.Charges; _worldPacket << item.OnUseEnchantmentID; _worldPacket << item.Flags; _worldPacket << item.Item; _worldPacket.WriteBits(item.SocketEnchant.size(), 2); _worldPacket.WriteBit(item.Locked); _worldPacket.FlushBits(); for (Item::ItemGemData const& socketEnchant : item.SocketEnchant) _worldPacket << socketEnchant; } return &_worldPacket; } void WorldPackets::Guild::GuildBankSwapItems::Read() { _worldPacket >> Banker; _worldPacket >> BankTab; _worldPacket >> BankSlot; _worldPacket >> ItemID; _worldPacket >> BankTab1; _worldPacket >> BankSlot1; _worldPacket >> ItemID1; _worldPacket >> BankItemCount; _worldPacket >> ContainerSlot; _worldPacket >> ContainerItemSlot; _worldPacket >> ToSlot; _worldPacket >> StackCount; _worldPacket.ResetBitPos(); BankOnly = _worldPacket.ReadBit(); AutoStore = _worldPacket.ReadBit(); } void WorldPackets::Guild::GuildBankLogQuery::Read() { _worldPacket >> Tab; } WorldPacket const* WorldPackets::Guild::GuildBankLogQueryResults::Write() { _worldPacket << Tab; _worldPacket << uint32(Entry.size()); _worldPacket.WriteBit(WeeklyBonusMoney.is_initialized()); _worldPacket.FlushBits(); for (GuildBankLogEntry const& logEntry : Entry) { _worldPacket << logEntry.PlayerGUID; _worldPacket << logEntry.TimeOffset; _worldPacket << logEntry.EntryType; _worldPacket.WriteBit(logEntry.Money.is_initialized()); _worldPacket.WriteBit(logEntry.ItemID.is_initialized()); _worldPacket.WriteBit(logEntry.Count.is_initialized()); _worldPacket.WriteBit(logEntry.OtherTab.is_initialized()); _worldPacket.FlushBits(); if (logEntry.Money.is_initialized()) _worldPacket << *logEntry.Money; if (logEntry.ItemID.is_initialized()) _worldPacket << *logEntry.ItemID; if (logEntry.Count.is_initialized()) _worldPacket << *logEntry.Count; if (logEntry.OtherTab.is_initialized()) _worldPacket << *logEntry.OtherTab; } if (WeeklyBonusMoney) _worldPacket << *WeeklyBonusMoney; return &_worldPacket; } void WorldPackets::Guild::GuildBankTextQuery::Read() { _worldPacket >> Tab; } WorldPacket const* WorldPackets::Guild::GuildBankTextQueryResult::Write() { _worldPacket << Tab; _worldPacket.WriteBits(Text.length(), 14); _worldPacket.FlushBits(); _worldPacket.WriteString(Text); return &_worldPacket; } void WorldPackets::Guild::GuildBankSetTabText::Read() { _worldPacket >> Tab; TabText = _worldPacket.ReadString(_worldPacket.ReadBits(14)); } void WorldPackets::Guild::GuildQueryNews::Read() { _worldPacket >> GuildGUID; } ByteBuffer& operator<<(ByteBuffer& data, WorldPackets::Guild::GuildNewsEvent const& newsEvent) { data << newsEvent.Id; data.AppendPackedTime(newsEvent.CompletedDate); data << newsEvent.Type; data << newsEvent.Flags; for (uint8 i = 0; i < 2; i++) data << newsEvent.Data[i]; data << newsEvent.MemberGuid; data << uint32(newsEvent.MemberList.size()); for (ObjectGuid memberGuid : newsEvent.MemberList) data << memberGuid; data.WriteBit(newsEvent.Item.is_initialized()); data.FlushBits(); if (newsEvent.Item) data << *newsEvent.Item; // WorldPackets::Item::ItemInstance return data; } WorldPacket const* WorldPackets::Guild::GuildNews::Write() { _worldPacket << uint32(NewsEvents.size()); for (GuildNewsEvent const& newsEvent : NewsEvents) _worldPacket << newsEvent; return &_worldPacket; } void WorldPackets::Guild::GuildNewsUpdateSticky::Read() { _worldPacket >> GuildGUID; _worldPacket >> NewsID; NewsID = _worldPacket.ReadBit(); } void WorldPackets::Guild::GuildSetGuildMaster::Read() { uint32 nameLen = _worldPacket.ReadBits(9); NewMasterName = _worldPacket.ReadString(nameLen); } WorldPacket const* WorldPackets::Guild::GuildChallengeUpdate::Write() { for (int32 i = 0; i < GUILD_CHALLENGES_TYPES; ++i) _worldPacket << int32(CurrentCount[i]); for (int32 i = 0; i < GUILD_CHALLENGES_TYPES; ++i) _worldPacket << int32(MaxCount[i]); for (int32 i = 0; i < GUILD_CHALLENGES_TYPES; ++i) _worldPacket << int32(MaxLevelGold[i]); for (int32 i = 0; i < GUILD_CHALLENGES_TYPES; ++i) _worldPacket << int32(Gold[i]); return &_worldPacket; } void WorldPackets::Guild::SaveGuildEmblem::Read() { _worldPacket >> Vendor; _worldPacket >> EStyle; _worldPacket >> EColor; _worldPacket >> BStyle; _worldPacket >> BColor; _worldPacket >> Bg; } WorldPacket const* WorldPackets::Guild::PlayerSaveGuildEmblem::Write() { _worldPacket << int32(Error); return &_worldPacket; } void WorldPackets::Guild::GuildSetAchievementTracking::Read() { uint32 count; _worldPacket >> count; for (uint32 i = 0; i < count; ++i) { uint32 value; _worldPacket >> value; AchievementIDs.insert(value); } } WorldPacket const* WorldPackets::Guild::GuildNameChanged::Write() { _worldPacket << GuildGUID; _worldPacket.WriteBits(GuildName.length(), 7); _worldPacket.FlushBits(); _worldPacket.WriteString(GuildName); return &_worldPacket; }
Dozorov/TrinityCore
src/server/game/Server/Packets/GuildPackets.cpp
C++
gpl-2.0
21,360
<?php /** * @file * Template for the 1 column panel layout. * * This template provides a three column 25%-50%-25% panel display layout. * * Variables: * - $id: An optional CSS id to use for the layout. * - $content: An array of content, each item in the array is keyed to one * panel of the layout. This layout supports the following sections: * - $content['left']: Content in the left column. * - $content['middle']: Content in the middle column. * - $content['right']: Content in the right column. */ ?> <div class="panel-display general-two-col clearfix" <?php if (!empty($css_id)) { print "id=\"$css_id\""; } ?>> <div class="panel-panel general-left"> <?php if ($content['left']): ?> <div class="inside"><?php print $content['left']; ?></div> <?php endif ?> </div> <div class="panel-panel general-right"> <?php if ($content['right']): ?> <div class="inside"><?php print $content['right']; ?></div> <?php endif ?> </div> <div class="vertical-line"></div> </div>
SLAC-OCIO/slac-www
sites/all/themes/slac_www/plugins/layouts/two_col/two-col.tpl.php
PHP
gpl-2.0
1,034
<?php /** * AJAX handler plugin manager * * PHP version 7 * * Copyright (C) Villanova University 2018. * * 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 AJAX * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development Wiki */ namespace VuFind\AjaxHandler; /** * AJAX handler plugin manager * * @category VuFind * @package AJAX * @author Demian Katz <demian.katz@villanova.edu> * @license http://opensource.org/licenses/gpl-2.0.php GNU General Public License * @link https://vufind.org/wiki/development Wiki */ class PluginManager extends \VuFind\ServiceManager\AbstractPluginManager { /** * Default plugin aliases. * * @var array */ protected $aliases = [ 'checkRequestIsValid' => CheckRequestIsValid::class, 'commentRecord' => CommentRecord::class, 'deleteRecordComment' => DeleteRecordComment::class, 'doiLookup' => DoiLookup::class, 'getACSuggestions' => GetACSuggestions::class, 'getFacetData' => GetFacetData::class, 'getIlsStatus' => GetIlsStatus::class, 'getItemStatuses' => GetItemStatuses::class, 'getLibraryPickupLocations' => GetLibraryPickupLocations::class, 'getRecordCommentsAsHTML' => GetRecordCommentsAsHTML::class, 'getRecordDetails' => GetRecordDetails::class, 'getRecordTags' => GetRecordTags::class, 'getRequestGroupPickupLocations' => GetRequestGroupPickupLocations::class, 'getResolverLinks' => GetResolverLinks::class, 'getSaveStatuses' => GetSaveStatuses::class, 'getSideFacets' => GetSideFacets::class, 'getUserFines' => GetUserFines::class, 'getUserHolds' => GetUserHolds::class, 'getUserILLRequests' => GetUserILLRequests::class, 'getUserStorageRetrievalRequests' => GetUserStorageRetrievalRequests::class, 'getUserTransactions' => GetUserTransactions::class, 'getVisData' => GetVisData::class, 'keepAlive' => KeepAlive::class, 'recommend' => Recommend::class, 'relaisAvailability' => RelaisAvailability::class, 'relaisInfo' => RelaisInfo::class, 'relaisOrder' => RelaisOrder::class, 'systemStatus' => SystemStatus::class, 'tagRecord' => TagRecord::class, ]; /** * Default plugin factories. * * @var array */ protected $factories = [ CheckRequestIsValid::class => AbstractIlsAndUserActionFactory::class, CommentRecord::class => CommentRecordFactory::class, DeleteRecordComment::class => DeleteRecordCommentFactory::class, DoiLookup::class => DoiLookupFactory::class, GetACSuggestions::class => GetACSuggestionsFactory::class, GetFacetData::class => GetFacetDataFactory::class, GetIlsStatus::class => GetIlsStatusFactory::class, GetItemStatuses::class => GetItemStatusesFactory::class, GetLibraryPickupLocations::class => AbstractIlsAndUserActionFactory::class, GetRecordCommentsAsHTML::class => GetRecordCommentsAsHTMLFactory::class, GetRecordDetails::class => GetRecordDetailsFactory::class, GetRecordTags::class => GetRecordTagsFactory::class, GetRequestGroupPickupLocations::class => AbstractIlsAndUserActionFactory::class, GetResolverLinks::class => GetResolverLinksFactory::class, GetSaveStatuses::class => GetSaveStatusesFactory::class, GetSideFacets::class => GetSideFacetsFactory::class, GetUserFines::class => GetUserFinesFactory::class, GetUserHolds::class => AbstractIlsAndUserActionFactory::class, GetUserILLRequests::class => AbstractIlsAndUserActionFactory::class, GetUserStorageRetrievalRequests::class => AbstractIlsAndUserActionFactory::class, GetUserTransactions::class => AbstractIlsAndUserActionFactory::class, GetVisData::class => GetVisDataFactory::class, KeepAlive::class => KeepAliveFactory::class, Recommend::class => RecommendFactory::class, RelaisAvailability::class => AbstractRelaisActionFactory::class, RelaisInfo::class => AbstractRelaisActionFactory::class, RelaisOrder::class => AbstractRelaisActionFactory::class, SystemStatus::class => SystemStatusFactory::class, TagRecord::class => TagRecordFactory::class, ]; /** * Return the name of the base class or interface that plug-ins must conform * to. * * @return string */ protected function getExpectedInterface() { return AjaxHandlerInterface::class; } }
arto70/NDL-VuFind2
module/VuFind/src/VuFind/AjaxHandler/PluginManager.php
PHP
gpl-2.0
5,361
<?php /** * @package WordPress * @subpackage GoodDay * @version 1.0.0 * * Post Options Functions * Created by CMSMasters * */ $cmsms_option = cmsms_get_global_options(); $cmsms_global_blog_post_layout = (isset($cmsms_option[CMSMS_SHORTNAME . '_blog_post_layout']) && $cmsms_option[CMSMS_SHORTNAME . '_blog_post_layout'] !== '') ? $cmsms_option[CMSMS_SHORTNAME . '_blog_post_layout'] : 'r_sidebar'; $cmsms_global_bottom_sidebar = (isset($cmsms_option[CMSMS_SHORTNAME . '_bottom_sidebar']) && $cmsms_option[CMSMS_SHORTNAME . '_bottom_sidebar'] !== '') ? (($cmsms_option[CMSMS_SHORTNAME . '_bottom_sidebar'] == 1) ? 'true' : 'false') : 'true'; $cmsms_global_bottom_sidebar_layout = (isset($cmsms_option[CMSMS_SHORTNAME . '_bottom_sidebar_layout'])) ? $cmsms_option[CMSMS_SHORTNAME . '_bottom_sidebar_layout'] : '14141414'; $cmsms_global_blog_post_title = (isset($cmsms_option[CMSMS_SHORTNAME . '_blog_post_title']) && $cmsms_option[CMSMS_SHORTNAME . '_blog_post_title'] !== '') ? (($cmsms_option[CMSMS_SHORTNAME . '_blog_post_title'] == 1) ? 'true' : 'false') : 'true'; $cmsms_global_blog_post_share_box = (isset($cmsms_option[CMSMS_SHORTNAME . '_blog_post_share_box']) && $cmsms_option[CMSMS_SHORTNAME . '_blog_post_share_box'] !== '') ? (($cmsms_option[CMSMS_SHORTNAME . '_blog_post_share_box'] == 1) ? 'true' : 'false') : 'true'; $cmsms_global_blog_post_author_box = (isset($cmsms_option[CMSMS_SHORTNAME . '_blog_post_author_box']) && $cmsms_option[CMSMS_SHORTNAME . '_blog_post_author_box'] !== '') ? (($cmsms_option[CMSMS_SHORTNAME . '_blog_post_author_box'] == 1) ? 'true' : 'false') : 'true'; $cmsms_global_bg = (isset($cmsms_option[CMSMS_SHORTNAME . '_theme_layout']) && $cmsms_option[CMSMS_SHORTNAME . '_theme_layout'] === 'boxed') ? true : false; if (isset($cmsms_option[CMSMS_SHORTNAME . '_blog_more_posts_box']) && $cmsms_option[CMSMS_SHORTNAME . '_blog_more_posts_box'] !== '') { $cmsms_global_blog_more_posts_box = array(); foreach($cmsms_option[CMSMS_SHORTNAME . '_blog_more_posts_box'] as $key => $val) { if ($val == 'true') { $cmsms_global_blog_more_posts_box[] = $key; } } } else { $cmsms_global_blog_more_posts_box = array( 'related', 'popular', 'recent' ); } $cmsms_option_name = 'cmsms_post_'; $tabs_array = array(); $tabs_array['cmsms_post'] = array( 'label' => __('Post', 'cmsmasters'), 'value' => 'cmsms_post' ); $tabs_array['cmsms_layout'] = array( 'label' => __('Layout', 'cmsmasters'), 'value' => 'cmsms_layout' ); if ($cmsms_global_bg) { $tabs_array['cmsms_bg'] = array( 'label' => __('Background', 'cmsmasters'), 'value' => 'cmsms_bg' ); } $tabs_array['cmsms_heading'] = array( 'label' => __('Heading', 'cmsmasters'), 'value' => 'cmsms_heading' ); $custom_post_meta_fields = array( array( 'id' => 'cmsms_post_aside', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Aside Text', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'aside_text', 'type' => 'textarea', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_aside', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_status', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Status Text', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'status_text', 'type' => 'textarea', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_status', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_chat', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Chat Text', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'chat_text', 'type' => 'textarea', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_chat', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_quote', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Quote Text', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'quote_text', 'type' => 'textarea', 'hide' => '', 'std' => '' ), array( 'label' => __('Quote Author', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'quote_author', 'type' => 'text', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_quote', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_link', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Link Text', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'link_text', 'type' => 'text', 'hide' => '', 'std' => '' ), array( 'label' => __('Link Address', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'link_address', 'type' => 'text_long', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_link', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_image', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Post Image', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'image_link', 'type' => 'image', 'hide' => '', 'cancel' => 'true', 'std' => '', 'frame' => 'select', 'multiple' => false ), array( 'id' => 'cmsms_post_image', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_gallery', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Post Gallery', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'images', 'type' => 'images_list', 'hide' => '', 'std' => '', 'frame' => 'post', 'multiple' => true ), array( 'id' => 'cmsms_post_gallery', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_video', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Video Type', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'video_type', 'type' => 'radio', 'hide' => '', 'std' => 'embedded', 'options' => array( 'embedded' => array( 'label' => __('Embedded (YouTube, Vimeo)', 'cmsmasters'), 'value' => 'embedded' ), 'selfhosted' => array( 'label' => __('Self-Hosted', 'cmsmasters'), 'value' => 'selfhosted' ) ) ), array( 'label' => __('Embedded Video Link', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'video_link', 'type' => 'text_long', 'hide' => 'true', 'std' => '' ), array( 'label' => __('Self-Hosted Video Links', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'video_links', 'type' => 'repeatable', 'hide' => 'true', 'std' => '' ), array( 'id' => 'cmsms_post_video', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_audio', 'type' => 'content_start', 'box' => 'true', 'hide' => 'true' ), array( 'label' => __('Audio Links', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'audio_links', 'type' => 'repeatable', 'hide' => '', 'std' => '' ), array( 'id' => 'cmsms_post_audio', 'type' => 'content_finish' ), array( 'id' => 'cmsms_post_format', 'type' => 'content_start', 'box' => '' ), array( 'id' => 'cmsms_post_format', 'type' => 'content_finish' ), array( 'id' => $cmsms_option_name . 'tabs', 'type' => 'tabs', 'std' => 'cmsms_post', 'options' => $tabs_array ), array( 'id' => 'cmsms_post', 'type' => 'tab_start', 'std' => 'true' ), array( 'label' => __('Post Title', 'cmsmasters'), 'desc' => __('Show', 'cmsmasters'), 'id' => $cmsms_option_name . 'title', 'type' => 'checkbox', 'hide' => '', 'std' => $cmsms_global_blog_post_title ), array( 'label' => __('Sharing Box', 'cmsmasters'), 'desc' => __('Show', 'cmsmasters'), 'id' => $cmsms_option_name . 'sharing_box', 'type' => 'checkbox', 'hide' => '', 'std' => $cmsms_global_blog_post_share_box ), array( 'label' => __('About Author Box', 'cmsmasters'), 'desc' => __('Show', 'cmsmasters'), 'id' => $cmsms_option_name . 'author_box', 'type' => 'checkbox', 'hide' => '', 'std' => $cmsms_global_blog_post_author_box ), array( 'label' => __('More Posts Box', 'cmsmasters'), 'desc' => '', 'id' => $cmsms_option_name . 'more_posts', 'type' => 'checkbox_group', 'hide' => '', 'std' => ((isset($_GET['post']) && get_post_meta($_GET['post'], 'cmsms_heading', true)) ? '' : $cmsms_global_blog_more_posts_box), 'options' => array( 'related' => array( 'label' => 'Show Related Tab', 'value' => 'related' ), 'popular' => array( 'label' => 'Show Popular Tab', 'value' => 'popular' ), 'recent' => array( 'label' => 'Show Recent Tab', 'value' => 'recent' ) ) ), array( 'label' => __("'Read More' Buttons Text", 'cmsmasters'), 'desc' => __("Enter the 'Read More' button text that should be used in you blog shortcode", 'cmsmasters'), 'id' => $cmsms_option_name . 'read_more', 'type' => 'text', 'hide' => '', 'std' => __('Read More', 'cmsmasters') ), array( 'id' => 'cmsms_post', 'type' => 'tab_finish' ), array( 'id' => 'cmsms_layout', 'type' => 'tab_start', 'std' => '' ), array( 'label' => __('Page Color Scheme', 'cmsmasters'), 'desc' => '', 'id' => 'cmsms_page_scheme', 'type' => 'select_scheme', 'hide' => 'false', 'std' => 'default' ), array( 'label' => __('Page Layout', 'cmsmasters'), 'desc' => '', 'id' => 'cmsms_layout', 'type' => 'radio_img', 'hide' => '', 'std' => $cmsms_global_blog_post_layout, 'options' => array( 'r_sidebar' => array( 'img' => get_template_directory_uri() . '/framework/admin/inc/img/sidebar_r.jpg', 'label' => __('Right Sidebar', 'cmsmasters'), 'value' => 'r_sidebar' ), 'l_sidebar' => array( 'img' => get_template_directory_uri() . '/framework/admin/inc/img/sidebar_l.jpg', 'label' => __('Left Sidebar', 'cmsmasters'), 'value' => 'l_sidebar' ), 'fullwidth' => array( 'img' => get_template_directory_uri() . '/framework/admin/inc/img/fullwidth.jpg', 'label' => __('Full Width', 'cmsmasters'), 'value' => 'fullwidth' ) ) ), array( 'label' => __('Choose Right\Left Sidebar', 'cmsmasters'), 'desc' => '', 'id' => 'cmsms_sidebar_id', 'type' => 'select_sidebar', 'hide' => 'true', 'std' => '' ), array( 'label' => __('Bottom Sidebar', 'cmsmasters'), 'desc' => __('Show', 'cmsmasters'), 'id' => 'cmsms_bottom_sidebar', 'type' => 'checkbox', 'hide' => '', 'std' => $cmsms_global_bottom_sidebar ), array( 'label' => __('Choose Bottom Sidebar', 'cmsmasters'), 'desc' => '', 'id' => 'cmsms_bottom_sidebar_id', 'type' => 'select_sidebar', 'hide' => 'true', 'std' => '' ), array( 'label' => __('Choose Bottom Sidebar Layout', 'cmsmasters'), 'desc' => '', 'id' => 'cmsms_bottom_sidebar_layout', 'type' => 'select', 'hide' => 'true', 'std' => $cmsms_global_bottom_sidebar_layout, 'options' => array( '11' => array( 'label' => '1/1', 'value' => '11' ), '1212' => array( 'label' => '1/2 + 1/2', 'value' => '1212' ), '1323' => array( 'label' => '1/3 + 2/3', 'value' => '1323' ), '2313' => array( 'label' => '2/3 + 1/3', 'value' => '2313' ), '1434' => array( 'label' => '1/4 + 3/4', 'value' => '1434' ), '3414' => array( 'label' => '3/4 + 1/4', 'value' => '3414' ), '131313' => array( 'label' => '1/3 + 1/3 + 1/3', 'value' => '131313' ), '121414' => array( 'label' => '1/2 + 1/4 + 1/4', 'value' => '121414' ), '141214' => array( 'label' => '1/4 + 1/2 + 1/4', 'value' => '141214' ), '141412' => array( 'label' => '1/4 + 1/4 + 1/2', 'value' => '141412' ), '14141414' => array( 'label' => '1/4 + 1/4 + 1/4 + 1/4', 'value' => '14141414' ) ) ), array( 'id' => 'cmsms_layout', 'type' => 'tab_finish' ) );
napalm255/makeachangewithmarie.com
wp-content/themes/goodday/framework/admin/options/cmsms-theme-options-post.php
PHP
gpl-2.0
12,758
<?php /** * thai language file * * @license GPL 2 (http://www.gnu.org/licenses/gpl.html) * @author Matthias Schulte <mailinglist@lupo49.de> */ // custom language strings for the plugin $lang['reveal'] = 'แสดง'; $lang['reveallong'] = 'แสดงเนื้อหาที่ซ่อนไว้'; $lang['hide'] = 'ซ่อน'; $lang['hidelong'] = 'ซ่อนเนื้อหา'; //Setup VIM: ex: et ts=2 :
claudehohl/dokuwiki-kickstart
lib/plugins/folded/lang/th/lang.php
PHP
gpl-2.0
450
<?php error_reporting(0);ini_set('display_errors', 0);header("Content-type: text/css; charset: UTF-8"); ?> <?php $parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] ); require_once( $parse_uri[0] . 'wp-load.php' ); //Get Plugin settings $frmcol = easy_get_option( 'easymedia_frm_col' ); $shdcol = easy_get_option( 'easymedia_shdw_col' ); $mrgnbox = easy_get_option( 'easymedia_margin_box' ); $imgborder = easy_get_option( 'easymedia_frm_border' ); $curstyle = strtolower( easy_get_option( 'easymedia_cur_style' ) ); $imgbbrdrradius = easy_get_option( 'easymedia_brdr_rds' ); $disenbor = easy_get_option( 'easymedia_disen_bor' ); $disenshadow = easy_get_option( 'easymedia_disen_sdw' ); $brdrbtm = $mrgnbox * 2; $marginhlf = $mrgnbox / 2; $theoptstl = easy_get_option( 'easymedia_frm_size' ); $globalwidth = stripslashes( $theoptstl[ 'width' ] ); $pattover = easy_get_option( 'easymedia_style_pattern' ); $overcol = easy_get_option( 'easymedia_overlay_col' ); $ttlcol = easy_get_option( 'easymedia_ttl_col' ); $thumbhov = ucfirst( easy_get_option( 'easymedia_hover_style' ) ) . '.png'; $thumbhov = plugins_url( 'css/images/' . $thumbhov . '', dirname(__FILE__) ); $thumbhovcol = easymedia_hex2rgb( easy_get_option( 'easymedia_thumb_col' ) ); $thumbhovcolopcty = easy_get_option( 'easymedia_hover_opcty' ) / 100; $thumbiconcol = easy_get_option( 'easymedia_icon_col' ); $disenico = easy_get_option( 'easymedia_disen_ticon' ); $borderrgba = easymedia_hex2rgb( easy_get_option( 'easymedia_frm_col' ) ); $borderrgbaopcty = easy_get_option( 'easymedia_thumb_border_opcty' ) / 100; // IMAGES echo '.view {margin-bottom:'.$mrgnbox.'px; margin-right:'.$marginhlf.'px; margin-left:'.$marginhlf.'px;}'; echo '.da-thumbs article.da-animate p{color:'.$ttlcol.' !important;}'; if ( easy_get_option( 'easymedia_disen_icocol' ) == '1' ) { echo 'span.link_post, span.zoom, span.zooma {background-color:'.$thumbiconcol.';}'; } if ( easy_get_option( 'easymedia_disen_hovstyle' ) == '1' ) { echo '.da-thumbs article.da-animate {cursor: '.$curstyle.';}'; } else { echo '.da-thumbs img {cursor: '.$curstyle.';}'; } ( $imgbbrdrradius != '' ) ? $addborradius = '.view,.view img,.da-thumbs,.da-thumbs article.da-animate {border-radius:'.$imgbbrdrradius.'px;}' : $addborradius = ''; echo $addborradius; ( $disenbor == 1 ) ? $addborder = '.view {border: '.$imgborder.'px solid rgba('.$borderrgba.','.$borderrgbaopcty.');}' : $addborder = ''; echo $addborder; ( $disenico == 1 ) ? $showicon = '' : $showicon = '.forspan {display: none !important;}' ; echo $showicon; ( $disenshadow == 1 ) ? $addshadow = '.view {-webkit-box-shadow: 1px 1px 3px '.$shdcol.'; -moz-box-shadow: 1px 1px 3px '.$shdcol.'; box-shadow: 1px 1px 3px '.$shdcol.';}' : $addshadow = '.view { box-shadow: none !important; -moz-box-shadow: none !important; -webkit-box-shadow: none !important;}'; echo $addshadow; // MEDIA BOX Patterns if ( $pattover != '' || $pattover != 'no_pattern' ) { echo '#mbOverlay {background: url(../css/images/patterns/'.$pattover.'); background-repeat: repeat;}'; } // Thumbnails Title Background color @since 1.2.61 echo '.da-thumbs article.da-animate p { background: rgba('.easymedia_hex2rgb( easy_get_option( 'easymedia_ttl_back_col' ) ).',0.5) !important;}'; // IE <8 Handle preg_match( '/MSIE (.*?);/', $_SERVER['HTTP_USER_AGENT'], $matches ); if ( isset($matches) ) { if ( count( $matches )>1 && $disenbor == 1 ){ $version = explode(".", $matches[1]); switch(true){ case ( $version[0] <= '8' ): echo '.view {border: 1px solid '.$shdcol.';}'; echo '.iehand {border: '.$imgborder.'px solid '.$frmcol.';}'; echo '.da-thumbs article{position: absolute; background-image:url('.$thumbhov.'); background-repeat:repeat; width: 100%; height: 100%;}'; break; case ( $version[0] > '8' ): ( $disenbor == 1 ) ? $addborder = '.view {border: '.$imgborder.'px solid rgba('.$borderrgba.','.$borderrgbaopcty.');}' : $addborder = ''; echo $addborder; echo '.da-thumbs article{position: absolute; background: rgba('.$thumbhovcol.','.$thumbhovcolopcty.'); background-repeat:repeat; width: 100%; height: 100%;}'; break; default: break; } } else if ( count( $matches )>1 && $disenbor != '1' ) { echo '.da-thumbs article{position: absolute; background-image:url('.$thumbhov.'); background-repeat:repeat; width: 100%; height: 100%;}'; } else { echo '.da-thumbs article{position: absolute; background: rgba('.$thumbhovcol.','.$thumbhovcolopcty.'); background-repeat:repeat; width: 100%; height: 100%;}'; } } // Magnify Icon if ( easy_get_option( 'easymedia_mag_icon' ) != '' && $disenico == 1 ) { echo ' span.zoom{ background-image:url(../css/images/magnify/'.easy_get_option( 'easymedia_mag_icon' ).'.png); background-repeat:no-repeat; background-position:center; }'; } ?>
icommstudios/localsharingtree
wp-content/plugins/easy-media-gallery/includes/dynamic-style.php
PHP
gpl-2.0
5,036
<?php function ninja_forms_output_tab_metabox($form_id = '', $slug, $metabox){ $plugin_settings = get_option( 'ninja_forms_settings' ); if($form_id != ''){ $form_row = ninja_forms_get_form_by_id($form_id); $current_settings = $form_row['data']; }else{ $form_id = ''; $current_settings = get_option("ninja_forms_settings"); } $page = $metabox['page']; $tab = $metabox['tab']; $title = $metabox['title']; if(isset($metabox['settings'])){ $settings = $metabox['settings']; }else{ $settings = ''; } if(isset($metabox['display_function'])){ $display_function = $metabox['display_function']; }else{ $display_function = ''; } if($metabox['state'] == 'closed'){ $state = 'display:none;'; }else{ $state = ''; } if( isset( $plugin_settings['metabox_state'][$page][$tab][$slug] ) ){ $state = $plugin_settings['metabox_state'][$page][$tab][$slug]; } if( isset( $metabox['display_container'] ) ){ $display_container = $metabox['display_container']; }else{ $display_container = true; } if( $display_container ){ ?> <div id="ninja_forms_metabox_<?php echo $slug;?>" class="postbox "> <span class="item-controls"> <a class="item-edit metabox-item-edit" id="edit_id" title="Edit Menu Item" href="#">Edit Menu Item</a> </span> <h3 class="hndle"><span><?php _e($title, 'ninja-forms');?></span></h3> <div class="inside" style="<?php echo $state;?>"> <table class="form-table"> <tbody> <?php } if( is_array( $settings ) AND !empty( $settings ) ){ foreach( $settings as $s ){ $value = ''; if(isset($s['name'])){ $name = $s['name']; }else{ $name = ''; } $name_array = ''; if( strpos( $name, '[') !== false ){ $name_array = str_replace( ']', '', $name ); $name_array = explode( '[', $name_array ); } if(isset($s['type'])){ $type = $s['type']; }else{ $type = ''; } if(isset($s['desc'])){ $desc = $s['desc']; }else{ $desc = ''; } if(isset($s['help_text'])){ $help_text = $s['help_text']; }else{ $help_text = ''; } if(isset($s['label'])){ $label = $s['label']; }else{ $label = ''; } if(isset($s['class'])){ $class = $s['class']; }else{ $class = ''; } if(isset($s['tr_class'])){ $tr_class = $s['tr_class']; }else{ $tr_class = ''; } if(isset($s['max_file_size'])){ $max_file_size = $s['max_file_size']; }else{ $max_file_size = ''; } if(isset($s['select_all'])){ $select_all = $s['select_all']; }else{ $select_all = false; } if(isset($s['default_value'])){ $default_value = $s['default_value']; }else{ $default_value = ''; } if( isset( $s['style'] ) ){ $style = $s['style']; }else{ $style = ''; } if(isset($s['size'])){ $size = $s['size']; }else{ $size = ''; } if( is_array( $name_array ) ){ $tmp = ''; foreach( $name_array as $n ){ if( $tmp == '' ){ if( isset( $current_settings[$n] ) ){ $tmp = $current_settings[$n]; } }else{ if( isset( $tmp[$n] ) ){ $tmp = $tmp[$n]; } } } $value = $tmp; }else{ if(isset($current_settings[$name])){ if(is_array($current_settings[$name])){ $value = ninja_forms_stripslashes_deep($current_settings[$name]); }else{ $value = stripslashes($current_settings[$name]); } }else{ $value = ''; } } if( $value == '' ){ $value = $default_value; } ?> <tr <?php if( $tr_class != '' ){ ?>class="<?php echo $tr_class;?>"<?php } ?> <?php if( $style != '' ){ ?> style="<?php echo $style;?>"<?php }?>> <?php if ( $s['type'] == 'desc' AND ! $label ) { ?> <td colspan="2"> <?php } else { ?> <th scope="row"> <label for="<?php echo $name;?>"><?php echo $label;?></label> </th> <td> <?php } ?> <?php switch( $s['type'] ){ case 'text': $value = ninja_forms_esc_html_deep( $value ); ?> <input type="text" class="code widefat <?php echo $class;?>" name="<?php echo $name;?>" id="<?php echo $name;?>" value="<?php echo $value;?>" /> <?php if( $help_text != ''){ ?> <a href="#" class="tooltip"> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""> <span> <img class="callout" src="<?php echo NINJA_FORMS_URL;?>/images/callout.gif" /> <?php echo $help_text;?> </span> </a> <?php } break; case 'select': ?> <select name="<?php echo $name;?>" id="<?php echo $name;?>" class="<?php echo $class;?>"> <?php if( is_array( $s['options']) AND !empty( $s['options'] ) ){ foreach( $s['options'] as $option ){ ?> <option value="<?php echo $option['value'];?>" <?php selected($value, $option['value']); ?>><?php echo $option['name'];?></option> <?php } } ?> </select> <?php if( $help_text != ''){ ?> <a href="#" class="tooltip"> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""> <span> <img class="callout" src="<?php echo NINJA_FORMS_URL;?>/images/callout.gif" /> <?php echo $help_text;?> </span> </a> <?php } break; case 'multi_select': if( $value == '' ){ $value = array(); } ?> <input type="hidden" name="<?php echo $name;?>" value=""> <select name="<?php echo $name;?>[]" id="<?php echo $name;?>" class="<?php echo $class;?>" multiple="multiple" size="<?php echo $size;?>"> <?php if( is_array( $s['options']) AND !empty( $s['options'] ) ){ foreach( $s['options'] as $option ){ ?> <option value="<?php echo $option['value'];?>" <?php selected( in_array( $option['value'], $value ) ); ?>><?php echo $option['name'];?></option> <?php } } ?> </select> <?php if( $help_text != ''){ ?> <a href="#" class="tooltip"> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""> <span> <img class="callout" src="<?php echo NINJA_FORMS_URL;?>/images/callout.gif" /> <?php echo $help_text;?> </span> </a> <?php } break; case 'checkbox': ?> <input type="hidden" name="<?php echo $name;?>" value="0"> <input type="checkbox" name="<?php echo $name;?>" value="1" <?php checked($value, 1);?> id="<?php echo $name;?>" class="<?php echo $class;?>"> <?php if( $help_text != ''){ ?> <a href="#" class="tooltip"> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""> <span> <img class="callout" src="<?php echo NINJA_FORMS_URL;?>/images/callout.gif" /> <?php echo $help_text;?> </span> </a> <?php } break; case 'checkbox_list': if( $value == '' ){ $value = array(); } ?> <input type="hidden" name="<?php echo $name;?>" value=""> <?php if( $select_all ){ ?> <label> <input type="checkbox" name="" value="" id="<?php echo $name;?>_select_all" class="ninja-forms-select-all" title="ninja-forms-<?php echo $name;?>"> - <?php _e( 'Select All', 'ninja-forms' );?> </label> <?php }else{ if( is_array( $s['options'] ) AND isset( $s['options'][0] ) ){ $option_name = $s['options'][0]['name']; $option_value = $s['options'][0]['value']; ?> <label> <input type="checkbox" class="ninja-forms-<?php echo $name;?> <?php echo $class;?>" name="<?php echo $name;?>[]" value="<?php echo $option_value;?>" <?php checked( in_array( $option_value, $value ) );?> id="<?php echo $option_name;?>"> <?php echo $option_name;?> </label> <?php } } ?> <?php if( is_array( $s['options'] ) AND !empty( $s['options'] ) ){ $x = 0; foreach( $s['options'] as $option ){ if( ( !$select_all AND $x > 0 ) OR $select_all ){ $option_name = $option['name']; $option_value = $option['value']; ?> <label> <input type="checkbox" class="ninja-forms-<?php echo $name;?> <?php echo $class;?>" name="<?php echo $name;?>[]" value="<?php echo $option_value;?>" <?php checked( in_array( $option_value, $value ) );?> id="<?php echo $option_name;?>"> <?php echo $option_name;?> </label> <?php } $x++; } } break; case 'radio': if( is_array( $s['options'] ) AND !empty( $s['options'] ) ){ $x = 0; ?> <?php foreach($s['options'] as $option){ ?> <input type="radio" name="<?php echo $name;?>" value="<?php echo $option['value'];?>" id="<?php echo $name."_".$x;?>" <?php checked($value, $option['value']);?> class="<?php echo $class;?>"> <label for="<?php echo $name."_".$x;?>"><?php echo $option['name'];?></label> <?php if( $help_text != ''){ ?> <a href="#" class="tooltip"> <img id="" class='ninja-forms-help-text' src="<?php echo NINJA_FORMS_URL;?>/images/question-ico.gif" title=""> <span> <img class="callout" src="<?php echo NINJA_FORMS_URL;?>/images/callout.gif" /> <?php echo $help_text;?> </span> </a> <?php } ?> <br /> <?php $x++; } } break; case 'textarea': $value = ninja_forms_esc_html_deep( $value ); ?> <textarea name="<?php echo $name;?>" id="<?php echo $name;?>" class="<?php echo $class;?>"><?php echo $value;?></textarea> <?php break; case 'rte': $args = apply_filters( 'ninja_forms_admin_metabox_rte', array() ); wp_editor( $value, $name, $args ); break; case 'file': ?> <input type="hidden" name="MAX_FILE_SIZE" value="<?php echo $max_file_size;?>" /> <input type="file" name="<?php echo $name;?>" id="<?php echo $name;?>" class="<?php echo $class;?>"> <?php break; case 'desc': echo $desc; break; case 'hidden': ?> <input type="hidden" name="<?php echo $name;?>" id="<?php echo $name;?>" value="<?php echo $value;?>"> <?php break; case 'submit': ?> <input type="submit" name="<?php echo $name;?>" class="<?php echo $class; ?>" value="<?php echo $label;?>"> <?php break; default: if( isset( $s['display_function'] ) ){ $s_display_function = $s['display_function']; if( $s_display_function != '' ){ $arguments['form_id'] = $form_id; $arguments['data'] = $current_settings; call_user_func_array( $s_display_function, $arguments ); } } break; } if( $desc != '' AND $s['type'] != 'desc' ){ ?> <p class="description"> <?php echo $desc;?> </p> <?php } echo '</td></tr>'; } } if( $display_function != '' ){ if( $form_id != '' ){ $arguments['form_id'] = $form_id; } $arguments['metabox'] = $metabox; call_user_func_array( $display_function, $arguments ); } if( $display_container ){ ?> </tbody> </table> </div> </div> <?php } }
ibrahimcesar/blumpa-wp
wp-content/plugins/ninja-forms/includes/admin/output-tab-metabox.php
PHP
gpl-2.0
11,378
## # This file is part of WhatWeb and may be subject to # redistribution and commercial restrictions. Please see the WhatWeb # web site for more information on licensing and terms of use. # http://www.morningstarsecurity.com/research/whatweb ## # Version 0.2 # 2011-03-06 # # Updated OS detection ## Plugin.define "SegPub" do author "Brendan Coles <bcoles@gmail.com>" # 2011-02-19 version "0.2" description "SegPub, a hosting solutions provider based in Sydney, Australia - Homepage: http://segpub.net/" # ShodanHQ resuls as at 2011-02-19 # # 458 for Server SegPache # 299 for X-Powered-By SegPub # 273 for X-Powered-By SegPub Server SegPache # 4 for X-Powered-By SegPod # Examples # examples %w| 65.61.176.66 65.61.176.118 66.216.83.164 66.216.83.170 66.216.93.163 66.216.83.165 66.216.103.206 66.216.93.188 66.216.93.186 66.216.103.216 | # Passive # def passive m=[] # Server: SegPache m << { :os=>"FreeBSD7" } if @headers['server'] =~ /SegPache/ # X-Powered-By: SegPub m << { :os=>"FreeBSD7" } if @headers['x-powered-by'] =~ /SegPub/ # X-Powered-By: SegPod m << { :os=>"FreeBSD7" } if @headers['x-powered-by'] =~ /SegPod/ # Return passive matches m end end
tennc/WhatWeb
plugins/SegPub.rb
Ruby
gpl-2.0
1,182
<?php /** * * Ajax Shoutbox extension for the phpBB Forum Software package. * @translated into French by Psykofloyd & Galixte (http://www.galixte.com) * * @copyright (c) 2014 Paul Sohier <http://www.ajax-shoutbox.com> * @license GNU General Public License, version 2 (GPL-2.0) * */ /** * DO NOT CHANGE */ if (!defined('IN_PHPBB')) { exit; } if (empty($lang) || !is_array($lang)) { $lang = array(); } // DEVELOPERS PLEASE NOTE // // All language files should use UTF-8 as their encoding and the files must not contain a BOM. // // Placeholders can now contain order information, e.g. instead of // 'Page %s of %s' you can (and should) write 'Page %1$s of %2$s', this allows // translators to re-order the output of data while ensuring it remains correct // // You do not need this where single placeholders are used, e.g. 'Message %d' is fine // equally where a string contains only two placeholders which are used to wrap text // in a url you again do not need to specify an order e.g., 'Click %sHERE%s' is fine // // Some characters you may want to copy&paste: // ’ « » “ ” … // $lang = array_merge( $lang, array( 'LOG_AJAX_SHOUTBOX_ERROR' => '<strong>Une erreur s’est produite durant l’envoi de votre message au serveur.</strong>', 'LOG_AJAX_SHOUTBOX_PRUNED' => '<strong>La shoutbox a été nettoyée et %d de ses messages ont été supprimés.</strong>', 'LOG_AJAX_SHOUTBOX_CONFIG_SETTINGS' => '<strong>Les paramètres de la shoutbox Ajax ont été mis à jour.</strong>', 'ACP_AJAX_SHOUTBOX' => 'Shoutbox Ajax', 'ACP_AJAX_SHOUTBOX_SETTINGS' => 'Paramètres de la shoutbox', ) );
alhitary/ajax-shoutbox-ext
language/fr/info_acp_ajaxshoutbox.php
PHP
gpl-2.0
1,648
/* * Media Plugin for FCKeditor 2.5 SVN * Copyright (C) 2007 Riceball LEE (riceballl@hotmail.com) * * == BEGIN LICENSE == * * Licensed under the terms of any of the following licenses at your * choice: * * - GNU General Public License Version 2 or later (the "GPL") * http://www.gnu.org/licenses/gpl.html * * - GNU Lesser General Public License Version 2.1 or later (the "LGPL") * http://www.gnu.org/licenses/lgpl.html * * - Mozilla Public License Version 1.1 or later (the "MPL") * http://www.mozilla.org/MPL/MPL-1.1.html * * == END LICENSE == * * Scripts related to the Media dialog window (see fck_media.html). */ var cWindowMediaPlayer = 0 , cRealMediaPlayer = 1 , cQuickTimePlayer = 2 , cFlashPlayer = 3 , cShockwavePlayer = 4 , cDefaultMediaPlayer = cWindowMediaPlayer ; var cFckMediaElementName = 'fckmedia'; //embed | object | fckmedia var cMediaTypeAttrName = 'mediatype'; //lowerCase only!! var cWMp6Compatible = false; //const cDefaultMediaPlayer = 0; //!!!DO NOT Use the constant! the IE do not support const! var cMediaPlayerTypes = ['application/x-mplayer2', 'audio/x-pn-realaudio-plugin', 'video/quicktime', 'application/x-shockwave-flash', 'application/x-director'] , cMediaPlayerClassId = [cWMp6Compatible? 'clsid:05589FA1-C356-11CE-BF01-00AA0055595A' : 'clsid:6BF52A52-394A-11D3-B153-00C04F79FAA6', 'clsid:CFCDAA03-8BE4-11cf-B84B-0020AFBBCCFA' , 'clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B', 'clsid:D27CDB6E-AE6D-11cf-96B8-444553540000' , 'clsid:166B1BCA-3F9C-11CF-8075-444553540000' ] , cMediaPlayerCodebase = ['http://microsoft.com/windows/mediaplayer/en/download/', 'http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab' , 'http://www.apple.com/quicktime/download/', 'http://www.macromedia.com/go/getflashplayer', 'http://download.macromedia.com/pub/shockwave/cabs/director/sw.cab' ] ; var cFCKMediaObjectAttrs = {width:1, height:1, align:1, id:1, name:1, 'class':1, className:1, style:1, title:1}; //the 'class' is keyword in IE!! //there are not object params in it. cFCKMediaSkipParams = {pluginspage:1, type:1}; cFCKMediaParamPrefix = 'MediaParam_'; var oWindowMediaPlayer = {id: cWindowMediaPlayer, type: cMediaPlayerTypes[cWindowMediaPlayer], ClsId: cMediaPlayerClassId[cWindowMediaPlayer], Codebase: cMediaPlayerCodebase[cWindowMediaPlayer] , Params: {autostart:true, enabled:true, enablecontextmenu:true, fullscreen:false, invokeurls:true, mute:false , stretchtofit:false, windowlessvideo:false, balance:'', baseurl:'', captioningid:'', currentmarker:'' , currentposition:'', defaultframe:'', playcount:'', rate:'', uimode:'', volume:'' } }; oRealMediaPlayer = {id: cRealMediaPlayer, type: cMediaPlayerTypes[cRealMediaPlayer], ClsId: cMediaPlayerClassId[cRealMediaPlayer], Codebase: cMediaPlayerCodebase[cRealMediaPlayer] , Params: {autostart:true, loop:false, autogotourl:true, center:false, imagestatus:true, maintainaspect:false , nojava:false, prefetch:true, shuffle:false, console:'', controls:'', numloop:'', scriptcallbacks:'' } }; oQuickTimePlayer = {id: cQuickTimePlayer, type: cMediaPlayerTypes[cQuickTimePlayer], ClsId: cMediaPlayerClassId[cQuickTimePlayer], Codebase: cMediaPlayerCodebase[cQuickTimePlayer] , Params: {autoplay:true, loop:false, cache:false, controller:true, correction:['none', 'full'], enablejavascript:false , kioskmode:false, autohref:false, playeveryframe:false, targetcache:false, scale:'', starttime:'', endtime:'', target:'', qtsrcchokespeed:'' , volume:'', qtsrc:'' } }; oFlashPlayer = {id: cFlashPlayer, type: cMediaPlayerTypes[cFlashPlayer], ClsId: cMediaPlayerClassId[cFlashPlayer], Codebase: cMediaPlayerCodebase[cFlashPlayer] , Params: {play:true, loop:false, menu:true, swliveconnect:true, quality:'', scale:['showall','noborder','exactfit'], salign:'', wmode:'', base:'' , flashvars:'' } }; oShockwavePlayer = {id: cShockwavePlayer, type: cMediaPlayerTypes[cShockwavePlayer], ClsId: cMediaPlayerClassId[cShockwavePlayer], Codebase: cMediaPlayerCodebase[cShockwavePlayer] , Params: {autostart:true, sound:true, progress:false, swliveconnect:false, swvolume:'', swstretchstyle:'', swstretchhalign:'', swstretchvalign:'' } }; var oFCKMediaPlayers = [oWindowMediaPlayer, oRealMediaPlayer, oQuickTimePlayer, oFlashPlayer, oShockwavePlayer]; String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g,""); } String.prototype.ltrim = function() { return this.replace(/^\s+/,""); } String.prototype.rtrim = function() { return this.replace(/\s+$/,""); } function debugListMember(o) { var s = '\n'; if (typeof(o) == 'object') s +=o.toSource(); else s+= o; return s; } function GetMediaPlayerObject(aMediaType) { for (i = 0; i < cMediaPlayerTypes.length; i++ ) if (aMediaType.toLowerCase() == cMediaPlayerTypes[i]) return oFCKMediaPlayers[i]; return oFCKMediaPlayers[cDefaultMediaPlayer]; } function GetMediaPlayerTypeId(aMediaType) { for (i = 0; i < cMediaPlayerTypes.length; i++ ) if (aMediaType.toLowerCase() == cMediaPlayerTypes[i]) return i; return cDefaultMediaPlayer; } function isInt(aStr) { var i = parseInt(aStr); if (isNaN(i)) return false; i = i.toString(); return (i == aStr); } function DequotedStr(aStr) { aStr = aStr.trim(); //aStr.replace(/^(['"])(.*?)(\1)$/g, '$2'); if (aStr.length > 2) { if (aStr.charAt(0) == '"' && aStr.charAt(aStr.length-1) == '"' ) aStr = aStr.substring(1,aStr.length-1); else if (aStrcharAt(0) == '\'' && aStr.charAt(aStr.length-1) == '\'' ) aStr = aStr.substring(1,aStr.length-1); } //alert(aStr+ ': dd:'+aStr.charAt(0)+ aStr.charAt(aStr.length-1)); return aStr; } function WrapObjectToMedia(html, aMediaElementName) { //check media first function _ConvertMedia( m, params ) { //split params to array m = params; var params = params.match(/[\s]*(.+?)=['"](.*?)['"][\s]*/gi); var vObjectAttrs = ''; var Result = ''; var vParamName, vParamValue; var vIsMedia = false; for (var i = 0; i < params.length; i++) { vPos = params[i].indexOf('='); vParamName = params[i].substring(0, vPos).trim(); vParamName = vParamName.toLowerCase(); vParamValue = params[i].substring(vPos+1); vParamValue = DequotedStr(vParamValue); if (vParamName == cMediaTypeAttrName) { //alert(vParamName+':'+vParamValue); if (isInt(vParamValue)) { vIsMedia = true; vObjectAttrs += ' '+ cMediaTypeAttrName + '="' + vParamValue + '"'; vObjectAttrs += ' classid="' + oFCKMediaPlayers[vParamValue].ClsId + '"'; vObjectAttrs += ' codebase="' + oFCKMediaPlayers[vParamValue].Codebase + '"'; }else { break; } } else if (cFCKMediaObjectAttrs[vParamName]) { vObjectAttrs += ' ' + vParamName + '="' + vParamValue + '"'; } else if (!cFCKMediaSkipParams[vParamName]) { Result += '<param name="' + vParamName + '" value="' + vParamValue + '"/>'; } } //for //wrap the <object> tag to <embed> if (vIsMedia) { Result = '<object' + vObjectAttrs + '>' + Result + '<embed' + m + '></embed></object>'; //alert(Result); return Result; } } if (aMediaElementName == '') aMediaElementName = cFckMediaElementName; var regexMedia = new RegExp( '<'+aMediaElementName+'(.+?)><\/'+aMediaElementName+'>', 'gi' ); //var regexMedia = /<fckMedia\s+(.+?)><\/fckMedia>/gi; //alert('b:'+html); return html.replace( regexMedia, _ConvertMedia ) ; }
zy73122/table2form
tools/fckeditor/editor/plugins/Media/js/fck_media_inc.js
JavaScript
gpl-2.0
7,657
<?php class FeatureToc { var $_anchor_locator; var $_document_updater; function FeatureToc() { $this->set_anchor_locator(new FeatureTocAnchorLocatorHeaders()); $this->set_document_updater(new FeatureTocDocumentUpdaterPrependPage()); } function handle_after_parse($params) { $pipeline =& $params['pipeline']; $document =& $params['document']; $media =& $params['media']; $toc =& $this->find_toc_anchors($pipeline, $media, $document); $this->update_document($toc, $pipeline, $media, $document); } function handle_before_document($params) { $pipeline =& $params['pipeline']; $document =& $params['document']; $media =& $params['media']; $page_heights =& $params['page-heights']; $toc =& $this->find_toc_anchors($pipeline, $media, $document); $this->update_page_numbers($toc, $pipeline, $document, $page_heights, $media); } function &find_toc_anchors(&$pipeline, &$media, &$document) { $locator =& $this->get_anchor_locator(); $toc =& $locator->run($pipeline, $media, $document); return $toc; } function &get_anchor_locator() { return $this->_anchor_locator; } function &get_document_updater() { return $this->_document_updater; } function guess_page(&$element, $page_heights, &$media) { $page_index = 0; $bottom = mm2pt($media->height() - $media->margins['top']); do { $bottom -= $page_heights[$page_index]; $page_index ++; } while ($element->get_top() < $bottom); return $page_index; } function install(&$pipeline, $params) { $dispatcher =& $pipeline->get_dispatcher(); $dispatcher->add_observer('after-parse', array(&$this, 'handle_after_parse')); $dispatcher->add_observer('before-document', array(&$this, 'handle_before_document')); if (isset($params['location'])) { switch ($params['location']) { case 'placeholder': $this->set_document_updater(new FeatureTocDocumentUpdaterPlaceholder()); break; case 'before': $this->set_document_updater(new FeatureTocDocumentUpdaterPrependPage()); break; case 'after': default: $this->set_document_updater(new FeatureTocDocumentUpdaterAppendPage()); break; }; }; } function set_anchor_locator(&$locator) { $this->_anchor_locator =& $locator; } function set_document_updater(&$updater) { $this->_document_updater =& $updater; } function make_toc_name_element_id($index) { return sprintf('html2ps-toc-name-%d', $index); } function make_toc_page_element_id($index) { return sprintf('html2ps-toc-page-%d', $index); } function update_document(&$toc, &$pipeline, &$media, &$document) { $code = ''; $index = 1; foreach ($toc as $toc_element) { $code .= sprintf(' <div id="html2ps-toc-%s" class="html2ps-toc-wrapper html2ps-toc-%d-wrapper"> <div id="%s" class="html2ps-toc-name html2ps-toc-%d-name"><a href="#%s">%s</a></div> <div id="%s" class="html2ps-toc-page html2ps-toc-%d-page">0000</div> </div>%s', $index, $toc_element['level'], $this->make_toc_name_element_id($index), $toc_element['level'], $toc_element['anchor'], $toc_element['name'], $this->make_toc_page_element_id($index), $toc_element['level'], "\n"); $index++; }; $toc_box_document =& $pipeline->parser->process('<body><div>'.$code.'</div></body>', $pipeline, $media); $context =& new FlowContext(); $pipeline->layout_engine->process($toc_box_document, $media, $pipeline->get_output_driver(), $context); $toc_box =& $toc_box_document->content[0]; $document_updater =& $this->get_document_updater(); $document_updater->run($toc_box, $media, $document); } function update_page_numbers(&$toc, &$pipeline, &$document, &$page_heights, &$media) { for ($i = 0, $size = count($toc); $i < $size; $i++) { $toc_element =& $document->get_element_by_id($this->make_toc_page_element_id($i+1)); $element =& $toc[$i]['element']; $toc_element->content[0]->content[0]->words[0] = $this->guess_page($element, $page_heights, $media); }; } } class FeatureTocAnchorLocatorHeaders { var $_locations; var $_last_generated_anchor_id; function FeatureTocAnchorLocatorHeaders() { $this->set_locations(array()); $this->_last_generated_anchor_id = 0; } function generate_toc_anchor_id() { $this->_last_generated_anchor_id++; $id = $this->_last_generated_anchor_id; return sprintf('html2ps-toc-element-%d', $id); } function get_locations() { return $this->_locations; } function process_node($params) { $node =& $params['node']; if (preg_match('/^h(\d)$/i', $node->get_tagname(), $matches)) { if (!$node->get_id()) { $id = $this->generate_toc_anchor_id(); $node->set_id($id); }; $this->_locations[] = array('name' => $node->get_content(), 'level' => (int)$matches[1], 'anchor' => $node->get_id(), 'element' => &$node); }; } function &run(&$pipeline, &$media, &$document) { $this->set_locations(array()); $walker =& new TreeWalkerDepthFirst(array(&$this, 'process_node')); $walker->run($document); $locations = $this->get_locations(); foreach ($locations as $location) { $location['element']->setCSSProperty(CSS_HTML2PS_LINK_DESTINATION, $location['element']->get_id()); // $Id: toc.php 5805 2008-08-24 20:31:37Z zeke $ // $pipeline->output_driver->anchors[$id] =& $location['element']->make_anchor($media, $id); }; return $locations; } function set_locations($locations) { $this->_locations = $locations; } } class FeatureTocDocumentUpdaterAppendPage { function FeatureTocDocumentUpdaterAppendPage() { } function run(&$toc_box, &$media, &$document) { $toc_box->setCSSProperty(CSS_PAGE_BREAK_BEFORE, PAGE_BREAK_ALWAYS); $document->append_child($toc_box); } } class FeatureTocDocumentUpdaterPrependPage { function FeatureTocDocumentUpdaterPrependPage() { } function run(&$toc_box, &$media, &$document) { $toc_box->setCSSProperty(CSS_PAGE_BREAK_AFTER, PAGE_BREAK_ALWAYS); $document->insert_before($toc_box, $document->content[0]); } } class FeatureTocDocumentUpdaterPlaceholder { function FeatureTocDocumentUpdaterPlaceholder() { } function run(&$toc_box, &$media, &$document) { $placeholder =& $document->get_element_by_id('html2ps-toc'); $placeholder->append_child($toc_box); } } ?>
diedsmiling/busenika
lib/html2pdf/features/toc.php
PHP
gpl-2.0
6,787
jQuery(document).ready(function($){ jQuery('.ifeature-tabbed-wrap').tabs(); }); jQuery(document).ready(function($){ $("ul").parent("li").addClass("parent"); }); jQuery(document).ready(function($){ $("#gallery ul a:hover img").css("opacity", 1); $("#portfolio_wrap .portfolio_caption").css("opacity", 0); $("#portfolio_wrap a").hover(function(){ $(this).children("img").fadeTo("fast", 0.6); $(this).children(".portfolio_caption").fadeTo("fast", 1.0); },function(){ $(this).children("img").fadeTo("fast", 1.0); $(this).children(".portfolio_caption").fadeTo("fast", 0); }); $(".featured-image img").hover(function(){ $(this).fadeTo("fast", 0.75); },function(){ $(this).fadeTo("fast", 1.0); }); });
cyberchimps/ifeaturepro4
core/library/js/menu.js
JavaScript
gpl-2.0
744
var Models = window.Models || {}; jQuery.noConflict(); Models.Grid = function(w, h, el) { this.width = w; this.height = h; this.blocks = []; this.field = new Models.Block(w, h, 0, 0); this.element = el; this.place = function(block, x, y, html, creationIndex) { block.setPosition(x, y); return this._induct(block); }; this.add = function(block) { var grid = this; var opening = _(this.field.units()).detect(function(unit) { return grid.canFit(block, unit.x, unit.y); }); return this._induct(block); }; this._induct = function(block) { if(this.canFit(block)) { this.blocks.push(block); this.renderChild(block); if(this.isComplete()) { this.element.trigger('complete'); } return this; } return false; }; this.removeBlockWithIndex = function(blockIndex) { if (this.blocks.length == 1) { _(this.blocks).each(function(block) { block.destroy(); }); this.blocks = []; return this; } var indexToRemove = false; var cIndex = 0; _(this.blocks).each(function(block) { if (block.creationIndex == blockIndex) { indexToRemove = cIndex; block.destroy(); } cIndex++; }); if (indexToRemove !== false) { this.blocks.splice(indexToRemove, 1); } return this; }; this.clear = function() { _(this.blocks).each(function(block) { block.destroy(); }); this.blocks = []; return this; }; this.canFit = function(block, blockX, blockY) { block.setPosition(blockX, blockY); for (var i = 0; i < this.blocks.length; i++) { if(this.blocks[i].overlapsAny(block)) { return false; } } return block.overlappedFullyBy(this.field); }; this.blockAtPosition = function(unit) { var testBlock = new Models.Block(1, 1, unit.x, unit.y); return _(this.blocks).detect(function(block){ return block.overlapsAny(testBlock); }); }; this.blocksOverlappedByBlock = function(overlapper) { var grid = this; return _(this.blocks).select(function(block) { return block.overlapsAny(overlapper); }); }; this.isComplete = function() { var gridUnitCount = this.field.units().length; var blockUnitCount = _.reduce(this.blocks, function(memo, block) { return memo + block.units().length; }, 0); return gridUnitCount == blockUnitCount; }; this.render = function() { if (_(this.element).isUndefined()) { this.element = jQuery(document.createElement('div')).addClass('grid'); _.each(this.blocks, function(block) { this.renderChild(block); }, this); } return this.element; }; this.renderChild = function(block) { this.render(); this.element.append(block.render()); }; };
m-godefroid76/devrestofactory
wp-content/themes/berg-wp/admin/includes/js/grid.js
JavaScript
gpl-2.0
2,636
@extends('emails.layout') @section('header') {{HTML::linkRoute('user-request-list', 'My Request')}} | {{HTML::linkRoute('user-profile-form', 'Profile')}} @stop @section('title') Respon dari admin @stop @section('description') Halo {{{$name}}}, <br> Permohonan informasi anda direspon oleh admin,<br> <br> Untuk melihat detail respon silahkan klik link berikut:<br> <h3>{{HTML::link($link, 'Detail respon')}}</h3> <br><br> Hormat kami,<br><br> {{{Config::get('setting.site_name')}}} @stop
arisst/kip
app/views/emails/response.blade.php
PHP
gpl-2.0
499
<?php /** * Modern Menu Widget * * Learn more: http://codex.wordpress.org/Widgets_API * * @package Total * @author Alexander Clarke * @copyright Copyright (c) 2014, Symple Workz LLC * @link http://www.wpexplorer.com * @since Total 1.6.0 */ if ( ! class_exists( 'WPEX_Modern_Menu' ) ) { class WPEX_Modern_Menu extends WP_Widget { /** * Register widget with WordPress. * * @since 1.0.0 */ function __construct() { parent::__construct( 'wpex_modern_menu', WPEX_THEME_BRANDING . ' - '. __( 'Modern Sidebar Menu', 'wpex' ), array( 'description' => __( 'A modern looking custom menu widget.', 'wpex' ) ) ); } /** * Front-end display of widget. * * @see WP_Widget::widget() * @since 1.0.0 * * @param array $args Widget arguments. * @param array $instance Saved values from database. */ function widget( $args, $instance ) { // Set vars $title = isset( $instance['title'] ) ? apply_filters( 'widget_title', $instance['title'] ) : __( 'Recent Posts', 'wpex' ); $nav_menu = ! empty( $instance['nav_menu'] ) ? wp_get_nav_menu_object( $instance['nav_menu'] ) : false; // Important hook echo $args['before_widget']; // Display title if ( $title ) { echo $args['before_title'] . $title . $args['after_title']; } if ( $nav_menu ) { echo wp_nav_menu( array( 'menu_class' => 'modern-menu-widget', 'fallback_cb' => '', 'menu' => $nav_menu, ) ); } // Important hook echo $args['after_widget']; } /** * Sanitize widget form values as they are saved. * * @see WP_Widget::update() * @since 1.0.0 * * @param array $new_instance Values just sent to be saved. * @param array $old_instance Previously saved values from database. * * @return array Updated safe values to be saved. */ function update( $new_instance, $old_instance ) { $instance = array(); $instance['title'] = ( ! empty( $new_instance['title'] ) ) ? strip_tags( $new_instance['title'] ) : ''; $instance['nav_menu'] = ( ! empty( $new_instance['nav_menu'] ) ) ? strip_tags( $new_instance['nav_menu'] ) : ''; return $instance; } /** * Back-end widget form. * * @see WP_Widget::form() * @since 1.0.0 * * @param array $instance Previously saved values from database. */ public function form( $instance ) { // Vars $title = isset( $instance['title'] ) ? $instance['title'] : __( 'Browse', 'wpex' ); $nav_menu = isset( $instance['nav_menu'] ) ? $instance['nav_menu'] : ''; ?> <p> <label for="<?php echo $this->get_field_id( 'title' ); ?>"><?php _e('Title:', 'wpex'); ?></label> <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title','wpex'); ?>" type="text" value="<?php echo $title; ?>" /> </p> <p> <label for="<?php echo $this->get_field_id( 'nav_menu' ); ?>"><?php _e( 'Select Menu:', 'wpex' ); ?></label> <select id="<?php echo $this->get_field_id( 'nav_menu' ); ?>" name="<?php echo $this->get_field_name( 'nav_menu' ); ?>"> <?php // Get all menus $menus = get_terms( 'nav_menu', array( 'hide_empty' => true ) ); // Loop through menus to add options if ( ! empty( $menus ) ) { $nav_menu = $nav_menu ? $nav_menu : ''; foreach ( $menus as $menu ) { echo '<option value="' . $menu->term_id . '"' . selected( $nav_menu, $menu->term_id, false ) . '>'. $menu->name . '</option>'; } } ?> </select> </p> <?php } } } // Register the WPEX_Tabs_Widget custom widget if ( ! function_exists( 'register_wpex_modern_menu' ) ) { function register_wpex_modern_menu() { register_widget( 'WPEX_Modern_Menu' ); } } add_action( 'widgets_init', 'register_wpex_modern_menu' );
naoyawada/Concurrent
wp-content/themes/Total/framework/widgets/widget-modern-menu.php
PHP
gpl-2.0
3,821
/* * libjingle * Copyright 2004--2005, Google Inc. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * 1. Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * 3. The name of the author may not be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR IMPLIED * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO * EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #if defined(_MSC_VER) && _MSC_VER < 1300 #pragma warning(disable:4786) #endif #include "talk/base/asyncudpsocket.h" #include "talk/base/logging.h" #include <cassert> #include <cstring> #include <iostream> #if defined(_MSC_VER) && _MSC_VER < 1300 namespace std { using ::strerror; } #endif #ifdef POSIX extern "C" { #include <errno.h> } #endif // POSIX namespace cricket { const int BUF_SIZE = 64 * 1024; AsyncUDPSocket::AsyncUDPSocket(AsyncSocket* socket) : AsyncPacketSocket(socket) { size_ = BUF_SIZE; buf_ = new char[size_]; assert(socket_); // The socket should start out readable but not writable. socket_->SignalReadEvent.connect(this, &AsyncUDPSocket::OnReadEvent); } AsyncUDPSocket::~AsyncUDPSocket() { delete [] buf_; } void AsyncUDPSocket::OnReadEvent(AsyncSocket* socket) { assert(socket == socket_); SocketAddress remote_addr; int len = socket_->RecvFrom(buf_, size_, &remote_addr); if (len < 0) { // TODO: Do something better like forwarding the error to the user. PLOG(LS_ERROR, socket_->GetError()) << "recvfrom"; return; } // TODO: Make sure that we got all of the packet. If we did not, then we // should resize our buffer to be large enough. SignalReadPacket(buf_, (size_t)len, remote_addr, this); } } // namespace cricket
serghei/kde3-kdenetwork
kopete/protocols/jabber/jingle/libjingle/talk/base/asyncudpsocket.cc
C++
gpl-2.0
2,770
<?php /** * This software is intended for use with Oxwall Free Community Software http://www.oxwall.org/ and is * licensed under The BSD license. * --- * Copyright (c) 2011, Oxwall Foundation * All rights reserved. * Redistribution and use in source and binary forms, with or without modification, are permitted provided that the * following conditions are met: * * - Redistributions of source code must retain the above copyright notice, this list of conditions and * the following disclaimer. * * - Redistributions in binary form must reproduce the above copyright notice, this list of conditions and * the following disclaimer in the documentation and/or other materials provided with the distribution. * * - Neither the name of the Oxwall Foundation nor the names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED * AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ /** * Forum topics widget component * * @author Egor Bulgakov <egor.bulgakov@gmail.com> * @package ow.ow_plugins.forum.components * @since 1.0 */ class FORUM_CMP_ForumTopicsWidget extends BASE_CLASS_Widget { private $forumService; /** * Class constructor */ public function __construct( BASE_CLASS_WidgetParameter $paramObj ) { parent::__construct(); if ( false /*!OW::getUser()->isAuthorized('forum', 'view')*/ ) // TODO: implement widget complex solution { $this->setVisible(false); return; } $this->forumService = FORUM_BOL_ForumService::getInstance(); $confTopicCount = (int) $paramObj->customParamList['topicCount']; $confPostLength = (int) $paramObj->customParamList['postLength']; if ( OW::getUser()->isAuthorized('forum') ) { $excludeGroupIdList = array(); } else { $excludeGroupIdList = $this->forumService->getPrivateUnavailableGroupIdList(OW::getUser()->getId()); } $topics = $this->forumService->getLatestTopicList($confTopicCount, $excludeGroupIdList); if ( $topics ) { $this->assign('topics', $topics); $userIds = array(); $groupIds = array(); $toolbars = array(); foreach ( $topics as $topic ) { if ( !in_array($topic['lastPost']['userId'], $userIds) ) { array_push($userIds, $topic['lastPost']['userId']); } if ( !in_array($topic['groupId'], $groupIds) ) { array_push($groupIds, $topic['groupId']); } } $avatars = BOL_AvatarService::getInstance()->getDataForUserAvatars($userIds, true, false); $this->assign('avatars', $avatars); $urls = BOL_UserService::getInstance()->getUserUrlsForList($userIds); // toolbars foreach ( $topics as $key => $topic ) { $userId = $topic['lastPost']['userId']; $toolbars[$topic['lastPost']['postId']][] = array( 'class' => 'ow_icon_control ow_ic_user', 'href' => !empty($urls[$userId]) ? $urls[$userId] : '#', 'label' => !empty($avatars[$userId]['title']) ? $avatars[$userId]['title'] : '' ); $toolbars[$topic['lastPost']['postId']][] = array( 'label' => $topic['lastPost']['createStamp'], 'class' => 'ow_ipc_date' ); } $this->assign('toolbars', $toolbars); $this->assign('postLength', $confPostLength); $groups = $this->forumService->findGroupByIdList($groupIds); $groupList = array(); $sectionIds = array(); foreach ( $groups as $group ) { $groupList[$group->id] = $group; if ( !in_array($group->sectionId, $sectionIds) ) { array_push($sectionIds, $group->sectionId); } } $this->assign('groups', $groupList); $sectionList = $this->forumService->findSectionsByIdList($sectionIds); $this->assign('sections', $sectionList); $tb = array(); if ( OW::getUser()->isAuthorized('forum', 'edit') ) { $tb[] = array( 'label' => OW::getLanguage()->text('forum', 'add_new'), 'href' => OW::getRouter()->urlForRoute('add-topic-default') ); } $tb[] = array( 'label' => OW::getLanguage()->text('forum', 'goto_forum'), 'href' => OW::getRouter()->urlForRoute('forum-default') ); $this->setSettingValue(self::SETTING_TOOLBAR, $tb); } else { if ( !OW::getUser()->isAuthorized('forum', 'edit') ) { $this->setVisible(false); return; } $this->assign('topics', null); } } public static function getSettingList() { $settingList = array(); $settingList['topicCount'] = array( 'presentation' => self::PRESENTATION_NUMBER, 'label' => OW::getLanguage()->text('forum', 'cmp_widget_forum_topics_count'), 'value' => 5 ); $settingList['postLength'] = array( 'presentation' => self::PRESENTATION_NUMBER, 'label' => OW::getLanguage()->text('forum', 'cmp_widget_forum_topics_post_lenght'), 'value' => 50 ); return $settingList; } public static function validateSettingList( $settingList ) { parent::validateSettingList($settingList); $validationMessage = OW::getLanguage()->text('forum', 'cmp_widget_forum_topics_count_msg'); if ( !preg_match('/^\d+$/', $settingList['topicCount']) ) { throw new WidgetSettingValidateException($validationMessage, 'topicCount'); } if ( $settingList['topicCount'] > 20 ) { throw new WidgetSettingValidateException($validationMessage, 'topicCount'); } $validationMessage = OW::getLanguage()->text('forum', 'cmp_widget_forum_topics_post_length_msg'); if ( !preg_match('/^\d+$/', $settingList['postLength']) ) { throw new WidgetSettingValidateException($validationMessage, 'postLength'); } if ( $settingList['postLength'] > 1000 ) { throw new WidgetSettingValidateException($validationMessage, 'postLength'); } } public static function getAccess() { return self::ACCESS_ALL; } public static function getStandardSettingValueList() { return array( self::SETTING_TITLE => OW::getLanguage()->text('forum', 'forum_topics_widget'), self::SETTING_ICON => self::ICON_FILES, self::SETTING_SHOW_TITLE => true ); } }
seret/oxtebafu
ow_plugins/forum/components/forum_topics_widget.php
PHP
gpl-2.0
7,902
<?php class GFSettings{ public static $addon_pages = array(); public static function add_settings_page($name, $handler, $icon_path){ add_action("gform_settings_" . str_replace(" " , "_", $name), $handler); self::$addon_pages[$name] = array("name" => $name, "icon" => $icon_path); } public static function settings_page(){ $addon_name = RGForms::get("addon"); $icon_path = empty($addon_name) ? "" : self::$addon_pages[$addon_name]["icon"]; $page_title = empty($addon_name) ? __("Gravity Forms Settings", "gravityforms") : $addon_name . " " . __("Settings", "gravityforms"); $icon_path = empty($icon_path) ? GFCommon::get_base_url() . "/images/gravity-settings-icon-32.png" : $icon_path; echo GFCommon::get_remote_message(); ?> <link rel="stylesheet" href="<?php echo GFCommon::get_base_url()?>/css/admin.css" /> <div class="wrap"> <img alt="<?php $page_title ?>" src="<?php echo $icon_path?>" style="float:left; margin:15px 7px 0 0;"/> <h2><?php echo $page_title ?></h2> <?php if(!empty(self::$addon_pages)){ ?> <ul class="subsubsub"> <li><a href="?page=gf_settings">Gravity Forms</a> |</li> <?php $count = sizeof(self::$addon_pages); for($i = 0; $i<$count; $i++){ $addon_keys = array_keys(self::$addon_pages); $addon = $addon_keys[$i]; ?> <li><a href="?page=gf_settings&addon=<?php echo urlencode($addon) ?>"><?php echo esc_html($addon) ?></a> <?php echo $i < $count-1 ? "|" : ""?></li> <?php } ?> </ul> <br style="clear:both;"/> <?php } if(empty($addon_name)){ self::gravityforms_settings_page(); } else{ do_action("gform_settings_" . str_replace(" ", "_", $addon_name)); } } public static function gravityforms_settings_page(){ global $wpdb; if(!GFCommon::ensure_wp_version()) return; if(isset($_POST["submit"])){ check_admin_referer('gforms_update_settings', 'gforms_update_settings'); if(!GFCommon::current_user_can_any("gravityforms_edit_settings")) die(__("You don't have adequate permission to edit settings.", "gravityforms")); RGFormsModel::save_key($_POST["gforms_key"]); update_option("rg_gforms_disable_css", $_POST["gforms_disable_css"]); update_option("rg_gforms_enable_html5", $_POST["gforms_enable_html5"]); update_option("rg_gforms_captcha_public_key", $_POST["gforms_captcha_public_key"]); update_option("rg_gforms_captcha_private_key", $_POST["gforms_captcha_private_key"]); update_option("rg_gforms_currency", $_POST["gforms_currency"]); //Updating message because key could have been changed GFCommon::cache_remote_message(); //Re-caching version info $version_info = GFCommon::get_version_info(false); ?> <div class="updated fade" style="padding:6px;"> <?php _e("Settings Updated", "gravityforms"); ?>. </div> <?php } else if(isset($_POST["uninstall"])){ if(!GFCommon::current_user_can_any("gravityforms_uninstall") || (function_exists("is_multisite") && is_multisite() && !is_super_admin())) die(__("You don't have adequate permission to uninstall Gravity Forms.", "gravityforms")); //droping all tables RGFormsModel::drop_tables(); //removing options delete_option("rg_form_version"); delete_option("rg_gforms_key"); delete_option("rg_gforms_disable_css"); delete_option("rg_gforms_enable_html5"); delete_option("rg_gforms_captcha_public_key"); delete_option("rg_gforms_captcha_private_key"); delete_option("rg_gforms_message"); delete_option("gf_dismissed_upgrades"); delete_option("rg_gforms_currency"); //removing gravity forms upload folder GFCommon::delete_directory(RGFormsModel::get_upload_root()); //Deactivating plugin $plugin = "gravityforms/gravityforms.php"; deactivate_plugins($plugin); update_option('recently_activated', array($plugin => time()) + (array)get_option('recently_activated')); ?> <div class="updated fade" style="padding:20px;"><?php echo sprintf(__("Gravity Forms have been successfully uninstalled. It can be re-activated from the %splugins page%s.", "gravityforms"), "<a href='plugins.php'>","</a>")?></div> <?php return; } if(!isset($version_info)) $version_info = GFCommon::get_version_info(); ?> <form method="post"> <?php wp_nonce_field('gforms_update_settings', 'gforms_update_settings') ?> <h3><?php _e("General Settings", "gravityforms"); ?></h3> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="gforms_key"><?php _e("Support License Key", "gravityforms"); ?></label> <?php gform_tooltip("settings_license_key") ?></th> <td> <?php $key = GFCommon::get_key(); $key_field = '<input type="password" name="gforms_key" id="gforms_key" style="width:350px;" value="' . $key . '" />'; if($version_info["is_valid_key"]) $key_field .= "&nbsp;<img src='" . GFCommon::get_base_url() ."/images/tick.png' class='gf_keystatus_valid' alt='valid key' title='valid key'/>"; else if (!empty($key)) $key_field .= "&nbsp;<img src='" . GFCommon::get_base_url() ."/images/cross.png' class='gf_keystatus_invalid' alt='invalid key' title='invalid key'/>"; echo apply_filters('gform_settings_key_field', $key_field); ?> <br /> <?php _e("The license key is used for access to automatic upgrades and support.", "gravityforms"); ?> </td> </tr> <tr valign="top"> <th scope="row"><label for="gforms_disable_css"><?php _e("Output CSS", "gravityforms"); ?></label> <?php gform_tooltip("settings_output_css") ?></th> <td> <input type="radio" name="gforms_disable_css" value="0" id="gforms_css_output_enabled" <?php echo get_option('rg_gforms_disable_css') == 1 ? "" : "checked='checked'" ?> /> <?php _e("Yes", "gravityforms"); ?>&nbsp;&nbsp; <input type="radio" name="gforms_disable_css" value="1" id="gforms_css_output_disabled" <?php echo get_option('rg_gforms_disable_css') == 1 ? "checked='checked'" : "" ?> /> <?php _e("No", "gravityforms"); ?><br /> <?php _e("Set this to No if you would like to disable the plugin from outputting the form CSS.", "gravityforms"); ?> </td> </tr> <tr valign="top"> <th scope="row"><label for="gforms_enable_html5"><?php _e("Output HTML5", "gravityforms"); ?></label> <?php gform_tooltip("settings_html5") ?></th> <td> <input type="radio" name="gforms_enable_html5" value="1" <?php echo get_option('rg_gforms_enable_html5') == 1 ? "checked='checked'" : "" ?> id="gforms_enable_html5"/> <?php _e("Yes", "gravityforms"); ?>&nbsp;&nbsp; <input type="radio" name="gforms_enable_html5" value="0" <?php echo get_option('rg_gforms_enable_html5') == 1 ? "" : "checked='checked'" ?> /><?php _e("No", "gravityforms"); ?><br /> <?php _e("Set this to No if you would like to disable the plugin from outputting HTML5 form fields.", "gravityforms"); ?> </td> </tr> <tr valign="top"> <th scope="row"><label for="gforms_currency"><?php _e("Currency", "gravityforms"); ?></label> <?php gform_tooltip("settings_currency") ?></th> <td> <select id="gforms_currency" name="gforms_currency"> <?php require_once("currency.php"); $current_currency = GFCommon::get_currency(); foreach(RGCurrency::get_currencies() as $code => $currency){ ?> <option value="<?php echo $code ?>" <?php echo $current_currency == $code ? "selected='selected'" : "" ?>><?php echo $currency["name"]?></option> <?php } ?> </select> </td> </tr> </table> <div class="hr-divider"></div> <h3><?php _e("reCAPTCHA Settings", "gravityforms"); ?></h3> <p style="text-align: left;"><?php _e("Gravity Forms integrates with reCAPTCHA, a free CAPTCHA service that helps to digitize books while protecting your forms from spam bots. ", "gravityforms"); ?><a href="http://www.google.com/recaptcha/" target="_blank"><?php _e("Read more about reCAPTCHA", "gravityforms"); ?></a>.</p> <table class="form-table"> <tr valign="top"> <th scope="row"><label for="gforms_captcha_public_key"><?php _e("reCAPTCHA Public Key", "gravityforms"); ?></label> <?php gform_tooltip("settings_recaptcha_public") ?></th> <td> <input type="text" name="gforms_captcha_public_key" style="width:350px;" value="<?php echo get_option("rg_gforms_captcha_public_key") ?>" /><br /> <?php _e("Required only if you decide to use the reCAPTCHA field.", "gravityforms"); ?> <?php printf(__("%sSign up%s for a free account to get the key.", "gravityforms"), '<a target="_blank" href="http://www.google.com/recaptcha/whyrecaptcha">', '</a>'); ?> </td> </tr> <tr valign="top"> <th scope="row"><label for="gforms_captcha_private_key"><?php _e("reCAPTCHA Private Key", "gravityforms"); ?></label> <?php gform_tooltip("settings_recaptcha_private") ?></th> <td> <input type="text" name="gforms_captcha_private_key" style="width:350px;" value="<?php echo esc_attr(get_option("rg_gforms_captcha_private_key")) ?>" /><br /> <?php _e("Required only if you decide to use the reCAPTCHA field.", "gravityforms"); ?> <?php printf(__("%sSign up%s for a free account to get the key.", "gravityforms"), '<a target="_blank" href="http://www.google.com/recaptcha/whyrecaptcha">', '</a>'); ?> </td> </tr> </table> <?php if(GFCommon::current_user_can_any("gravityforms_edit_settings")){ ?> <br/><br/> <p class="submit" style="text-align: left;"> <?php $save_button = '<input type="submit" name="submit" value="' . __("Save Settings", "gravityforms"). '" class="button-primary gf_settings_savebutton"/>'; echo apply_filters("gform_settings_save_button", $save_button); ?> </p> <?php } ?> </form> <div id='gform_upgrade_license' style="display:none;"></div> <script type="text/javascript"> jQuery(document).ready(function(){ jQuery.post(ajaxurl,{ action:"gf_upgrade_license", gf_upgrade_license: "<?php echo wp_create_nonce("gf_upgrade_license") ?>", cookie: encodeURIComponent(document.cookie)}, function(data){ if(data.trim().length > 0) jQuery("#gform_upgrade_license").replaceWith(data); } ); }); </script> <div class="hr-divider"></div> <h3><?php _e("Installation Status", "gravityforms"); ?></h3> <table class="form-table"> <tr valign="top"> <th scope="row"><label><?php _e("PHP Version", "gravityforms"); ?></label></th> <td class="installation_item_cell"> <strong><?php echo phpversion(); ?></strong> </td> <td> <?php if(version_compare(phpversion(), '5.0.0', '>')){ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/tick.png"/> <?php } else{ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/cross.png"/> <span class="installation_item_message"><?php _e("Gravity Forms requires PHP 5 or above.", "gravityforms"); ?></span> <?php } ?> </td> </tr> <tr valign="top"> <th scope="row"><label><?php _e("MySQL Version", "gravityforms"); ?></label></th> <td class="installation_item_cell"> <strong><?php echo $wpdb->db_version();?></strong> </td> <td> <?php if(version_compare($wpdb->db_version(), '5.0.0', '>')){ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/tick.png"/> <?php } else{ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/cross.png"/> <span class="installation_item_message"><?php _e("Gravity Forms requires MySQL 5 or above.", "gravityforms"); ?></span> <?php } ?> </td> </tr> <tr valign="top"> <th scope="row"><label><?php _e("WordPress Version", "gravityforms"); ?></label></th> <td class="installation_item_cell"> <strong><?php echo get_bloginfo("version"); ?></strong> </td> <td> <?php if(version_compare(get_bloginfo("version"), '2.8.0', '>')){ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/tick.png"/> <?php } else{ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/cross.png"/> <span class="installation_item_message"><?php _e("Gravity Forms requires WordPress 2.8 or above.", "gravityforms"); ?></span> <?php } ?> </td> </tr> <tr valign="top"> <th scope="row"><label><?php _e("Gravity Forms Version", "gravityforms"); ?></label></th> <td class="installation_item_cell"> <strong><?php echo GFCommon::$version ?></strong> </td> <td> <?php if(version_compare(GFCommon::$version, $version_info["version"], '>=')){ ?> <img src="<?php echo GFCommon::get_base_url() ?>/images/tick.png"/> <?php } else{ echo sprintf(__("New version %s available. Automatic upgrade available on the %splugins page%s", "gravityforms"), $version_info["version"], '<a href="plugins.php">', '</a>'); } ?> </td> </tr> </table> <form action="" method="post"> <?php if(GFCommon::current_user_can_any("gravityforms_uninstall") && (!function_exists("is_multisite") || !is_multisite() || is_super_admin())){ ?> <div class="hr-divider"></div> <h3><?php _e("Uninstall Gravity Forms", "gravityforms") ?></h3> <div class="delete-alert alert_red"><h3><?php _e("Warning", "gravityforms") ?></h3><p><?php _e("This operation deletes ALL Gravity Forms data. If you continue, You will not be able to retrieve or restore your forms or entries.", "gravityforms") ?></p> <?php $uninstall_button = '<input type="submit" name="uninstall" value="' . __("Uninstall Gravity Forms", "gravityforms") . '" class="button" onclick="return confirm(\'' . __("Warning! ALL Gravity Forms data, including form entries will be deleted. This cannot be undone. \'OK\' to delete, \'Cancel\' to stop", "gravityforms") . '\');"/>'; echo apply_filters("gform_uninstall_button", $uninstall_button); ?> </div> <?php } ?> </form> <?php } public static function upgrade_license(){ check_ajax_referer('gf_upgrade_license','gf_upgrade_license'); $key = GFCommon::get_key(); $body = "key=$key"; $options = array('method' => 'POST', 'timeout' => 3, 'body' => $body); $options['headers'] = array( 'Content-Type' => 'application/x-www-form-urlencoded; charset=' . get_option('blog_charset'), 'Content-Length' => strlen($body), 'User-Agent' => 'WordPress/' . get_bloginfo("version"), 'Referer' => get_bloginfo("url") ); $request_url = GRAVITY_MANAGER_URL . "/api.php?op=upgrade_message&key=" . GFCommon::get_key(); $raw_response = wp_remote_request($request_url, $options); if ( is_wp_error( $raw_response ) || 200 != $raw_response['response']['code'] ) $message = ""; else $message = $raw_response['body']; //validating that message is a valid Gravity Form message. If message is invalid, don't display anything if(substr($message, 0, 10) != "<!--GFM-->") $message = ""; echo $message; exit; } } ?>
noahjohn9259/emberrcom
wp-content/plugins/gravityforms_1.5.2.8/settings.php
PHP
gpl-2.0
19,359
<?php include_once('../../config/symbini.php'); include_once($SERVER_ROOT.'/content/lang/collections/list.'.$LANG_TAG.'.php'); include_once($SERVER_ROOT.'/classes/OccurrenceListManager.php'); include_once($SERVER_ROOT.'/classes/SOLRManager.php'); $stArrCollJson = $_REQUEST["jsoncollstarr"]; $stArrSearchJson = $_REQUEST["starr"]; $targetTid = $_REQUEST["targettid"]; $occIndex = $_REQUEST['occindex']; $sortField1 = $_REQUEST['sortfield1']; $sortField2 = $_REQUEST['sortfield2']; $sortOrder = $_REQUEST['sortorder']; $stArrSearchJson = str_replace("%apos;","'",$stArrSearchJson); $collStArr = json_decode($stArrCollJson, true); $searchStArr = json_decode($stArrSearchJson, true); if($collStArr && $searchStArr) $stArr = array_merge($searchStArr,$collStArr); if(!$collStArr && $searchStArr) $stArr = $searchStArr; if($collStArr && !$searchStArr) $stArr = $collStArr; if($SOLR_MODE){ $collManager = new SOLRManager(); $collManager->setSearchTermsArr($stArr); $collManager->setSorting($sortField1,$sortField2,$sortOrder); $solrArr = $collManager->getRecordArr($occIndex,1000); $recArr = $collManager->translateSOLRRecList($solrArr); } else{ $collManager = new OccurrenceListManager(false); $collManager->setSearchTermsArr($stArr); $collManager->setSorting($sortField1,$sortField2,$sortOrder); $recArr = $collManager->getRecordArr($occIndex,1000); } $targetClid = $collManager->getSearchTerm("targetclid"); $urlPrefix = (isset($_SERVER['HTTPS'])?'https://':'http://').$_SERVER['HTTP_HOST'].$CLIENT_ROOT.'/collections/listtabledisplay.php'; $recordListHtml = ''; $qryCnt = $collManager->getRecordCnt(); $navStr = '<div style="float:right;">'; if(($occIndex*1000) > 1000){ $navStr .= "<a href='' title='Previous 1000 records' onclick='changeTablePage(".($occIndex-1).");return false;'>&lt;&lt;</a>"; } $navStr .= ' | '; $navStr .= ($occIndex <= 1?1:(($occIndex-1)*1000)+1).'-'.($qryCnt<1000+$occIndex?$qryCnt:(($occIndex-1)*1000)+1000).' of '.$qryCnt.' records'; $navStr .= ' | '; if($qryCnt > (1000+$occIndex)){ $navStr .= "<a href='' title='Next 1000 records' onclick='changeTablePage(".($occIndex+1).");return false;'>&gt;&gt;</a>"; } $navStr .= '</div>'; if($recArr){ $recordListHtml .= '<div style="width:790px;clear:both;margin:5px;">'; $recordListHtml .= '<div style="float:left;"><button type="button" id="copyurl" onclick="copySearchUrl();">Copy URL to These Results</button></div>'; if($qryCnt > 1){ $recordListHtml .= $navStr; } $recordListHtml .= '</div>'; $recordListHtml .= '<div style="clear:both;height:5px;"></div>'; $recordListHtml .= '<table class="styledtable" style="font-family:Arial;font-size:12px;"><tr>'; $recordListHtml .= '<th>Symbiota ID</th>'; $recordListHtml .= '<th>Collection</th>'; $recordListHtml .= '<th>Catalog Number</th>'; $recordListHtml .= '<th>Family</th>'; $recordListHtml .= '<th>Scientific Name</th>'; $recordListHtml .= '<th>Country</th>'; $recordListHtml .= '<th>State/Province</th>'; $recordListHtml .= '<th>County</th>'; $recordListHtml .= '<th>Locality</th>'; $recordListHtml .= '<th>Habitat</th>'; if($QUICK_HOST_ENTRY_IS_ACTIVE) $recordListHtml .= '<th>Host</th>'; $recordListHtml .= '<th>Elevation</th>'; $recordListHtml .= '<th>Event Date</th>'; $recordListHtml .= '<th>Collector</th>'; $recordListHtml .= '<th>Number</th>'; $recordListHtml .= '<th>Individual Count</th>'; $recordListHtml .= '<th>Life Stage</th>'; $recordListHtml .= '<th>Sex</th>'; $recordListHtml .= '</tr>'; $recCnt = 0; foreach($recArr as $id => $occArr){ $isEditor = false; if($SYMB_UID && ($IS_ADMIN || (array_key_exists('CollAdmin',$USER_RIGHTS) && in_array($occArr['collid'],$USER_RIGHTS['CollAdmin'])) || (array_key_exists('CollEditor',$USER_RIGHTS) && in_array($occArr['collid'],$USER_RIGHTS['CollEditor'])))){ $isEditor = true; } $collection = $occArr['institutioncode']; if($occArr['collectioncode']) $collection .= ':'.$occArr['collectioncode']; if($occArr['sciname']) $occArr['sciname'] = '<i>'.$occArr['sciname'].'</i> '; $recordListHtml .= "<tr ".($recCnt%2?'class="alt"':'').">\n"; $recordListHtml .= '<td>'; $recordListHtml .= '<a href="#" onclick="return openIndPU('.$id.",".($targetClid?$targetClid:"0").');">'.$id.'</a> '; if($isEditor || ($SYMB_UID && $SYMB_UID == $fieldArr['observeruid'])){ $recordListHtml .= '<a href="editor/occurrenceeditor.php?occid='.$id.'" target="_blank">'; $recordListHtml .= '<img src="../images/edit.png" style="height:13px;" title="Edit Record" />'; $recordListHtml .= '</a>'; } if(isset($occArr['img'])){ $recordListHtml .= '<img src="../images/image.png" style="height:13px;margin-left:5px;" title="Has Image" />'; } $recordListHtml .= '</td>'."\n"; $recordListHtml .= '<td>'.$collection.'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['accession'].'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['family'].'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['sciname'].($occArr['author']?" ".$occArr['author']:"").'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['country'].'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['state'].'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['county'].'</td>'."\n"; $recordListHtml .= '<td>'.((strlen($occArr['locality'])>80)?substr($occArr['locality'],0,80).'...':$occArr['locality']).'</td>'."\n"; $recordListHtml .= '<td>'.((strlen($occArr['habitat'])>80)?substr($occArr['habitat'],0,80).'...':$occArr['habitat']).'</td>'."\n"; if($QUICK_HOST_ENTRY_IS_ACTIVE){ if(array_key_exists('assochost',$occArr)){ $recordListHtml .= '<td>'.((strlen($occArr['assochost'])>80)?substr($occArr['assochost'],0,80).'...':$occArr['assochost']).'</td>'."\n"; } else{ $recordListHtml .= '<td></td>'."\n"; } } $recordListHtml .= '<td>'.(array_key_exists("elev",$occArr)?$occArr['elev']:"").'</td>'."\n"; $recordListHtml .= '<td>'.(array_key_exists("date",$occArr)?$occArr['date']:"").'</td>'."\n"; $recordListHtml .= '<td>'.$occArr['collector'].'</td>'."\n"; $recordListHtml .= '<td>'.(array_key_exists("collnumber",$occArr)?$occArr['collnumber']:"").'</td>'."\n"; $recordListHtml .= '<td>'.(array_key_exists("individualCount",$occArr)?$occArr['individualCount']:"").'</td>'."\n"; $recordListHtml .= '<td>'.(array_key_exists("lifeStage",$occArr)?$occArr['lifeStage']:"").'</td>'."\n"; $recordListHtml .= '<td>'.(array_key_exists("sex",$occArr)?$occArr['sex']:"").'</td>'."\n"; $recordListHtml .= "</tr>\n"; $recCnt++; } $recordListHtml .= '</table>'; $recordListHtml .= '<div style="clear:both;height:5px;"></div>'; $recordListHtml .= '<textarea id="urlPrefixBox" style="position:absolute;left:-9999px;top:-9999px">'.$urlPrefix.$collManager->getSearchResultUrl().'</textarea>'; $recordListHtml .= '<textarea id="urlFullBox" style="position:absolute;left:-9999px;top:-9999px"></textarea>'; if($qryCnt > 1){ $recordListHtml .= '<div style="width:790px;">'.$navStr.'</div>'; } $recordListHtml .= '*Click on the Symbiota identifier in the first column to see Full Record Details.'; } else{ $recordListHtml .= '<div style="font-weight:bold;font-size:120%;">No records found matching the query</div>'; } //output the response echo $recordListHtml; //echo json_encode($recordListHtml); ?>
seltmann/Symbiota
collections/rpc/changetablepage.php
PHP
gpl-2.0
7,873
<?php /** * PEAR_Common, the base class for the PEAR Installer * * PHP versions 4 and 5 * * LICENSE: This source file is subject to version 3.0 of the PHP license * that is available through the world-wide-web at the following URI: * http://www.php.net/license/3_0.txt. If you did not receive a copy of * the PHP License and are unable to obtain it through the web, please * send a note to license@php.net so we can mail you a copy immediately. * * @category pear * @package PEAR * @author Stig Bakken <ssb@php.net> * @author Tomas V. V. Cox <cox@idecnet.com> * @author Greg Beaver <cellog@php.net> * @copyright 1997-2008 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version CVS: $Id: Common.php,v 1.1 2010/06/17 11:19:23 soonchoy Exp $ * @link http://pear.php.net/package/PEAR * @since File available since Release 0.1.0 * @deprecated File deprecated since Release 1.4.0a1 */ /** * Include error handling */ require_once 'PEAR.php'; // {{{ constants and globals /** * PEAR_Common error when an invalid PHP file is passed to PEAR_Common::analyzeSourceCode() */ define('PEAR_COMMON_ERROR_INVALIDPHP', 1); define('_PEAR_COMMON_PACKAGE_NAME_PREG', '[A-Za-z][a-zA-Z0-9_]+'); define('PEAR_COMMON_PACKAGE_NAME_PREG', '/^' . _PEAR_COMMON_PACKAGE_NAME_PREG . '\\z/'); // this should allow: 1, 1.0, 1.0RC1, 1.0dev, 1.0dev123234234234, 1.0a1, 1.0b1, 1.0pl1 define('_PEAR_COMMON_PACKAGE_VERSION_PREG', '\d+(?:\.\d+)*(?:[a-zA-Z]+\d*)?'); define('PEAR_COMMON_PACKAGE_VERSION_PREG', '/^' . _PEAR_COMMON_PACKAGE_VERSION_PREG . '\\z/i'); // XXX far from perfect :-) define('_PEAR_COMMON_PACKAGE_DOWNLOAD_PREG', '(' . _PEAR_COMMON_PACKAGE_NAME_PREG . ')(-([.0-9a-zA-Z]+))?'); define('PEAR_COMMON_PACKAGE_DOWNLOAD_PREG', '/^' . _PEAR_COMMON_PACKAGE_DOWNLOAD_PREG . '\\z/'); define('_PEAR_CHANNELS_NAME_PREG', '[A-Za-z][a-zA-Z0-9\.]+'); define('PEAR_CHANNELS_NAME_PREG', '/^' . _PEAR_CHANNELS_NAME_PREG . '\\z/'); // this should allow any dns or IP address, plus a path - NO UNDERSCORES ALLOWED define('_PEAR_CHANNELS_SERVER_PREG', '[a-zA-Z0-9\-]+(?:\.[a-zA-Z0-9\-]+)*(\/[a-zA-Z0-9\-]+)*'); define('PEAR_CHANNELS_SERVER_PREG', '/^' . _PEAR_CHANNELS_SERVER_PREG . '\\z/i'); define('_PEAR_CHANNELS_PACKAGE_PREG', '(' ._PEAR_CHANNELS_SERVER_PREG . ')\/(' . _PEAR_COMMON_PACKAGE_NAME_PREG . ')'); define('PEAR_CHANNELS_PACKAGE_PREG', '/^' . _PEAR_CHANNELS_PACKAGE_PREG . '\\z/i'); define('_PEAR_COMMON_CHANNEL_DOWNLOAD_PREG', '(' . _PEAR_CHANNELS_NAME_PREG . ')::(' . _PEAR_COMMON_PACKAGE_NAME_PREG . ')(-([.0-9a-zA-Z]+))?'); define('PEAR_COMMON_CHANNEL_DOWNLOAD_PREG', '/^' . _PEAR_COMMON_CHANNEL_DOWNLOAD_PREG . '\\z/'); /** * List of temporary files and directories registered by * PEAR_Common::addTempFile(). * @var array */ $GLOBALS['_PEAR_Common_tempfiles'] = array(); /** * Valid maintainer roles * @var array */ $GLOBALS['_PEAR_Common_maintainer_roles'] = array('lead','developer','contributor','helper'); /** * Valid release states * @var array */ $GLOBALS['_PEAR_Common_release_states'] = array('alpha','beta','stable','snapshot','devel'); /** * Valid dependency types * @var array */ $GLOBALS['_PEAR_Common_dependency_types'] = array('pkg','ext','php','prog','ldlib','rtlib','os','websrv','sapi'); /** * Valid dependency relations * @var array */ $GLOBALS['_PEAR_Common_dependency_relations'] = array('has','eq','lt','le','gt','ge','not', 'ne'); /** * Valid file roles * @var array */ $GLOBALS['_PEAR_Common_file_roles'] = array('php','ext','test','doc','data','src','script'); /** * Valid replacement types * @var array */ $GLOBALS['_PEAR_Common_replacement_types'] = array('php-const', 'pear-config', 'package-info'); /** * Valid "provide" types * @var array */ $GLOBALS['_PEAR_Common_provide_types'] = array('ext', 'prog', 'class', 'function', 'feature', 'api'); /** * Valid "provide" types * @var array */ $GLOBALS['_PEAR_Common_script_phases'] = array('pre-install', 'post-install', 'pre-uninstall', 'post-uninstall', 'pre-build', 'post-build', 'pre-configure', 'post-configure', 'pre-setup', 'post-setup'); // }}} /** * Class providing common functionality for PEAR administration classes. * @category pear * @package PEAR * @author Stig Bakken <ssb@php.net> * @author Tomas V. V. Cox <cox@idecnet.com> * @author Greg Beaver <cellog@php.net> * @copyright 1997-2008 The PHP Group * @license http://www.php.net/license/3_0.txt PHP License 3.0 * @version Release: 1.7.2 * @link http://pear.php.net/package/PEAR * @since Class available since Release 1.4.0a1 * @deprecated This class will disappear, and its components will be spread * into smaller classes, like the AT&T breakup, as of Release 1.4.0a1 */ class PEAR_Common extends PEAR { // {{{ properties /** stack of elements, gives some sort of XML context */ var $element_stack = array(); /** name of currently parsed XML element */ var $current_element; /** array of attributes of the currently parsed XML element */ var $current_attributes = array(); /** assoc with information about a package */ var $pkginfo = array(); /** * User Interface object (PEAR_Frontend_* class). If null, * the log() method uses print. * @var object */ var $ui = null; /** * Configuration object (PEAR_Config). * @var PEAR_Config */ var $config = null; var $current_path = null; /** * PEAR_SourceAnalyzer instance * @var object */ var $source_analyzer = null; /** * Flag variable used to mark a valid package file * @var boolean * @access private */ var $_validPackageFile; // }}} // {{{ constructor /** * PEAR_Common constructor * * @access public */ function PEAR_Common() { parent::PEAR(); $this->config = &PEAR_Config::singleton(); $this->debug = $this->config->get('verbose'); } // }}} // {{{ destructor /** * PEAR_Common destructor * * @access private */ function _PEAR_Common() { // doesn't work due to bug #14744 //$tempfiles = $this->_tempfiles; $tempfiles =& $GLOBALS['_PEAR_Common_tempfiles']; while ($file = array_shift($tempfiles)) { if (@is_dir($file)) { if (!class_exists('System')) { require_once 'System.php'; } System::rm(array('-rf', $file)); } elseif (file_exists($file)) { unlink($file); } } } // }}} // {{{ addTempFile() /** * Register a temporary file or directory. When the destructor is * executed, all registered temporary files and directories are * removed. * * @param string $file name of file or directory * * @return void * * @access public */ function addTempFile($file) { if (!class_exists('PEAR_Frontend')) { require_once 'PEAR/Frontend.php'; } PEAR_Frontend::addTempFile($file); } // }}} // {{{ mkDirHier() /** * Wrapper to System::mkDir(), creates a directory as well as * any necessary parent directories. * * @param string $dir directory name * * @return bool TRUE on success, or a PEAR error * * @access public */ function mkDirHier($dir) { $this->log(2, "+ create dir $dir"); if (!class_exists('System')) { require_once 'System.php'; } return System::mkDir(array('-p', $dir)); } // }}} // {{{ log() /** * Logging method. * * @param int $level log level (0 is quiet, higher is noisier) * @param string $msg message to write to the log * * @return void * * @access public * @static */ function log($level, $msg, $append_crlf = true) { if ($this->debug >= $level) { if (!class_exists('PEAR_Frontend')) { require_once 'PEAR/Frontend.php'; } $ui = &PEAR_Frontend::singleton(); if (is_a($ui, 'PEAR_Frontend')) { $ui->log($msg, $append_crlf); } else { print "$msg\n"; } } } // }}} // {{{ mkTempDir() /** * Create and register a temporary directory. * * @param string $tmpdir (optional) Directory to use as tmpdir. * Will use system defaults (for example * /tmp or c:\windows\temp) if not specified * * @return string name of created directory * * @access public */ function mkTempDir($tmpdir = '') { if ($tmpdir) { $topt = array('-t', $tmpdir); } else { $topt = array(); } $topt = array_merge($topt, array('-d', 'pear')); if (!class_exists('System')) { require_once 'System.php'; } if (!$tmpdir = System::mktemp($topt)) { return false; } $this->addTempFile($tmpdir); return $tmpdir; } // }}} // {{{ setFrontendObject() /** * Set object that represents the frontend to be used. * * @param object Reference of the frontend object * @return void * @access public */ function setFrontendObject(&$ui) { $this->ui = &$ui; } // }}} // {{{ infoFromTgzFile() /** * Returns information about a package file. Expects the name of * a gzipped tar file as input. * * @param string $file name of .tgz file * * @return array array with package information * * @access public * @deprecated use PEAR_PackageFile->fromTgzFile() instead * */ function infoFromTgzFile($file) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromTgzFile($file, PEAR_VALIDATE_NORMAL); if (PEAR::isError($pf)) { $errs = $pf->getUserinfo(); if (is_array($errs)) { foreach ($errs as $error) { $e = $this->raiseError($error['message'], $error['code'], null, null, $error); } } return $pf; } return $this->_postProcessValidPackagexml($pf); } // }}} // {{{ infoFromDescriptionFile() /** * Returns information about a package file. Expects the name of * a package xml file as input. * * @param string $descfile name of package xml file * * @return array array with package information * * @access public * @deprecated use PEAR_PackageFile->fromPackageFile() instead * */ function infoFromDescriptionFile($descfile) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromPackageFile($descfile, PEAR_VALIDATE_NORMAL); if (PEAR::isError($pf)) { $errs = $pf->getUserinfo(); if (is_array($errs)) { foreach ($errs as $error) { $e = $this->raiseError($error['message'], $error['code'], null, null, $error); } } return $pf; } return $this->_postProcessValidPackagexml($pf); } // }}} // {{{ infoFromString() /** * Returns information about a package file. Expects the contents * of a package xml file as input. * * @param string $data contents of package.xml file * * @return array array with package information * * @access public * @deprecated use PEAR_PackageFile->fromXmlstring() instead * */ function infoFromString($data) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromXmlString($data, PEAR_VALIDATE_NORMAL, false); if (PEAR::isError($pf)) { $errs = $pf->getUserinfo(); if (is_array($errs)) { foreach ($errs as $error) { $e = $this->raiseError($error['message'], $error['code'], null, null, $error); } } return $pf; } return $this->_postProcessValidPackagexml($pf); } // }}} /** * @param PEAR_PackageFile_v1|PEAR_PackageFile_v2 * @return array */ function _postProcessValidPackagexml(&$pf) { if (is_a($pf, 'PEAR_PackageFile_v2')) { // sort of make this into a package.xml 1.0-style array // changelog is not converted to old format. $arr = $pf->toArray(true); $arr = array_merge($arr, $arr['old']); unset($arr['old']); unset($arr['xsdversion']); unset($arr['contents']); unset($arr['compatible']); unset($arr['channel']); unset($arr['uri']); unset($arr['dependencies']); unset($arr['phprelease']); unset($arr['extsrcrelease']); unset($arr['zendextsrcrelease']); unset($arr['extbinrelease']); unset($arr['zendextbinrelease']); unset($arr['bundle']); unset($arr['lead']); unset($arr['developer']); unset($arr['helper']); unset($arr['contributor']); $arr['filelist'] = $pf->getFilelist(); $this->pkginfo = $arr; return $arr; } else { $this->pkginfo = $pf->toArray(); return $this->pkginfo; } } // {{{ infoFromAny() /** * Returns package information from different sources * * This method is able to extract information about a package * from a .tgz archive or from a XML package definition file. * * @access public * @param string Filename of the source ('package.xml', '<package>.tgz') * @return string * @deprecated use PEAR_PackageFile->fromAnyFile() instead */ function infoFromAny($info) { if (is_string($info) && file_exists($info)) { $packagefile = &new PEAR_PackageFile($this->config); $pf = &$packagefile->fromAnyFile($info, PEAR_VALIDATE_NORMAL); if (PEAR::isError($pf)) { $errs = $pf->getUserinfo(); if (is_array($errs)) { foreach ($errs as $error) { $e = $this->raiseError($error['message'], $error['code'], null, null, $error); } } return $pf; } return $this->_postProcessValidPackagexml($pf); } return $info; } // }}} // {{{ xmlFromInfo() /** * Return an XML document based on the package info (as returned * by the PEAR_Common::infoFrom* methods). * * @param array $pkginfo package info * * @return string XML data * * @access public * @deprecated use a PEAR_PackageFile_v* object's generator instead */ function xmlFromInfo($pkginfo) { $config = &PEAR_Config::singleton(); $packagefile = &new PEAR_PackageFile($config); $pf = &$packagefile->fromArray($pkginfo); $gen = &$pf->getDefaultGenerator(); return $gen->toXml(PEAR_VALIDATE_PACKAGING); } // }}} // {{{ validatePackageInfo() /** * Validate XML package definition file. * * @param string $info Filename of the package archive or of the * package definition file * @param array $errors Array that will contain the errors * @param array $warnings Array that will contain the warnings * @param string $dir_prefix (optional) directory where source files * may be found, or empty if they are not available * @access public * @return boolean * @deprecated use the validation of PEAR_PackageFile objects */ function validatePackageInfo($info, &$errors, &$warnings, $dir_prefix = '') { $config = &PEAR_Config::singleton(); $packagefile = &new PEAR_PackageFile($config); PEAR::staticPushErrorHandling(PEAR_ERROR_RETURN); if (strpos($info, '<?xml') !== false) { $pf = &$packagefile->fromXmlString($info, PEAR_VALIDATE_NORMAL, ''); } else { $pf = &$packagefile->fromAnyFile($info, PEAR_VALIDATE_NORMAL); } PEAR::staticPopErrorHandling(); if (PEAR::isError($pf)) { $errs = $pf->getUserinfo(); if (is_array($errs)) { foreach ($errs as $error) { if ($error['level'] == 'error') { $errors[] = $error['message']; } else { $warnings[] = $error['message']; } } } return false; } return true; } // }}} // {{{ buildProvidesArray() /** * Build a "provides" array from data returned by * analyzeSourceCode(). The format of the built array is like * this: * * array( * 'class;MyClass' => 'array('type' => 'class', 'name' => 'MyClass'), * ... * ) * * * @param array $srcinfo array with information about a source file * as returned by the analyzeSourceCode() method. * * @return void * * @access public * */ function buildProvidesArray($srcinfo) { $file = basename($srcinfo['source_file']); $pn = ''; if (isset($this->_packageName)) { $pn = $this->_packageName; } $pnl = strlen($pn); foreach ($srcinfo['declared_classes'] as $class) { $key = "class;$class"; if (isset($this->pkginfo['provides'][$key])) { continue; } $this->pkginfo['provides'][$key] = array('file'=> $file, 'type' => 'class', 'name' => $class); if (isset($srcinfo['inheritance'][$class])) { $this->pkginfo['provides'][$key]['extends'] = $srcinfo['inheritance'][$class]; } } foreach ($srcinfo['declared_methods'] as $class => $methods) { foreach ($methods as $method) { $function = "$class::$method"; $key = "function;$function"; if ($method{0} == '_' || !strcasecmp($method, $class) || isset($this->pkginfo['provides'][$key])) { continue; } $this->pkginfo['provides'][$key] = array('file'=> $file, 'type' => 'function', 'name' => $function); } } foreach ($srcinfo['declared_functions'] as $function) { $key = "function;$function"; if ($function{0} == '_' || isset($this->pkginfo['provides'][$key])) { continue; } if (!strstr($function, '::') && strncasecmp($function, $pn, $pnl)) { $warnings[] = "in1 " . $file . ": function \"$function\" not prefixed with package name \"$pn\""; } $this->pkginfo['provides'][$key] = array('file'=> $file, 'type' => 'function', 'name' => $function); } } // }}} // {{{ analyzeSourceCode() /** * Analyze the source code of the given PHP file * * @param string Filename of the PHP file * @return mixed * @access public */ function analyzeSourceCode($file) { if (!function_exists("token_get_all")) { return false; } if (!defined('T_DOC_COMMENT')) { define('T_DOC_COMMENT', T_COMMENT); } if (!defined('T_INTERFACE')) { define('T_INTERFACE', -1); } if (!defined('T_IMPLEMENTS')) { define('T_IMPLEMENTS', -1); } if (!$fp = @fopen($file, "r")) { return false; } fclose($fp); $contents = file_get_contents($file); $tokens = token_get_all($contents); /* for ($i = 0; $i < sizeof($tokens); $i++) { @list($token, $data) = $tokens[$i]; if (is_string($token)) { var_dump($token); } else { print token_name($token) . ' '; var_dump(rtrim($data)); } } */ $look_for = 0; $paren_level = 0; $bracket_level = 0; $brace_level = 0; $lastphpdoc = ''; $current_class = ''; $current_interface = ''; $current_class_level = -1; $current_function = ''; $current_function_level = -1; $declared_classes = array(); $declared_interfaces = array(); $declared_functions = array(); $declared_methods = array(); $used_classes = array(); $used_functions = array(); $extends = array(); $implements = array(); $nodeps = array(); $inquote = false; $interface = false; for ($i = 0; $i < sizeof($tokens); $i++) { if (is_array($tokens[$i])) { list($token, $data) = $tokens[$i]; } else { $token = $tokens[$i]; $data = ''; } if ($inquote) { if ($token != '"') { continue; } else { $inquote = false; continue; } } switch ($token) { case T_WHITESPACE: continue; case ';': if ($interface) { $current_function = ''; $current_function_level = -1; } break; case '"': $inquote = true; break; case T_CURLY_OPEN: case T_DOLLAR_OPEN_CURLY_BRACES: case '{': $brace_level++; continue 2; case '}': $brace_level--; if ($current_class_level == $brace_level) { $current_class = ''; $current_class_level = -1; } if ($current_function_level == $brace_level) { $current_function = ''; $current_function_level = -1; } continue 2; case '[': $bracket_level++; continue 2; case ']': $bracket_level--; continue 2; case '(': $paren_level++; continue 2; case ')': $paren_level--; continue 2; case T_INTERFACE: $interface = true; case T_CLASS: if (($current_class_level != -1) || ($current_function_level != -1)) { PEAR::raiseError("Parser error: invalid PHP found in file \"$file\"", PEAR_COMMON_ERROR_INVALIDPHP); return false; } case T_FUNCTION: case T_NEW: case T_EXTENDS: case T_IMPLEMENTS: $look_for = $token; continue 2; case T_STRING: if (version_compare(zend_version(), '2.0', '<')) { if (in_array(strtolower($data), array('public', 'private', 'protected', 'abstract', 'interface', 'implements', 'throw') )) { PEAR::raiseError('Error: PHP5 token encountered in ' . $file . 'packaging should be done in PHP 5'); return false; } } if ($look_for == T_CLASS) { $current_class = $data; $current_class_level = $brace_level; $declared_classes[] = $current_class; } elseif ($look_for == T_INTERFACE) { $current_interface = $data; $current_class_level = $brace_level; $declared_interfaces[] = $current_interface; } elseif ($look_for == T_IMPLEMENTS) { $implements[$current_class] = $data; } elseif ($look_for == T_EXTENDS) { $extends[$current_class] = $data; } elseif ($look_for == T_FUNCTION) { if ($current_class) { $current_function = "$current_class::$data"; $declared_methods[$current_class][] = $data; } elseif ($current_interface) { $current_function = "$current_interface::$data"; $declared_methods[$current_interface][] = $data; } else { $current_function = $data; $declared_functions[] = $current_function; } $current_function_level = $brace_level; $m = array(); } elseif ($look_for == T_NEW) { $used_classes[$data] = true; } $look_for = 0; continue 2; case T_VARIABLE: $look_for = 0; continue 2; case T_DOC_COMMENT: case T_COMMENT: if (preg_match('!^/\*\*\s!', $data)) { $lastphpdoc = $data; if (preg_match_all('/@nodep\s+(\S+)/', $lastphpdoc, $m)) { $nodeps = array_merge($nodeps, $m[1]); } } continue 2; case T_DOUBLE_COLON: if (!($tokens[$i - 1][0] == T_WHITESPACE || $tokens[$i - 1][0] == T_STRING)) { PEAR::raiseError("Parser error: invalid PHP found in file \"$file\"", PEAR_COMMON_ERROR_INVALIDPHP); return false; } $class = $tokens[$i - 1][1]; if (strtolower($class) != 'parent') { $used_classes[$class] = true; } continue 2; } } return array( "source_file" => $file, "declared_classes" => $declared_classes, "declared_interfaces" => $declared_interfaces, "declared_methods" => $declared_methods, "declared_functions" => $declared_functions, "used_classes" => array_diff(array_keys($used_classes), $nodeps), "inheritance" => $extends, "implements" => $implements, ); } // }}} // {{{ betterStates() /** * Return an array containing all of the states that are more stable than * or equal to the passed in state * * @param string Release state * @param boolean Determines whether to include $state in the list * @return false|array False if $state is not a valid release state */ function betterStates($state, $include = false) { static $states = array('snapshot', 'devel', 'alpha', 'beta', 'stable'); $i = array_search($state, $states); if ($i === false) { return false; } if ($include) { $i--; } return array_slice($states, $i + 1); } // }}} // {{{ detectDependencies() function detectDependencies($any, $status_callback = null) { if (!function_exists("token_get_all")) { return false; } if (PEAR::isError($info = $this->infoFromAny($any))) { return $this->raiseError($info); } if (!is_array($info)) { return false; } $deps = array(); $used_c = $decl_c = $decl_f = $decl_m = array(); foreach ($info['filelist'] as $file => $fa) { $tmp = $this->analyzeSourceCode($file); $used_c = @array_merge($used_c, $tmp['used_classes']); $decl_c = @array_merge($decl_c, $tmp['declared_classes']); $decl_f = @array_merge($decl_f, $tmp['declared_functions']); $decl_m = @array_merge($decl_m, $tmp['declared_methods']); $inheri = @array_merge($inheri, $tmp['inheritance']); } $used_c = array_unique($used_c); $decl_c = array_unique($decl_c); $undecl_c = array_diff($used_c, $decl_c); return array('used_classes' => $used_c, 'declared_classes' => $decl_c, 'declared_methods' => $decl_m, 'declared_functions' => $decl_f, 'undeclared_classes' => $undecl_c, 'inheritance' => $inheri, ); } // }}} // {{{ getUserRoles() /** * Get the valid roles for a PEAR package maintainer * * @return array * @static */ function getUserRoles() { return $GLOBALS['_PEAR_Common_maintainer_roles']; } // }}} // {{{ getReleaseStates() /** * Get the valid package release states of packages * * @return array * @static */ function getReleaseStates() { return $GLOBALS['_PEAR_Common_release_states']; } // }}} // {{{ getDependencyTypes() /** * Get the implemented dependency types (php, ext, pkg etc.) * * @return array * @static */ function getDependencyTypes() { return $GLOBALS['_PEAR_Common_dependency_types']; } // }}} // {{{ getDependencyRelations() /** * Get the implemented dependency relations (has, lt, ge etc.) * * @return array * @static */ function getDependencyRelations() { return $GLOBALS['_PEAR_Common_dependency_relations']; } // }}} // {{{ getFileRoles() /** * Get the implemented file roles * * @return array * @static */ function getFileRoles() { return $GLOBALS['_PEAR_Common_file_roles']; } // }}} // {{{ getReplacementTypes() /** * Get the implemented file replacement types in * * @return array * @static */ function getReplacementTypes() { return $GLOBALS['_PEAR_Common_replacement_types']; } // }}} // {{{ getProvideTypes() /** * Get the implemented file replacement types in * * @return array * @static */ function getProvideTypes() { return $GLOBALS['_PEAR_Common_provide_types']; } // }}} // {{{ getScriptPhases() /** * Get the implemented file replacement types in * * @return array * @static */ function getScriptPhases() { return $GLOBALS['_PEAR_Common_script_phases']; } // }}} // {{{ validPackageName() /** * Test whether a string contains a valid package name. * * @param string $name the package name to test * * @return bool * * @access public */ function validPackageName($name) { return (bool)preg_match(PEAR_COMMON_PACKAGE_NAME_PREG, $name); } // }}} // {{{ validPackageVersion() /** * Test whether a string contains a valid package version. * * @param string $ver the package version to test * * @return bool * * @access public */ function validPackageVersion($ver) { return (bool)preg_match(PEAR_COMMON_PACKAGE_VERSION_PREG, $ver); } // }}} // {{{ downloadHttp() /** * Download a file through HTTP. Considers suggested file name in * Content-disposition: header and can run a callback function for * different events. The callback will be called with two * parameters: the callback type, and parameters. The implemented * callback types are: * * 'setup' called at the very beginning, parameter is a UI object * that should be used for all output * 'message' the parameter is a string with an informational message * 'saveas' may be used to save with a different file name, the * parameter is the filename that is about to be used. * If a 'saveas' callback returns a non-empty string, * that file name will be used as the filename instead. * Note that $save_dir will not be affected by this, only * the basename of the file. * 'start' download is starting, parameter is number of bytes * that are expected, or -1 if unknown * 'bytesread' parameter is the number of bytes read so far * 'done' download is complete, parameter is the total number * of bytes read * 'connfailed' if the TCP connection fails, this callback is called * with array(host,port,errno,errmsg) * 'writefailed' if writing to disk fails, this callback is called * with array(destfile,errmsg) * * If an HTTP proxy has been configured (http_proxy PEAR_Config * setting), the proxy will be used. * * @param string $url the URL to download * @param object $ui PEAR_Frontend_* instance * @param object $config PEAR_Config instance * @param string $save_dir (optional) directory to save file in * @param mixed $callback (optional) function/method to call for status * updates * * @return string Returns the full path of the downloaded file or a PEAR * error on failure. If the error is caused by * socket-related errors, the error object will * have the fsockopen error code available through * getCode(). * * @access public * @deprecated in favor of PEAR_Downloader::downloadHttp() */ function downloadHttp($url, &$ui, $save_dir = '.', $callback = null) { if (!class_exists('PEAR_Downloader')) { require_once 'PEAR/Downloader.php'; } return PEAR_Downloader::downloadHttp($url, $ui, $save_dir, $callback); } // }}} /** * @param string $path relative or absolute include path * @return boolean * @static */ function isIncludeable($path) { if (file_exists($path) && is_readable($path)) { return true; } $ipath = explode(PATH_SEPARATOR, ini_get('include_path')); foreach ($ipath as $include) { $test = realpath($include . DIRECTORY_SEPARATOR . $path); if (file_exists($test) && is_readable($test)) { return true; } } return false; } } require_once 'PEAR/Config.php'; require_once 'PEAR/PackageFile.php'; ?>
alucard263096/XMLRPC
DEMO/ta_portal_dev/libs/PEAR/PEAR/Common.php
PHP
gpl-2.0
36,771
/* * Copyright (C) 2011 Google, Inc. All rights reserved. * Copyright (C) 2016 Apple Inc. All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY GOOGLE INC. ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR * PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY * OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #include "config.h" #include "ContentSecurityPolicySource.h" #include "ContentSecurityPolicy.h" #include "URL.h" namespace WebCore { ContentSecurityPolicySource::ContentSecurityPolicySource(const ContentSecurityPolicy& policy, const String& scheme, const String& host, int port, const String& path, bool hostHasWildcard, bool portHasWildcard) : m_policy(policy) , m_scheme(scheme) , m_host(host) , m_port(port) , m_path(path) , m_hostHasWildcard(hostHasWildcard) , m_portHasWildcard(portHasWildcard) { } bool ContentSecurityPolicySource::matches(const URL& url) const { if (!schemeMatches(url)) return false; if (isSchemeOnly()) return true; return hostMatches(url) && portMatches(url) && pathMatches(url); } bool ContentSecurityPolicySource::schemeMatches(const URL& url) const { if (m_scheme.isEmpty()) return m_policy.protocolMatchesSelf(url); return equalIgnoringASCIICase(url.protocol(), m_scheme); } bool ContentSecurityPolicySource::hostMatches(const URL& url) const { const String& host = url.host(); if (equalIgnoringASCIICase(host, m_host)) return true; return m_hostHasWildcard && host.endsWith("." + m_host, false); } bool ContentSecurityPolicySource::pathMatches(const URL& url) const { if (m_path.isEmpty()) return true; String path = decodeURLEscapeSequences(url.path()); if (m_path.endsWith("/")) return path.startsWith(m_path); return path == m_path; } bool ContentSecurityPolicySource::portMatches(const URL& url) const { if (m_portHasWildcard) return true; int port = url.port(); if (port == m_port) return true; if (!port) return isDefaultPortForProtocol(m_port, url.protocol()); if (!m_port) return isDefaultPortForProtocol(port, url.protocol()); return false; } bool ContentSecurityPolicySource::isSchemeOnly() const { return m_host.isEmpty(); } } // namespace WebCore
qtproject/qtwebkit
Source/WebCore/page/csp/ContentSecurityPolicySource.cpp
C++
gpl-2.0
3,383
<?php $profile_page = get_option('booked_profile_page'); if ($profile_page): if(!class_exists('booked_profiles')) { class booked_profiles { public function __construct() { add_action('init', array(&$this,'rewrite_add_rewrites')); add_action('the_content', array(&$this,'display_profile_markup')); add_filter('wp_title', array(&$this,'wp_profile_title'),10,2); register_activation_hook( __FILE__, array(&$this, 'rewrite_activation') ); } public function rewrite_add_rewrites(){ $profile_page = get_option('booked_profile_page'); if ($profile_page): $profile_page_data = get_post($profile_page, ARRAY_A); $profile_slug = $profile_page_data['post_name']; else : $profile_slug = 'profile'; endif; add_rewrite_tag( '%profile%', '([^&]+)' ); add_rewrite_rule( '^'.$profile_slug.'/([^/]*)/?', 'index.php?profile=$matches[1]', 'top' ); } public function rewrite_activation(){ $this->rewrite_add_rewrites(); flush_rewrite_rules(); } public function display_profile_markup($content){ $profile_page = get_option('booked_profile_page'); if(is_page($profile_page) || get_query_var('profile')): if (is_user_logged_in() || get_query_var('profile')): ob_start(); $this->display_profile_page_content(); $content = ob_get_clean(); return $content; else : return $content; endif; endif; return $content; } public function display_profile_page_content() { require(BOOKED_PLUGIN_TEMPLATES_DIR . 'profile.php'); } public function wp_profile_title( $title, $sep = false ) { if (get_query_var('profile')): echo get_query_var('profile'); $user_data = get_user_by( 'id', get_query_var('profile') ); $title = sprintf(__("%s's Profile","booked"), $user_data->data->display_name) . ' - '; return $title; endif; return $title; } } new booked_profiles(); } endif;
annegrundhoefer/mark
wp-content/plugins/booked/includes/profiles.php
PHP
gpl-2.0
2,040
/*************************************************************************** kbordercoltextexport.cpp - description ------------------- begin : Sam Aug 30 2003 copyright : (C) 2003 by Friedrich W. H. Kossebau email : Friedrich.W.H@Kossebau.de ***************************************************************************/ /*************************************************************************** * * * This library is free software; you can redistribute it and/or * * modify it under the terms of the GNU Library General Public * * License version 2 as published by the Free Software Foundation. * * * ***************************************************************************/ // qt specific #include <qstring.h> // lib specific #include "kbordercoltextexport.h" using namespace KHE; static const uint BorderColumnTEWidth = 3; int KBorderColTextExport::charsPerLine() const { return BorderColumnTEWidth; } void KBorderColTextExport::printFirstLine( QString &T, int /*Line*/ ) const { print( T ); } void KBorderColTextExport::printNextLine( QString &T ) const { print( T ); } void KBorderColTextExport::print( QString &T ) const { T.append( " | " ); }
serghei/kde3-kdeutils
khexedit/lib/kbordercoltextexport.cpp
C++
gpl-2.0
1,464
/* Copyright (C) 2012 Samsung Electronics Copyright (C) 2012 Intel Corporation. All rights reserved. This library is free software; you can redistribute it and/or modify it under the terms of the GNU Library General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Library General Public License for more details. You should have received a copy of the GNU Library General Public License along with this library; see the file COPYING.LIB. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ #include "config.h" #include "GraphicsContext3DPrivate.h" #include "HostWindow.h" #include "NotImplemented.h" namespace WebCore { PassOwnPtr<GraphicsContext3DPrivate> GraphicsContext3DPrivate::create(GraphicsContext3D* context, HostWindow* hostWindow) { OwnPtr<GraphicsContext3DPrivate> platformLayer = adoptPtr(new GraphicsContext3DPrivate(context, hostWindow)); if (platformLayer && platformLayer->initialize()) return platformLayer.release(); return nullptr; } GraphicsContext3DPrivate::GraphicsContext3DPrivate(GraphicsContext3D* context, HostWindow* hostWindow) : m_context(context) , m_hostWindow(hostWindow) { } bool GraphicsContext3DPrivate::initialize() { if (m_context->m_renderStyle == GraphicsContext3D::RenderDirectlyToHostWindow) return false; if (m_hostWindow && m_hostWindow->platformPageClient()) { // FIXME: Implement this code path for WebKit1. // Get Evas object from platformPageClient and set EvasGL related members. return false; } m_offScreenContext = GLPlatformContext::createContext(m_context->m_renderStyle); if (!m_offScreenContext) return false; if (m_context->m_renderStyle == GraphicsContext3D::RenderOffscreen) { m_offScreenSurface = GLPlatformSurface::createOffScreenSurface(); if (!m_offScreenSurface) return false; if (!m_offScreenContext->initialize(m_offScreenSurface.get())) return false; if (!makeContextCurrent()) return false; #if USE(GRAPHICS_SURFACE) m_surfaceOperation = CreateSurface; #endif } return true; } GraphicsContext3DPrivate::~GraphicsContext3DPrivate() { releaseResources(); } void GraphicsContext3DPrivate::releaseResources() { if (m_context->m_renderStyle == GraphicsContext3D::RenderToCurrentGLContext) return; // Release the current context and drawable only after destroying any associated gl resources. #if USE(GRAPHICS_SURFACE) if (m_previousGraphicsSurface) m_previousGraphicsSurface = nullptr; if (m_graphicsSurface) m_graphicsSurface = nullptr; m_surfaceHandle = GraphicsSurfaceToken(); #endif if (m_offScreenSurface) m_offScreenSurface->destroy(); if (m_offScreenContext) { m_offScreenContext->destroy(); m_offScreenContext->releaseCurrent(); } } void GraphicsContext3DPrivate::setContextLostCallback(PassOwnPtr<GraphicsContext3D::ContextLostCallback> callBack) { m_contextLostCallback = callBack; } PlatformGraphicsContext3D GraphicsContext3DPrivate::platformGraphicsContext3D() const { return m_offScreenContext->handle(); } bool GraphicsContext3DPrivate::makeContextCurrent() const { bool success = m_offScreenContext->makeCurrent(m_offScreenSurface.get()); if (!m_offScreenContext->isValid()) { // FIXME: Restore context if (m_contextLostCallback) m_contextLostCallback->onContextLost(); return false; } return success; } bool GraphicsContext3DPrivate::prepareBuffer() const { if (!makeContextCurrent()) return false; m_context->markLayerComposited(); if (m_context->m_attrs.antialias) { bool enableScissorTest = false; int width = m_context->m_currentWidth; int height = m_context->m_currentHeight; // We should copy the full buffer, and not respect the current scissor bounds. // FIXME: It would be more efficient to track the state of the scissor test. if (m_context->isEnabled(GraphicsContext3D::SCISSOR_TEST)) { enableScissorTest = true; m_context->disable(GraphicsContext3D::SCISSOR_TEST); } glBindFramebuffer(Extensions3D::READ_FRAMEBUFFER, m_context->m_multisampleFBO); glBindFramebuffer(Extensions3D::DRAW_FRAMEBUFFER, m_context->m_fbo); // Use NEAREST as no scale is performed during the blit. m_context->getExtensions()->blitFramebuffer(0, 0, width, height, 0, 0, width, height, GraphicsContext3D::COLOR_BUFFER_BIT, GraphicsContext3D::NEAREST); if (enableScissorTest) m_context->enable(GraphicsContext3D::SCISSOR_TEST); glBindFramebuffer(GL_FRAMEBUFFER, m_context->m_state.boundFBO); } return true; } #if USE(TEXTURE_MAPPER_GL) void GraphicsContext3DPrivate::paintToTextureMapper(TextureMapper*, const FloatRect& /* target */, const TransformationMatrix&, float /* opacity */) { notImplemented(); } #endif #if USE(GRAPHICS_SURFACE) void GraphicsContext3DPrivate::createGraphicsSurface() { static PendingSurfaceOperation pendingOperation = DeletePreviousSurface | Resize | CreateSurface; if (!(m_surfaceOperation & pendingOperation)) return; if (m_surfaceOperation & DeletePreviousSurface) { m_previousGraphicsSurface = nullptr; m_surfaceOperation &= ~DeletePreviousSurface; } if (!(m_surfaceOperation & pendingOperation)) return; // Don't release current graphics surface until we have prepared surface // with requested size. This is to avoid flashing during resize. if (m_surfaceOperation & Resize) { m_previousGraphicsSurface = m_graphicsSurface; m_surfaceOperation &= ~Resize; m_surfaceOperation |= DeletePreviousSurface; m_size = IntSize(m_context->m_currentWidth, m_context->m_currentHeight); } else m_surfaceOperation &= ~CreateSurface; m_targetRect = IntRect(IntPoint(), m_size); if (m_size.isEmpty()) { if (m_graphicsSurface) { m_graphicsSurface = nullptr; m_surfaceHandle = GraphicsSurfaceToken(); makeContextCurrent(); } return; } m_offScreenContext->releaseCurrent(); GraphicsSurface::Flags flags = GraphicsSurface::SupportsTextureTarget | GraphicsSurface::SupportsSharing; if (m_context->m_attrs.alpha) flags |= GraphicsSurface::SupportsAlpha; m_graphicsSurface = GraphicsSurface::create(m_size, flags, m_offScreenContext->handle()); if (!m_graphicsSurface) m_surfaceHandle = GraphicsSurfaceToken(); else m_surfaceHandle = GraphicsSurfaceToken(m_graphicsSurface->exportToken()); makeContextCurrent(); } void GraphicsContext3DPrivate::didResizeCanvas(const IntSize& size) { if (m_surfaceOperation & CreateSurface) { m_size = size; createGraphicsSurface(); return; } m_surfaceOperation |= Resize; } uint32_t GraphicsContext3DPrivate::copyToGraphicsSurface() { createGraphicsSurface(); if (!m_graphicsSurface || m_context->m_layerComposited || !prepareBuffer()) return 0; m_graphicsSurface->copyFromTexture(m_context->m_texture, m_targetRect); makeContextCurrent(); return m_graphicsSurface->frontBuffer(); } GraphicsSurfaceToken GraphicsContext3DPrivate::graphicsSurfaceToken() const { return m_surfaceHandle; } IntSize GraphicsContext3DPrivate::platformLayerSize() const { return m_size; } GraphicsSurface::Flags GraphicsContext3DPrivate::graphicsSurfaceFlags() const { if (m_graphicsSurface) return m_graphicsSurface->flags(); return TextureMapperPlatformLayer::graphicsSurfaceFlags(); } #endif } // namespace WebCore
loveyoupeng/rt
modules/web/src/main/native/Source/WebCore/platform/graphics/efl/GraphicsContext3DPrivate.cpp
C++
gpl-2.0
8,176
#ifndef FONT_HPP #define FONT_HPP #include "renderer/OpenGL.hpp" #include <string> class Texture; class Font { public: Font(const char *texture); ~Font(); void SetColor(const Math::Vector4f &color) { m_color = color; } void SetPosition(const Math::Vector3f &position) { m_position = position; } void SetScale(const Math::Vector2f &scale) { m_scale = scale; } void drawText(const std::string &text); void drawText(const std::string &text, float x, float y, float z, float r, float g, float b, float a); void drawText(const std::string &text, const Math::Vector3f &position, const Math::Vector4f &color=Math::Vector4f(1.f, 1.f, 1.f, 1.f)); void drawText(const std::string &text, float x, float y, float z=-1.0f); private: void renderAt(const Math::Vector3f &pos, int w, int h, int uo, int vo, const Math::Vector4f &color); Texture* m_texture; Math::Vector2f m_scale; Math::Vector3f m_position; Math::Vector4f m_color; // OpenGL thingamabobs GLuint m_fontVertexArray; // VAO GLuint m_vertexBuffer; // VBO GLuint m_indexBuffer; // IBO GLuint m_vertexPosAttr; // attribute location }; #endif
fluffyfreak/oculusvr_samples
common_src/renderer/Font.hpp
C++
gpl-2.0
1,188
#!/usr/bin/env node console.log("Hello World!");
sumeettalwar/develop
node-js/src/week1/hello.js
JavaScript
gpl-2.0
49
$(document).ready(function(){ $("#startDate").datepicker({dateFormat:'yy-mm-dd'}); $("#endDate").datepicker({dateFormat:'yy-mm-dd'}); //$('#startDate').datepicker(); //$('#endDate').datepicker(); })
sorabhv6/mylib
php_lib/google_analytics/js/custom.js
JavaScript
gpl-2.0
211
// /* -*- Mode:C++; c-file-style:"gnu"; indent-tabs-mode:nil; -*- */ /* * Copyright © 2011 Marcos Talau * * 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * * Author: Marcos Talau (talau@users.sourceforge.net) * * Thanks to: Duy Nguyen<duy@soe.ucsc.edu> by RED efforts in NS3 * * * This file incorporates work covered by the following copyright and * permission notice: * * Copyright (c) 1990-1997 Regents of the University of California. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor of the Laboratory may be used * to endorse or promote products derived from this software without * specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ /* * PORT NOTE: This code was ported from ns-2 (queue/red.cc). Almost all * comments have also been ported from NS-2 */ #include "ns3/log.h" #include "ns3/enum.h" #include "ns3/uinteger.h" #include "ns3/double.h" #include "ns3/simulator.h" #include "ns3/abort.h" #include "red-queue-disc.h" #include "ns3/drop-tail-queue.h" #include "ns3/net-device-queue-interface.h" namespace ns3 { NS_LOG_COMPONENT_DEFINE ("RedQueueDisc"); NS_OBJECT_ENSURE_REGISTERED (RedQueueDisc); TypeId RedQueueDisc::GetTypeId (void) { static TypeId tid = TypeId ("ns3::RedQueueDisc") .SetParent<QueueDisc> () .SetGroupName("TrafficControl") .AddConstructor<RedQueueDisc> () .AddAttribute ("MeanPktSize", "Average of packet size", UintegerValue (500), MakeUintegerAccessor (&RedQueueDisc::m_meanPktSize), MakeUintegerChecker<uint32_t> ()) .AddAttribute ("IdlePktSize", "Average packet size used during idle times. Used when m_cautions = 3", UintegerValue (0), MakeUintegerAccessor (&RedQueueDisc::m_idlePktSize), MakeUintegerChecker<uint32_t> ()) .AddAttribute ("Wait", "True for waiting between dropped packets", BooleanValue (true), MakeBooleanAccessor (&RedQueueDisc::m_isWait), MakeBooleanChecker ()) .AddAttribute ("Gentle", "True to increases dropping probability slowly when average queue exceeds maxthresh", BooleanValue (true), MakeBooleanAccessor (&RedQueueDisc::m_isGentle), MakeBooleanChecker ()) .AddAttribute ("ARED", "True to enable ARED", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_isARED), MakeBooleanChecker ()) .AddAttribute ("AdaptMaxP", "True to adapt m_curMaxP", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_isAdaptMaxP), MakeBooleanChecker ()) .AddAttribute ("FengAdaptive", "True to enable Feng's Adaptive RED", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_isFengAdaptive), MakeBooleanChecker ()) .AddAttribute ("NLRED", "True to enable Nonlinear RED", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_isNonlinear), MakeBooleanChecker ()) .AddAttribute ("MinTh", "Minimum average length threshold in packets/bytes", DoubleValue (5), MakeDoubleAccessor (&RedQueueDisc::m_minTh), MakeDoubleChecker<double> ()) .AddAttribute ("MaxTh", "Maximum average length threshold in packets/bytes", DoubleValue (15), MakeDoubleAccessor (&RedQueueDisc::m_maxTh), MakeDoubleChecker<double> ()) .AddAttribute ("MaxSize", "The maximum number of packets accepted by this queue disc", QueueSizeValue (QueueSize ("25p")), MakeQueueSizeAccessor (&QueueDisc::SetMaxSize, &QueueDisc::GetMaxSize), MakeQueueSizeChecker ()) .AddAttribute ("QW", "Queue weight related to the exponential weighted moving average (EWMA)", DoubleValue (0.002), MakeDoubleAccessor (&RedQueueDisc::m_qW), MakeDoubleChecker <double> ()) .AddAttribute ("LInterm", "The maximum probability of dropping a packet", DoubleValue (50), MakeDoubleAccessor (&RedQueueDisc::m_lInterm), MakeDoubleChecker <double> ()) .AddAttribute ("TargetDelay", "Target average queuing delay in ARED", TimeValue (Seconds (0.005)), MakeTimeAccessor (&RedQueueDisc::m_targetDelay), MakeTimeChecker ()) .AddAttribute ("Interval", "Time interval to update m_curMaxP", TimeValue (Seconds (0.5)), MakeTimeAccessor (&RedQueueDisc::m_interval), MakeTimeChecker ()) .AddAttribute ("Top", "Upper bound for m_curMaxP in ARED", DoubleValue (0.5), MakeDoubleAccessor (&RedQueueDisc::m_top), MakeDoubleChecker <double> (0, 1)) .AddAttribute ("Bottom", "Lower bound for m_curMaxP in ARED", DoubleValue (0.0), MakeDoubleAccessor (&RedQueueDisc::m_bottom), MakeDoubleChecker <double> (0, 1)) .AddAttribute ("Alpha", "Increment parameter for m_curMaxP in ARED", DoubleValue (0.01), MakeDoubleAccessor (&RedQueueDisc::SetAredAlpha), MakeDoubleChecker <double> (0, 1)) .AddAttribute ("Beta", "Decrement parameter for m_curMaxP in ARED", DoubleValue (0.9), MakeDoubleAccessor (&RedQueueDisc::SetAredBeta), MakeDoubleChecker <double> (0, 1)) .AddAttribute ("FengAlpha", "Decrement parameter for m_curMaxP in Feng's Adaptive RED", DoubleValue (3.0), MakeDoubleAccessor (&RedQueueDisc::SetFengAdaptiveA), MakeDoubleChecker <double> ()) .AddAttribute ("FengBeta", "Increment parameter for m_curMaxP in Feng's Adaptive RED", DoubleValue (2.0), MakeDoubleAccessor (&RedQueueDisc::SetFengAdaptiveB), MakeDoubleChecker <double> ()) .AddAttribute ("LastSet", "Store the last time m_curMaxP was updated", TimeValue (Seconds (0.0)), MakeTimeAccessor (&RedQueueDisc::m_lastSet), MakeTimeChecker ()) .AddAttribute ("Rtt", "Round Trip Time to be considered while automatically setting m_bottom", TimeValue (Seconds (0.1)), MakeTimeAccessor (&RedQueueDisc::m_rtt), MakeTimeChecker ()) .AddAttribute ("Ns1Compat", "NS-1 compatibility", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_isNs1Compat), MakeBooleanChecker ()) .AddAttribute ("LinkBandwidth", "The RED link bandwidth", DataRateValue (DataRate ("1.5Mbps")), MakeDataRateAccessor (&RedQueueDisc::m_linkBandwidth), MakeDataRateChecker ()) .AddAttribute ("LinkDelay", "The RED link delay", TimeValue (MilliSeconds (20)), MakeTimeAccessor (&RedQueueDisc::m_linkDelay), MakeTimeChecker ()) .AddAttribute ("UseEcn", "True to use ECN (packets are marked instead of being dropped)", BooleanValue (false), MakeBooleanAccessor (&RedQueueDisc::m_useEcn), MakeBooleanChecker ()) .AddAttribute ("UseHardDrop", "True to always drop packets above max threshold", BooleanValue (true), MakeBooleanAccessor (&RedQueueDisc::m_useHardDrop), MakeBooleanChecker ()) ; return tid; } RedQueueDisc::RedQueueDisc () : QueueDisc (QueueDiscSizePolicy::SINGLE_INTERNAL_QUEUE) { NS_LOG_FUNCTION (this); m_uv = CreateObject<UniformRandomVariable> (); } RedQueueDisc::~RedQueueDisc () { NS_LOG_FUNCTION (this); } void RedQueueDisc::DoDispose (void) { NS_LOG_FUNCTION (this); m_uv = 0; QueueDisc::DoDispose (); } void RedQueueDisc::SetAredAlpha (double alpha) { NS_LOG_FUNCTION (this << alpha); m_alpha = alpha; if (m_alpha > 0.01) { NS_LOG_WARN ("Alpha value is above the recommended bound!"); } } double RedQueueDisc::GetAredAlpha (void) { NS_LOG_FUNCTION (this); return m_alpha; } void RedQueueDisc::SetAredBeta (double beta) { NS_LOG_FUNCTION (this << beta); m_beta = beta; if (m_beta < 0.83) { NS_LOG_WARN ("Beta value is below the recommended bound!"); } } double RedQueueDisc::GetAredBeta (void) { NS_LOG_FUNCTION (this); return m_beta; } void RedQueueDisc::SetFengAdaptiveA (double a) { NS_LOG_FUNCTION (this << a); m_a = a; if (m_a != 3) { NS_LOG_WARN ("Alpha value does not follow the recommendations!"); } } double RedQueueDisc::GetFengAdaptiveA (void) { NS_LOG_FUNCTION (this); return m_a; } void RedQueueDisc::SetFengAdaptiveB (double b) { NS_LOG_FUNCTION (this << b); m_b = b; if (m_b != 2) { NS_LOG_WARN ("Beta value does not follow the recommendations!"); } } double RedQueueDisc::GetFengAdaptiveB (void) { NS_LOG_FUNCTION (this); return m_b; } void RedQueueDisc::SetTh (double minTh, double maxTh) { NS_LOG_FUNCTION (this << minTh << maxTh); NS_ASSERT (minTh <= maxTh); m_minTh = minTh; m_maxTh = maxTh; } int64_t RedQueueDisc::AssignStreams (int64_t stream) { NS_LOG_FUNCTION (this << stream); m_uv->SetStream (stream); return 1; } bool RedQueueDisc::DoEnqueue (Ptr<QueueDiscItem> item) { NS_LOG_FUNCTION (this << item); uint32_t nQueued = GetInternalQueue (0)->GetCurrentSize ().GetValue (); // simulate number of packets arrival during idle period uint32_t m = 0; if (m_idle == 1) { NS_LOG_DEBUG ("RED Queue Disc is idle."); Time now = Simulator::Now (); if (m_cautious == 3) { double ptc = m_ptc * m_meanPktSize / m_idlePktSize; m = uint32_t (ptc * (now - m_idleTime).GetSeconds ()); } else { m = uint32_t (m_ptc * (now - m_idleTime).GetSeconds ()); } m_idle = 0; } m_qAvg = Estimator (nQueued, m + 1, m_qAvg, m_qW); NS_LOG_DEBUG ("\t bytesInQueue " << GetInternalQueue (0)->GetNBytes () << "\tQavg " << m_qAvg); NS_LOG_DEBUG ("\t packetsInQueue " << GetInternalQueue (0)->GetNPackets () << "\tQavg " << m_qAvg); m_count++; m_countBytes += item->GetSize (); uint32_t dropType = DTYPE_NONE; if (m_qAvg >= m_minTh && nQueued > 1) { if ((!m_isGentle && m_qAvg >= m_maxTh) || (m_isGentle && m_qAvg >= 2 * m_maxTh)) { NS_LOG_DEBUG ("adding DROP FORCED MARK"); dropType = DTYPE_FORCED; } else if (m_old == 0) { /* * The average queue size has just crossed the * threshold from below to above m_minTh, or * from above m_minTh with an empty queue to * above m_minTh with a nonempty queue. */ m_count = 1; m_countBytes = item->GetSize (); m_old = 1; } else if (DropEarly (item, nQueued)) { NS_LOG_LOGIC ("DropEarly returns 1"); dropType = DTYPE_UNFORCED; } } else { // No packets are being dropped m_vProb = 0.0; m_old = 0; } if (dropType == DTYPE_UNFORCED) { if (!m_useEcn || !Mark (item, UNFORCED_MARK)) { NS_LOG_DEBUG ("\t Dropping due to Prob Mark " << m_qAvg); DropBeforeEnqueue (item, UNFORCED_DROP); return false; } NS_LOG_DEBUG ("\t Marking due to Prob Mark " << m_qAvg); } else if (dropType == DTYPE_FORCED) { if (m_useHardDrop || !m_useEcn || !Mark (item, FORCED_MARK)) { NS_LOG_DEBUG ("\t Dropping due to Hard Mark " << m_qAvg); DropBeforeEnqueue (item, FORCED_DROP); if (m_isNs1Compat) { m_count = 0; m_countBytes = 0; } return false; } NS_LOG_DEBUG ("\t Marking due to Hard Mark " << m_qAvg); } bool retval = GetInternalQueue (0)->Enqueue (item); // If Queue::Enqueue fails, QueueDisc::DropBeforeEnqueue is called by the // internal queue because QueueDisc::AddInternalQueue sets the trace callback NS_LOG_LOGIC ("Number packets " << GetInternalQueue (0)->GetNPackets ()); NS_LOG_LOGIC ("Number bytes " << GetInternalQueue (0)->GetNBytes ()); return retval; } /* * Note: if the link bandwidth changes in the course of the * simulation, the bandwidth-dependent RED parameters do not change. * This should be fixed, but it would require some extra parameters, * and didn't seem worth the trouble... */ void RedQueueDisc::InitializeParams (void) { NS_LOG_FUNCTION (this); NS_LOG_INFO ("Initializing RED params."); m_cautious = 0; m_ptc = m_linkBandwidth.GetBitRate () / (8.0 * m_meanPktSize); if (m_isARED) { // Set m_minTh, m_maxTh and m_qW to zero for automatic setting m_minTh = 0; m_maxTh = 0; m_qW = 0; // Turn on m_isAdaptMaxP to adapt m_curMaxP m_isAdaptMaxP = true; } if (m_isFengAdaptive) { // Initialize m_fengStatus m_fengStatus = Above; } if (m_minTh == 0 && m_maxTh == 0) { m_minTh = 5.0; // set m_minTh to max(m_minTh, targetqueue/2.0) [Ref: http://www.icir.org/floyd/papers/adaptiveRed.pdf] double targetqueue = m_targetDelay.GetSeconds() * m_ptc; if (m_minTh < targetqueue / 2.0 ) { m_minTh = targetqueue / 2.0; } if (GetMaxSize ().GetUnit () == QueueSizeUnit::BYTES) { m_minTh = m_minTh * m_meanPktSize; } // set m_maxTh to three times m_minTh [Ref: http://www.icir.org/floyd/papers/adaptiveRed.pdf] m_maxTh = 3 * m_minTh; } NS_ASSERT (m_minTh <= m_maxTh); m_qAvg = 0.0; m_count = 0; m_countBytes = 0; m_old = 0; m_idle = 1; double th_diff = (m_maxTh - m_minTh); if (th_diff == 0) { th_diff = 1.0; } m_vA = 1.0 / th_diff; m_curMaxP = 1.0 / m_lInterm; m_vB = -m_minTh / th_diff; if (m_isGentle) { m_vC = (1.0 - m_curMaxP) / m_maxTh; m_vD = 2.0 * m_curMaxP - 1.0; } m_idleTime = NanoSeconds (0); /* * If m_qW=0, set it to a reasonable value of 1-exp(-1/C) * This corresponds to choosing m_qW to be of that value for * which the packet time constant -1/ln(1-m)qW) per default RTT * of 100ms is an order of magnitude more than the link capacity, C. * * If m_qW=-1, then the queue weight is set to be a function of * the bandwidth and the link propagation delay. In particular, * the default RTT is assumed to be three times the link delay and * transmission delay, if this gives a default RTT greater than 100 ms. * * If m_qW=-2, set it to a reasonable value of 1-exp(-10/C). */ if (m_qW == 0.0) { m_qW = 1.0 - std::exp (-1.0 / m_ptc); } else if (m_qW == -1.0) { double rtt = 3.0 * (m_linkDelay.GetSeconds () + 1.0 / m_ptc); if (rtt < 0.1) { rtt = 0.1; } m_qW = 1.0 - std::exp (-1.0 / (10 * rtt * m_ptc)); } else if (m_qW == -2.0) { m_qW = 1.0 - std::exp (-10.0 / m_ptc); } if (m_bottom == 0) { m_bottom = 0.01; // Set bottom to at most 1/W, where W is the delay-bandwidth // product in packets for a connection. // So W = m_linkBandwidth.GetBitRate () / (8.0 * m_meanPktSize * m_rtt.GetSeconds()) double bottom1 = (8.0 * m_meanPktSize * m_rtt.GetSeconds()) / m_linkBandwidth.GetBitRate(); if (bottom1 < m_bottom) { m_bottom = bottom1; } } NS_LOG_DEBUG ("\tm_delay " << m_linkDelay.GetSeconds () << "; m_isWait " << m_isWait << "; m_qW " << m_qW << "; m_ptc " << m_ptc << "; m_minTh " << m_minTh << "; m_maxTh " << m_maxTh << "; m_isGentle " << m_isGentle << "; th_diff " << th_diff << "; lInterm " << m_lInterm << "; va " << m_vA << "; cur_max_p " << m_curMaxP << "; v_b " << m_vB << "; m_vC " << m_vC << "; m_vD " << m_vD); } // Updating m_curMaxP, following the pseudocode // from: A Self-Configuring RED Gateway, INFOCOMM '99. // They recommend m_a = 3, and m_b = 2. void RedQueueDisc::UpdateMaxPFeng (double newAve) { NS_LOG_FUNCTION (this << newAve); if (m_minTh < newAve && newAve < m_maxTh) { m_fengStatus = Between; } else if (newAve < m_minTh && m_fengStatus != Below) { m_fengStatus = Below; m_curMaxP = m_curMaxP / m_a; } else if (newAve > m_maxTh && m_fengStatus != Above) { m_fengStatus = Above; m_curMaxP = m_curMaxP * m_b; } } // Update m_curMaxP to keep the average queue length within the target range. void RedQueueDisc::UpdateMaxP (double newAve) { NS_LOG_FUNCTION (this << newAve); Time now = Simulator::Now (); double m_part = 0.4 * (m_maxTh - m_minTh); // AIMD rule to keep target Q~1/2(m_minTh + m_maxTh) if (newAve < m_minTh + m_part && m_curMaxP > m_bottom) { // we should increase the average queue size, so decrease m_curMaxP m_curMaxP = m_curMaxP * m_beta; m_lastSet = now; } else if (newAve > m_maxTh - m_part && m_top > m_curMaxP) { // we should decrease the average queue size, so increase m_curMaxP double alpha = m_alpha; if (alpha > 0.25 * m_curMaxP) { alpha = 0.25 * m_curMaxP; } m_curMaxP = m_curMaxP + alpha; m_lastSet = now; } } // Compute the average queue size double RedQueueDisc::Estimator (uint32_t nQueued, uint32_t m, double qAvg, double qW) { NS_LOG_FUNCTION (this << nQueued << m << qAvg << qW); double newAve = qAvg * std::pow (1.0 - qW, m); newAve += qW * nQueued; Time now = Simulator::Now (); if (m_isAdaptMaxP && now > m_lastSet + m_interval) { UpdateMaxP (newAve); } else if (m_isFengAdaptive) { UpdateMaxPFeng (newAve); // Update m_curMaxP in MIMD fashion. } return newAve; } // Check if packet p needs to be dropped due to probability mark uint32_t RedQueueDisc::DropEarly (Ptr<QueueDiscItem> item, uint32_t qSize) { NS_LOG_FUNCTION (this << item << qSize); double prob1 = CalculatePNew (); m_vProb = ModifyP (prob1, item->GetSize ()); // Drop probability is computed, pick random number and act if (m_cautious == 1) { /* * Don't drop/mark if the instantaneous queue is much below the average. * For experimental purposes only. * pkts: the number of packets arriving in 50 ms */ double pkts = m_ptc * 0.05; double fraction = std::pow ((1 - m_qW), pkts); if ((double) qSize < fraction * m_qAvg) { // Queue could have been empty for 0.05 seconds return 0; } } double u = m_uv->GetValue (); if (m_cautious == 2) { /* * Decrease the drop probability if the instantaneous * queue is much below the average. * For experimental purposes only. * pkts: the number of packets arriving in 50 ms */ double pkts = m_ptc * 0.05; double fraction = std::pow ((1 - m_qW), pkts); double ratio = qSize / (fraction * m_qAvg); if (ratio < 1.0) { u *= 1.0 / ratio; } } if (u <= m_vProb) { NS_LOG_LOGIC ("u <= m_vProb; u " << u << "; m_vProb " << m_vProb); // DROP or MARK m_count = 0; m_countBytes = 0; /// \todo Implement set bit to mark return 1; // drop } return 0; // no drop/mark } // Returns a probability using these function parameters for the DropEarly function double RedQueueDisc::CalculatePNew (void) { NS_LOG_FUNCTION (this); double p; if (m_isGentle && m_qAvg >= m_maxTh) { // p ranges from m_curMaxP to 1 as the average queue // size ranges from m_maxTh to twice m_maxTh p = m_vC * m_qAvg + m_vD; } else if (!m_isGentle && m_qAvg >= m_maxTh) { /* * OLD: p continues to range linearly above m_curMaxP as * the average queue size ranges above m_maxTh. * NEW: p is set to 1.0 */ p = 1.0; } else { /* * p ranges from 0 to m_curMaxP as the average queue size ranges from * m_minTh to m_maxTh */ p = m_vA * m_qAvg + m_vB; if (m_isNonlinear) { p *= p * 1.5; } p *= m_curMaxP; } if (p > 1.0) { p = 1.0; } return p; } // Returns a probability using these function parameters for the DropEarly function double RedQueueDisc::ModifyP (double p, uint32_t size) { NS_LOG_FUNCTION (this << p << size); double count1 = (double) m_count; if (GetMaxSize ().GetUnit () == QueueSizeUnit::BYTES) { count1 = (double) (m_countBytes / m_meanPktSize); } if (m_isWait) { if (count1 * p < 1.0) { p = 0.0; } else if (count1 * p < 2.0) { p /= (2.0 - count1 * p); } else { p = 1.0; } } else { if (count1 * p < 1.0) { p /= (1.0 - count1 * p); } else { p = 1.0; } } if ((GetMaxSize ().GetUnit () == QueueSizeUnit::BYTES) && (p < 1.0)) { p = (p * size) / m_meanPktSize; } if (p > 1.0) { p = 1.0; } return p; } Ptr<QueueDiscItem> RedQueueDisc::DoDequeue (void) { NS_LOG_FUNCTION (this); if (GetInternalQueue (0)->IsEmpty ()) { NS_LOG_LOGIC ("Queue empty"); m_idle = 1; m_idleTime = Simulator::Now (); return 0; } else { m_idle = 0; Ptr<QueueDiscItem> item = GetInternalQueue (0)->Dequeue (); NS_LOG_LOGIC ("Popped " << item); NS_LOG_LOGIC ("Number packets " << GetInternalQueue (0)->GetNPackets ()); NS_LOG_LOGIC ("Number bytes " << GetInternalQueue (0)->GetNBytes ()); return item; } } Ptr<const QueueDiscItem> RedQueueDisc::DoPeek (void) { NS_LOG_FUNCTION (this); if (GetInternalQueue (0)->IsEmpty ()) { NS_LOG_LOGIC ("Queue empty"); return 0; } Ptr<const QueueDiscItem> item = GetInternalQueue (0)->Peek (); NS_LOG_LOGIC ("Number packets " << GetInternalQueue (0)->GetNPackets ()); NS_LOG_LOGIC ("Number bytes " << GetInternalQueue (0)->GetNBytes ()); return item; } bool RedQueueDisc::CheckConfig (void) { NS_LOG_FUNCTION (this); if (GetNQueueDiscClasses () > 0) { NS_LOG_ERROR ("RedQueueDisc cannot have classes"); return false; } if (GetNPacketFilters () > 0) { NS_LOG_ERROR ("RedQueueDisc cannot have packet filters"); return false; } if (GetNInternalQueues () == 0) { // add a DropTail queue AddInternalQueue (CreateObjectWithAttributes<DropTailQueue<QueueDiscItem> > ("MaxSize", QueueSizeValue (GetMaxSize ()))); } if (GetNInternalQueues () != 1) { NS_LOG_ERROR ("RedQueueDisc needs 1 internal queue"); return false; } if ((m_isARED || m_isAdaptMaxP) && m_isFengAdaptive) { NS_LOG_ERROR ("m_isAdaptMaxP and m_isFengAdaptive cannot be simultaneously true"); } return true; } } // namespace ns3
tomhenderson/ns-3-dev-git
src/traffic-control/model/red-queue-disc.cc
C++
gpl-2.0
26,145
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using LeagueSharp; using LeagueSharp.Common; using Item = LeagueSharp.Common.Items.Item; namespace Kalista { public class ItemManager { private static Obj_AI_Hero player = ObjectManager.Player; // Offensive items public static readonly Item CUTLASS = ItemData.Bilgewater_Cutlass.GetItem(); public static readonly Item BOTRK = ItemData.Blade_of_the_Ruined_King.GetItem(); public static readonly Item YOUMUU = ItemData.Youmuus_Ghostblade.GetItem(); public static bool UseBotrk(Obj_AI_Hero target) { if (Config.BoolLinks["itemsBotrk"].Value && BOTRK.IsReady() && target.IsValidTarget(BOTRK.Range) && player.Health + player.GetItemDamage(target, Damage.DamageItems.Botrk) < player.MaxHealth) { return BOTRK.Cast(target); } else if (Config.BoolLinks["itemsCutlass"].Value && CUTLASS.IsReady() && target.IsValidTarget(CUTLASS.Range)) { return CUTLASS.Cast(target); } return false; } public static bool UseYoumuu(Obj_AI_Base target) { if (Config.BoolLinks["itemsYoumuu"].Value && YOUMUU.IsReady() && target.IsValidTarget(Orbwalking.GetRealAutoAttackRange(player) + 50)) { return YOUMUU.Cast(); } return false; } } }
onuremix/LeagueSharp
Kalista/ItemManager.cs
C#
gpl-2.0
1,531
<?php /** * RokTwittie Module * * @package RocketTheme * @subpackage roktwittie.tmpl * @version 1.8 September 3, 2012 * @author RocketTheme http://www.rockettheme.com * @copyright Copyright (C) 2007 - 2012 RocketTheme, LLC * @license http://www.gnu.org/licenses/gpl-2.0.html GNU/GPLv2 only * */ defined('_JEXEC') or die('Restricted access'); $error = (isset($status) && is_string($status)) ? $status : (isset($friends) ? $friends : ''); $error = (is_string($error)) ? $error : ''; ?> <div id="roktwittie" class="roktwittie<?php echo $params->get('moduleclass_sfx'); ?>"> <div class="error"> <?php echo $error; ?> </div> </div>
jntd11/dev2
modules/mod_roktwittie/tmpl/error.php
PHP
gpl-2.0
650
package com.freezingwind.animereleasenotifier.updater; import android.content.Context; import android.content.SharedPreferences; import android.preference.PreferenceManager; import android.util.Log; import com.android.volley.Request; import com.android.volley.Response; import com.android.volley.VolleyError; import com.android.volley.toolbox.JsonObjectRequest; import com.freezingwind.animereleasenotifier.data.Anime; import com.freezingwind.animereleasenotifier.helpers.NetworkManager; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.util.ArrayList; public class AnimeUpdater { protected ArrayList<Anime> animeList; protected boolean completedOnly; public AnimeUpdater(boolean fetchCompletedOnly) { animeList = new ArrayList<Anime>(); completedOnly = fetchCompletedOnly; } // GetAnimeList public ArrayList<Anime> getAnimeList() { return animeList; } public void update(String response, final Context context, final AnimeListUpdateCallBack callBack) { try { JSONObject responseObject = new JSONObject(response); update(responseObject, context, callBack); } catch(JSONException e) { Log.d("AnimeUpdater", e.toString()); } } public void update(JSONObject response, final Context context, final AnimeListUpdateCallBack callBack) { try { animeList.clear(); SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); SharedPreferences.Editor editor = sharedPrefs.edit(); JSONArray watchingList = response.getJSONArray("watching"); for (int i = 0; i < watchingList.length(); i++) { JSONObject animeJSON = watchingList.getJSONObject(i); JSONObject episodes = animeJSON.getJSONObject("episodes"); JSONObject airingDate = animeJSON.getJSONObject("airingDate"); JSONObject animeProvider = null; try { animeProvider = animeJSON.getJSONObject("animeProvider"); } catch(JSONException e) { //Log.d("AnimeUpdater", "No anime provider available"); } Anime anime = new Anime( animeJSON.getString("title"), animeJSON.getString("image"), animeJSON.getString("url"), animeProvider != null ? animeProvider.getString("url") : "", animeProvider != null ? animeProvider.getString("nextEpisodeUrl") : "", animeProvider != null ? animeProvider.getString("videoUrl") : "", episodes.getInt("watched"), episodes.getInt("available"), episodes.getInt("max"), episodes.getInt("offset"), airingDate.getString("remainingString"), completedOnly ? "completed" : "watching" ); // Load cached episode count String key = anime.title + ":episodes-available"; int availableCached = sharedPrefs.getInt(key, -1); anime.notify = anime.available > availableCached && availableCached != -1; // Save data in preferences editor.putInt(anime.title + ":episodes-available", anime.available); // Add to list animeList.add(anime); } // Write preferences editor.apply(); } catch (JSONException e) { Log.d("AnimeUpdater", "Error parsing JSON: " + e.toString()); } finally { callBack.execute(); } } // Update public void updateByUser(String userName, final Context context, final AnimeListUpdateCallBack callBack) { String apiUrl = "https://animereleasenotifier.com/api/animelist/" + userName; if(completedOnly) apiUrl += "&completed=1"; final SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(context); apiUrl += "&animeProvider=" + sharedPrefs.getString("animeProvider", "KissAnime"); //Toast.makeText(activity, "Loading anime list of " + userName, Toast.LENGTH_SHORT).show(); final JsonObjectRequest jsObjRequest = new JsonObjectRequest(Request.Method.GET, apiUrl, (String)null, new Response.Listener<JSONObject>() { @Override public void onResponse(JSONObject response) { update(response, context, callBack); // Cache it SharedPreferences.Editor editor = sharedPrefs.edit(); editor.putString("cachedAnimeListJSON" + (completedOnly ? "Completed" : ""), response.toString()); editor.apply(); } }, new Response.ErrorListener() { @Override public void onErrorResponse(VolleyError error) { System.out.println("Error: " + error.toString()); } }); NetworkManager.getRequestQueue().add(jsObjRequest); } }
animenotifier/anime-release-notifier-android
app/src/main/java/com/freezingwind/animereleasenotifier/updater/AnimeUpdater.java
Java
gpl-2.0
4,366
sap.ui.define([ "sap/ui/core/UIComponent", "sap/ui/Device", "opensap/manageproducts/model/models", "opensap/manageproducts/controller/ErrorHandler" ], function (UIComponent, Device, models, ErrorHandler) { "use strict"; return UIComponent.extend("opensap.manageproducts.Component", { metadata : { manifest: "json" }, /** * The component is initialized by UI5 automatically during the startup of the app and calls the init method once. * In this function, the device models are set and the router is initialized. * @public * @override */ init : function () { // call the base component's init function UIComponent.prototype.init.apply(this, arguments); // initialize the error handler with the component this._oErrorHandler = new ErrorHandler(this); // set the device model this.setModel(models.createDeviceModel(), "device"); // create the views based on the url/hash this.getRouter().initialize(); }, /** * The component is destroyed by UI5 automatically. * In this method, the ErrorHandler is destroyed. * @public * @override */ destroy : function () { this._oErrorHandler.destroy(); // call the base component's destroy function UIComponent.prototype.destroy.apply(this, arguments); }, /** * This method can be called to determine whether the sapUiSizeCompact or sapUiSizeCozy * design mode class should be set, which influences the size appearance of some controls. * @public * @return {string} css class, either 'sapUiSizeCompact' or 'sapUiSizeCozy' - or an empty string if no css class should be set */ getContentDensityClass : function() { if (this._sContentDensityClass === undefined) { // check whether FLP has already set the content density class; do nothing in this case if (jQuery(document.body).hasClass("sapUiSizeCozy") || jQuery(document.body).hasClass("sapUiSizeCompact")) { this._sContentDensityClass = ""; } else if (!Device.support.touch) { // apply "compact" mode if touch is not supported this._sContentDensityClass = "sapUiSizeCompact"; } else { // "cozy" in case of touch support; default for most sap.m controls, but needed for desktop-first controls like sap.ui.table.Table this._sContentDensityClass = "sapUiSizeCozy"; } } return this._sContentDensityClass; } }); } );
carlitosalcala/openui
ManageProducts/webapp/Component.js
JavaScript
gpl-2.0
2,424
<div class="categoryMenu"> <ul> <?php foreach($root_categories as $key => $value) { if($key == 13) echo "<div class='hiddenCategories'>"; ?> <li<?php if($key == 0) { ?> class="first"<?php } ?>><a href="<?php echo zen_href_link('index', zen_get_path($value['id']));?>"><?php echo $value['text'] ?></a></li> <?php if($key == $catcount - 1) echo "</div>"; } ?> <li class="last"><a href="#">All Categories &gt;&gt;</a></li> </ul> </div> <div class="clear"></div>
joshyan/everymarket
includes/templates/everymarket_classic/common/tpl_left_categories.php
PHP
gpl-2.0
536
<?php /* ** Zabbix ** Copyright (C) 2001-2013 Zabbix SIA ** ** 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. **/ class CConfigFile { const CONFIG_NOT_FOUND = 1; const CONFIG_ERROR = 2; const CONFIG_FILE_PATH = '/conf/zabbix.conf.php'; public $configFile = null; public $config = array(); public $error = ''; private static function exception($error, $code = self::CONFIG_ERROR) { throw new ConfigFileException($error, $code); } public function __construct($file = null) { $this->setDefaults(); if (!is_null($file)) { $this->setFile($file); } } public function setFile($file) { $this->configFile = $file; } public function load() { if (!file_exists($this->configFile)) { self::exception('Config file does not exist.', self::CONFIG_NOT_FOUND); } if (!is_readable($this->configFile)) { self::exception('Permission denied.'); } ob_start(); include($this->configFile); ob_end_clean(); // config file in plain php is bad $dbs = array(ZBX_DB_MYSQL, ZBX_DB_POSTGRESQL, ZBX_DB_ORACLE, ZBX_DB_DB2, ZBX_DB_SQLITE3); if (!isset($DB['TYPE'])) { self::exception('DB type is not set.'); } elseif (isset($DB['TYPE']) && !in_array($DB['TYPE'], $dbs)) { self::exception('DB type has wrong value. Possible values '.implode(', ', $dbs)); } elseif (!isset($DB['DATABASE'])) { self::exception('DB database is not set.'); } $this->setDefaults(); if (isset($DB['TYPE'])) { $this->config['DB']['TYPE'] = $DB['TYPE']; } if (isset($DB['DATABASE'])) { $this->config['DB']['DATABASE'] = $DB['DATABASE']; } if (isset($DB['SERVER'])) { $this->config['DB']['SERVER'] = $DB['SERVER']; } if (isset($DB['PORT'])) { $this->config['DB']['PORT'] = $DB['PORT']; } if (isset($DB['USER'])) { $this->config['DB']['USER'] = $DB['USER']; } if (isset($DB['PASSWORD'])) { $this->config['DB']['PASSWORD'] = $DB['PASSWORD']; } if (isset($DB['SCHEMA'])) { $this->config['DB']['SCHEMA'] = $DB['SCHEMA']; } if (isset($ZBX_SERVER)) { $this->config['ZBX_SERVER'] = $ZBX_SERVER; } if (isset($ZBX_SERVER_PORT)) { $this->config['ZBX_SERVER_PORT'] = $ZBX_SERVER_PORT; } if (isset($ZBX_SERVER_NAME)) { $this->config['ZBX_SERVER_NAME'] = $ZBX_SERVER_NAME; } $this->makeGlobal(); return $this->config; } public function makeGlobal() { global $DB, $ZBX_SERVER, $ZBX_SERVER_PORT, $ZBX_SERVER_NAME; $DB = $this->config['DB']; $ZBX_SERVER = $this->config['ZBX_SERVER']; $ZBX_SERVER_PORT = $this->config['ZBX_SERVER_PORT']; $ZBX_SERVER_NAME = $this->config['ZBX_SERVER_NAME']; } public function save() { try { if (is_null($this->configFile)) { self::exception('Cannot save, config file is not set.'); } $this->check(); if (!file_put_contents($this->configFile, $this->getString())) { self::exception('Cannot write config file.'); } } catch (Exception $e) { $this->error = $e->getMessage(); return false; } } public function getString() { return '<?php // Zabbix GUI configuration file global $DB; $DB[\'TYPE\'] = \''.addcslashes($this->config['DB']['TYPE'], "'\\").'\'; $DB[\'SERVER\'] = \''.addcslashes($this->config['DB']['SERVER'], "'\\").'\'; $DB[\'PORT\'] = \''.addcslashes($this->config['DB']['PORT'], "'\\").'\'; $DB[\'DATABASE\'] = \''.addcslashes($this->config['DB']['DATABASE'], "'\\").'\'; $DB[\'USER\'] = \''.addcslashes($this->config['DB']['USER'], "'\\").'\'; $DB[\'PASSWORD\'] = \''.addcslashes($this->config['DB']['PASSWORD'], "'\\").'\'; // SCHEMA is relevant only for IBM_DB2 database $DB[\'SCHEMA\'] = \''.addcslashes($this->config['DB']['SCHEMA'], "'\\").'\'; $ZBX_SERVER = \''.addcslashes($this->config['ZBX_SERVER'], "'\\").'\'; $ZBX_SERVER_PORT = \''.addcslashes($this->config['ZBX_SERVER_PORT'], "'\\").'\'; $ZBX_SERVER_NAME = \''.addcslashes($this->config['ZBX_SERVER_NAME'], "'\\").'\'; $IMAGE_FORMAT_DEFAULT = IMAGE_FORMAT_PNG; ?> '; } protected function setDefaults() { $this->config['DB'] = array( 'TYPE' => null, 'SERVER' => 'localhost', 'PORT' => '0', 'DATABASE' => null, 'USER' => '', 'PASSWORD' => '', 'SCHEMA' => '' ); $this->config['ZBX_SERVER'] = 'localhost'; $this->config['ZBX_SERVER_PORT'] = '10051'; $this->config['ZBX_SERVER_NAME'] = ''; } protected function check() { $dbs = array(ZBX_DB_MYSQL, ZBX_DB_POSTGRESQL, ZBX_DB_ORACLE, ZBX_DB_DB2, ZBX_DB_SQLITE3); if (!isset($this->config['DB']['TYPE'])) { self::exception('DB type is not set.'); } elseif (!in_array($this->config['DB']['TYPE'], $dbs)) { self::exception('DB type has wrong value. Possible values '.implode(', ', $dbs)); } elseif (!isset($this->config['DB']['DATABASE'])) { self::exception('DB database is not set.'); } } }
volter/zabbix-d3
include/classes/class.cconfigfile.php
PHP
gpl-2.0
5,446
/* * Copyright (C) 2010-2012 Project SkyFire <http://www.projectskyfire.org/> * Copyright (C) 2008-2012 TrinityCore <http://www.trinitycore.org/> * Copyright (C) 2005-2012 MaNGOS <http://getmangos.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, see <http://www.gnu.org/licenses/>. */ #include "Common.h" #include "ObjectAccessor.h" #include "ObjectMgr.h" #include "WorldPacket.h" #include "WorldSession.h" #include "Battlefield.h" #include "BattlefieldMgr.h" #include "Opcodes.h" //This send to player windows for invite player to join the war //Param1:(BattleId) the BattleId of Bf //Param2:(ZoneId) the zone where the battle is (4197 for wg) //Param3:(time) Time in second that the player have for accept void WorldSession::SendBfInvitePlayerToWar(uint32 BattleId, uint32 ZoneId, uint32 p_time) { //Send packet WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTRY_INVITE, 16); data << uint32(0); data << uint32(ZoneId); data << uint64(BattleId | 0x20000); //Sending the packet to player SendPacket(&data); } //This send invitation to player to join the queue //Param1:(BattleId) the BattleId of Bf void WorldSession::SendBfInvitePlayerToQueue(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_INVITE, 5); data << uint8(0); data << uint8(1); // warmup data << uint32(0); data << uint32(0); data << uint32(0); data << uint32(0); data << uint32(0); data << uint64(BattleId); // BattleId //warmup ? used ? //Sending packet to player SendPacket(&data); } //This send packet for inform player that he join queue //Param1:(BattleId) the BattleId of Bf //Param2:(ZoneId) the zone where the battle is (4197 for wg) void WorldSession::SendBfQueueInviteResponce(uint32 BattleId, uint32 ZoneId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_QUEUE_REQUEST_RESPONSE, 11); data << uint8(0); // unk, Logging In??? data << uint64(BattleId); data << uint32(ZoneId); data << uint64(GetPlayer()->GetGUID()); data << uint8(1); // 1 = accepted, 0 = You cant join queue right now data << uint8(1); // 1 = queued for next battle, 0 = you are queued, please wait... SendPacket(&data); } //This is call when player accept to join war //Param1:(BattleId) the BattleId of Bf void WorldSession::SendBfEntered(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_ENTERED, 7); data << uint32(BattleId); data << uint8(1); //unk data << uint8(1); //unk data << uint8(_player->isAFK()?1:0); //Clear AFK SendPacket(&data); } //Send when player is kick from Battlefield void WorldSession::SendBfLeaveMessage(uint32 BattleId) { WorldPacket data(SMSG_BATTLEFIELD_MGR_EJECTED, 7); data << uint8(8); //byte Reason data << uint8(2); //byte BattleStatus data << uint64(BattleId); data << uint8(0); //bool Relocated SendPacket(&data); } //Send by client when he click on accept for queue void WorldSession::HandleBfQueueInviteResponse(WorldPacket & recv_data) { uint32 BattleId; uint8 Accepted; recv_data >> BattleId >> Accepted; sLog->outError("HandleQueueInviteResponse: BattleID:%u Accepted:%u", BattleId, Accepted); Battlefield* Bf = sBattlefieldMgr.GetBattlefieldByBattleId(BattleId); if (!Bf) return; if (Accepted) { Bf->PlayerAcceptInviteToQueue(_player); } } //Send by client on clicking in accept or refuse of invitation windows for join game void WorldSession::HandleBfEntryInviteResponse(WorldPacket & recv_data) { uint64 data; uint8 Accepted; recv_data >> Accepted >> data; uint64 BattleId = data &~ 0x20000; Battlefield* Bf= sBattlefieldMgr.GetBattlefieldByBattleId((uint32)BattleId); if(!Bf) return; //If player accept invitation if (Accepted) { Bf->PlayerAcceptInviteToWar(_player); } else { if (_player->GetZoneId() == Bf->GetZoneId()) Bf->KickPlayerFromBf(_player->GetGUID()); } } void WorldSession::HandleBfExitRequest(WorldPacket & recv_data) { uint32 BattleId; recv_data >> BattleId; sLog->outError("HandleBfExitRequest: BattleID:%u ", BattleId); Battlefield* Bf = sBattlefieldMgr.GetBattlefieldByBattleId(BattleId); if (!Bf) return; Bf->AskToLeaveQueue(_player); }
Macavity/SkyFireEMU
src/server/game/Handlers/BattlefieldHandler.cpp
C++
gpl-2.0
4,910
<?php /** * Admin functions for post types * * @author WooThemes * @category Admin * @package WooCommerce/Admin/Post Types * @version 2.1.0 */ if ( ! defined( 'ABSPATH' ) ) exit; // Exit if accessed directly if ( ! class_exists( 'WC_Admin_CPT' ) ) : /** * WC_Admin_CPT Class */ class WC_Admin_CPT { protected $type = ''; /** * Constructor */ public function __construct() { // Insert into X media browser add_filter( 'media_view_strings', array( $this, 'change_insert_into_post' ) ); } /** * Change label for insert buttons. * * @access public * @param mixed $translation * @param mixed $original * @return void */ function change_insert_into_post( $strings ) { global $post_type; if ( $post_type == $this->type ) { $obj = get_post_type_object( $this->type ); $strings['insertIntoPost'] = sprintf( __( 'Insert into %s', 'woocommerce' ), $obj->labels->singular_name ); $strings['uploadedToThisPost'] = sprintf( __( 'Uploaded to this %s', 'woocommerce' ), $obj->labels->singular_name ); } return $strings; } } endif;
Minasokoni/coasties
wp-content/plugins/woocommerce/includes/admin/post-types/class-wc-admin-cpt.php
PHP
gpl-2.0
1,091
<?php /** * Generates the normalizer data file for Malayalam. * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. * http://www.gnu.org/copyleft/gpl.html * * @file * @ingroup MaintenanceLanguage */ require_once __DIR__ . '/../Maintenance.php'; /** * Generates the normalizer data file for Malayalam. * For NFC see includes/compat/normal. * * @ingroup MaintenanceLanguage */ class GenerateNormalizerDataMl extends Maintenance { public function __construct() { parent::__construct(); $this->mDescription = 'Generate the normalizer data file for Malayalam'; } public function getDbType() { return Maintenance::DB_NONE; } public function execute() { $hexPairs = array( # From http://unicode.org/versions/Unicode5.1.0/#Malayalam_Chillu_Characters '0D23 0D4D 200D' => '0D7A', '0D28 0D4D 200D' => '0D7B', '0D30 0D4D 200D' => '0D7C', '0D32 0D4D 200D' => '0D7D', '0D33 0D4D 200D' => '0D7E', # From http://permalink.gmane.org/gmane.science.linguistics.wikipedia.technical/46413 '0D15 0D4D 200D' => '0D7F', ); $pairs = array(); foreach ( $hexPairs as $hexSource => $hexDest ) { $source = UtfNormal\Utils::hexSequenceToUtf8( $hexSource ); $dest = UtfNormal\Utils::hexSequenceToUtf8( $hexDest ); $pairs[$source] = $dest; } global $IP; file_put_contents( "$IP/serialized/normalize-ml.ser", serialize( $pairs ) ); echo "ml: " . count( $pairs ) . " pairs written.\n"; } } $maintClass = 'GenerateNormalizerDataMl'; require_once RUN_MAINTENANCE_IF_MAIN;
lcp0578/mediawiki
maintenance/language/generateNormalizerDataMl.php
PHP
gpl-2.0
2,183
/* * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER * * Copyright (c) 2012-2013 Universidad Politécnica de Madrid * Copyright (c) 2012-2013 the Center for Open Middleware * * 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. */ /*global gettext, ngettext, interpolate, StyledElements, Wirecloud*/ (function () { "use strict"; /************************************************************************* * Private functions *************************************************************************/ var updateErrorInfo = function updateErrorInfo() { var label, errorCount = this.entity.logManager.getErrorCount(); this.log_button.setDisabled(errorCount === 0); label = ngettext("%(errorCount)s error", "%(errorCount)s errors", errorCount); label = interpolate(label, {errorCount: errorCount}, true); this.log_button.setTitle(label); }; /************************************************************************* * Constructor *************************************************************************/ /** * GenericInterface Class */ var GenericInterface = function GenericInterface(extending, wiringEditor, entity, title, manager, className, isGhost) { if (extending === true) { return; } var del_button, log_button, type, msg, ghostNotification; StyledElements.Container.call(this, {'class': className}, []); Object.defineProperty(this, 'entity', {value: entity}); this.editingPos = false; this.targetAnchorsByName = {}; this.sourceAnchorsByName = {}; this.targetAnchors = []; this.sourceAnchors = []; this.wiringEditor = wiringEditor; this.title = title; this.className = className; this.initPos = {'x': 0, 'y': 0}; this.draggableSources = []; this.draggableTargets = []; this.activatedTree = null; this.hollowConnections = {}; this.fullConnections = {}; this.subdataConnections = {}; this.isMinimized = false; this.minWidth = ''; this.movement = false; this.numberOfSources = 0; this.numberOfTargets = 0; this.potentialArrow = null; // Only for minimize maximize operators. this.initialPos = null; this.isGhost = isGhost; this.readOnlyEndpoints = 0; this.readOnly = false; if (manager instanceof Wirecloud.ui.WiringEditor.ArrowCreator) { this.isMiniInterface = false; this.arrowCreator = manager; } else { this.isMiniInterface = true; this.arrowCreator = null; } // Interface buttons, not for miniInterface if (!this.isMiniInterface) { if (className == 'iwidget') { type = 'widget'; this.version = this.entity.version; this.vendor = this.entity.vendor; this.name = this.entity.name; } else { type = 'operator'; this.version = this.entity.meta.version; this.vendor = this.entity.meta.vendor; this.name = this.entity.meta.name; } // header, sources and targets for the widget this.resourcesDiv = new StyledElements.BorderLayout({'class': "geContainer"}); this.sourceDiv = this.resourcesDiv.getEastContainer(); this.sourceDiv.addClassName("sources"); this.targetDiv = this.resourcesDiv.getWestContainer(); this.targetDiv.addClassName("targets"); this.header = this.resourcesDiv.getNorthContainer(); this.header.addClassName('header'); this.wrapperElement.appendChild(this.resourcesDiv.wrapperElement); // Ghost interface if (isGhost) { this.vendor = this.entity.name.split('/')[0]; this.name = this.entity.name.split('/')[1]; this.version = new Wirecloud.Version(this.entity.name.split('/')[2].trim()); this.wrapperElement.classList.add('ghost'); ghostNotification = document.createElement("span"); ghostNotification.classList.add('ghostNotification'); msg = gettext('Warning: %(type)s not found!'); msg = interpolate(msg, {type: type}, true); ghostNotification.textContent = msg; this.header.appendChild(ghostNotification); } // Version Status if (type == 'operator' && this.wiringEditor.operatorVersions[this.vendor + '/' + this.name] && this.wiringEditor.operatorVersions[this.vendor + '/' + this.name].lastVersion.compareTo(this.version) > 0) { // Old Entity Version this.versionStatus = document.createElement("span"); this.versionStatus.classList.add('status'); this.versionStatus.classList.add('icon-exclamation-sign'); this.versionStatus.setAttribute('title', 'Outdated Version (' + this.version.text + ')'); this.header.appendChild(this.versionStatus); this.wrapperElement.classList.add('old') } // Widget name this.nameElement = document.createElement("span"); this.nameElement.textContent = title; this.nameElement.title = title; this.header.appendChild(this.nameElement); // Close button del_button = new StyledElements.StyledButton({ 'title': gettext("Remove"), 'class': 'closebutton icon-remove', 'plain': true }); del_button.insertInto(this.header); del_button.addEventListener('click', function () { if (this.readOnly == true) { return; } if (className == 'iwidget') { this.wiringEditor.events.widgetremoved.dispatch(this); } else { this.wiringEditor.events.operatorremoved.dispatch(this); } }.bind(this)); // Log button this.log_button = new StyledElements.StyledButton({ 'plain': true, 'class': 'logbutton icon-warning-sign' }); if (!isGhost) { this.log_button.addEventListener("click", function () { var dialog = new Wirecloud.ui.LogWindowMenu(this.entity.logManager); dialog.show(); }.bind(this)); updateErrorInfo.call(this); this.entity.logManager.addEventListener('newentry', updateErrorInfo.bind(this)); } else { this.log_button.disable(); } this.log_button.insertInto(this.header); // special icon for minimized interface this.iconAux = document.createElement("div"); this.iconAux.classList.add("specialIcon"); this.iconAux.classList.add("icon-cogs"); this.iconAux.setAttribute('title', title); this.resourcesDiv.wrapperElement.appendChild(this.iconAux); this.iconAux.addEventListener('click', function () { if (!this.movement) { this.restore(); } }.bind(this)); // Add a menu button except on mini interfaces this.menu_button = new StyledElements.PopupButton({ 'title': gettext("Menu"), 'class': 'editPos_button icon-cog', 'plain': true }); this.menu_button.insertInto(this.header); this.menu_button.popup_menu.append(new Wirecloud.ui.WiringEditor.GenericInterfaceSettingsMenuItems(this)); } else { // MiniInterface this.header = document.createElement("div"); this.header.classList.add('header'); this.wrapperElement.appendChild(this.header); // MiniInterface name this.nameElement = document.createElement("span"); this.nameElement.textContent = title; this.header.appendChild(this.nameElement); // MiniInterface status this.miniStatus = document.createElement("span"); this.miniStatus.classList.add('status'); this.miniStatus.classList.add('icon-exclamation-sign'); this.miniStatus.setAttribute('title', gettext('Warning! this is an old version of the operator, click to change the version')); this._miniwidgetMenu_button_callback = function _miniwidgetMenu_button_callback(e) { // Context Menu e.stopPropagation(); if (this.contextmenu.isVisible()) { this.contextmenu.hide(); } else { this.contextmenu.show(this.wrapperElement.getBoundingClientRect()); } return; }.bind(this); this.miniStatus.addEventListener('mousedown', Wirecloud.Utils.stopPropagationListener, false); this.miniStatus.addEventListener('click', this._miniwidgetMenu_button_callback, false); this.miniStatus.addEventListener('contextmenu', this._miniwidgetMenu_button_callback, false); this.header.appendChild(this.miniStatus); // MiniInterface Context Menu if (className == 'ioperator') { this.contextmenu = new StyledElements.PopupMenu({'position': ['bottom-left', 'top-left']}); this._miniwidgetMenu_callback = function _miniwidgetMenu_callback(e) { // Context Menu e.stopPropagation(); if (e.button === 2) { if (this.contextmenu.isVisible()) { this.contextmenu.hide(); } else { this.contextmenu.show(this.wrapperElement.getBoundingClientRect()); } return; } }.bind(this); this.wrapperElement.addEventListener('mousedown', this._miniwidgetMenu_callback, false); this.contextmenu.append(new Wirecloud.ui.WiringEditor.MiniInterfaceSettingsMenuItems(this)); } this.wrapperElement.addEventListener('contextmenu', Wirecloud.Utils.preventDefaultListener); } // Draggable if (!this.isMiniInterface) { this.makeDraggable(); } else { //miniInterface this.draggable = new Wirecloud.ui.Draggable(this.wrapperElement, {iObject: this}, function onStart(draggable, context) { var miniwidget_clon, pos_miniwidget, headerHeight; headerHeight = context.iObject.wiringEditor.getBoundingClientRect().top; //initial position pos_miniwidget = context.iObject.getBoundingClientRect(); context.y = pos_miniwidget.top - (headerHeight); context.x = pos_miniwidget.left; //create a miniwidget clon if (context.iObject instanceof Wirecloud.ui.WiringEditor.WidgetInterface) { miniwidget_clon = new Wirecloud.ui.WiringEditor.WidgetInterface(context.iObject.wiringEditor, context.iObject.iwidget, context.iObject.wiringEditor, true); } else { miniwidget_clon = new Wirecloud.ui.WiringEditor.OperatorInterface(context.iObject.wiringEditor, context.iObject.ioperator, context.iObject.wiringEditor, true); } miniwidget_clon.addClassName('clon'); //set the clon position over the originar miniWidget miniwidget_clon.setBoundingClientRect(pos_miniwidget, {top: -headerHeight, left: 0, width: -2, height: -10}); // put the miniwidget clon in the layout context.iObject.wiringEditor.layout.wrapperElement.appendChild(miniwidget_clon.wrapperElement); //put the clon in the context.iObject context.iObjectClon = miniwidget_clon; }, function onDrag(e, draggable, context, xDelta, yDelta) { context.iObjectClon.setPosition({posX: context.x + xDelta, posY: context.y + yDelta}); context.iObjectClon.repaint(); }, this.onFinish.bind(this), function () { return this.enabled && !this.wrapperElement.classList.contains('clon'); }.bind(this) ); }//else miniInterface }; GenericInterface.prototype = new StyledElements.Container({'extending': true}); /************************************************************************* * Private methods *************************************************************************/ var getElementPos = function getElementPos(elemList, elem) { var i; for (i = 0; i < elemList.length; i++) { if (elem === elemList[i]) { return i; } } }; /** * @Private * is empty object? */ var isEmpty = function isEmpty(obj) { for(var key in obj) { return false; } return true; }; var createMulticonnector = function createMulticonnector(name, anchor) { var multiconnector; multiconnector = new Wirecloud.ui.WiringEditor.Multiconnector(this.wiringEditor.nextMulticonnectorId, this.getId(), name, this.wiringEditor.layout.getCenterContainer().wrapperElement, this.wiringEditor, anchor, null, null); this.wiringEditor.nextMulticonnectorId = parseInt(this.wiringEditor.nextMulticonnectorId, 10) + 1; this.wiringEditor.addMulticonnector(multiconnector); multiconnector.addMainArrow(); }; /** * OutputSubendpoint */ var OutputSubendpoint = function OutputSubendpoint(name, description, iwidget, type) { var nameList, subdata, i; this.iwidget = iwidget; this.name = name; this.subdata = description.subdata; this.variable = description; this.type = type; this.friendcode = description.friendcode; nameList = name.split('/'); subdata = JSON.parse(description.subdata); for (i = 1; i < nameList.length; i++) { if (nameList[0] == nameList[1]) { break; } subdata = subdata[nameList[i]]; this.friendcode = subdata.semanticType; subdata = subdata.subdata; } }; /** * Serialize OutputSubendpoint */ OutputSubendpoint.prototype.serialize = function serialize() { return { 'type': this.type, 'id': this.iwidget.id, 'endpoint': this.name }; }; /** * Set ActionLabel listeners in a endpoint */ var setlabelActionListeners = function setlabelActionListeners(labelActionLayer, checkbox) { // Emphasize listeners labelActionLayer.addEventListener('mouseover',function (thecheckbox) { this.wiringEditor.recommendations.emphasize(thecheckbox); }.bind(this, checkbox), false); labelActionLayer.addEventListener('mouseout',function (thecheckbox) { this.wiringEditor.recommendations.deemphasize(thecheckbox); }.bind(this, checkbox), false); checkbox.wrapperElement.addEventListener('mouseover',function (thecheckbox) { this.wiringEditor.recommendations.emphasize(thecheckbox); }.bind(this, checkbox), false); checkbox.wrapperElement.addEventListener('mouseout',function (thecheckbox) { this.wiringEditor.recommendations.deemphasize(thecheckbox); }.bind(this, checkbox), false); // Sticky effect labelActionLayer.addEventListener('mouseover', checkbox._mouseover_callback, false); labelActionLayer.addEventListener('mouseout', checkbox._mouseout_callback, false); // Connect anchor whith mouseup on the label labelActionLayer.addEventListener('mouseup', checkbox._mouseup_callback, false); }; /** * format Tree */ var formatTree = function(treeDiv, entityWidth) { var heightPerLeaf, branchList, i, j, nleafsAux, desp, checkbox, label, height, firstFrame, firstTree, width, diff, treeWidth, actionLayer, bounding, treeBounding, leafs, lastTop, subtrees; firstFrame = treeDiv.getElementsByClassName("labelsFrame")[0]; firstTree = treeDiv.getElementsByClassName("tree")[0]; diff = (firstTree.getBoundingClientRect().top - firstFrame.getBoundingClientRect().top); if (diff == -10) { return; } firstFrame.style.top = diff + 10 + 'px'; height = firstFrame.getBoundingClientRect().height + 10; width = firstFrame.getBoundingClientRect().width; firstTree.style.height = height + 10 + 'px'; treeWidth = treeDiv.getBoundingClientRect().width; if (treeWidth < entityWidth - 14) { treeDiv.style.width = entityWidth - 14 + 'px'; treeDiv.style.left = 7 + 'px'; } treeDiv.style.height = height + 'px'; // Vertical Alignment leafs = treeDiv.getElementsByClassName('leaf'); heightPerLeaf = height/leafs.length; branchList = treeDiv.getElementsByClassName("dataTree branch"); for (i = 0; i < branchList.length; i++) { // Set Label position nleafsAux = branchList[i].getElementsByClassName('leaf').length; desp = -(((nleafsAux / 2) * heightPerLeaf) - (heightPerLeaf / 2)); label = branchList[i].getElementsByClassName('labelTree')[branchList[i].getElementsByClassName('labelTree').length - 1]; // Set label and anchor position checkbox = branchList[i].getElementsByClassName('subAnchor')[branchList[i].getElementsByClassName('subAnchor').length - 1]; label.style.top = desp + 'px'; checkbox.style.top = desp + 'px'; // Set action layer bounding for the label treeBounding = branchList[i].getBoundingClientRect(); if (i == 0) { lastTop = treeBounding.top; } actionLayer = branchList[i].nextElementSibling; bounding = label.getBoundingClientRect(); actionLayer.style.height = bounding.height + 'px'; actionLayer.style.width = bounding.width + 'px'; actionLayer.style.left = (bounding.left - treeBounding.left) + 'px'; actionLayer.style.top = Math.abs(lastTop - bounding.top) + 'px'; lastTop = treeBounding.top + 1; // Set leaf action layers setLeafActionLayers(branchList[i].parentNode.children); // Set leaf action layers in only-leafs subtree if (branchList[i].getElementsByClassName("dataTree branch").length == 0) { subtrees = branchList[i].getElementsByClassName('subTree'); for (j = 0; j < subtrees.length; j++) { // All leafs subtree found setLeafActionLayers(subtrees[j].getElementsByClassName('labelsFrame')[0].children); } } } }; var setLeafActionLayers = function setLeafActionLayers (brothers) { var acumulatedTop, j, treeBounding, bounding, actionLayer; acumulatedTop = 5; for (j = 0; j < brothers.length; j += 2) { treeBounding = brothers[j].getBoundingClientRect(); if (brothers[j].hasClassName('dataTree leaf')) { bounding = brothers[j].getElementsByClassName('labelTree')[0].getBoundingClientRect(); actionLayer = brothers[j].nextElementSibling; actionLayer.style.height = bounding.height + 'px'; actionLayer.style.width = bounding.width + 'px'; actionLayer.style.left = (bounding.left - treeBounding.left) + 'px'; actionLayer.style.top = acumulatedTop + 'px'; } acumulatedTop += treeBounding.height; } }; /************************************************************************* * Public methods *************************************************************************/ /** * Making Interface Draggable. */ GenericInterface.prototype.makeDraggable = function makeDraggable() { this.draggable = new Wirecloud.ui.Draggable(this.wrapperElement, {iObject: this}, function onStart(draggable, context) { context.y = context.iObject.wrapperElement.style.top === "" ? 0 : parseInt(context.iObject.wrapperElement.style.top, 10); context.x = context.iObject.wrapperElement.style.left === "" ? 0 : parseInt(context.iObject.wrapperElement.style.left, 10); context.preselected = context.iObject.selected; context.iObject.select(true); context.iObject.wiringEditor.onStarDragSelected(); }, function onDrag(e, draggable, context, xDelta, yDelta) { context.iObject.setPosition({posX: context.x + xDelta, posY: context.y + yDelta}); context.iObject.repaint(); context.iObject.wiringEditor.onDragSelectedObjects(xDelta, yDelta); }, function onFinish(draggable, context) { context.iObject.wiringEditor.onFinishSelectedObjects(); var position = context.iObject.getStylePosition(); if (position.posX < 0) { position.posX = 8; } if (position.posY < 0) { position.posY = 8; } context.iObject.setPosition(position); context.iObject.repaint(); //pseudoClick if ((Math.abs(context.x - position.posX) < 2) && (Math.abs(context.y - position.posY) < 2)) { if (context.preselected) { context.iObject.unselect(true); } context.iObject.movement = false; } else { if (!context.preselected) { context.iObject.unselect(true); } context.iObject.movement = true; } }, function () {return true; } ); }; /** * Make draggable all sources and targets for sorting */ GenericInterface.prototype.makeSlotsDraggable = function makeSlotsDraggable() { var i; for (i = 0; i < this.draggableSources.length; i++) { this.makeSlotDraggable(this.draggableSources[i], this.wiringEditor.layout.center, 'source_clon'); } for (i = 0; i < this.draggableTargets.length; i++) { this.makeSlotDraggable(this.draggableTargets[i], this.wiringEditor.layout.center, 'target_clon'); } }; /** * Make draggable a specific sources or targets for sorting */ GenericInterface.prototype.makeSlotDraggable = function makeSlotDraggable(element, place, className) { element.draggable = new Wirecloud.ui.Draggable(element.wrapperElement, {iObject: element, genInterface: this, wiringEditor: this.wiringEditor}, function onStart(draggable, context) { var clon, pos_miniwidget, gridbounds, childsN, childPos; //initial position pos_miniwidget = context.iObject.wrapperElement.getBoundingClientRect(); gridbounds = context.wiringEditor.getGridElement().getBoundingClientRect(); context.y = pos_miniwidget.top - gridbounds.top; context.x = pos_miniwidget.left - gridbounds.left; //create clon context.iObject.wrapperElement.classList.add('moving'); clon = context.iObject.wrapperElement.cloneNode(true); clon.classList.add(className); // put the clon in place place.wrapperElement.appendChild(clon); //set the clon position over the originar miniWidget clon.style.height = (pos_miniwidget.height) + 'px'; clon.style.left = (context.x) + 'px'; clon.style.top = (context.y) + 'px'; clon.style.width = (pos_miniwidget.width) + 'px'; //put the clon in the context.iObjectClon context.iObjectClon = clon; //put the reference height for change position context.refHeigth = context.iObject.wrapperElement.getBoundingClientRect().height + 2; context.refHeigthUp = context.refHeigth; context.refHeigthDown = context.refHeigth; childsN = context.iObject.wrapperElement.parentNode.childElementCount; childPos = getElementPos(context.iObject.wrapperElement.parentNode.children, context.iObject.wrapperElement); context.maxUps = childPos; context.maxDowns = childsN - (childPos + 1); }, function onDrag(e, draggable, context, xDelta, yDelta) { var top; context.iObjectClon.style.left = (context.x + xDelta) + 'px'; context.iObjectClon.style.top = (context.y + yDelta) + 'px'; top = parseInt(context.iObjectClon.style.top, 10); if (((context.y - top) > context.refHeigthUp) && (context.maxUps > 0)) { context.maxDowns += 1; context.maxUps -= 1; context.refHeigthUp += context.refHeigth; context.refHeigthDown -= context.refHeigth; context.genInterface.up(context.iObject); } else if (((top - context.y) > context.refHeigthDown) && (context.maxDowns > 0)) { context.maxUps += 1; context.maxDowns -= 1; context.refHeigthDown += context.refHeigth; context.refHeigthUp -= context.refHeigth; context.genInterface.down(context.iObject); } }, function onFinish(draggable, context) { context.iObject.wrapperElement.classList.remove('moving'); if (context.iObjectClon.parentNode) { context.iObjectClon.parentNode.removeChild(context.iObjectClon); } context.iObjectClon = null; }, function () {return true; } ); }; /** * Get the GenericInterface position. */ GenericInterface.prototype.getPosition = function getPosition() { var coordinates = {posX: this.wrapperElement.offsetLeft, posY: this.wrapperElement.offsetTop}; return coordinates; }; /** * Get the GenericInterface style position. */ GenericInterface.prototype.getStylePosition = function getStylePosition() { var coordinates; coordinates = {posX: parseInt(this.wrapperElement.style.left, 10), posY: parseInt(this.wrapperElement.style.top, 10)}; return coordinates; }; /** * Gets an anchor given a name */ GenericInterface.prototype.getAnchor = function getAnchor(name) { if (name in this.sourceAnchorsByName) { return this.sourceAnchorsByName[name]; } else if (name in this.targetAnchorsByName) { return this.targetAnchorsByName[name]; } else { return null; } }; /** * Add Ghost Endpoint */ GenericInterface.prototype.addGhostEndpoint = function addGhostEndpoint(theEndpoint, isSource) { var context; if (isSource) { context = {'data': new Wirecloud.wiring.GhostSourceEndpoint(theEndpoint, this.entity), 'iObject': this}; this.addSource(theEndpoint.endpoint, '', theEndpoint.endpoint, context, true); return this.sourceAnchorsByName[theEndpoint.endpoint]; } else { context = {'data': new Wirecloud.wiring.GhostTargetEndpoint(theEndpoint, this.entity), 'iObject': this}; this.addTarget(theEndpoint.endpoint, '', theEndpoint.endpoint, context, true); return this.targetAnchorsByName[theEndpoint.endpoint]; } }; /** * Set the GenericInterface position. */ GenericInterface.prototype.setPosition = function setPosition(coordinates) { this.wrapperElement.style.left = coordinates.posX + 'px'; this.wrapperElement.style.top = coordinates.posY + 'px'; }; /** * Set the BoundingClientRect parameters */ GenericInterface.prototype.setBoundingClientRect = function setBoundingClientRect(BoundingClientRect, move) { this.wrapperElement.style.height = (BoundingClientRect.height + move.height) + 'px'; this.wrapperElement.style.left = (BoundingClientRect.left + move.left) + 'px'; this.wrapperElement.style.top = (BoundingClientRect.top + move.top) + 'px'; this.wrapperElement.style.width = (BoundingClientRect.width + move.width) + 'px'; }; /** * Set the initial position in the menubar, miniobjects. */ GenericInterface.prototype.setMenubarPosition = function setMenubarPosition(menubarPosition) { this.menubarPosition = menubarPosition; }; /** * Set the initial position in the menubar, miniobjects. */ GenericInterface.prototype.getMenubarPosition = function getMenubarPosition() { return this.menubarPosition; }; /** * Increasing the number of read only connections */ GenericInterface.prototype.incReadOnlyConnectionsCount = function incReadOnlyConnectionsCount() { this.readOnlyEndpoints += 1; this.readOnly = true; }; /** * Reduce the number of read only connections */ GenericInterface.prototype.reduceReadOnlyConnectionsCount = function reduceReadOnlyConnectionsCount() { this.readOnlyEndpoints -= 1; if (this.readOnlyEndpoints == 0) { this.readOnly = false; } }; /** * Generic repaint */ GenericInterface.prototype.repaint = function repaint(temporal) { var key; StyledElements.Container.prototype.repaint.apply(this, arguments); for (key in this.sourceAnchorsByName) { this.sourceAnchorsByName[key].repaint(temporal); } for (key in this.targetAnchorsByName) { this.targetAnchorsByName[key].repaint(temporal); } }; /** * Generate SubTree */ GenericInterface.prototype.generateSubTree = function generateSubTree(anchorContext, subAnchors) { var treeFrame, key, lab, checkbox, subdata, subTree, labelsFrame, context, name, labelActionLayer, entity, type; treeFrame = document.createElement("div"); treeFrame.classList.add('subTree'); labelsFrame = document.createElement("div"); labelsFrame.classList.add('labelsFrame'); treeFrame.appendChild(labelsFrame); if (!isEmpty(subAnchors.subdata)) { for (key in subAnchors.subdata) { lab = document.createElement("span"); lab.classList.add("labelTree"); lab.textContent = subAnchors.subdata[key].label; name = anchorContext.data.name + "/" + key; if (anchorContext.data.iwidget != null) { entity = anchorContext.data.iwidget; type = 'iwidget'; } else { entity = anchorContext.data.operator; type = 'ioperator'; } context = {'data': new OutputSubendpoint(name, anchorContext.data, entity, type), 'iObject': this}; checkbox = new Wirecloud.ui.WiringEditor.SourceAnchor(context, anchorContext.iObject.arrowCreator, subAnchors.subdata[key]); checkbox.wrapperElement.classList.add("subAnchor"); checkbox.wrapperElement.classList.add("icon-circle"); this.sourceAnchorsByName[name] = checkbox; this.sourceAnchors.push(checkbox); subdata = document.createElement("div"); subdata.classList.add("dataTree"); labelActionLayer = document.createElement("div"); labelActionLayer.classList.add("labelActionLayer"); setlabelActionListeners.call(this, labelActionLayer, checkbox); subTree = this.generateSubTree(context, subAnchors.subdata[key], checkbox); if (subTree !== null) { subdata.appendChild(subTree); subdata.classList.add("branch"); } else{ subdata.classList.add("leaf"); } subdata.appendChild(lab); subdata.appendChild(checkbox.wrapperElement); labelsFrame.appendChild(subdata); labelsFrame.appendChild(labelActionLayer); } return treeFrame; } else { return null; } }; /** * Generate Tree */ GenericInterface.prototype.generateTree = function generateTree(anchor, name, anchorContext, subtree, label, closeHandler) { var subAnchors, treeFrame, lab, checkbox, subdata, key, subTree, subTreeFrame, type, labelsFrame, labelMain, close_button, context, name, labelActionLayer, entity, treeDiv; // Generate tree treeDiv = document.createElement("div"); treeDiv.classList.add('anchorTree'); treeDiv.addEventListener('click', function (e) { e.stopPropagation(); }.bind(this), false); treeDiv.addEventListener('mousedown', function (e) { e.stopPropagation(); }.bind(this), false); treeFrame = document.createElement("div"); treeFrame.classList.add('tree'); treeFrame.classList.add('sources'); // Close button close_button = new StyledElements.StyledButton({ 'title': gettext("Hide"), 'class': 'hideTreeButton icon-off', 'plain': true }); close_button.insertInto(treeFrame); close_button.addEventListener('click', function () {closeHandler();}, false); subAnchors = JSON.parse(subtree); subTreeFrame = null; labelsFrame = document.createElement("div"); labelsFrame.classList.add('labelsFrame'); if (subAnchors !== null) { subTreeFrame = document.createElement("div"); subTreeFrame.classList.add('subTree'); for (key in subAnchors) { lab = document.createElement("span"); lab.classList.add("labelTree"); lab.textContent = subAnchors[key].label; name = anchorContext.data.name + "/" + key; if (anchorContext.data.iwidget != null) { entity = anchorContext.data.iwidget; type = 'iwidget'; } else { entity = anchorContext.data.operator; type = 'ioperator'; } context = {'data': new OutputSubendpoint(name, anchorContext.data, entity, type), 'iObject': this}; checkbox = new Wirecloud.ui.WiringEditor.SourceAnchor(context, anchorContext.iObject.arrowCreator, subAnchors[key]); checkbox.wrapperElement.classList.add("subAnchor"); checkbox.wrapperElement.classList.add("icon-circle"); this.sourceAnchorsByName[name] = checkbox; this.sourceAnchors.push(checkbox); subdata = document.createElement("div"); subdata.classList.add("dataTree"); labelActionLayer = document.createElement("div"); labelActionLayer.classList.add("labelActionLayer"); setlabelActionListeners.call(this, labelActionLayer, checkbox); subTree = this.generateSubTree(context, subAnchors[key], checkbox); if (subTree !== null) { subdata.appendChild(subTree); subdata.classList.add("branch"); } else{ subdata.classList.add("leaf"); } subdata.appendChild(lab); subdata.appendChild(checkbox.wrapperElement); labelsFrame.appendChild(subdata); labelsFrame.appendChild(labelActionLayer); subTreeFrame.appendChild(labelsFrame); } } lab = document.createElement("span"); lab.classList.add("labelTree"); lab.textContent = label; name = anchorContext.data.name + "/" + anchorContext.data.name; if (anchorContext.data.iwidget != null) { entity = anchorContext.data.iwidget; type = 'iwidget'; } else { entity = anchorContext.data.operator; type = 'ioperator'; } context = {'data': new OutputSubendpoint(name, anchorContext.data, entity, type), 'iObject': this}; checkbox = new Wirecloud.ui.WiringEditor.SourceAnchor(context, anchorContext.iObject.arrowCreator, subAnchors); checkbox.wrapperElement.classList.add("subAnchor"); checkbox.wrapperElement.classList.add("icon-circle"); this.sourceAnchorsByName[name] = checkbox; this.sourceAnchors.push(checkbox); subdata = document.createElement("div"); subdata.classList.add("dataTree"); labelActionLayer = document.createElement("div"); labelActionLayer.classList.add("labelActionLayer"); setlabelActionListeners.call(this, labelActionLayer, checkbox); if (subTreeFrame !== null) { subdata.appendChild(subTreeFrame); subdata.classList.add("branch"); } else { subdata.classList.add("leaf"); } subdata.appendChild(lab); subdata.appendChild(checkbox.wrapperElement); labelMain = document.createElement("div"); labelMain.classList.add('labelsFrame'); labelMain.appendChild(subdata); labelMain.appendChild(labelActionLayer); treeFrame.appendChild(labelMain); treeDiv.appendChild(treeFrame); this.wrapperElement.appendChild(treeDiv); // Handler for subdata tree menu anchor.menu.append(new StyledElements.MenuItem(gettext("Unfold data structure"), this.subdataHandler.bind(this, treeDiv, name))); }; /** * handler for show/hide anchorTrees */ GenericInterface.prototype.subdataHandler = function subdataHandler(treeDiv, name) { var initialHeiht, initialWidth, key, i, externalRep, layer, subDataArrow, firstIndex, mainEndpoint, mainSubEndPoint, theArrow, mainEndpointArrows; if (treeDiv == null) { // Descend canvas this.wiringEditor.canvas.canvasElement.classList.remove("elevated"); // Hide tree this.activatedTree.classList.remove('activated'); this.activatedTree = null; // Deactivate subdataMode this.wrapperElement.classList.remove('subdataMode'); // Hide subdata connections, and show hollow and full connections if (!isEmpty(this.subdataConnections[name])) { for (key in this.subdataConnections[name]) { firstIndex = this.subdataConnections[name][key].length - 1; for (i = firstIndex; i >= 0 ; i -= 1) { externalRep = this.subdataConnections[name][key][i].externalRep; subDataArrow = this.subdataConnections[name][key][i].subDataArrow; externalRep.show(); if (externalRep.hasClassName('hollow')) { subDataArrow.hide(); } else { // Remove all subconnections that represent full connections subDataArrow.destroy(); this.subdataConnections[name][key].splice(i, 1); this.fullConnections[name][key].splice(this.fullConnections[name][key].indexOf(externalRep), 1); } } } } } else { // Elevate canvas this.wiringEditor.canvas.canvasElement.classList.add("elevated"); // Show tree initialWidth = this.wrapperElement.getBoundingClientRect().width; treeDiv.classList.add('activated'); this.activatedTree = treeDiv; formatTree(treeDiv, initialWidth); // Activate subdataMode this.wrapperElement.classList.add('subdataMode'); // Add a subconnection for each main connexion in the main endpoint layer = this.wiringEditor.arrowCreator.layer; mainEndpoint = this.sourceAnchorsByName[name]; mainSubEndPoint = this.sourceAnchorsByName[name + "/" + name]; mainEndpointArrows = mainEndpoint.getArrows(); for (i = 0; i < mainEndpointArrows.length ; i += 1) { if (!mainEndpointArrows[i].hasClassName('hollow')) { // New full subConnection theArrow = this.wiringEditor.canvas.drawArrow(mainSubEndPoint.getCoordinates(layer), mainEndpointArrows[i].endAnchor.getCoordinates(layer), "arrow subdataConnection full"); theArrow.setEndAnchor(mainEndpointArrows[i].endAnchor); theArrow.setStartAnchor(mainSubEndPoint); mainSubEndPoint.addArrow(theArrow); mainEndpointArrows[i].endAnchor.addArrow(theArrow); // Add this connections to subdataConnections if (this.subdataConnections[name] == null) { this.subdataConnections[name] = {}; } if (this.subdataConnections[name][name + "/" + name] == null) { this.subdataConnections[name][name + "/" + name] = []; } this.subdataConnections[name][name + "/" + name].push({'subDataArrow' : theArrow, 'externalRep': mainEndpointArrows[i]}); // Add this connections to fullConnections if (this.fullConnections[name] == null) { this.fullConnections[name] = {}; } if (this.fullConnections[name][name + "/" + name] == null) { this.fullConnections[name][name + "/" + name] = []; } this.fullConnections[name][name + "/" + name].push(mainEndpointArrows[i]); } } // Show subdata connections, and hide hollow connections for (key in this.subdataConnections[name]) { for (i = 0; i < this.subdataConnections[name][key].length ; i += 1) { this.subdataConnections[name][key][i].externalRep.hide(); this.subdataConnections[name][key][i].subDataArrow.show(); } } } this.repaint(); this.wiringEditor.activatedTree = this.activatedTree; }; /** * Add subdata connection. */ GenericInterface.prototype.addSubdataConnection = function addSubdataConnection(endpoint, subdatakey, connection, sourceAnchor, targetAnchor, isLoadingWiring) { var theArrow, mainEndpoint, layer; if (this.subdataConnections[endpoint] == null) { this.subdataConnections[endpoint] = {}; } if (this.subdataConnections[endpoint][subdatakey] == null) { this.subdataConnections[endpoint][subdatakey] = []; } layer = this.wiringEditor.arrowCreator.layer; mainEndpoint = this.sourceAnchorsByName[endpoint]; if ((endpoint + "/" + endpoint) == subdatakey) { // Add full connection if (this.fullConnections[endpoint] == null) { this.fullConnections[endpoint] = {}; } if (this.fullConnections[endpoint][subdatakey] == null) { this.fullConnections[endpoint][subdatakey] = []; } connection.addClassName('full'); theArrow = this.wiringEditor.canvas.drawArrow(mainEndpoint.getCoordinates(layer), targetAnchor.getCoordinates(layer), "arrow"); this.fullConnections[endpoint][subdatakey].push(theArrow); } else { // Add a hollow connection if (this.hollowConnections[endpoint] == null) { this.hollowConnections[endpoint] = {}; } if (this.hollowConnections[endpoint][subdatakey] == null) { this.hollowConnections[endpoint][subdatakey] = []; } theArrow = this.wiringEditor.canvas.drawArrow(mainEndpoint.getCoordinates(layer), targetAnchor.getCoordinates(layer), "arrow hollow"); this.hollowConnections[endpoint][subdatakey].push(theArrow); } theArrow.setEndAnchor(targetAnchor); theArrow.setStartAnchor(mainEndpoint); mainEndpoint.addArrow(theArrow); targetAnchor.addArrow(theArrow); if (isLoadingWiring) { connection.hide(); } else { theArrow.hide(); } this.subdataConnections[endpoint][subdatakey].push({'subDataArrow' : connection, 'externalRep': theArrow}); }; /** * Remove subdata connection. */ GenericInterface.prototype.removeSubdataConnection = function removeSubdataConnection(endpoint, subdatakey, connection) { var i, externalRep; if ((endpoint + "/" + endpoint) == subdatakey) { // Remove full connection if (this.fullConnections[endpoint] != null && this.fullConnections[endpoint][subdatakey] != null) { for (i = 0; i < this.subdataConnections[endpoint][subdatakey].length ; i += 1) { if (this.subdataConnections[endpoint][subdatakey][i].subDataArrow == connection) { externalRep = this.subdataConnections[endpoint][subdatakey][i].externalRep; this.fullConnections[endpoint][subdatakey].splice(this.fullConnections[endpoint][subdatakey].indexOf(externalRep), 1); externalRep.destroy(); connection.destroy(); this.subdataConnections[endpoint][subdatakey].splice(i, 1); break; } } } else { // Error } } else { // Remove a hollow connection if (this.hollowConnections[endpoint] != null && this.hollowConnections[endpoint][subdatakey] != null) { for (i = 0; i < this.subdataConnections[endpoint][subdatakey].length ; i += 1) { if (this.subdataConnections[endpoint][subdatakey][i].subDataArrow == connection) { externalRep = this.subdataConnections[endpoint][subdatakey][i].externalRep; this.hollowConnections[endpoint][subdatakey].splice(this.hollowConnections[endpoint][subdatakey].indexOf(externalRep), 1); externalRep.destroy(); connection.destroy(); this.subdataConnections[endpoint][subdatakey].splice(i, 1); break; } } } else { // Error } } }; /** * Add Source. */ GenericInterface.prototype.addSource = function addSource(label, desc, name, anchorContext, isGhost) { var anchor, anchorDiv, labelDiv, anchorLabel, treeDiv, subAnchors; // Sources counter this.numberOfSources += 1; // AnchorDiv anchorDiv = document.createElement("div"); // If the output have not description, take the label if (desc === '') { desc = label; } if (isGhost) { anchorDiv.setAttribute('title', gettext("Mismatch endpoint! ") + label); } else { anchorDiv.setAttribute('title', label + ': ' + desc); } anchorDiv.classList.add('anchorDiv'); if (isGhost) { anchorDiv.classList.add('ghost'); } // Anchor visible label anchorLabel = document.createElement("span"); anchorLabel.textContent = label; labelDiv = document.createElement("div"); anchorDiv.appendChild(labelDiv); labelDiv.setAttribute('class', 'labelDiv'); labelDiv.appendChild(anchorLabel); if (!this.isMiniInterface) { anchor = new Wirecloud.ui.WiringEditor.SourceAnchor(anchorContext, this.arrowCreator, null, isGhost); labelDiv.appendChild(anchor.wrapperElement); anchor.menu.append(new StyledElements.MenuItem(gettext('Add multiconnector'), createMulticonnector.bind(this, name, anchor))); subAnchors = anchorContext.data.subdata; if (subAnchors != null) { // Generate the tree this.generateTree(anchor, name, anchorContext, subAnchors, label, this.subdataHandler.bind(this, null, name)); } labelDiv.addEventListener('mouseover', function () { this.wiringEditor.recommendations.emphasize(anchor); }.bind(this)); labelDiv.addEventListener('mouseout', function () { this.wiringEditor.recommendations.deemphasize(anchor); }.bind(this)); // Sticky effect anchorDiv.addEventListener('mouseover', function (e) { anchor._mouseover_callback(e); }.bind(this)); anchorDiv.addEventListener('mouseout', function (e) { anchor._mouseout_callback(e); }.bind(this)); // Connect anchor whith mouseup on the label anchorDiv.addEventListener('mouseup', function (e) { anchor._mouseup_callback(e); }.bind(this)); this.sourceAnchorsByName[name] = anchor; this.sourceAnchors.push(anchor); } this.sourceDiv.appendChild(anchorDiv); this.draggableSources.push({'wrapperElement': anchorDiv, 'context': anchorContext}); }; /** * Add Target. */ GenericInterface.prototype.addTarget = function addTarget(label, desc, name, anchorContext, isGhost) { var anchor, anchorDiv, labelDiv, anchorLabel; // Targets counter this.numberOfTargets += 1; // AnchorDiv anchorDiv = document.createElement("div"); // If the output have not description, take the label if (desc === '') { desc = label; } if (isGhost) { anchorDiv.setAttribute('title', gettext('Mismatch endpoint! ') + label); } else { anchorDiv.setAttribute('title', label + ': ' + desc); } anchorDiv.classList.add('anchorDiv'); if (isGhost) { anchorDiv.classList.add('ghost'); } // Anchor visible label anchorLabel = document.createElement("span"); anchorLabel.textContent = label; labelDiv = document.createElement("div"); anchorDiv.appendChild(labelDiv); labelDiv.setAttribute('class', 'labelDiv'); labelDiv.appendChild(anchorLabel); if (!this.isMiniInterface) { anchor = new Wirecloud.ui.WiringEditor.TargetAnchor(anchorContext, this.arrowCreator, isGhost); labelDiv.appendChild(anchor.wrapperElement); anchor.menu.append(new StyledElements.MenuItem(gettext('Add multiconnector'), createMulticonnector.bind(this, name, anchor))); labelDiv.addEventListener('mouseover', function () { if (!this.wiringEditor.recommendationsActivated) { this.wiringEditor.recommendations.emphasize(anchor); } }.bind(this)); labelDiv.addEventListener('mouseout', function () { if (!this.wiringEditor.recommendationsActivated) { this.wiringEditor.recommendations.deemphasize(anchor); } }.bind(this)); // Sticky effect anchorDiv.addEventListener('mouseover', function (e) { anchor._mouseover_callback(e); }.bind(this)); anchorDiv.addEventListener('mouseout', function (e) { anchor._mouseout_callback(e); }.bind(this)); // Connect anchor whith mouseup on the label anchorDiv.addEventListener('mouseup', function (e) { anchor._mouseup_callback(e); }.bind(this)); this.targetAnchorsByName[name] = anchor; this.targetAnchors.push(anchor); } this.targetDiv.appendChild(anchorDiv); this.draggableTargets.push({'wrapperElement': anchorDiv, 'context': anchorContext}); }; /** * Add new class in to the genericInterface */ GenericInterface.prototype.addClassName = function addClassName(className) { var atr; if (className == null) { return; } atr = this.wrapperElement.getAttribute('class'); if (atr == null) { atr = ''; } this.wrapperElement.setAttribute('class', Wirecloud.Utils.appendWord(atr, className)); }; /** * Remove a genericInterface Class name */ GenericInterface.prototype.removeClassName = function removeClassName(className) { var atr; if (className == null) { return; } atr = this.wrapperElement.getAttribute('class'); if (atr == null) { atr = ''; } this.wrapperElement.setAttribute('class', Wirecloud.Utils.removeWord(atr, className)); }; /** * Select this genericInterface */ GenericInterface.prototype.select = function select(withCtrl) { var i, j, arrows; if (this.hasClassName('disabled')) { return; } if (this.hasClassName('selected')) { return; } if (!(this.wiringEditor.ctrlPushed) && (this.wiringEditor.selectedCount > 0) && (withCtrl)) { this.wiringEditor.resetSelection(); } this.selected = true; this.addClassName('selected'); // Arrows for (i = 0; i < this.targetAnchors.length; i += 1) { arrows = this.targetAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].emphasize(); } } for (i = 0; i < this.sourceAnchors.length; i += 1) { arrows = this.sourceAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].emphasize(); } } this.wiringEditor.addSelectedObject(this); }; /** * Unselect this genericInterface */ GenericInterface.prototype.unselect = function unselect(withCtrl) { var i, j, arrows; this.selected = false; this.removeClassName('selected'); //arrows for (i = 0; i < this.targetAnchors.length; i += 1) { arrows = this.targetAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].deemphasize(); } } for (i = 0; i < this.sourceAnchors.length; i += 1) { arrows = this.sourceAnchors[i].arrows; for (j = 0; j < arrows.length; j += 1) { arrows[j].deemphasize(); } } this.wiringEditor.removeSelectedObject(this); if (!(this.wiringEditor.ctrlPushed) && (this.wiringEditor.selectedCount > 0) && (withCtrl)) { this.wiringEditor.resetSelection(); } }; /** * Destroy */ GenericInterface.prototype.destroy = function destroy() { var i, j, arrows; this.unselect(); if (this.editingPos === true) { this.disableEdit(); } StyledElements.Container.prototype.destroy.call(this); for (i = 0; i < this.sourceAnchors.length; i += 1) { arrows = this.sourceAnchors[i].arrows.slice(0); for (j = 0; j < arrows.length; j += 1) { if (!arrows[j].controlledDestruction()) { arrows[j].destroy(); } } this.sourceAnchors[i].destroy(); } for (i = 0; i < this.targetAnchors.length; i += 1) { arrows = this.targetAnchors[i].arrows.slice(0); for (j = 0; j < arrows.length; j += 1) { if (!arrows[j].controlledDestruction()) { arrows[j].destroy(); } } this.targetAnchors[i].destroy(); } this.draggable.destroy(); this.draggable = null; this.draggableSources = null; this.draggableTargets = null; this.wrapperElement = null; this.hollowConnections = null; this.subdataConnections = null; }; /** * Edit source and targets positions */ GenericInterface.prototype.editPos = function editPos() { var obj; obj = null; if ((this.targetAnchors.length <= 1) && (this.sourceAnchors.length <= 1)) { return; } if (this.editingPos === true) { this.disableEdit(); } else { this.enableEdit(); obj = this; } this.repaint(); return obj; }; /** * Enable poditions editor */ GenericInterface.prototype.enableEdit = function enableEdit() { this.draggable.destroy(); this.editingPos = true; this.sourceDiv.wrapperElement.classList.add("editing"); this.targetDiv.wrapperElement.classList.add("editing"); this.addClassName("editing"); this.makeSlotsDraggable(); }; /** * Disable poditions editor */ GenericInterface.prototype.disableEdit = function disableEdit() { var i; this.makeDraggable(); this.editingPos = false; this.sourceDiv.wrapperElement.classList.remove("editing"); this.targetDiv.wrapperElement.classList.remove("editing"); this.removeClassName("editing"); for (i = 0; i < this.draggableSources.length; i++) { this.draggableSources[i].draggable.destroy(); } for (i = 0; i < this.draggableTargets.length; i++) { this.draggableTargets[i].draggable.destroy(); } }; /** * Move an endpoint up 1 position. */ GenericInterface.prototype.up = function up(element) { element.wrapperElement.parentNode.insertBefore(element.wrapperElement, element.wrapperElement.previousElementSibling); this.repaint(); }; /** * Move an endpoint down 1 position. */ GenericInterface.prototype.down = function down(element) { if (element.wrapperElement.nextElementSibling !== null) { element.wrapperElement.parentNode.insertBefore(element.wrapperElement, element.wrapperElement.nextElementSibling.nextElementSibling); this.repaint(); } }; /** * Get sources and targets titles lists in order to save positions */ GenericInterface.prototype.getInOutPositions = function getInOutPositions() { var i, sources, targets; sources = []; targets = []; for (i = 0; i < this.sourceDiv.wrapperElement.childNodes.length; i++) { sources[i] = this.getNameForSort(this.sourceDiv.wrapperElement.childNodes[i], 'source'); } for (i = 0; i < this.targetDiv.wrapperElement.childNodes.length; i++) { targets[i] = this.getNameForSort(this.targetDiv.wrapperElement.childNodes[i], 'target'); } return {'sources': sources, 'targets': targets}; }; /** * Get the source or target name for the especific node */ GenericInterface.prototype.getNameForSort = function getNameForSort(node, type) { var i, collection; if (type === 'source') { collection = this.draggableSources; } else { collection = this.draggableTargets; } for (i = 0; collection.length; i++) { if (collection[i].wrapperElement === node) { return collection[i].context.data.name; } } }; /** * Change to minimized view for operators */ GenericInterface.prototype.minimize = function minimize(omitEffects) { var position, oc, scrollX, scrollY; if (!omitEffects) { this.resizeTransitStart(); } this.initialPos = this.wrapperElement.getBoundingClientRect(); this.minWidth = this.wrapperElement.style.minWidth; this.wrapperElement.classList.add('reducedInt'); this.wrapperElement.style.minWidth = '55px'; // Scroll correction oc = this.wiringEditor.layout.getCenterContainer(); scrollX = parseInt(oc.wrapperElement.scrollLeft, 10); scrollY = parseInt(oc.wrapperElement.scrollTop, 10); this.wrapperElement.style.top = (this.initialPos.top + scrollY - this.wiringEditor.headerHeight) + ((this.initialPos.height - 8) / 2) - 12 + 'px'; this.wrapperElement.style.left = (this.initialPos.left + scrollX - this.wiringEditor.menubarWidth) + (this.initialPos.width / 2) - 32 + 'px'; // correct it pos if is out of grid position = this.getStylePosition(); if (position.posX < 0) { position.posX = 8; } if (position.posY < 0) { position.posY = 8; } this.setPosition(position); this.isMinimized = true; this.repaint(); }; /** * Change to normal view for operators */ GenericInterface.prototype.restore = function restore(omitEffects) { var currentPos, position, oc, scrollX, scrollY; if (!omitEffects) { this.resizeTransitStart(); } // Scroll correction oc = this.wiringEditor.layout.getCenterContainer(); scrollX = parseInt(oc.wrapperElement.scrollLeft, 10) + 1; scrollY = parseInt(oc.wrapperElement.scrollTop, 10); currentPos = this.wrapperElement.getBoundingClientRect(); this.wrapperElement.style.top = (currentPos.top + scrollY - this.wiringEditor.headerHeight) - ((this.initialPos.height + 8) / 2) + 'px'; this.wrapperElement.style.left = (currentPos.left + scrollX - this.wiringEditor.menubarWidth) - (this.initialPos.width / 2) + 32 + 'px'; // correct it position if is out of grid position = this.getStylePosition(); if (position.posX < 0) { position.posX = 8; } if (position.posY < 0) { position.posY = 8; } this.setPosition(position); this.wrapperElement.style.minWidth = this.minWidth; this.wrapperElement.classList.remove('reducedInt'); this.isMinimized = false; this.repaint(); }; /** * Resize Transit Start */ GenericInterface.prototype.resizeTransitStart = function resizeTransitStart() { var interval; // transition events this.wrapperElement.classList.add('flex'); /*this.wrapperElement.addEventListener('webkitTransitionEnd', this.resizeTransitEnd.bind(this), false); this.wrapperElement.addEventListener('transitionend', this.resizeTransitEnd.bind(this), false); this.wrapperElement.addEventListener('oTransitionEnd', this.resizeTransitEnd.bind(this), false);*/ interval = setInterval(this.animateArrows.bind(this), 20); setTimeout(function () { clearInterval(interval); }, 400); setTimeout(function () { this.resizeTransitEnd(); }.bind(this), 450); }; /** * Resize Transit End */ GenericInterface.prototype.resizeTransitEnd = function resizeTransitEnd() { // transition events this.wrapperElement.classList.remove('flex'); /*this.wrapperElement.removeEventListener('webkitTransitionEnd', this.resizeTransitEnd.bind(this), false); this.wrapperElement.removeEventListener('transitionend', this.resizeTransitEnd.bind(this), false); this.wrapperElement.removeEventListener('oTransitionEnd', this.resizeTransitEnd.bind(this), false);*/ this.repaint(); }; /** * Animated arrows for the transitions betwen minimized an normal shape */ GenericInterface.prototype.animateArrows = function animateArrows() { var key, layer; for (key in this.sourceAnchorsByName) { this.sourceAnchorsByName[key].repaint(); } for (key in this.targetAnchorsByName) { this.targetAnchorsByName[key].repaint(); } if (this.potentialArrow != null) { layer = this.wiringEditor.canvas.getHTMLElement().parentNode; if (this.potentialArrow.startAnchor != null) { // from source to target this.potentialArrow.setStart(this.potentialArrow.startAnchor.getCoordinates(layer)); } else { // from target to source this.potentialArrow.setEnd(this.potentialArrow.endAnchor.getCoordinates(layer)); } } }; /************************************************************************* * Make GenericInterface public *************************************************************************/ Wirecloud.ui.WiringEditor.GenericInterface = GenericInterface; })();
sixuanwang/SAMSaaS
wirecloud-develop/src/wirecloud/platform/static/js/wirecloud/ui/WiringEditor/GenericInterface.js
JavaScript
gpl-2.0
67,661
module.exports = { browserSync: { hostname: "localhost", port: 8080, openAutomatically: false, reloadDelay: 50 }, drush: { enabled: false, alias: 'drush @SITE-ALIAS cache-rebuild' }, twig: { useCache: true } };
erdfisch/DBCD16
web/themes/custom/dbcd_theme_base/example.config.js
JavaScript
gpl-2.0
253
package anon.psd.gui.activities; import android.content.ContextWrapper; import android.content.Intent; import android.graphics.BitmapFactory; import android.os.Bundle; import android.support.v7.widget.SearchView; import android.view.View; import android.widget.AdapterView; import com.nhaarman.listviewanimations.itemmanipulation.DynamicListView; import java.io.File; import anon.psd.R; import anon.psd.gui.activities.global.PSDActivity; import anon.psd.gui.adapters.PassItemsAdapter; import anon.psd.gui.exchange.ActivitiesExchange; import anon.psd.models.AppearancesList; import anon.psd.models.PasswordList; import anon.psd.models.gui.PrettyPassword; import anon.psd.storage.AppearanceCfg; import static anon.psd.utils.DebugUtils.Log; public class MainActivity extends PSDActivity implements SearchView.OnQueryTextListener, AdapterView.OnItemClickListener, AdapterView.OnItemLongClickListener { DynamicListView lvPasses; File appearanceCfgFile; AppearancesList passes; PassItemsAdapter adapter; AppearanceCfg appearanceCfg; @Override public void passItemChanged() { adapter.notifyDataSetChanged(); } @Override public void onPassesInfo(PasswordList passesInfo) { checkOrUpdateAppearanceCfg(); passes = AppearancesList.Merge(passesInfo, appearanceCfg.getPassesAppearances()); bindAdapter(); } /** * Activity events */ @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log(this, "[ ACTIVITY ] [ CREATE ]"); setContentView(R.layout.activity_main); initVariables(); } @Override protected void onResume() { super.onResume(); checkOrUpdateAppearanceCfg(); //if (passes != null) // bindAdapter(); } private void initVariables() { //load path to appearance.cfg file appearanceCfgFile = new File(new ContextWrapper(this).getFilesDir().getPath(), "appearance.cfg"); //init passes list element lvPasses = (DynamicListView) findViewById(R.id.lvPassesList); lvPasses.setOnItemClickListener(this); lvPasses.setOnItemLongClickListener(this); //set default pic for passes PrettyPassword.setDefaultPic(BitmapFactory.decodeResource(getResources(), R.drawable.default_key_pic)); PrettyPassword.setPicsDir(new File(new ContextWrapper(this).getFilesDir().getPath(), "pics")); } /** * Search */ @Override public boolean onQueryTextSubmit(String query) { return false; } @Override public boolean onQueryTextChange(String newText) { return false; } /** * Items */ @Override public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) { PrettyPassword item = (PrettyPassword) (lvPasses).getAdapter().getItem(position); openItem(item); } public void openItem(PrettyPassword item) { ActivitiesExchange.addObject("PASSES", passes); ActivitiesExchange.addObject("ACTIVITIES_SERVICE_WORKER", serviceWorker); Intent intent = new Intent(getApplicationContext(), PassActivity.class); intent.putExtra("ID", item.getPassItem().getPsdId()); startActivity(intent); } @Override public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) { PrettyPassword selectedPassWrapper = (PrettyPassword) adapterView.getItemAtPosition(position); serviceWorker.sendPrettyPass(selectedPassWrapper); return true; } private void bindAdapter() { adapter = new PassItemsAdapter<>(this, android.R.layout.simple_list_item_1, passes); lvPasses.setAdapter(adapter); } private void checkOrUpdateAppearanceCfg() { //loading appearanceCfg appearanceCfg = new AppearanceCfg(appearanceCfgFile); AppearancesList prevPasses = ActivitiesExchange.getObject("PASSES"); if (prevPasses != null) appearanceCfg.setPassesAppearances(prevPasses); else appearanceCfg.update(); } @Override public void killService() { serviceWorker.killService(); } }
dc914337/PSD
PSD/app/src/main/java/anon/psd/gui/activities/MainActivity.java
Java
gpl-2.0
4,342
require File.expand_path(File.dirname(__FILE__) + '/../spec_helper') describe 'ValidatesTimeliness::ActionView::InstanceTag' do include ActionView::Helpers::DateHelper include ActionController::Assertions::SelectorAssertions before do @person = Person.new end def params @params ||= {} end describe "datetime_select" do it "should use param values when attribute is nil" do params["person"] = { "birth_date_and_time(1i)" => 2009, "birth_date_and_time(2i)" => 2, "birth_date_and_time(3i)" => 29, "birth_date_and_time(4i)" => 12, "birth_date_and_time(5i)" => 13, "birth_date_and_time(6i)" => 14, } @person.birth_date_and_time = nil output = datetime_select(:person, :birth_date_and_time, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_and_time_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_and_time_2i] option[selected=selected]', 'February') output.should have_tag('select[id=person_birth_date_and_time_3i] option[selected=selected]', '29') output.should have_tag('select[id=person_birth_date_and_time_4i] option[selected=selected]', '12') output.should have_tag('select[id=person_birth_date_and_time_5i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_date_and_time_6i] option[selected=selected]', '14') end it "should override object values and use params if present" do params["person"] = { "birth_date_and_time(1i)" => 2009, "birth_date_and_time(2i)" => 2, "birth_date_and_time(3i)" => 29, "birth_date_and_time(4i)" => 13, "birth_date_and_time(5i)" => 14, "birth_date_and_time(6i)" => 15, } @person.birth_date_and_time = "2009-03-01 13:14:15" output = datetime_select(:person, :birth_date_and_time, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_and_time_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_and_time_2i] option[selected=selected]', 'February') output.should have_tag('select[id=person_birth_date_and_time_3i] option[selected=selected]', '29') output.should have_tag('select[id=person_birth_date_and_time_4i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_date_and_time_5i] option[selected=selected]', '14') output.should have_tag('select[id=person_birth_date_and_time_6i] option[selected=selected]', '15') end it "should select attribute values from object if no params" do @person.birth_date_and_time = "2009-01-02 13:14:15" output = datetime_select(:person, :birth_date_and_time, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_and_time_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_and_time_2i] option[selected=selected]', 'January') output.should have_tag('select[id=person_birth_date_and_time_3i] option[selected=selected]', '2') output.should have_tag('select[id=person_birth_date_and_time_4i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_date_and_time_5i] option[selected=selected]', '14') output.should have_tag('select[id=person_birth_date_and_time_6i] option[selected=selected]', '15') end it "should select attribute values if params does not contain attribute params" do @person.birth_date_and_time = "2009-01-02 13:14:15" params["person"] = { } output = datetime_select(:person, :birth_date_and_time, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_and_time_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_and_time_2i] option[selected=selected]', 'January') output.should have_tag('select[id=person_birth_date_and_time_3i] option[selected=selected]', '2') output.should have_tag('select[id=person_birth_date_and_time_4i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_date_and_time_5i] option[selected=selected]', '14') output.should have_tag('select[id=person_birth_date_and_time_6i] option[selected=selected]', '15') end it "should not select values when attribute value is nil and has no param values" do @person.birth_date_and_time = nil output = datetime_select(:person, :birth_date_and_time, :include_blank => true, :include_seconds => true) output.should_not have_tag('select[id=person_birth_date_and_time_1i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_and_time_2i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_and_time_3i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_and_time_4i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_and_time_5i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_and_time_6i] option[selected=selected]') end end describe "date_select" do it "should use param values when attribute is nil" do params["person"] = { "birth_date(1i)" => 2009, "birth_date(2i)" => 2, "birth_date(3i)" => 29, } @person.birth_date = nil output = date_select(:person, :birth_date, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_2i] option[selected=selected]', 'February') output.should have_tag('select[id=person_birth_date_3i] option[selected=selected]', '29') end it "should override object values and use params if present" do params["person"] = { "birth_date(1i)" => 2009, "birth_date(2i)" => 2, "birth_date(3i)" => 29, } @person.birth_date = "2009-03-01" output = date_select(:person, :birth_date, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_2i] option[selected=selected]', 'February') output.should have_tag('select[id=person_birth_date_3i] option[selected=selected]', '29') end it "should select attribute values from object if no params" do @person.birth_date = "2009-01-02" output = date_select(:person, :birth_date, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_2i] option[selected=selected]', 'January') output.should have_tag('select[id=person_birth_date_3i] option[selected=selected]', '2') end it "should select attribute values if params does not contain attribute params" do @person.birth_date = "2009-01-02" params["person"] = { } output = date_select(:person, :birth_date, :include_blank => true, :include_seconds => true) output.should have_tag('select[id=person_birth_date_1i] option[selected=selected]', '2009') output.should have_tag('select[id=person_birth_date_2i] option[selected=selected]', 'January') output.should have_tag('select[id=person_birth_date_3i] option[selected=selected]', '2') end it "should not select values when attribute value is nil and has no param values" do @person.birth_date = nil output = date_select(:person, :birth_date, :include_blank => true, :include_seconds => true) output.should_not have_tag('select[id=person_birth_date_1i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_2i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_date_3i] option[selected=selected]') end end describe "time_select" do before :all do Time.now = Time.mktime(2009,1,1) end it "should use param values when attribute is nil" do params["person"] = { "birth_time(1i)" => 2000, "birth_time(2i)" => 1, "birth_time(3i)" => 1, "birth_time(4i)" => 12, "birth_time(5i)" => 13, "birth_time(6i)" => 14, } @person.birth_time = nil output = time_select(:person, :birth_time, :include_blank => true, :include_seconds => true) output.should have_tag('input[id=person_birth_time_1i][value=2000]') output.should have_tag('input[id=person_birth_time_2i][value=1]') output.should have_tag('input[id=person_birth_time_3i][value=1]') output.should have_tag('select[id=person_birth_time_4i] option[selected=selected]', '12') output.should have_tag('select[id=person_birth_time_5i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_time_6i] option[selected=selected]', '14') end it "should select attribute values from object if no params" do @person.birth_time = "13:14:15" output = time_select(:person, :birth_time, :include_blank => true, :include_seconds => true) output.should have_tag('input[id=person_birth_time_1i][value=2000]') output.should have_tag('input[id=person_birth_time_2i][value=1]') output.should have_tag('input[id=person_birth_time_3i][value=1]') output.should have_tag('select[id=person_birth_time_4i] option[selected=selected]', '13') output.should have_tag('select[id=person_birth_time_5i] option[selected=selected]', '14') output.should have_tag('select[id=person_birth_time_6i] option[selected=selected]', '15') end it "should not select values when attribute value is nil and has no param values" do @person.birth_time = nil output = time_select(:person, :birth_time, :include_blank => true, :include_seconds => true) output.should have_tag('input[id=person_birth_time_1i][value=""]') # Annoyingly these may or not have value attribute depending on rails version. # output.should have_tag('input[id=person_birth_time_2i][value=""]') # output.should have_tag('input[id=person_birth_time_3i][value=""]') output.should_not have_tag('select[id=person_birth_time_4i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_time_5i] option[selected=selected]') output.should_not have_tag('select[id=person_birth_time_6i] option[selected=selected]') end after :all do Time.now = nil end end end
valdas-s/sandelys2
vendor/plugins/validates_timeliness/spec/action_view/instance_tag_spec.rb
Ruby
gpl-2.0
10,844
/* * Copyright (C) 2012 Samsung Electronics * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Library General Public * License as published by the Free Software Foundation; either * version 2 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Library General Public License for more details. * * You should have received a copy of the GNU Library General Public License * along with this library; see the file COPYING.LIB. If not, write to * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, * Boston, MA 02110-1301, USA. */ #include "config.h" #include "NavigatorVibration.h" #if ENABLE(VIBRATION) #include "Frame.h" #include "Navigator.h" #include "Page.h" #include "Vibration.h" #include <runtime/Uint32Array.h> namespace WebCore { NavigatorVibration::NavigatorVibration() { } NavigatorVibration::~NavigatorVibration() { } bool NavigatorVibration::vibrate(Navigator& navigator, unsigned time) { return NavigatorVibration::vibrate(navigator, VibrationPattern(1, time)); } bool NavigatorVibration::vibrate(Navigator& navigator, const VibrationPattern& pattern) { if (!navigator.frame()->page()) return false; if (navigator.frame()->page()->visibilityState() == PageVisibilityState::Hidden) return false; return Vibration::from(navigator.frame()->page())->vibrate(pattern); } } // namespace WebCore #endif // ENABLE(VIBRATION)
Debian/openjfx
modules/web/src/main/native/Source/WebCore/Modules/vibration/NavigatorVibration.cpp
C++
gpl-2.0
1,684
<?php /** * Theme Customizer */ function presentation_lite_customize_register( $wp_customize ) { /** =============== * Extends CONTROLS class to add textarea */ class presentation_lite_customize_textarea_control extends WP_Customize_Control { public $type = 'textarea'; public function render_content() { ?> <label> <span class="customize-control-title"><?php echo esc_html( $this->label ); ?></span> <textarea rows="5" style="width:98%;" <?php $this->link(); ?>><?php echo esc_textarea( $this->value() ); ?></textarea> </label> <?php } } /** =============== * Site Title (Logo) & Tagline */ // section adjustments $wp_customize->get_section( 'title_tagline' )->title = __( 'Site Title (Logo) & Tagline', 'presentation_lite' ); $wp_customize->get_section( 'title_tagline' )->priority = 10; //site title $wp_customize->get_control( 'blogname' )->priority = 10; $wp_customize->get_setting( 'blogname' )->transport = 'postMessage'; // tagline $wp_customize->get_control( 'blogdescription' )->priority = 30; $wp_customize->get_setting( 'blogdescription' )->transport = 'postMessage'; // logo uploader $wp_customize->add_setting( 'presentation_lite_logo', array( 'default' => null ) ); $wp_customize->add_control( new WP_Customize_Image_Control( $wp_customize, 'presentation_lite_logo', array( 'label' => __( 'Custom Site Logo (replaces title)', 'presentation_lite' ), 'section' => 'title_tagline', 'settings' => 'presentation_lite_logo', 'priority' => 20 ) ) ); /** =============== * Presentation Lite Design Options */ $wp_customize->add_section( 'presentation_lite_style_section', array( 'title' => __( 'Design Options', 'presentation_lite' ), 'description' => __( 'Choose a color scheme for Presentation Lite. Individual styles can be overwritten in your child theme stylesheet.', 'presentation_lite' ), 'priority' => 25, ) ); $wp_customize->add_setting( 'presentation_lite_stylesheet', array( 'default' => 'blue', 'sanitize_callback' => 'presentation_lite_sanitize_stylesheet' ) ); $wp_customize->add_control( 'presentation_lite_stylesheet', array( 'type' => 'select', 'label' => __( 'Choose a color scheme:', 'presentation_lite' ), 'section' => 'presentation_lite_style_section', 'choices' => array( 'blue' => 'Blue', 'purple' => 'Purple', 'red' => 'Red', 'gray' => 'Gray' ) ) ); /** =============== * Content Options */ $wp_customize->add_section( 'presentation_lite_content_section', array( 'title' => __( 'Content Options', 'presentation_lite' ), 'description' => __( 'Adjust the display of content on your website. All options have a default value that can be left as-is but you are free to customize.', 'presentation_lite' ), 'priority' => 20, ) ); // post content $wp_customize->add_setting( 'presentation_lite_post_content', array( 'default' => 'full_content', 'sanitize_callback' => 'presentation_lite_sanitize_radio' ) ); $wp_customize->add_control( new WP_Customize_Control( $wp_customize, 'presentation_lite_post_content', array( 'label' => __( 'Post Feed Content', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'settings' => 'presentation_lite_post_content', 'priority' => 10, 'type' => 'radio', 'choices' => array( 'excerpt' => 'Excerpt', 'full_content' => 'Full Content' ), ) ) ); // show single post footer? $wp_customize->add_setting( 'presentation_lite_post_footer', array( 'default' => 1, 'sanitize_callback' => 'presentation_lite_sanitize_checkbox' ) ); $wp_customize->add_control( 'presentation_lite_post_footer', array( 'label' => __( 'Show Post Footer on Single Posts?', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'priority' => 50, 'type' => 'checkbox', ) ); // twitter url $wp_customize->add_setting( 'presentation_lite_twitter', array( 'default' => null, 'sanitize_callback' => 'presentation_lite_sanitize_text' ) ); $wp_customize->add_control( 'presentation_lite_twitter', array( 'label' => __( 'Twitter Profile URL', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'settings' => 'presentation_lite_twitter', 'priority' => 80, ) ); // facebook url $wp_customize->add_setting( 'presentation_lite_facebook', array( 'default' => null, 'sanitize_callback' => 'presentation_lite_sanitize_text' ) ); $wp_customize->add_control( 'presentation_lite_facebook', array( 'label' => __( 'Facebook Profile URL', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'settings' => 'presentation_lite_facebook', 'priority' => 90, ) ); // google plus url $wp_customize->add_setting( 'presentation_lite_gplus', array( 'default' => null, 'sanitize_callback' => 'presentation_lite_sanitize_text' ) ); $wp_customize->add_control( 'presentation_lite_gplus', array( 'label' => __( 'Google Plus Profile URL', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'settings' => 'presentation_lite_gplus', 'priority' => 100, ) ); // linkedin url $wp_customize->add_setting( 'presentation_lite_linkedin', array( 'default' => null, 'sanitize_callback' => 'presentation_lite_sanitize_text' ) ); $wp_customize->add_control( 'presentation_lite_linkedin', array( 'label' => __( 'LinkedIn Profile URL', 'presentation_lite' ), 'section' => 'presentation_lite_content_section', 'settings' => 'presentation_lite_linkedin', 'priority' => 110, ) ); /** =============== * Navigation Menu(s) */ // section adjustments $wp_customize->get_section( 'nav' )->title = __( 'Navigation Menu(s)', 'presentation_lite' ); $wp_customize->get_section( 'nav' )->priority = 40; /** =============== * Static Front Page */ // section adjustments $wp_customize->get_section( 'static_front_page' )->priority = 50; } add_action( 'customize_register', 'presentation_lite_customize_register' ); /** =============== * Sanitize the theme design select option */ function presentation_lite_sanitize_stylesheet( $input ) { $valid = array( 'blue' => 'Blue', 'purple' => 'Purple', 'red' => 'Red', 'gray' => 'Gray' ); if ( array_key_exists( $input, $valid ) ) { return $input; } else { return ''; } } /** =============== * Sanitize checkbox options */ function presentation_lite_sanitize_checkbox( $input ) { if ( $input == 1 ) { return 1; } else { return 0; } } /** =============== * Sanitize radio options */ function presentation_lite_sanitize_radio( $input ) { $valid = array( 'excerpt' => 'Excerpt', 'full_content' => 'Full Content' ); if ( array_key_exists( $input, $valid ) ) { return $input; } else { return ''; } } /** =============== * Sanitize text input */ function presentation_lite_sanitize_text( $input ) { return strip_tags( stripslashes( $input ) ); } /** =============== * Add Customizer UI styles to the <head> only on Customizer page */ function presentation_lite_customizer_styles() { ?> <style type="text/css"> body { background: #fff; } #customize-controls #customize-theme-controls .description { display: block; color: #999; margin: 2px 0 15px; font-style: italic; } textarea, input, select, .customize-description { font-size: 12px !important; } .customize-control-title { font-size: 13px !important; margin: 10px 0 3px !important; } .customize-control label { font-size: 12px !important; } </style> <?php } add_action('customize_controls_print_styles', 'presentation_lite_customizer_styles'); /** * Binds JS handlers to make Theme Customizer preview reload changes asynchronously. */ function presentation_lite_customize_preview_js() { wp_enqueue_script( 'presentation_lite_customizer', get_template_directory_uri() . '/inc/js/customizer.js', array( 'customize-preview' ), '20130508', true ); } add_action( 'customize_preview_init', 'presentation_lite_customize_preview_js' );
mihaienescu1/wp_wmihu
wp-content/themes/presentation-lite/inc/customizer.php
PHP
gpl-2.0
8,069
<?php /** * @version $Id$ * @package Joomla.Administrator * @subpackage JoomDOC * @author ARTIO s.r.o., info@artio.net, http:://www.artio.net * @copyright Copyright (C) 2011 Artio s.r.o.. All rights reserved. * @license GNU General Public License version 2 or later; see LICENSE.txt */ defined('_JEXEC') or die(); include_once(JPATH_ADMINISTRATOR . DS . 'components' . DS . 'com_joomdoc' . DS . 'defines.php'); class JElementIcons extends JElement { var $_name = 'Icons'; function fetchElement ($name, $value, &$node, $control_name) { $field = JText::_('JOOMDOC_ICON_THEME_NOT_AVAILABLE'); if (JFolder::exists(JOOMDOC_PATH_ICONS)) { $themes = JFolder::folders(JOOMDOC_PATH_ICONS, '.', false, false); foreach ($themes as $theme) $options[] = JHtml::_('select.option', $theme, $theme, 'id', 'title'); if (isset($options)) { $fieldName = $control_name ? $control_name . '[' . $name . ']' : $name; $field = JHtml::_('select.genericlist', $options, $fieldName, '', 'id', 'title', $value); } } return $field; } } ?>
berkeley-amsa/past-site
administrator/tmp/install_4e65459e58fe3/admin/elements/icons.php
PHP
gpl-2.0
1,170
/* Adept MobileRobots Robotics Interface for Applications (ARIA) Copyright (C) 2004-2005 ActivMedia Robotics LLC Copyright (C) 2006-2010 MobileRobots Inc. Copyright (C) 2011-2014 Adept Technology 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 If you wish to redistribute ARIA under different terms, contact Adept MobileRobots for information about a commercial version of ARIA at robots@mobilerobots.com or Adept MobileRobots, 10 Columbia Drive, Amherst, NH 03031; +1-603-881-7960 */ /* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 1.3.40 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ package com.mobilerobots.Aria; public class ArJoyVec3f { /* (begin code from javabody typemap) */ private long swigCPtr; protected boolean swigCMemOwn; /* for internal use by swig only */ public ArJoyVec3f(long cPtr, boolean cMemoryOwn) { swigCMemOwn = cMemoryOwn; swigCPtr = cPtr; } /* for internal use by swig only */ public static long getCPtr(ArJoyVec3f obj) { return (obj == null) ? 0 : obj.swigCPtr; } /* (end code from javabody typemap) */ protected void finalize() { delete(); } public synchronized void delete() { if (swigCPtr != 0) { if (swigCMemOwn) { swigCMemOwn = false; AriaJavaJNI.delete_ArJoyVec3f(swigCPtr); } swigCPtr = 0; } } public void setX(double value) { AriaJavaJNI.ArJoyVec3f_x_set(swigCPtr, this, value); } public double getX() { return AriaJavaJNI.ArJoyVec3f_x_get(swigCPtr, this); } public void setY(double value) { AriaJavaJNI.ArJoyVec3f_y_set(swigCPtr, this, value); } public double getY() { return AriaJavaJNI.ArJoyVec3f_y_get(swigCPtr, this); } public void setZ(double value) { AriaJavaJNI.ArJoyVec3f_z_set(swigCPtr, this, value); } public double getZ() { return AriaJavaJNI.ArJoyVec3f_z_get(swigCPtr, this); } public ArJoyVec3f() { this(AriaJavaJNI.new_ArJoyVec3f(), true); } }
lakid/libaria
java/com/mobilerobots/Aria/ArJoyVec3f.java
Java
gpl-2.0
2,914
/* Copyright (c) 2002-2011 by XMLVM.org * * Project Info: http://www.xmlvm.org * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. */ package org.xmlvm.iphone; import org.xmlvm.XMLVMSkeletonOnly; @XMLVMSkeletonOnly public abstract class SKRequest extends NSObject { private SKRequestDelegate delegate; public void start() { } public void cancel() { } public SKRequestDelegate getDelegate() { return delegate; } public void setDelegate(SKRequestDelegate delegate) { this.delegate = delegate; } }
skyHALud/codenameone
Ports/iOSPort/xmlvm/src/xmlvm2objc/compat-lib/java/org/xmlvm/iphone/SKRequest.java
Java
gpl-2.0
1,255
<?php /** * @copyright Ilch 2.0 * @package ilch */ namespace Modules\Sample\Models; class Sample extends \Ilch\Model { }
Saarlonz/Ilch-2.0
application/modules/sample/models/Sample.php
PHP
gpl-2.0
126
<?php /* +---------------------------------------------------------------------------+ | OpenX v2.8 | | ========== | | | | Copyright (c) 2003-2009 OpenX Limited | | For contact details, see: http://www.openx.org/ | | | | This program is free software; you can redistribute it and/or modify | | it under the terms of the GNU General Public License as published by | | the Free Software Foundation; either version 2 of the License, or | | (at your option) 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 | +---------------------------------------------------------------------------+ $Id: template.php 79311 2011-11-03 21:18:14Z chris.nutting $ */ /** * * This is autogenerated merged delivery file which contains all files * from delivery merged into one output file. * * !!!Warning!!! * * Do not edit this file. If you need to do any changes to any delivery PHP file * checkout sourcecode from the svn repository, do a necessary changes inside * "delivery_dev" folder and regenerate delivery files using command: * # php rebuild.php * * For more information on ant generator or if you want to check why we do this * check out the documentation wiki page: * https://developer.openx.org/wiki/display/COMM/Using+Ant#UsingAnt-Generatingoptimizeddelivery * */ function parseDeliveryIniFile($configPath = null, $configFile = null, $sections = true) { if (!$configPath) { $configPath = MAX_PATH . '/var'; } if ($configFile) { $configFile = '.' . $configFile; } $host = OX_getHostName(); $configFileName = $configPath . '/' . $host . $configFile . '.conf.php'; $conf = @parse_ini_file($configFileName, $sections); if (isset($conf['realConfig'])) { $realconf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections); $conf = mergeConfigFiles($realconf, $conf); } if (!empty($conf)) { return $conf; } elseif ($configFile === '.plugin') { $pluginType = basename($configPath); $defaultConfig = MAX_PATH . '/plugins/' . $pluginType . '/default.plugin.conf.php'; $conf = @parse_ini_file($defaultConfig, $sections); if ($conf !== false) { return $conf; } echo "OpenX could not read the default configuration file for the {$pluginType} plugin"; exit(1); } $configFileName = $configPath . '/default' . $configFile . '.conf.php'; $conf = @parse_ini_file($configFileName, $sections); if (isset($conf['realConfig'])) { $conf = @parse_ini_file(MAX_PATH . '/var/' . $conf['realConfig'] . '.conf.php', $sections); } if (!empty($conf)) { return $conf; } if (file_exists(MAX_PATH . '/var/INSTALLED')) { echo "OpenX has been installed, but no configuration file was found.\n"; exit(1); } echo "OpenX has not been installed yet -- please read the INSTALL.txt file.\n"; exit(1); } if (!function_exists('mergeConfigFiles')) { function mergeConfigFiles($realConfig, $fakeConfig) { foreach ($fakeConfig as $key => $value) { if (is_array($value)) { if (!isset($realConfig[$key])) { $realConfig[$key] = array(); } $realConfig[$key] = mergeConfigFiles($realConfig[$key], $value); } else { if (isset($realConfig[$key]) && is_array($realConfig[$key])) { $realConfig[$key][0] = $value; } else { if (isset($realConfig) && !is_array($realConfig)) { $temp = $realConfig; $realConfig = array(); $realConfig[0] = $temp; } $realConfig[$key] = $value; } } } unset($realConfig['realConfig']); return $realConfig; } } function OX_getMinimumRequiredMemory($limit = null) { if ($limit == 'maintenance') { return 134217728; } return 134217728; } function OX_getMemoryLimitSizeInBytes() { $phpMemoryLimit = ini_get('memory_limit'); if (empty($phpMemoryLimit) || $phpMemoryLimit == -1) { return -1; } $aSize = array( 'G' => 1073741824, 'M' => 1048576, 'K' => 1024 ); $phpMemoryLimitInBytes = $phpMemoryLimit; foreach($aSize as $type => $multiplier) { $pos = strpos($phpMemoryLimit, $type); if (!$pos) { $pos = strpos($phpMemoryLimit, strtolower($type)); } if ($pos) { $phpMemoryLimitInBytes = substr($phpMemoryLimit, 0, $pos) * $multiplier; } } return $phpMemoryLimitInBytes; } function OX_checkMemoryCanBeSet() { $phpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes(); if ($phpMemoryLimitInBytes == -1) { return true; } OX_increaseMemoryLimit($phpMemoryLimitInBytes + 1); $newPhpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes(); $memoryCanBeSet = ($phpMemoryLimitInBytes != $newPhpMemoryLimitInBytes); @ini_set('memory_limit', $phpMemoryLimitInBytes); return $memoryCanBeSet; } function OX_increaseMemoryLimit($setMemory) { $phpMemoryLimitInBytes = OX_getMemoryLimitSizeInBytes(); if ($phpMemoryLimitInBytes == -1) { return true; } if ($setMemory > $phpMemoryLimitInBytes) { if (@ini_set('memory_limit', $setMemory) === false) { return false; } } return true; } function setupConfigVariables() { $GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'] = '|'; $GLOBALS['_MAX']['MAX_COOKIELESS_PREFIX'] = '__'; $GLOBALS['_MAX']['thread_id'] = uniqid(); $GLOBALS['_MAX']['SSL_REQUEST'] = false; if ( (!empty($_SERVER['SERVER_PORT']) && ($_SERVER['SERVER_PORT'] == $GLOBALS['_MAX']['CONF']['openads']['sslPort'])) || (!empty($_SERVER['HTTPS']) && ((strtolower($_SERVER['HTTPS']) == 'on') || ($_SERVER['HTTPS'] == 1))) || (!empty($_SERVER['HTTP_X_FORWARDED_PROTO']) && (strtolower($_SERVER['HTTP_X_FORWARDED_PROTO']) == 'https')) || (!empty($_SERVER['HTTP_X_FORWARDED_SSL']) && (strtolower($_SERVER['HTTP_X_FORWARDED_SSL']) == 'on')) || (!empty($_SERVER['HTTP_FRONT_END_HTTPS']) && (strtolower($_SERVER['HTTP_FRONT_END_HTTPS']) == 'on')) || (!empty($_SERVER['FRONT-END-HTTPS']) && (strtolower($_SERVER['FRONT-END-HTTPS']) == 'on')) ) { $GLOBALS['_MAX']['SSL_REQUEST'] = true; } $GLOBALS['_MAX']['MAX_RAND'] = isset($GLOBALS['_MAX']['CONF']['priority']['randmax']) ? $GLOBALS['_MAX']['CONF']['priority']['randmax'] : 2147483647; list($micro_seconds, $seconds) = explode(" ", microtime()); $GLOBALS['_MAX']['NOW_ms'] = round(1000 *((float)$micro_seconds + (float)$seconds)); if (substr($_SERVER['SCRIPT_NAME'], -11) != 'install.php') { $GLOBALS['serverTimezone'] = date_default_timezone_get(); OA_setTimeZoneUTC(); } } function setupServerVariables() { if (empty($_SERVER['REQUEST_URI'])) { $_SERVER['REQUEST_URI'] = $_SERVER['SCRIPT_NAME']; if (!empty($_SERVER['QUERY_STRING'])) { $_SERVER['REQUEST_URI'] .= '?' . $_SERVER['QUERY_STRING']; } } } function setupDeliveryConfigVariables() { if (!defined('MAX_PATH')) { define('MAX_PATH', dirname(__FILE__).'/../..'); } if (!defined('OX_PATH')) { define('OX_PATH', MAX_PATH); } if (!defined('LIB_PATH')) { define('LIB_PATH', MAX_PATH. DIRECTORY_SEPARATOR. 'lib'. DIRECTORY_SEPARATOR. 'OX'); } if ( !(isset($GLOBALS['_MAX']['CONF']))) { $GLOBALS['_MAX']['CONF'] = parseDeliveryIniFile(); } setupConfigVariables(); } function OA_setTimeZone($timezone) { date_default_timezone_set($timezone); $GLOBALS['_DATE_TIMEZONE_DEFAULT'] = $timezone; } function OA_setTimeZoneUTC() { OA_setTimeZone('UTC'); } function OA_setTimeZoneLocal() { $tz = !empty($GLOBALS['_MAX']['PREF']['timezone']) ? $GLOBALS['_MAX']['PREF']['timezone'] : 'GMT'; OA_setTimeZone($tz); } function OX_getHostName() { if (!empty($_SERVER['HTTP_HOST'])) { $host = explode(':', $_SERVER['HTTP_HOST']); $host = $host[0]; } else if (!empty($_SERVER['SERVER_NAME'])) { $host = explode(':', $_SERVER['SERVER_NAME']); $host = $host[0]; } return $host; } function OX_getHostNameWithPort() { if (!empty($_SERVER['HTTP_HOST'])) { $host = $_SERVER['HTTP_HOST']; } else if (!empty($_SERVER['SERVER_NAME'])) { $host = $_SERVER['SERVER_NAME']; } return $host; } function setupIncludePath() { static $checkIfAlreadySet; if (isset($checkIfAlreadySet)) { return; } $checkIfAlreadySet = true; $oxPearPath = MAX_PATH . DIRECTORY_SEPARATOR . 'lib' . DIRECTORY_SEPARATOR . 'pear'; $oxZendPath = MAX_PATH . DIRECTORY_SEPARATOR . 'lib'; set_include_path($oxPearPath . PATH_SEPARATOR . $oxZendPath . PATH_SEPARATOR . get_include_path()); } OX_increaseMemoryLimit(OX_getMinimumRequiredMemory()); if (!defined('E_DEPRECATED')) { define('E_DEPRECATED', 0); } setupServerVariables(); setupDeliveryConfigVariables(); $conf = $GLOBALS['_MAX']['CONF']; $GLOBALS['_OA']['invocationType'] = array_search(basename($_SERVER['SCRIPT_FILENAME']), $conf['file']); if (!empty($conf['debug']['production'])) { error_reporting(E_ALL ^ E_NOTICE ^ E_WARNING ^ E_DEPRECATED); } else { error_reporting(E_ALL ^ E_DEPRECATED); } $file = '/lib/max/Delivery/common.php'; $GLOBALS['_MAX']['FILES'][$file] = true; $file = '/lib/max/Delivery/cookie.php'; $GLOBALS['_MAX']['FILES'][$file] = true; $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'] = array(); if (!is_callable('MAX_cookieSet')) { if (!empty($conf['cookie']['plugin']) && is_readable(MAX_PATH . "/plugins/cookieStorage/{$conf['cookie']['plugin']}.delivery.php")) { include MAX_PATH . "/plugins/cookieStorage/{$conf['cookie']['plugin']}.delivery.php"; } else { function MAX_cookieSet($name, $value, $expire, $path = '/', $domain = null) { return MAX_cookieClientCookieSet($name, $value, $expire, $path, $domain); } function MAX_cookieUnset($name) { return MAX_cookieClientCookieUnset($name); } function MAX_cookieFlush() { return MAX_cookieClientCookieFlush(); } function MAX_cookieLoad() { return true; } } } function MAX_cookieAdd($name, $value, $expire = 0) { if (!isset($GLOBALS['_MAX']['COOKIE']['CACHE'])) { $GLOBALS['_MAX']['COOKIE']['CACHE'] = array(); } $GLOBALS['_MAX']['COOKIE']['CACHE'][$name] = array($value, $expire); } function MAX_cookieSetViewerIdAndRedirect($viewerId) { $aConf = $GLOBALS['_MAX']['CONF']; MAX_cookieAdd($aConf['var']['viewerId'], $viewerId, _getTimeYearFromNow()); MAX_cookieFlush(); if ($GLOBALS['_MAX']['SSL_REQUEST']) { $url = MAX_commonConstructSecureDeliveryUrl(basename($_SERVER['SCRIPT_NAME'])); } else { $url = MAX_commonConstructDeliveryUrl(basename($_SERVER['SCRIPT_NAME'])); } $url .= "?{$aConf['var']['cookieTest']}=1&" . $_SERVER['QUERY_STRING']; MAX_header("Location: {$url}"); exit; } function _getTimeThirtyDaysFromNow() { return MAX_commonGetTimeNow() + 2592000; } function _getTimeYearFromNow() { return MAX_commonGetTimeNow() + 31536000; } function _getTimeYearAgo() { return MAX_commonGetTimeNow() - 31536000; } function MAX_cookieUnpackCapping() { $conf = $GLOBALS['_MAX']['CONF']; $cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames']; if (!is_array($cookieNames)) return; foreach ($cookieNames as $cookieName) { if (!empty($_COOKIE[$cookieName])) { if (!is_array($_COOKIE[$cookieName])) { $output = array(); $data = explode('_', $_COOKIE[$cookieName]); foreach ($data as $pair) { list($name, $value) = explode('.', $pair); $output[$name] = $value; } $_COOKIE[$cookieName] = $output; } } if (!empty($_COOKIE['_' . $cookieName]) && is_array($_COOKIE['_' . $cookieName])) { foreach ($_COOKIE['_' . $cookieName] as $adId => $cookie) { if (_isBlockCookie($cookieName)) { $_COOKIE[$cookieName][$adId] = $cookie; } else { if (isset($_COOKIE[$cookieName][$adId])) { $_COOKIE[$cookieName][$adId] += $cookie; } else { $_COOKIE[$cookieName][$adId] = $cookie; } } MAX_cookieUnset("_{$cookieName}[{$adId}]"); } } } } function _isBlockCookie($cookieName) { return in_array($cookieName, array( $GLOBALS['_MAX']['CONF']['var']['blockAd'], $GLOBALS['_MAX']['CONF']['var']['blockCampaign'], $GLOBALS['_MAX']['CONF']['var']['blockZone'], $GLOBALS['_MAX']['CONF']['var']['lastView'], $GLOBALS['_MAX']['CONF']['var']['lastClick'], $GLOBALS['_MAX']['CONF']['var']['blockLoggingClick'], )); } function MAX_cookieGetUniqueViewerId($create = true) { static $uniqueViewerId = null; if(!is_null($uniqueViewerId)) { return $uniqueViewerId; } $conf = $GLOBALS['_MAX']['CONF']; if (isset($_COOKIE[$conf['var']['viewerId']])) { $uniqueViewerId = $_COOKIE[$conf['var']['viewerId']]; } elseif ($create) { $uniqueViewerId = md5(uniqid('', true)); $GLOBALS['_MAX']['COOKIE']['newViewerId'] = true; } return $uniqueViewerId; } function MAX_cookieGetCookielessViewerID() { if (empty($_SERVER['REMOTE_ADDR']) || empty($_SERVER['HTTP_USER_AGENT'])) { return ''; } $cookiePrefix = $GLOBALS['_MAX']['MAX_COOKIELESS_PREFIX']; return $cookiePrefix . substr(md5($_SERVER['REMOTE_ADDR'].$_SERVER['HTTP_USER_AGENT']), 0, 32-(strlen($cookiePrefix))); } function MAX_Delivery_cookie_cappingOnRequest() { if (isset($GLOBALS['_OA']['invocationType']) && ($GLOBALS['_OA']['invocationType'] == 'xmlrpc' || $GLOBALS['_OA']['invocationType'] == 'view') ) { return true; } return !$GLOBALS['_MAX']['CONF']['logging']['adImpressions']; } function MAX_Delivery_cookie_setCapping($type, $id, $block = 0, $cap = 0, $sessionCap = 0) { $conf = $GLOBALS['_MAX']['CONF']; $setBlock = false; if ($cap > 0) { $expire = MAX_commonGetTimeNow() + $conf['cookie']['permCookieSeconds']; if (!isset($_COOKIE[$conf['var']['cap' . $type]][$id])) { $value = 1; $setBlock = true; } else if ($_COOKIE[$conf['var']['cap' . $type]][$id] >= $cap) { $value = -$_COOKIE[$conf['var']['cap' . $type]][$id]+1; $setBlock = true; } else { $value = 1; } MAX_cookieAdd("_{$conf['var']['cap' . $type]}[{$id}]", $value, $expire); } if ($sessionCap > 0) { if (!isset($_COOKIE[$conf['var']['sessionCap' . $type]][$id])) { $value = 1; $setBlock = true; } else if ($_COOKIE[$conf['var']['sessionCap' . $type]][$id] >= $sessionCap) { $value = -$_COOKIE[$conf['var']['sessionCap' . $type]][$id]+1; $setBlock = true; } else { $value = 1; } MAX_cookieAdd("_{$conf['var']['sessionCap' . $type]}[{$id}]", $value, 0); } if ($block > 0 || $setBlock) { MAX_cookieAdd("_{$conf['var']['block' . $type]}[{$id}]", MAX_commonGetTimeNow(), _getTimeThirtyDaysFromNow()); } } function MAX_cookieClientCookieSet($name, $value, $expire, $path = '/', $domain = null) { if (isset($GLOBALS['_OA']['invocationType']) && $GLOBALS['_OA']['invocationType'] == 'xmlrpc') { if (!isset($GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'])) { $GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'] = array(); } $GLOBALS['_OA']['COOKIE']['XMLRPC_CACHE'][$name] = array($value, $expire); } else { @setcookie($name, $value, $expire, $path, $domain); } } function MAX_cookieClientCookieUnset($name) { $conf = $GLOBALS['_MAX']['CONF']; $domain = (!empty($conf['cookie']['domain'])) ? $conf['cookie']['domain'] : null; MAX_cookieSet($name, false, _getTimeYearAgo(), '/', $domain); MAX_cookieSet(str_replace('_', '%5F', urlencode($name)), false, _getTimeYearAgo(), '/', $domain); } function MAX_cookieClientCookieFlush() { $conf = $GLOBALS['_MAX']['CONF']; MAX_cookieSendP3PHeaders(); if (!empty($GLOBALS['_MAX']['COOKIE']['CACHE'])) { reset($GLOBALS['_MAX']['COOKIE']['CACHE']); while (list($name,$v) = each ($GLOBALS['_MAX']['COOKIE']['CACHE'])) { list($value, $expire) = $v; if ($name == $conf['var']['viewerId']) { MAX_cookieClientCookieSet($name, $value, $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null)); } else { MAX_cookieSet($name, $value, $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null)); } } $GLOBALS['_MAX']['COOKIE']['CACHE'] = array(); } $cookieNames = $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames']; if (!is_array($cookieNames)) return; $maxCookieSize = !empty($conf['cookie']['maxCookieSize']) ? $conf['cookie']['maxCookieSize'] : 2048; foreach ($cookieNames as $cookieName) { if (empty($_COOKIE["_{$cookieName}"])) { continue; } switch ($cookieName) { case $conf['var']['blockAd'] : case $conf['var']['blockCampaign'] : case $conf['var']['blockZone'] : $expire = _getTimeThirtyDaysFromNow(); break; case $conf['var']['lastClick'] : case $conf['var']['lastView'] : case $conf['var']['capAd'] : case $conf['var']['capCampaign'] : case $conf['var']['capZone'] : $expire = _getTimeYearFromNow(); break; case $conf['var']['sessionCapCampaign'] : case $conf['var']['sessionCapAd'] : case $conf['var']['sessionCapZone'] : $expire = 0; break; } if (!empty($_COOKIE[$cookieName]) && is_array($_COOKIE[$cookieName])) { $data = array(); foreach ($_COOKIE[$cookieName] as $adId => $value) { $data[] = "{$adId}.{$value}"; } while (strlen(implode('_', $data)) > $maxCookieSize) { $data = array_slice($data, 1); } MAX_cookieSet($cookieName, implode('_', $data), $expire, '/', (!empty($conf['cookie']['domain']) ? $conf['cookie']['domain'] : null)); } } } function MAX_cookieSendP3PHeaders() { if ($GLOBALS['_MAX']['CONF']['p3p']['policies']) { MAX_header("P3P: ". _generateP3PHeader()); } } function _generateP3PHeader() { $conf = $GLOBALS['_MAX']['CONF']; $p3p_header = ''; if ($conf['p3p']['policies']) { if ($conf['p3p']['policyLocation'] != '') { $p3p_header .= " policyref=\"".$conf['p3p']['policyLocation']."\""; } if ($conf['p3p']['policyLocation'] != '' && $conf['p3p']['compactPolicy'] != '') { $p3p_header .= ", "; } if ($conf['p3p']['compactPolicy'] != '') { $p3p_header .= " CP=\"".$conf['p3p']['compactPolicy']."\""; } } return $p3p_header; } $file = '/lib/max/Delivery/remotehost.php'; $GLOBALS['_MAX']['FILES'][$file] = true; function MAX_remotehostSetInfo($run = false) { if (empty($GLOBALS['_OA']['invocationType']) || $run || ($GLOBALS['_OA']['invocationType'] != 'xmlrpc')) { MAX_remotehostProxyLookup(); MAX_remotehostReverseLookup(); MAX_remotehostSetGeoInfo(); } } function MAX_remotehostProxyLookup() { $conf = $GLOBALS['_MAX']['CONF']; if ($conf['logging']['proxyLookup']) { OX_Delivery_logMessage('checking remote host proxy', 7); $proxy = false; if (!empty($_SERVER['HTTP_VIA']) || !empty($_SERVER['HTTP_X_FORWARDED_FOR'])) { $proxy = true; } elseif (!empty($_SERVER['REMOTE_HOST'])) { $aProxyHosts = array( 'proxy', 'cache', 'inktomi' ); foreach ($aProxyHosts as $proxyName) { if (strpos($_SERVER['REMOTE_HOST'], $proxyName) !== false) { $proxy = true; break; } } } if ($proxy) { OX_Delivery_logMessage('proxy detected', 7); $aHeaders = array( 'HTTP_FORWARDED', 'HTTP_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_FORWARDED_FOR', 'HTTP_CLIENT_IP' ); foreach ($aHeaders as $header) { if (!empty($_SERVER[$header])) { $ip = $_SERVER[$header]; break; } } if (!empty($ip)) { foreach (explode(',', $ip) as $ip) { $ip = trim($ip); if (($ip != 'unknown') && (!MAX_remotehostPrivateAddress($ip))) { $_SERVER['REMOTE_ADDR'] = $ip; $_SERVER['REMOTE_HOST'] = ''; $_SERVER['HTTP_VIA'] = ''; OX_Delivery_logMessage('real address set to '.$ip, 7); break; } } } } } } function MAX_remotehostReverseLookup() { if (empty($_SERVER['REMOTE_HOST'])) { if ($GLOBALS['_MAX']['CONF']['logging']['reverseLookup']) { $_SERVER['REMOTE_HOST'] = @gethostbyaddr($_SERVER['REMOTE_ADDR']); } else { $_SERVER['REMOTE_HOST'] = $_SERVER['REMOTE_ADDR']; } } } function MAX_remotehostSetGeoInfo() { if (!function_exists('parseDeliveryIniFile')) { } $aConf = $GLOBALS['_MAX']['CONF']; $type = (!empty($aConf['geotargeting']['type'])) ? $aConf['geotargeting']['type'] : null; if (!is_null($type) && $type != 'none') { $aComponent = explode(':', $aConf['geotargeting']['type']); if (!empty($aComponent[1]) && (!empty($aConf['pluginGroupComponents'][$aComponent[1]]))) { $GLOBALS['_MAX']['CLIENT_GEO'] = OX_Delivery_Common_hook('getGeoInfo', array(), $type); } } } function MAX_remotehostPrivateAddress($ip) { setupIncludePath(); require_once 'Net/IPv4.php'; $aPrivateNetworks = array( '10.0.0.0/8', '172.16.0.0/12', '192.168.0.0/16', '127.0.0.0/24' ); foreach ($aPrivateNetworks as $privateNetwork) { if (Net_IPv4::ipInNetwork($ip, $privateNetwork)) { return true; } } return false; } $file = '/lib/max/Delivery/log.php'; $GLOBALS['_MAX']['FILES'][$file] = true; $file = '/lib/max/Dal/Delivery.php'; $GLOBALS['_MAX']['FILES'][$file] = true; $file = '/lib/OA/Dal/Delivery.php'; $GLOBALS['_MAX']['FILES'][$file] = true; function OA_Dal_Delivery_getAccountTZs() { $aConf = $GLOBALS['_MAX']['CONF']; $query = " SELECT value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['application_variable'])." WHERE name = 'admin_account_id' "; $res = OA_Dal_Delivery_query($query); if (is_resource($res) && OA_Dal_Delivery_numRows($res)) { $adminAccountId = (int)OA_Dal_Delivery_result($res, 0, 0); } else { $adminAccountId = false; } $query = " SELECT a.account_id AS account_id, apa.value AS timezone FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a JOIN ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa ON (apa.account_id = a.account_id) JOIN ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['preferences'])." AS p ON (p.preference_id = apa.preference_id) WHERE a.account_type IN ('ADMIN', 'MANAGER') AND p.preference_name = 'timezone' "; $res = OA_Dal_Delivery_query($query); $aResult = array( 'adminAccountId' => $adminAccountId, 'aAccounts' => array() ); if (is_resource($res)) { while ($row = OA_Dal_Delivery_fetchAssoc($res)) { $accountId = (int)$row['account_id']; if ($accountId === $adminAccountId) { $aResult['default'] = $row['timezone']; } else { $aResult['aAccounts'][$accountId] = $row['timezone']; } } } if (empty($aResult['default'])) { $aResult['default'] = 'UTC'; } return $aResult; } function OA_Dal_Delivery_getZoneInfo($zoneid) { $aConf = $GLOBALS['_MAX']['CONF']; $zoneid = (int)$zoneid; $query = " SELECT z.zoneid AS zone_id, z.zonename AS name, z.delivery AS type, z.description AS description, z.width AS width, z.height AS height, z.chain AS chain, z.prepend AS prepend, z.append AS append, z.appendtype AS appendtype, z.forceappend AS forceappend, z.inventory_forecast_type AS inventory_forecast_type, z.block AS block_zone, z.capping AS cap_zone, z.session_capping AS session_cap_zone, z.show_capped_no_cookie AS show_capped_no_cookie_zone, z.ext_adselection AS ext_adselection, z.affiliateid AS publisher_id, a.agencyid AS agency_id, a.account_id AS trafficker_account_id, m.account_id AS manager_account_id FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['zones'])." AS z, ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['affiliates'])." AS a, ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['agency'])." AS m WHERE z.zoneid = {$zoneid} AND z.affiliateid = a.affiliateid AND a.agencyid = m.agencyid"; $rZoneInfo = OA_Dal_Delivery_query($query); if (!is_resource($rZoneInfo)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false; } $aZoneInfo = OA_Dal_Delivery_fetchAssoc($rZoneInfo); $query = " SELECT p.preference_id AS preference_id, p.preference_name AS preference_name FROM {$aConf['table']['prefix']}{$aConf['table']['preferences']} AS p WHERE p.preference_name = 'default_banner_image_url' OR p.preference_name = 'default_banner_destination_url'"; $rPreferenceInfo = OA_Dal_Delivery_query($query); if (!is_resource($rPreferenceInfo)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false; } if (OA_Dal_Delivery_numRows($rPreferenceInfo) != 2) { return $aZoneInfo; } $aPreferenceInfo = OA_Dal_Delivery_fetchAssoc($rPreferenceInfo); $variableName = $aPreferenceInfo['preference_name'] . '_id'; $$variableName = $aPreferenceInfo['preference_id']; $aPreferenceInfo = OA_Dal_Delivery_fetchAssoc($rPreferenceInfo); $variableName = $aPreferenceInfo['preference_name'] . '_id'; $$variableName = $aPreferenceInfo['preference_id']; $query = " SELECT 'default_banner_destination_url_trafficker' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa WHERE apa.account_id = {$aZoneInfo['trafficker_account_id']} AND apa.preference_id = $default_banner_destination_url_id UNION SELECT 'default_banner_destination_url_manager' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa WHERE apa.account_id = {$aZoneInfo['manager_account_id']} AND apa.preference_id = $default_banner_destination_url_id UNION SELECT 'default_banner_image_url_trafficker' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa WHERE apa.account_id = {$aZoneInfo['trafficker_account_id']} AND apa.preference_id = $default_banner_image_url_id UNION SELECT 'default_banner_image_url_manager' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa WHERE apa.account_id = {$aZoneInfo['manager_account_id']} AND apa.preference_id = $default_banner_image_url_id UNION SELECT 'default_banner_image_url_admin' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa, ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a WHERE apa.account_id = a.account_id AND a.account_type = 'ADMIN' AND apa.preference_id = $default_banner_image_url_id UNION SELECT 'default_banner_destination_url_admin' AS item, apa.value AS value FROM ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['account_preference_assoc'])." AS apa, ".OX_escapeIdentifier($aConf['table']['prefix'].$aConf['table']['accounts'])." AS a WHERE apa.account_id = a.account_id AND a.account_type = 'ADMIN' AND apa.preference_id = $default_banner_destination_url_id"; $rDefaultBannerInfo = OA_Dal_Delivery_query($query); if (!is_resource($rDefaultBannerInfo)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false; } if (OA_Dal_Delivery_numRows($rDefaultBannerInfo) == 0) { if ($aConf['defaultBanner']['imageUrl'] != '') { $aZoneInfo['default_banner_image_url'] = $aConf['defaultBanner']['imageUrl']; } return $aZoneInfo; } $aDefaultImageURLs = array(); $aDefaultDestinationURLs = array(); while ($aRow = OA_Dal_Delivery_fetchAssoc($rDefaultBannerInfo)) { if (stristr($aRow['item'], 'default_banner_image_url')) { $aDefaultImageURLs[$aRow['item']] = $aRow['value']; } else if (stristr($aRow['item'], 'default_banner_destination_url')) { $aDefaultDestinationURLs[$aRow['item']] = $aRow['value']; } } $aTypes = array( 0 => 'admin', 1 => 'manager', 2 => 'trafficker' ); foreach ($aTypes as $type) { if (isset($aDefaultImageURLs['default_banner_image_url_' . $type])) { $aZoneInfo['default_banner_image_url'] = $aDefaultImageURLs['default_banner_image_url_' . $type]; } if (isset($aDefaultDestinationURLs['default_banner_destination_url_' . $type])) { $aZoneInfo['default_banner_destination_url'] = $aDefaultDestinationURLs['default_banner_destination_url_' . $type]; } } return $aZoneInfo; } function OA_Dal_Delivery_getPublisherZones($publisherid) { $conf = $GLOBALS['_MAX']['CONF']; $publisherid = (int)$publisherid; $rZones = OA_Dal_Delivery_query(" SELECT z.zoneid AS zone_id, z.affiliateid AS publisher_id, z.zonename AS name, z.delivery AS type FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['zones'])." AS z WHERE z.affiliateid={$publisherid} "); if (!is_resource($rZones)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : false; } while ($aZone = OA_Dal_Delivery_fetchAssoc($rZones)) { $aZones[$aZone['zone_id']] = $aZone; } return ($aZones); } function OA_Dal_Delivery_getZoneLinkedAds($zoneid) { $conf = $GLOBALS['_MAX']['CONF']; $zoneid = (int)$zoneid; $aRows = OA_Dal_Delivery_getZoneInfo($zoneid); $aRows['xAds'] = array(); $aRows['ads'] = array(); $aRows['lAds'] = array(); $aRows['eAds'] = array(); $aRows['count_active'] = 0; $aRows['zone_companion'] = false; $aRows['count_active'] = 0; $totals = array( 'xAds' => 0, 'ads' => 0, 'lAds' => 0 ); $query = " SELECT d.bannerid AS ad_id, d.campaignid AS placement_id, d.status AS status, d.description AS name, d.storagetype AS type, d.contenttype AS contenttype, d.pluginversion AS pluginversion, d.filename AS filename, d.imageurl AS imageurl, d.htmltemplate AS htmltemplate, d.htmlcache AS htmlcache, d.width AS width, d.height AS height, d.weight AS weight, d.seq AS seq, d.target AS target, d.url AS url, d.alt AS alt, d.statustext AS statustext, d.bannertext AS bannertext, d.adserver AS adserver, d.block AS block_ad, d.capping AS cap_ad, d.session_capping AS session_cap_ad, d.compiledlimitation AS compiledlimitation, d.acl_plugins AS acl_plugins, d.prepend AS prepend, d.append AS append, d.bannertype AS bannertype, d.alt_filename AS alt_filename, d.alt_imageurl AS alt_imageurl, d.alt_contenttype AS alt_contenttype, d.parameters AS parameters, d.transparent AS transparent, d.ext_bannertype AS ext_bannertype, az.priority AS priority, az.priority_factor AS priority_factor, az.to_be_delivered AS to_be_delivered, c.campaignid AS campaign_id, c.priority AS campaign_priority, c.weight AS campaign_weight, c.companion AS campaign_companion, c.block AS block_campaign, c.capping AS cap_campaign, c.session_capping AS session_cap_campaign, c.show_capped_no_cookie AS show_capped_no_cookie, c.clientid AS client_id, c.expire_time AS expire_time, c.revenue_type AS revenue_type, c.ecpm_enabled AS ecpm_enabled, c.ecpm AS ecpm, c.clickwindow AS clickwindow, c.viewwindow AS viewwindow, m.advertiser_limitation AS advertiser_limitation, a.account_id AS account_id, z.affiliateid AS affiliate_id, a.agencyid as agency_id FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id) JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['zones'])." AS z ON (az.zone_id = z.zoneid) JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c ON (c.campaignid = d.campaignid) LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS m ON (m.clientid = c.clientid) LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = m.agencyid) WHERE az.zone_id = {$zoneid} AND d.status <= 0 AND c.status <= 0 "; $rAds = OA_Dal_Delivery_query($query); if (!is_resource($rAds)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } $aConversionLinkedCreatives = MAX_cacheGetTrackerLinkedCreatives(); while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) { $aAd['tracker_status'] = (!empty($aConversionLinkedCreatives[$aAd['ad_id']]['status'])) ? $aConversionLinkedCreatives[$aAd['ad_id']]['status'] : null; if ($aAd['campaign_priority'] == -1) { $aRows['xAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } elseif ($aAd['campaign_priority'] == 0) { $aRows['lAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } elseif ($aAd['campaign_priority'] == -2) { $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } else { $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } if ($aAd['campaign_companion'] == 1) { $aRows['zone_companion'][] = $aAd['placement_id']; } } if (is_array($aRows['xAds'])) { $totals['xAds'] = _setPriorityFromWeights($aRows['xAds']); } if (is_array($aRows['ads'])) { $totals['ads'] = _getTotalPrioritiesByCP($aRows['ads']); } if (is_array($aRows['eAds'])) { $totals['eAds'] = _getTotalPrioritiesByCP($aRows['eAds']); } if (is_array($aRows['lAds'])) { $totals['lAds'] = _setPriorityFromWeights($aRows['lAds']); } $aRows['priority'] = $totals; return $aRows; } function OA_Dal_Delivery_getZoneLinkedAdInfos($zoneid) { $conf = $GLOBALS['_MAX']['CONF']; $zoneid = (int)$zoneid; $aRows['xAds'] = array(); $aRows['ads'] = array(); $aRows['lAds'] = array(); $aRows['eAds'] = array(); $aRows['zone_companion'] = false; $aRows['count_active'] = 0; $query = "SELECT " ."d.bannerid AS ad_id, " ."d.campaignid AS placement_id, " ."d.status AS status, " ."d.width AS width, " ."d.ext_bannertype AS ext_bannertype, " ."d.height AS height, " ."d.storagetype AS type, " ."d.contenttype AS contenttype, " ."d.weight AS weight, " ."d.adserver AS adserver, " ."d.block AS block_ad, " ."d.capping AS cap_ad, " ."d.session_capping AS session_cap_ad, " ."d.compiledlimitation AS compiledlimitation, " ."d.acl_plugins AS acl_plugins, " ."d.alt_filename AS alt_filename, " ."az.priority AS priority, " ."az.priority_factor AS priority_factor, " ."az.to_be_delivered AS to_be_delivered, " ."c.campaignid AS campaign_id, " ."c.priority AS campaign_priority, " ."c.weight AS campaign_weight, " ."c.companion AS campaign_companion, " ."c.block AS block_campaign, " ."c.capping AS cap_campaign, " ."c.session_capping AS session_cap_campaign, " ."c.show_capped_no_cookie AS show_capped_no_cookie, " ."c.clientid AS client_id, " ."c.expire_time AS expire_time, " ."c.revenue_type AS revenue_type, " ."c.ecpm_enabled AS ecpm_enabled, " ."c.ecpm AS ecpm, " ."ct.status AS tracker_status, " .OX_Dal_Delivery_regex("d.htmlcache", "src\\s?=\\s?[\\'\"]http:")." AS html_ssl_unsafe, " .OX_Dal_Delivery_regex("d.imageurl", "^http:")." AS url_ssl_unsafe " ."FROM " .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d JOIN " .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id) JOIN " .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c ON (c.campaignid = d.campaignid) LEFT JOIN " .OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns_trackers'])." AS ct ON (ct.campaignid = c.campaignid) " ."WHERE " ."az.zone_id = {$zoneid} " ."AND " ."d.status <= 0 " ."AND " ."c.status <= 0 "; $rAds = OA_Dal_Delivery_query($query); if (!is_resource($rAds)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) { if ($aAd['campaign_priority'] == -1) { $aRows['xAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } elseif ($aAd['campaign_priority'] == 0) { $aRows['lAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } elseif ($aAd['campaign_priority'] == -2) { $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } else { $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } if ($aAd['campaign_companion'] == 1) { $aRows['zone_companion'][] = $aAd['placement_id']; } } return $aRows; } function OA_Dal_Delivery_getLinkedAdInfos($search, $campaignid = '', $lastpart = true) { $conf = $GLOBALS['_MAX']['CONF']; $campaignid = (int)$campaignid; if ($campaignid > 0) { $precondition = " AND d.campaignid = '".$campaignid."' "; } else { $precondition = ''; } $aRows['xAds'] = array(); $aRows['ads'] = array(); $aRows['lAds'] = array(); $aRows['count_active'] = 0; $aRows['zone_companion'] = false; $aRows['count_active'] = 0; $totals = array( 'xAds' => 0, 'ads' => 0, 'lAds' => 0 ); $query = OA_Dal_Delivery_buildAdInfoQuery($search, $lastpart, $precondition); $rAds = OA_Dal_Delivery_query($query); if (!is_resource($rAds)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) { if ($aAd['campaign_priority'] == -1) { $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight']; $aRows['xAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; $totals['xAds'] += $aAd['priority']; } elseif ($aAd['campaign_priority'] == 0) { $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight']; $aRows['lAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; $totals['lAds'] += $aAd['priority']; } elseif ($aAd['campaign_priority'] == -2) { $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } else { $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } } return $aRows; } function OA_Dal_Delivery_getLinkedAds($search, $campaignid = '', $lastpart = true) { $conf = $GLOBALS['_MAX']['CONF']; $campaignid = (int)$campaignid; if ($campaignid > 0) { $precondition = " AND d.campaignid = '".$campaignid."' "; } else { $precondition = ''; } $aRows['xAds'] = array(); $aRows['ads'] = array(); $aRows['lAds'] = array(); $aRows['count_active'] = 0; $aRows['zone_companion'] = false; $aRows['count_active'] = 0; $totals = array( 'xAds' => 0, 'ads' => 0, 'lAds' => 0 ); $query = OA_Dal_Delivery_buildQuery($search, $lastpart, $precondition); $rAds = OA_Dal_Delivery_query($query); if (!is_resource($rAds)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } $aConversionLinkedCreatives = MAX_cacheGetTrackerLinkedCreatives(); while ($aAd = OA_Dal_Delivery_fetchAssoc($rAds)) { $aAd['tracker_status'] = (!empty($aConversionLinkedCreatives[$aAd['ad_id']]['status'])) ? $aConversionLinkedCreatives[$aAd['ad_id']]['status'] : null; if ($aAd['campaign_priority'] == -1) { $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight']; $aRows['xAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; $totals['xAds'] += $aAd['priority']; } elseif ($aAd['campaign_priority'] == 0) { $aAd['priority'] = $aAd['campaign_weight'] * $aAd['weight']; $aRows['lAds'][$aAd['ad_id']] = $aAd; $aRows['count_active']++; $totals['lAds'] += $aAd['priority']; } elseif ($aAd['campaign_priority'] == -2) { $aRows['eAds'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } else { $aRows['ads'][$aAd['campaign_priority']][$aAd['ad_id']] = $aAd; $aRows['count_active']++; } } if (isset($aRows['xAds']) && is_array($aRows['xAds'])) { $totals['xAds'] = _setPriorityFromWeights($aRows['xAds']); } if (isset($aRows['ads']) && is_array($aRows['ads'])) { if (isset($aRows['lAds']) && is_array($aRows['lAds']) && count($aRows['lAds']) > 0) { $totals['ads'] = _getTotalPrioritiesByCP($aRows['ads'], true); } else { $totals['ads'] = _getTotalPrioritiesByCP($aRows['ads'], false); } } if (is_array($aRows['eAds'])) { $totals['eAds'] = _getTotalPrioritiesByCP($aRows['eAds']); } if (isset($aRows['lAds']) && is_array($aRows['lAds'])) { $totals['lAds'] = _setPriorityFromWeights($aRows['lAds']); } $aRows['priority'] = $totals; return $aRows; } function OA_Dal_Delivery_getAd($ad_id) { $conf = $GLOBALS['_MAX']['CONF']; $ad_id = (int)$ad_id; $query = " SELECT d.bannerid AS ad_id, d.campaignid AS placement_id, d.status AS status, d.description AS name, d.storagetype AS type, d.contenttype AS contenttype, d.pluginversion AS pluginversion, d.filename AS filename, d.imageurl AS imageurl, d.htmltemplate AS htmltemplate, d.htmlcache AS htmlcache, d.width AS width, d.height AS height, d.weight AS weight, d.seq AS seq, d.target AS target, d.url AS url, d.alt AS alt, d.statustext AS statustext, d.bannertext AS bannertext, d.adserver AS adserver, d.block AS block_ad, d.capping AS cap_ad, d.session_capping AS session_cap_ad, d.compiledlimitation AS compiledlimitation, d.acl_plugins AS acl_plugins, d.prepend AS prepend, d.append AS append, d.bannertype AS bannertype, d.alt_filename AS alt_filename, d.alt_imageurl AS alt_imageurl, d.alt_contenttype AS alt_contenttype, d.parameters AS parameters, d.transparent AS transparent, d.ext_bannertype AS ext_bannertype, c.campaignid AS campaign_id, c.block AS block_campaign, c.capping AS cap_campaign, c.session_capping AS session_cap_campaign, c.show_capped_no_cookie AS show_capped_no_cookie, m.clientid AS client_id, c.clickwindow AS clickwindow, c.viewwindow AS viewwindow, m.advertiser_limitation AS advertiser_limitation, m.agencyid AS agency_id FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d, ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS c, ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS m WHERE d.bannerid={$ad_id} AND d.campaignid = c.campaignid AND m.clientid = c.clientid "; $rAd = OA_Dal_Delivery_query($query); if (!is_resource($rAd)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { return (OA_Dal_Delivery_fetchAssoc($rAd)); } } function OA_Dal_Delivery_getChannelLimitations($channelid) { $conf = $GLOBALS['_MAX']['CONF']; $channelid = (int)$channelid; $rLimitation = OA_Dal_Delivery_query(" SELECT acl_plugins,compiledlimitation FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['channel'])." WHERE channelid={$channelid}"); if (!is_resource($rLimitation)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } $limitations = OA_Dal_Delivery_fetchAssoc($rLimitation); return $limitations; } function OA_Dal_Delivery_getCreative($filename) { $conf = $GLOBALS['_MAX']['CONF']; $rCreative = OA_Dal_Delivery_query(" SELECT contents, t_stamp FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['images'])." WHERE filename = '".OX_escapeString($filename)."' "); if (!is_resource($rCreative)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { $aResult = OA_Dal_Delivery_fetchAssoc($rCreative); $aResult['t_stamp'] = strtotime($aResult['t_stamp'] . ' GMT'); return ($aResult); } } function OA_Dal_Delivery_getTracker($trackerid) { $conf = $GLOBALS['_MAX']['CONF']; $trackerid = (int)$trackerid; $rTracker = OA_Dal_Delivery_query(" SELECT t.clientid AS advertiser_id, t.trackerid AS tracker_id, t.trackername AS name, t.variablemethod AS variablemethod, t.description AS description, t.viewwindow AS viewwindow, t.clickwindow AS clickwindow, t.blockwindow AS blockwindow, t.appendcode AS appendcode FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['trackers'])." AS t WHERE t.trackerid={$trackerid} "); if (!is_resource($rTracker)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { return (OA_Dal_Delivery_fetchAssoc($rTracker)); } } function OA_Dal_Delivery_getTrackerLinkedCreatives($trackerid = null) { $aConf = $GLOBALS['_MAX']['CONF']; $trackerid = (int)$trackerid; $rCreatives = OA_Dal_Delivery_query(" SELECT b.bannerid AS ad_id, b.campaignid AS placement_id, c.viewwindow AS view_window, c.clickwindow AS click_window, ct.status AS status, t.type AS tracker_type FROM {$aConf['table']['prefix']}{$aConf['table']['banners']} AS b, {$aConf['table']['prefix']}{$aConf['table']['campaigns_trackers']} AS ct, {$aConf['table']['prefix']}{$aConf['table']['campaigns']} AS c, {$aConf['table']['prefix']}{$aConf['table']['trackers']} AS t WHERE ct.trackerid=t.trackerid AND c.campaignid=b.campaignid AND b.campaignid = ct.campaignid " . ((!empty($trackerid)) ? ' AND t.trackerid='.$trackerid : '') . " "); if (!is_resource($rCreatives)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { $output = array(); while ($aRow = OA_Dal_Delivery_fetchAssoc($rCreatives)) { $output[$aRow['ad_id']] = $aRow; } return $output; } } function OA_Dal_Delivery_getTrackerVariables($trackerid) { $conf = $GLOBALS['_MAX']['CONF']; $trackerid = (int)$trackerid; $rVariables = OA_Dal_Delivery_query(" SELECT v.variableid AS variable_id, v.trackerid AS tracker_id, v.name AS name, v.datatype AS type, purpose AS purpose, reject_if_empty AS reject_if_empty, is_unique AS is_unique, unique_window AS unique_window, v.variablecode AS variablecode FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['variables'])." AS v WHERE v.trackerid={$trackerid} "); if (!is_resource($rVariables)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { $output = array(); while ($aRow = OA_Dal_Delivery_fetchAssoc($rVariables)) { $output[$aRow['variable_id']] = $aRow; } return $output; } } function OA_Dal_Delivery_getMaintenanceInfo() { $conf = $GLOBALS['_MAX']['CONF']; $result = OA_Dal_Delivery_query(" SELECT value AS maintenance_timestamp FROM ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['application_variable'])." WHERE name = 'maintenance_timestamp' "); if (!is_resource($result)) { return (defined('OA_DELIVERY_CACHE_FUNCTION_ERROR')) ? OA_DELIVERY_CACHE_FUNCTION_ERROR : null; } else { $result = OA_Dal_Delivery_fetchAssoc($result); return $result['maintenance_timestamp']; } } function OA_Dal_Delivery_buildQuery($part, $lastpart, $precondition) { $conf = $GLOBALS['_MAX']['CONF']; $aColumns = array( 'd.bannerid AS ad_id', 'd.campaignid AS placement_id', 'd.status AS status', 'd.description AS name', 'd.storagetype AS type', 'd.contenttype AS contenttype', 'd.pluginversion AS pluginversion', 'd.filename AS filename', 'd.imageurl AS imageurl', 'd.htmltemplate AS htmltemplate', 'd.htmlcache AS htmlcache', 'd.width AS width', 'd.height AS height', 'd.weight AS weight', 'd.seq AS seq', 'd.target AS target', 'd.url AS url', 'd.alt AS alt', 'd.statustext AS statustext', 'd.bannertext AS bannertext', 'd.adserver AS adserver', 'd.block AS block_ad', 'd.capping AS cap_ad', 'd.session_capping AS session_cap_ad', 'd.compiledlimitation AS compiledlimitation', 'd.acl_plugins AS acl_plugins', 'd.prepend AS prepend', 'd.append AS append', 'd.bannertype AS bannertype', 'd.alt_filename AS alt_filename', 'd.alt_imageurl AS alt_imageurl', 'd.alt_contenttype AS alt_contenttype', 'd.parameters AS parameters', 'd.transparent AS transparent', 'd.ext_bannertype AS ext_bannertype', 'az.priority AS priority', 'az.priority_factor AS priority_factor', 'az.to_be_delivered AS to_be_delivered', 'm.campaignid AS campaign_id', 'm.priority AS campaign_priority', 'm.weight AS campaign_weight', 'm.companion AS campaign_companion', 'm.block AS block_campaign', 'm.capping AS cap_campaign', 'm.session_capping AS session_cap_campaign', 'm.show_capped_no_cookie AS show_capped_no_cookie', 'm.clickwindow AS clickwindow', 'm.viewwindow AS viewwindow', 'cl.clientid AS client_id', 'm.expire_time AS expire_time', 'm.revenue_type AS revenue_type', 'm.ecpm_enabled AS ecpm_enabled', 'm.ecpm AS ecpm', 'cl.advertiser_limitation AS advertiser_limitation', 'a.account_id AS account_id', 'a.agencyid AS agency_id' ); $aTables = array( "".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d", "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS m ON (d.campaignid = m.campaignid) ", "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS cl ON (m.clientid = cl.clientid) ", "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id)" ); $select = " az.zone_id = 0 AND m.status <= 0 AND d.status <= 0"; if ($precondition != '') $select .= " $precondition "; if ($part != '') { $conditions = ''; $onlykeywords = true; $part_array = explode(',', $part); for ($k=0; $k < count($part_array); $k++) { if (substr($part_array[$k], 0, 1) == '+' || substr($part_array[$k], 0, 1) == '_') { $operator = 'AND'; $part_array[$k] = substr($part_array[$k], 1); } elseif (substr($part_array[$k], 0, 1) == '-') { $operator = 'NOT'; $part_array[$k] = substr($part_array[$k], 1); } else $operator = 'OR'; if($part_array[$k] != '' && $part_array[$k] != ' ') { if(preg_match('#^(?:size:)?([0-9]+x[0-9]+)$#', $part_array[$k], $m)) { list($width, $height) = explode('x', $m[1]); if ($operator == 'OR') $conditions .= "OR (d.width = $width AND d.height = $height) "; elseif ($operator == 'AND') $conditions .= "AND (d.width = $width AND d.height = $height) "; else $conditions .= "AND (d.width != $width OR d.height != $height) "; $onlykeywords = false; } elseif (substr($part_array[$k],0,6) == 'width:') { $part_array[$k] = substr($part_array[$k], 6); if ($part_array[$k] != '' && $part_array[$k] != ' ') { if (is_int(strpos($part_array[$k], '-'))) { list($min, $max) = explode('-', $part_array[$k]); if ($min == '') $min = 1; if ($max == '') { if ($operator == 'OR') $conditions .= "OR d.width >= '".trim($min)."' "; elseif ($operator == 'AND') $conditions .= "AND d.width >= '".trim($min)."' "; else $conditions .= "AND d.width < '".trim($min)."' "; } if ($max != '') { if ($operator == 'OR') $conditions .= "OR (d.width >= '".trim($min)."' AND d.width <= '".trim($max)."') "; elseif ($operator == 'AND') $conditions .= "AND (d.width >= '".trim($min)."' AND d.width <= '".trim($max)."') "; else $conditions .= "AND (d.width < '".trim($min)."' OR d.width > '".trim($max)."') "; } } else { if ($operator == 'OR') $conditions .= "OR d.width = '".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.width = '".trim($part_array[$k])."' "; else $conditions .= "AND d.width != '".trim($part_array[$k])."' "; } } $onlykeywords = false; } elseif (substr($part_array[$k],0,7) == 'height:') { $part_array[$k] = substr($part_array[$k], 7); if ($part_array[$k] != '' && $part_array[$k] != ' ') { if (is_int(strpos($part_array[$k], '-'))) { list($min, $max) = explode('-', $part_array[$k]); if ($min == '') $min = 1; if ($max == '') { if ($operator == 'OR') $conditions .= "OR d.height >= '".trim($min)."' "; elseif ($operator == 'AND') $conditions .= "AND d.height >= '".trim($min)."' "; else $conditions .= "AND d.height < '".trim($min)."' "; } if ($max != '') { if ($operator == 'OR') $conditions .= "OR (d.height >= '".trim($min)."' AND d.height <= '".trim($max)."') "; elseif ($operator == 'AND') $conditions .= "AND (d.height >= '".trim($min)."' AND d.height <= '".trim($max)."') "; else $conditions .= "AND (d.height < '".trim($min)."' OR d.height > '".trim($max)."') "; } } else { if ($operator == 'OR') $conditions .= "OR d.height = '".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.height = '".trim($part_array[$k])."' "; else $conditions .= "AND d.height != '".trim($part_array[$k])."' "; } } $onlykeywords = false; } elseif (preg_match('#^(?:(?:bannerid|adid|ad_id):)?([0-9]+)$#', $part_array[$k], $m)) { $part_array[$k] = $m[1]; if ($part_array[$k]) { if ($operator == 'OR') $conditions .= "OR d.bannerid='".$part_array[$k]."' "; elseif ($operator == 'AND') $conditions .= "AND d.bannerid='".$part_array[$k]."' "; else $conditions .= "AND d.bannerid!='".$part_array[$k]."' "; } $onlykeywords = false; } elseif (preg_match('#^(?:(?:clientid|campaignid|placementid|placement_id):)?([0-9]+)$#', $part_array[$k], $m)) { $part_array[$k] = $m[1]; if ($part_array[$k]) { if ($operator == 'OR') $conditions .= "OR d.campaignid='".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.campaignid='".trim($part_array[$k])."' "; else $conditions .= "AND d.campaignid!='".trim($part_array[$k])."' "; } $onlykeywords = false; } elseif (substr($part_array[$k], 0, 7) == 'format:') { $part_array[$k] = substr($part_array[$k], 7); if($part_array[$k] != '' && $part_array[$k] != ' ') { if ($operator == 'OR') $conditions .= "OR d.contenttype='".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.contenttype='".trim($part_array[$k])."' "; else $conditions .= "AND d.contenttype!='".trim($part_array[$k])."' "; } $onlykeywords = false; } elseif($part_array[$k] == 'html') { if ($operator == 'OR') $conditions .= "OR d.storagetype='html' "; elseif ($operator == 'AND') $conditions .= "AND d.storagetype='html' "; else $conditions .= "AND d.storagetype!='html' "; $onlykeywords = false; } elseif($part_array[$k] == 'textad') { if ($operator == 'OR') $conditions .= "OR d.storagetype='txt' "; elseif ($operator == 'AND') $conditions .= "AND d.storagetype='txt' "; else $conditions .= "AND d.storagetype!='txt' "; $onlykeywords = false; } else { $conditions .= OA_Dal_Delivery_getKeywordCondition($operator, $part_array[$k]); } } } $conditions = strstr($conditions, ' '); if ($lastpart == true && $onlykeywords == true) $conditions .= OA_Dal_Delivery_getKeywordCondition('OR', 'global'); if ($conditions != '') $select .= ' AND ('.$conditions.') '; } $columns = implode(",\n ", $aColumns); $tables = implode("\n ", $aTables); $leftJoin = " LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS c ON (c.clientid = m.clientid) LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = c.agencyid) "; $query = "SELECT\n " . $columns . "\nFROM\n " . $tables . $leftJoin . "\nWHERE " . $select; return $query; } function OA_Dal_Delivery_buildAdInfoQuery($part, $lastpart, $precondition) { $conf = $GLOBALS['_MAX']['CONF']; $aColumns = array( 'd.bannerid AS ad_id', 'd.campaignid AS placement_id', 'd.status AS status', 'd.storagetype AS type', 'd.contenttype AS contenttype', 'd.weight AS weight', 'd.width AS width', 'd.ext_bannertype AS ext_bannertype', 'd.height AS height', 'd.adserver AS adserver', 'd.block AS block_ad', 'd.capping AS cap_ad', 'd.session_capping AS session_cap_ad', 'd.compiledlimitation AS compiledlimitation', 'd.acl_plugins AS acl_plugins', 'd.alt_filename AS alt_filename', 'az.priority AS priority', 'az.priority_factor AS priority_factor', 'az.to_be_delivered AS to_be_delivered', 'm.campaignid AS campaign_id', 'm.priority AS campaign_priority', 'm.weight AS campaign_weight', 'm.companion AS campaign_companion', 'm.block AS block_campaign', 'm.capping AS cap_campaign', 'm.session_capping AS session_cap_campaign', 'm.show_capped_no_cookie AS show_capped_no_cookie', 'cl.clientid AS client_id', 'm.expire_time AS expire_time', 'm.revenue_type AS revenue_type', 'm.ecpm_enabled AS ecpm_enabled', 'm.ecpm AS ecpm', 'ct.status AS tracker_status', OX_Dal_Delivery_regex("d.htmlcache", "src\\s?=\\s?[\\'\"]http:")." AS html_ssl_unsafe", OX_Dal_Delivery_regex("d.imageurl", "^http:")." AS url_ssl_unsafe", ); $aTables = array( "".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['banners'])." AS d", "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['ad_zone_assoc'])." AS az ON (d.bannerid = az.ad_id)", "JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns'])." AS m ON (m.campaignid = d.campaignid) ", ); $select = " az.zone_id = 0 AND m.status <= 0 AND d.status <= 0"; if ($precondition != '') $select .= " $precondition "; if ($part != '') { $conditions = ''; $onlykeywords = true; $part_array = explode(',', $part); for ($k=0; $k < count($part_array); $k++) { if (substr($part_array[$k], 0, 1) == '+' || substr($part_array[$k], 0, 1) == '_') { $operator = 'AND'; $part_array[$k] = substr($part_array[$k], 1); } elseif (substr($part_array[$k], 0, 1) == '-') { $operator = 'NOT'; $part_array[$k] = substr($part_array[$k], 1); } else $operator = 'OR'; if($part_array[$k] != '' && $part_array[$k] != ' ') { if(preg_match('#^(?:size:)?([0-9]+x[0-9]+)$#', $part_array[$k], $m)) { list($width, $height) = explode('x', $m[1]); if ($operator == 'OR') $conditions .= "OR (d.width = $width AND d.height = $height) "; elseif ($operator == 'AND') $conditions .= "AND (d.width = $width AND d.height = $height) "; else $conditions .= "AND (d.width != $width OR d.height != $height) "; $onlykeywords = false; } elseif (substr($part_array[$k],0,6) == 'width:') { $part_array[$k] = substr($part_array[$k], 6); if ($part_array[$k] != '' && $part_array[$k] != ' ') { if (is_int(strpos($part_array[$k], '-'))) { list($min, $max) = explode('-', $part_array[$k]); if ($min == '') $min = 1; if ($max == '') { if ($operator == 'OR') $conditions .= "OR d.width >= '".trim($min)."' "; elseif ($operator == 'AND') $conditions .= "AND d.width >= '".trim($min)."' "; else $conditions .= "AND d.width < '".trim($min)."' "; } if ($max != '') { if ($operator == 'OR') $conditions .= "OR (d.width >= '".trim($min)."' AND d.width <= '".trim($max)."') "; elseif ($operator == 'AND') $conditions .= "AND (d.width >= '".trim($min)."' AND d.width <= '".trim($max)."') "; else $conditions .= "AND (d.width < '".trim($min)."' OR d.width > '".trim($max)."') "; } } else { if ($operator == 'OR') $conditions .= "OR d.width = '".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.width = '".trim($part_array[$k])."' "; else $conditions .= "AND d.width != '".trim($part_array[$k])."' "; } } $onlykeywords = false; } elseif (substr($part_array[$k],0,7) == 'height:') { $part_array[$k] = substr($part_array[$k], 7); if ($part_array[$k] != '' && $part_array[$k] != ' ') { if (is_int(strpos($part_array[$k], '-'))) { list($min, $max) = explode('-', $part_array[$k]); if ($min == '') $min = 1; if ($max == '') { if ($operator == 'OR') $conditions .= "OR d.height >= '".trim($min)."' "; elseif ($operator == 'AND') $conditions .= "AND d.height >= '".trim($min)."' "; else $conditions .= "AND d.height < '".trim($min)."' "; } if ($max != '') { if ($operator == 'OR') $conditions .= "OR (d.height >= '".trim($min)."' AND d.height <= '".trim($max)."') "; elseif ($operator == 'AND') $conditions .= "AND (d.height >= '".trim($min)."' AND d.height <= '".trim($max)."') "; else $conditions .= "AND (d.height < '".trim($min)."' OR d.height > '".trim($max)."') "; } } else { if ($operator == 'OR') $conditions .= "OR d.height = '".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.height = '".trim($part_array[$k])."' "; else $conditions .= "AND d.height != '".trim($part_array[$k])."' "; } } $onlykeywords = false; } elseif (preg_match('#^(?:(?:bannerid|adid|ad_id):)?([0-9]+)$#', $part_array[$k], $m)) { $part_array[$k] = $m[1]; if ($part_array[$k]) { if ($operator == 'OR') $conditions .= "OR d.bannerid='".$part_array[$k]."' "; elseif ($operator == 'AND') $conditions .= "AND d.bannerid='".$part_array[$k]."' "; else $conditions .= "AND d.bannerid!='".$part_array[$k]."' "; } $onlykeywords = false; } elseif (preg_match('#^(?:(?:clientid|campaignid|placementid|placement_id):)?([0-9]+)$#', $part_array[$k], $m)) { $part_array[$k] = $m[1]; if ($part_array[$k]) { if ($operator == 'OR') $conditions .= "OR d.campaignid='".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.campaignid='".trim($part_array[$k])."' "; else $conditions .= "AND d.campaignid!='".trim($part_array[$k])."' "; } $onlykeywords = false; } elseif (substr($part_array[$k], 0, 7) == 'format:') { $part_array[$k] = substr($part_array[$k], 7); if($part_array[$k] != '' && $part_array[$k] != ' ') { if ($operator == 'OR') $conditions .= "OR d.contenttype='".trim($part_array[$k])."' "; elseif ($operator == 'AND') $conditions .= "AND d.contenttype='".trim($part_array[$k])."' "; else $conditions .= "AND d.contenttype!='".trim($part_array[$k])."' "; } $onlykeywords = false; } elseif($part_array[$k] == 'html') { if ($operator == 'OR') $conditions .= "OR d.storagetype='html' "; elseif ($operator == 'AND') $conditions .= "AND d.storagetype='html' "; else $conditions .= "AND d.storagetype!='html' "; $onlykeywords = false; } elseif($part_array[$k] == 'textad') { if ($operator == 'OR') $conditions .= "OR d.storagetype='txt' "; elseif ($operator == 'AND') $conditions .= "AND d.storagetype='txt' "; else $conditions .= "AND d.storagetype!='txt' "; $onlykeywords = false; } else { $conditions .= OA_Dal_Delivery_getKeywordCondition($operator, $part_array[$k]); } } } $conditions = strstr($conditions, ' '); if ($lastpart == true && $onlykeywords == true) $conditions .= OA_Dal_Delivery_getKeywordCondition('OR', 'global'); if ($conditions != '') $select .= ' AND ('.$conditions.') '; } $columns = implode(",\n ", $aColumns); $tables = implode("\n ", $aTables); $leftJoin = " LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['campaigns_trackers'])." AS ct ON (ct.campaignid = m.campaignid) LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['clients'])." AS cl ON (cl.clientid = m.clientid) LEFT JOIN ".OX_escapeIdentifier($conf['table']['prefix'].$conf['table']['agency'])." AS a ON (a.agencyid = cl.agencyid) "; $query = "SELECT\n " . $columns . "\nFROM\n " . $tables . $leftJoin . "\nWHERE " . $select; return $query; } function _setPriorityFromWeights(&$aAds) { if (!count($aAds)) { return 0; } $aCampaignWeights = array(); $aCampaignAdWeight = array(); foreach ($aAds as $v) { if (!isset($aCampaignWeights[$v['placement_id']])) { $aCampaignWeights[$v['placement_id']] = $v['campaign_weight']; $aCampaignAdWeight[$v['placement_id']] = 0; } $aCampaignAdWeight[$v['placement_id']] += $v['weight']; } foreach ($aCampaignWeights as $k => $v) { if ($aCampaignAdWeight[$k]) { $aCampaignWeights[$k] /= $aCampaignAdWeight[$k]; } } $totalPri = 0; foreach ($aAds as $k => $v) { $aAds[$k]['priority'] = $aCampaignWeights[$v['placement_id']] * $v['weight']; $totalPri += $aAds[$k]['priority']; } if ($totalPri) { foreach ($aAds as $k => $v) { $aAds[$k]['priority'] /= $totalPri; } return 1; } return 0; } function _getTotalPrioritiesByCP($aAdsByCP, $includeBlank = true) { $totals = array(); $total_priority_cp = array(); $blank_priority = 1; foreach ($aAdsByCP as $campaign_priority => $aAds) { $total_priority_cp[$campaign_priority] = 0; foreach ($aAds as $key => $aAd) { $blank_priority -= (double)$aAd['priority']; if ($aAd['to_be_delivered']) { $priority = $aAd['priority'] * $aAd['priority_factor']; } else { $priority = 0.00001; } $total_priority_cp[$campaign_priority] += $priority; } } $total_priority = 0; if ($includeBlank) { $total_priority = $blank_priority <= 1e-15 ? 0 : $blank_priority; } ksort($total_priority_cp); foreach($total_priority_cp as $campaign_priority => $priority) { $total_priority += $priority; if ($total_priority) { $totals[$campaign_priority] = $priority / $total_priority; } else { $totals[$campaign_priority] = 0; } } return $totals; } function MAX_Dal_Delivery_Include() { static $included; if (isset($included)) { return; } $included = true; $conf = $GLOBALS['_MAX']['CONF']; if (isset($conf['origin']['type']) && is_readable(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['origin']['type']) . '.php')) { require(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['origin']['type']) . '.php'); } else { require(MAX_PATH . '/lib/OA/Dal/Delivery/' . strtolower($conf['database']['type']) . '.php'); } } function MAX_trackerbuildJSVariablesScript($trackerid, $conversionInfo, $trackerJsCode = null) { $conf = $GLOBALS['_MAX']['CONF']; $buffer = ''; $url = MAX_commonGetDeliveryUrl($conf['file']['conversionvars']); $tracker = MAX_cacheGetTracker($trackerid); $variables = MAX_cacheGetTrackerVariables($trackerid); $variableQuerystring = ''; if (empty($trackerJsCode)) { $trackerJsCode = md5(uniqid('', true)); } else { $tracker['variablemethod'] = 'default'; } if (!empty($variables)) { if ($tracker['variablemethod'] == 'dom') { $buffer .= " function MAX_extractTextDom(o) { var txt = ''; if (o.nodeType == 3) { txt = o.data; } else { for (var i = 0; i < o.childNodes.length; i++) { txt += MAX_extractTextDom(o.childNodes[i]); } } return txt; } function MAX_TrackVarDom(id, v) { if (max_trv[id][v]) { return; } var o = document.getElementById(v); if (o) { max_trv[id][v] = escape(o.tagName == 'INPUT' ? o.value : MAX_extractTextDom(o)); } }"; $funcName = 'MAX_TrackVarDom'; } elseif ($tracker['variablemethod'] == 'default') { $buffer .= " function MAX_TrackVarDefault(id, v) { if (max_trv[id][v]) { return; } if (typeof(window[v]) == undefined) { return; } max_trv[id][v] = window[v]; }"; $funcName = 'MAX_TrackVarDefault'; } else { $buffer .= " function MAX_TrackVarJs(id, v, c) { if (max_trv[id][v]) { return; } if (typeof(window[v]) == undefined) { return; } if (typeof(c) != 'undefined') { eval(c); } max_trv[id][v] = window[v]; }"; $funcName = 'MAX_TrackVarJs'; } $buffer .= " if (!max_trv) { var max_trv = new Array(); } if (!max_trv['{$trackerJsCode}']) { max_trv['{$trackerJsCode}'] = new Array(); }"; foreach($variables as $key => $variable) { $variableQuerystring .= "&{$variable['name']}=\"+max_trv['{$trackerJsCode}']['{$variable['name']}']+\""; if ($tracker['variablemethod'] == 'custom') { $buffer .= " {$funcName}('{$trackerJsCode}', '{$variable['name']}', '".addcslashes($variable['variablecode'], "'")."');"; } else { $buffer .= " {$funcName}('{$trackerJsCode}', '{$variable['name']}');"; } } if (!empty($variableQuerystring)) { $conversionInfoParams = array(); foreach ($conversionInfo as $plugin => $pluginData) { if (is_array($pluginData)) { foreach ($pluginData as $key => $value) { $conversionInfoParams[] = $key . '=' . urlencode($value); } } } $conversionInfoParams = '&' . implode('&', $conversionInfoParams); $buffer .= " document.write (\"<\" + \"script language='JavaScript' type='text/javascript' src='\"); document.write (\"$url?trackerid=$trackerid{$conversionInfoParams}{$variableQuerystring}'\");"; $buffer .= "\n\tdocument.write (\"><\\/scr\"+\"ipt>\");"; } } if(!empty($tracker['appendcode'])) { $tracker['appendcode'] = preg_replace('/("\?trackerid=\d+&amp;inherit)=1/', '$1='.$trackerJsCode, $tracker['appendcode']); $jscode = MAX_javascriptToHTML($tracker['appendcode'], "MAX_{$trackerid}_appendcode"); $jscode = preg_replace("/\{m3_trackervariable:(.+?)\}/", "\"+max_trv['{$trackerJsCode}']['$1']+\"", $jscode); $buffer .= "\n".preg_replace('/^/m', "\t", $jscode)."\n"; } if (empty($buffer)) { $buffer = "document.write(\"\");"; } return $buffer; } function MAX_trackerCheckForValidAction($trackerid) { $aTrackerLinkedAds = MAX_cacheGetTrackerLinkedCreatives($trackerid); if (empty($aTrackerLinkedAds)) { return false; } $aPossibleActions = _getActionTypes(); $now = MAX_commonGetTimeNow(); $aConf = $GLOBALS['_MAX']['CONF']; $aMatchingActions = array(); foreach ($aTrackerLinkedAds as $creativeId => $aLinkedInfo) { foreach ($aPossibleActions as $actionId => $action) { if (!empty($aLinkedInfo[$action . '_window']) && !empty($_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId])) { if (stristr($_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId], ' ')) { list($value, $extra) = explode(' ', $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId], 2); $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId] = $value; } else { $extra = ''; } list($lastAction, $zoneId) = explode('-', $_COOKIE[$aConf['var']['last' . ucfirst($action)]][$creativeId]); $lastAction = MAX_commonUnCompressInt($lastAction); $lastSeenSecondsAgo = $now - $lastAction; if ($lastSeenSecondsAgo <= $aLinkedInfo[$action . '_window'] && $lastSeenSecondsAgo > 0) { $aMatchingActions[$lastSeenSecondsAgo] = array( 'action_type' => $actionId, 'tracker_type' => $aLinkedInfo['tracker_type'], 'status' => $aLinkedInfo['status'], 'cid' => $creativeId, 'zid' => $zoneId, 'dt' => $lastAction, 'window' => $aLinkedInfo[$action . '_window'], 'extra' => $extra, ); } } } } if (empty($aMatchingActions)) { return false; } ksort($aMatchingActions); return array_shift($aMatchingActions); } function _getActionTypes() { return array(0 => 'view', 1 => 'click'); } function _getTrackerTypes() { return array(1 => 'sale', 2 => 'lead', 3 => 'signup'); } function MAX_Delivery_log_logAdRequest($adId, $zoneId, $aAd = array()) { if (empty($GLOBALS['_MAX']['CONF']['logging']['adRequests'])) { return true; } OX_Delivery_Common_hook('logRequest', array($adId, $zoneId, $aAd, _viewersHostOkayToLog($adId, $zoneId))); } function MAX_Delivery_log_logAdImpression($adId, $zoneId) { if (empty($GLOBALS['_MAX']['CONF']['logging']['adImpressions'])) { return true; } OX_Delivery_Common_hook('logImpression', array($adId, $zoneId, _viewersHostOkayToLog($adId, $zoneId))); } function MAX_Delivery_log_logAdClick($adId, $zoneId) { if (empty($GLOBALS['_MAX']['CONF']['logging']['adClicks'])) { return true; } OX_Delivery_Common_hook('logClick', array($adId, $zoneId, _viewersHostOkayToLog($adId, $zoneId))); } function MAX_Delivery_log_logConversion($trackerId, $aConversion) { if (empty($GLOBALS['_MAX']['CONF']['logging']['trackerImpressions'])) { return true; } $aConf = $GLOBALS['_MAX']['CONF']; if (!empty($aConf['lb']['enabled'])) { $aConf['rawDatabase']['host'] = $_SERVER['SERVER_ADDR']; } else { $aConf['rawDatabase']['host'] = 'singleDB'; } if (isset($aConf['rawDatabase']['serverRawIp'])) { $serverRawIp = $aConf['rawDatabase']['serverRawIp']; } else { $serverRawIp = $aConf['rawDatabase']['host']; } $aConversionInfo = OX_Delivery_Common_hook('logConversion', array($trackerId, $serverRawIp, $aConversion, _viewersHostOkayToLog(null, null, $trackerId))); if (is_array($aConversionInfo)) { return $aConversionInfo; } return false; } function MAX_Delivery_log_logVariableValues($aVariables, $trackerId, $serverConvId, $serverRawIp) { $aConf = $GLOBALS['_MAX']['CONF']; foreach ($aVariables as $aVariable) { if (isset($_GET[$aVariable['name']])) { $value = $_GET[$aVariable['name']]; if (!strlen($value) || $value == 'undefined') { unset($aVariables[$aVariable['variable_id']]); continue; } switch ($aVariable['type']) { case 'int': case 'numeric': $value = preg_replace('/[^0-9.]/', '', $value); $value = floatval($value); break; case 'date': if (!empty($value)) { $value = date('Y-m-d H:i:s', strtotime($value)); } else { $value = ''; } break; } } else { unset($aVariables[$aVariable['variable_id']]); continue; } $aVariables[$aVariable['variable_id']]['value'] = $value; } if (count($aVariables)) { OX_Delivery_Common_hook('logConversionVariable', array($aVariables, $trackerId, $serverConvId, $serverRawIp, _viewersHostOkayToLog(null, null, $trackerId))); } } function _viewersHostOkayToLog($adId=0, $zoneId=0, $trackerId=0) { $aConf = $GLOBALS['_MAX']['CONF']; $agent = strtolower($_SERVER['HTTP_USER_AGENT']); $okToLog = true; if (!empty($aConf['logging']['enforceUserAgents'])) { $aKnownBrowsers = explode('|', strtolower($aConf['logging']['enforceUserAgents'])); $allowed = false; foreach ($aKnownBrowsers as $browser) { if (strpos($agent, $browser) !== false) { $allowed = true; break; } } OX_Delivery_logMessage('user-agent browser : '.$agent.' is '.($allowed ? '' : 'not ').'allowed', 7); if (!$allowed) { $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'enforceUserAgents'; $okToLog = false; } } if (!empty($aConf['logging']['ignoreUserAgents'])) { $aKnownBots = explode('|', strtolower($aConf['logging']['ignoreUserAgents'])); foreach ($aKnownBots as $bot) { if (strpos($agent, $bot) !== false) { OX_Delivery_logMessage('user-agent '.$agent.' is a known bot '.$bot, 7); $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreUserAgents'; $okToLog = false; } } } if (!empty($aConf['logging']['ignoreHosts'])) { $hosts = str_replace(',', '|', $aConf['logging']['ignoreHosts']); $hosts = '#^('.$hosts.')$#i'; $hosts = str_replace('.', '\.', $hosts); $hosts = str_replace('*', '[^.]+', $hosts); if (preg_match($hosts, $_SERVER['REMOTE_ADDR'])) { OX_Delivery_logMessage('viewer\'s ip is in the ignore list '.$_SERVER['REMOTE_ADDR'], 7); $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreHosts_ip'; $okToLog = false; } if (preg_match($hosts, $_SERVER['REMOTE_HOST'])) { OX_Delivery_logMessage('viewer\'s host is in the ignore list '.$_SERVER['REMOTE_HOST'], 7); $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = 'ignoreHosts_host'; $okToLog = false; } } if ($okToLog) OX_Delivery_logMessage('viewer\'s host is OK to log', 7); $result = OX_Delivery_Common_Hook('filterEvent', array($adId, $zoneId, $trackerId)); if (!empty($result) && is_array($result)) { foreach ($result as $pci => $value) { if ($value == true) { $GLOBALS['_MAX']['EVENT_FILTER_FLAGS'][] = $pci; $okToLog = false; } } } return $okToLog; } function MAX_Delivery_log_getArrGetVariable($name) { $varName = $GLOBALS['_MAX']['CONF']['var'][$name]; return isset($_GET[$varName]) ? explode($GLOBALS['_MAX']['MAX_DELIVERY_MULTIPLE_DELIMITER'], $_GET[$varName]) : array(); } function MAX_Delivery_log_ensureIntegerSet(&$aArray, $index) { if (!is_array($aArray)) { $aArray = array(); } if (empty($aArray[$index])) { $aArray[$index] = 0; } else { if (!is_integer($aArray[$index])) { $aArray[$index] = intval($aArray[$index]); } } } function MAX_Delivery_log_setAdLimitations($index, $aAds, $aCaps) { _setLimitations('Ad', $index, $aAds, $aCaps); } function MAX_Delivery_log_setCampaignLimitations($index, $aCampaigns, $aCaps) { _setLimitations('Campaign', $index, $aCampaigns, $aCaps); } function MAX_Delivery_log_setZoneLimitations($index, $aZones, $aCaps) { _setLimitations('Zone', $index, $aZones, $aCaps); } function MAX_Delivery_log_setLastAction($index, $aAdIds, $aZoneIds, $aSetLastSeen, $action = 'view') { $aConf = $GLOBALS['_MAX']['CONF']; if (!empty($aSetLastSeen[$index])) { $cookieData = MAX_commonCompressInt(MAX_commonGetTimeNow()) . "-" . $aZoneIds[$index]; $conversionParams = OX_Delivery_Common_hook('addConversionParams', array(&$index, &$aAdIds, &$aZoneIds, &$aSetLastSeen, &$action, &$cookieData)); if (!empty($conversionParams) && is_array($conversionParams)) { foreach ($conversionParams as $params) { if (!empty($params) && is_array($params)) { foreach ($params as $key => $value) { $cookieData .= " {$value}"; } } } } MAX_cookieAdd("_{$aConf['var']['last' . ucfirst($action)]}[{$aAdIds[$index]}]", $cookieData, _getTimeThirtyDaysFromNow()); } } function MAX_Delivery_log_setClickBlocked($index, $aAdIds) { $aConf = $GLOBALS['_MAX']['CONF']; MAX_cookieAdd("_{$aConf['var']['blockLoggingClick']}[{$aAdIds[$index]}]", MAX_commonCompressInt(MAX_commonGetTimeNow()), _getTimeThirtyDaysFromNow()); } function MAX_Delivery_log_isClickBlocked($adId, $aBlockLoggingClick) { if (isset($GLOBALS['conf']['logging']['blockAdClicksWindow']) && $GLOBALS['conf']['logging']['blockAdClicksWindow'] != 0) { if (isset($aBlockLoggingClick[$adId])) { $endBlock = MAX_commonUnCompressInt($aBlockLoggingClick[$adId]) + $GLOBALS['conf']['logging']['blockAdClicksWindow']; if ($endBlock >= MAX_commonGetTimeNow()) { OX_Delivery_logMessage('adID '.$adId.' click is still blocked by block logging window ', 7); return true; } } } return false; } function _setLimitations($type, $index, $aItems, $aCaps) { MAX_Delivery_log_ensureIntegerSet($aCaps['block'], $index); MAX_Delivery_log_ensureIntegerSet($aCaps['capping'], $index); MAX_Delivery_log_ensureIntegerSet($aCaps['session_capping'], $index); MAX_Delivery_cookie_setCapping( $type, $aItems[$index], $aCaps['block'][$index], $aCaps['capping'][$index], $aCaps['session_capping'][$index] ); } function MAX_commonGetDeliveryUrl($file = null) { $conf = $GLOBALS['_MAX']['CONF']; if ($GLOBALS['_MAX']['SSL_REQUEST']) { $url = MAX_commonConstructSecureDeliveryUrl($file); } else { $url = MAX_commonConstructDeliveryUrl($file); } return $url; } function MAX_commonConstructDeliveryUrl($file) { $conf = $GLOBALS['_MAX']['CONF']; return 'http://' . $conf['webpath']['delivery'] . '/' . $file; } function MAX_commonConstructSecureDeliveryUrl($file) { $conf = $GLOBALS['_MAX']['CONF']; if ($conf['openads']['sslPort'] != 443) { $path = preg_replace('#/#', ':' . $conf['openads']['sslPort'] . '/', $conf['webpath']['deliverySSL'], 1); } else { $path = $conf['webpath']['deliverySSL']; } return 'https://' . $path . '/' . $file; } function MAX_commonConstructPartialDeliveryUrl($file, $ssl = false) { $conf = $GLOBALS['_MAX']['CONF']; if ($ssl) { return '//' . $conf['webpath']['deliverySSL'] . '/' . $file; } else { return '//' . $conf['webpath']['delivery'] . '/' . $file; } } function MAX_commonRemoveSpecialChars(&$var) { static $magicQuotes; if (!isset($magicQuotes)) { $magicQuotes = get_magic_quotes_gpc(); } if (isset($var)) { if (!is_array($var)) { if ($magicQuotes) { $var = stripslashes($var); } $var = strip_tags($var); $var = str_replace(array("\n", "\r"), array('', ''), $var); $var = trim($var); } else { array_walk($var, 'MAX_commonRemoveSpecialChars'); } } } function MAX_commonConvertEncoding($content, $toEncoding, $fromEncoding = 'UTF-8', $aExtensions = null) { if (($toEncoding == $fromEncoding) || empty($toEncoding)) { return $content; } if (!isset($aExtensions) || !is_array($aExtensions)) { $aExtensions = array('iconv', 'mbstring', 'xml'); } if (is_array($content)) { foreach ($content as $key => $value) { $content[$key] = MAX_commonConvertEncoding($value, $toEncoding, $fromEncoding, $aExtensions); } return $content; } else { $toEncoding = strtoupper($toEncoding); $fromEncoding = strtoupper($fromEncoding); $aMap = array(); $aMap['mbstring']['WINDOWS-1255'] = 'ISO-8859-8'; $aMap['xml']['ISO-8859-15'] = 'ISO-8859-1'; $converted = false; foreach ($aExtensions as $extension) { $mappedFromEncoding = isset($aMap[$extension][$fromEncoding]) ? $aMap[$extension][$fromEncoding] : $fromEncoding; $mappedToEncoding = isset($aMap[$extension][$toEncoding]) ? $aMap[$extension][$toEncoding] : $toEncoding; switch ($extension) { case 'iconv': if (function_exists('iconv')) { $converted = @iconv($mappedFromEncoding, $mappedToEncoding, $content); } break; case 'mbstring': if (function_exists('mb_convert_encoding')) { $converted = @mb_convert_encoding($content, $mappedToEncoding, $mappedFromEncoding); } break; case 'xml': if (function_exists('utf8_encode')) { if ($mappedToEncoding == 'UTF-8' && $mappedFromEncoding == 'ISO-8859-1') { $converted = utf8_encode($content); } elseif ($mappedToEncoding == 'ISO-8859-1' && $mappedFromEncoding == 'UTF-8') { $converted = utf8_decode($content); } } break; } } return $converted ? $converted : $content; } } function MAX_commonSendContentTypeHeader($type = 'text/html', $charset = null) { $header = 'Content-type: ' . $type; if (!empty($charset) && preg_match('/^[a-zA-Z0-9_-]+$/D', $charset)) { $header .= '; charset=' . $charset; } MAX_header($header); } function MAX_commonSetNoCacheHeaders() { MAX_header('Pragma: no-cache'); MAX_header('Cache-Control: private, max-age=0, no-cache'); MAX_header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); } function MAX_commonAddslashesRecursive($a) { if (is_array($a)) { reset($a); while (list($k,$v) = each($a)) { $a[$k] = MAX_commonAddslashesRecursive($v); } reset ($a); return ($a); } else { return is_null($a) ? null : addslashes($a); } } function MAX_commonRegisterGlobalsArray($args = array()) { static $magic_quotes_gpc; if (!isset($magic_quotes_gpc)) { $magic_quotes_gpc = ini_get('magic_quotes_gpc'); } $found = false; foreach($args as $key) { if (isset($_GET[$key])) { $value = $_GET[$key]; $found = true; } if (isset($_POST[$key])) { $value = $_POST[$key]; $found = true; } if ($found) { if (!$magic_quotes_gpc) { if (!is_array($value)) { $value = addslashes($value); } else { $value = MAX_commonAddslashesRecursive($value); } } $GLOBALS[$key] = $value; $found = false; } } } function MAX_commonDeriveSource($source) { return MAX_commonEncrypt(trim(urldecode($source))); } function MAX_commonEncrypt($string) { $convert = ''; if (isset($string) && substr($string,1,4) != 'obfs' && $GLOBALS['_MAX']['CONF']['delivery']['obfuscate']) { $strLen = strlen($string); for ($i=0; $i < $strLen; $i++) { $dec = ord(substr($string,$i,1)); if (strlen($dec) == 2) { $dec = 0 . $dec; } $dec = 324 - $dec; $convert .= $dec; } $convert = '{obfs:' . $convert . '}'; return ($convert); } else { return $string; } } function MAX_commonDecrypt($string) { $conf = $GLOBALS['_MAX']['CONF']; $convert = ''; if (isset($string) && substr($string,1,4) == 'obfs' && $conf['delivery']['obfuscate']) { $strLen = strlen($string); for ($i=6; $i < $strLen-1; $i = $i+3) { $dec = substr($string,$i,3); $dec = 324 - $dec; $dec = chr($dec); $convert .= $dec; } return ($convert); } else { return($string); } } function MAX_commonInitVariables() { MAX_commonRegisterGlobalsArray(array('context', 'source', 'target', 'withText', 'withtext', 'ct0', 'what', 'loc', 'referer', 'zoneid', 'campaignid', 'bannerid', 'clientid', 'charset')); global $context, $source, $target, $withText, $withtext, $ct0, $what, $loc, $referer, $zoneid, $campaignid, $bannerid, $clientid, $charset; if (isset($withText) && !isset($withtext)) $withtext = $withText; $withtext = (isset($withtext) && is_numeric($withtext) ? $withtext : 0 ); $ct0 = (isset($ct0) ? $ct0 : '' ); $context = (isset($context) ? $context : array() ); $target = (isset($target) && (!empty($target)) && (!strpos($target , chr(32))) ? $target : '' ); $charset = (isset($charset) && (!empty($charset)) && (!strpos($charset, chr(32))) ? $charset : 'UTF-8' ); $bannerid = (isset($bannerid) && is_numeric($bannerid) ? $bannerid : '' ); $campaignid = (isset($campaignid) && is_numeric($campaignid) ? $campaignid : '' ); $clientid = (isset($clientid) && is_numeric($clientid) ? $clientid : '' ); $zoneid = (isset($zoneid) && is_numeric($zoneid) ? $zoneid : '' ); if (!isset($what)) { if (!empty($bannerid)) { $what = 'bannerid:'.$bannerid; } elseif (!empty($campaignid)) { $what = 'campaignid:'.$campaignid; } elseif (!empty($zoneid)) { $what = 'zone:'.$zoneid; } else { $what = ''; } } elseif (preg_match('/^([a-z]+):(\d+)$/', $what, $matches)) { switch ($matches[1]) { case 'zoneid': case 'zone': $zoneid = $matches[2]; break; case 'bannerid': $bannerid = $matches[2]; break; case 'campaignid': $campaignid = $matches[2]; break; case 'clientid': $clientid = $matches[2]; break; } } if (!isset($clientid)) $clientid = ''; if (empty($campaignid)) $campaignid = $clientid; $source = MAX_commonDeriveSource($source); if (!empty($loc)) { $loc = stripslashes($loc); } elseif (!empty($_SERVER['HTTP_REFERER'])) { $loc = $_SERVER['HTTP_REFERER']; } else { $loc = ''; } if (!empty($referer)) { $_SERVER['HTTP_REFERER'] = stripslashes($referer); } else { if (isset($_SERVER['HTTP_REFERER'])) unset($_SERVER['HTTP_REFERER']); } $GLOBALS['_MAX']['COOKIE']['LIMITATIONS']['arrCappingCookieNames'] = array( $GLOBALS['_MAX']['CONF']['var']['blockAd'], $GLOBALS['_MAX']['CONF']['var']['capAd'], $GLOBALS['_MAX']['CONF']['var']['sessionCapAd'], $GLOBALS['_MAX']['CONF']['var']['blockCampaign'], $GLOBALS['_MAX']['CONF']['var']['capCampaign'], $GLOBALS['_MAX']['CONF']['var']['sessionCapCampaign'], $GLOBALS['_MAX']['CONF']['var']['blockZone'], $GLOBALS['_MAX']['CONF']['var']['capZone'], $GLOBALS['_MAX']['CONF']['var']['sessionCapZone'], $GLOBALS['_MAX']['CONF']['var']['lastClick'], $GLOBALS['_MAX']['CONF']['var']['lastView'], $GLOBALS['_MAX']['CONF']['var']['blockLoggingClick'], ); if (strtolower($charset) == 'unicode') { $charset = 'utf-8'; } } function MAX_commonDisplay1x1() { MAX_header('Content-Type: image/gif'); MAX_header('Content-Length: 43'); echo base64_decode('R0lGODlhAQABAIAAAP///wAAACH5BAAAAAAALAAAAAABAAEAAAICRAEAOw=='); } function MAX_commonGetTimeNow() { if (!isset($GLOBALS['_MAX']['NOW'])) { $GLOBALS['_MAX']['NOW'] = time(); } return $GLOBALS['_MAX']['NOW']; } function MAX_getRandomNumber($length = 10) { return substr(md5(uniqid(time(), true)), 0, $length); } function MAX_header($value) { header($value); } function MAX_redirect($url) { if (!preg_match('/^(?:javascript|data):/i', $url)) { header('Location: '.$url); MAX_sendStatusCode(302); } } function MAX_sendStatusCode($iStatusCode) { $aConf = $GLOBALS['_MAX']['CONF']; $arr = array( 100 => 'Continue', 101 => 'Switching Protocols', 200 => 'OK', 201 => 'Created', 202 => 'Accepted', 203 => 'Non-Authoritative Information', 204 => 'No Content', 205 => 'Reset Content', 206 => 'Partial Content', 300 => 'Multiple Choices', 301 => 'Moved Permanently', 302 => 'Found', 303 => 'See Other', 304 => 'Not Modified', 305 => 'Use Proxy', 306 => '[Unused]', 307 => 'Temporary Redirect', 400 => 'Bad Request', 401 => 'Unauthorized', 402 => 'Payment Required', 403 => 'Forbidden', 404 => 'Not Found', 405 => 'Method Not Allowed', 406 => 'Not Acceptable', 407 => 'Proxy Authentication Required', 408 => 'Request Timeout', 409 => 'Conflict', 410 => 'Gone', 411 => 'Length Required', 412 => 'Precondition Failed', 413 => 'Request Entity Too Large', 414 => 'Request-URI Too Long', 415 => 'Unsupported Media Type', 416 => 'Requested Range Not Satisfiable', 417 => 'Expectation Failed', 500 => 'Internal Server Error', 501 => 'Not Implemented', 502 => 'Bad Gateway', 503 => 'Service Unavailable', 504 => 'Gateway Timeout', 505 => 'HTTP Version Not Supported' ); if (isset($arr[$iStatusCode])) { $text = $iStatusCode . ' ' . $arr[$iStatusCode]; if (!empty($aConf['delivery']['cgiForceStatusHeader']) && strpos(php_sapi_name(), 'cgi') !== 0) { MAX_header('Status: ' . $text); } else { MAX_header($_SERVER["SERVER_PROTOCOL"] .' ' . $text); } } } function MAX_commonPackContext($context = array()) { $include = array(); $exclude = array(); foreach ($context as $idx => $value) { reset($value); list($key, $value) = each($value); list($item,$id) = explode(':', $value); switch ($item) { case 'campaignid': $value = 'c:' . $id; break; case 'clientid': $value = 'a:' . $id; break; case 'bannerid': $value = 'b:' . $id; break; case 'companionid': $value = 'p:' . $id; break; } switch ($key) { case '!=': $exclude[$value] = true; break; case '==': $include[$value] = true; break; } } $exclude = array_keys($exclude); $include = array_keys($include); return base64_encode(implode('#', $exclude) . '|' . implode('#', $include)); } function MAX_commonUnpackContext($context = '') { list($exclude,$include) = explode('|', base64_decode($context)); return array_merge(_convertContextArray('!=', explode('#', $exclude)), _convertContextArray('==', explode('#', $include))); } function MAX_commonCompressInt($int) { return base_convert($int, 10, 36); } function MAX_commonUnCompressInt($string) { return base_convert($string, 36, 10); } function _convertContextArray($key, $array) { $unpacked = array(); foreach ($array as $value) { if (empty($value)) { continue; } list($item, $id) = explode(':', $value); switch ($item) { case 'c': $unpacked[] = array($key => 'campaignid:' . $id); break; case 'a': $unpacked[] = array($key => 'clientid:' . $id); break; case 'b': $unpacked[] = array($key => 'bannerid:' . $id); break; case 'p': $unpacked[] = array($key => 'companionid:'.$id); break; } } return $unpacked; } function OX_Delivery_Common_hook($hookName, $aParams = array(), $functionName = '') { $return = null; if (!empty($functionName)) { $aParts = explode(':', $functionName); if (count($aParts) === 3) { $functionName = OX_Delivery_Common_getFunctionFromComponentIdentifier($functionName, $hookName); } if (function_exists($functionName)) { $return = call_user_func_array($functionName, $aParams); } } else { if (!empty($GLOBALS['_MAX']['CONF']['deliveryHooks'][$hookName])) { $return = array(); $hooks = explode('|', $GLOBALS['_MAX']['CONF']['deliveryHooks'][$hookName]); foreach ($hooks as $identifier) { $functionName = OX_Delivery_Common_getFunctionFromComponentIdentifier($identifier, $hookName); if (function_exists($functionName)) { OX_Delivery_logMessage('calling on '.$functionName, 7); $return[$identifier] = call_user_func_array($functionName, $aParams); } } } } return $return; } function OX_Delivery_Common_getFunctionFromComponentIdentifier($identifier, $hook = null) { $aInfo = explode(':', $identifier); $functionName = 'Plugin_' . implode('_', $aInfo) . '_Delivery' . (!empty($hook) ? '_' . $hook : ''); if (!function_exists($functionName)) { if (!empty($GLOBALS['_MAX']['CONF']['pluginSettings']['useMergedFunctions'])) _includeDeliveryPluginFile('/var/cache/' . OX_getHostName() . '_mergedDeliveryFunctions.php'); if (!function_exists($functionName)) { _includeDeliveryPluginFile($GLOBALS['_MAX']['CONF']['pluginPaths']['plugins'] . '/' . implode('/', $aInfo) . '.delivery.php'); if (!function_exists($functionName)) { _includeDeliveryPluginFile('/lib/OX/Extension/' . $aInfo[0] . '/' . $aInfo[0] . 'Delivery.php'); $functionName = 'Plugin_' . $aInfo[0] . '_delivery'; if (!empty($hook) && function_exists($functionName . '_' . $hook)) { $functionName .= '_' . $hook; } } } } return $functionName; } function _includeDeliveryPluginFile($fileName) { if (!in_array($fileName, array_keys($GLOBALS['_MAX']['FILES']))) { $GLOBALS['_MAX']['FILES'][$fileName] = true; if (file_exists(MAX_PATH . $fileName)) { include MAX_PATH . $fileName; } } } function OX_Delivery_logMessage($message, $priority = 6) { $conf = $GLOBALS['_MAX']['CONF']; if (empty($conf['deliveryLog']['enabled'])) return true; $priorityLevel = is_numeric($conf['deliveryLog']['priority']) ? $conf['deliveryLog']['priority'] : 6; if ($priority > $priorityLevel && empty($_REQUEST[$conf['var']['trace']])) { return true; } error_log('[' . date('r') . "] {$conf['log']['ident']}-delivery-{$GLOBALS['_MAX']['thread_id']}: {$message}\n", 3, MAX_PATH . '/var/' . $conf['deliveryLog']['name']); OX_Delivery_Common_hook('logMessage', array($message, $priority)); return true; } $file = '/lib/max/Delivery/cache.php'; $GLOBALS['_MAX']['FILES'][$file] = true; define ('OA_DELIVERY_CACHE_FUNCTION_ERROR', 'Function call returned an error'); $GLOBALS['OA_Delivery_Cache'] = array( 'prefix' => 'deliverycache_', 'host' => OX_getHostName(), 'expiry' => $GLOBALS['_MAX']['CONF']['delivery']['cacheExpire'] ); function OA_Delivery_Cache_fetch($name, $isHash = false, $expiryTime = null) { $filename = OA_Delivery_Cache_buildFileName($name, $isHash); $aCacheVar = OX_Delivery_Common_hook( 'cacheRetrieve', array($filename), $GLOBALS['_MAX']['CONF']['delivery']['cacheStorePlugin'] ); if ($aCacheVar !== false) { if ($aCacheVar['cache_name'] != $name) { OX_Delivery_logMessage("Cache ERROR: {$name} != {$aCacheVar['cache_name']}", 7); return false; } if ($expiryTime === null) { $expiryTime = $GLOBALS['OA_Delivery_Cache']['expiry']; } $now = MAX_commonGetTimeNow(); if ( (isset($aCacheVar['cache_time']) && $aCacheVar['cache_time'] + $expiryTime < $now) || (isset($aCacheVar['cache_expire']) && $aCacheVar['cache_expire'] < $now) ) { OA_Delivery_Cache_store($name, $aCacheVar['cache_contents'], $isHash); OX_Delivery_logMessage("Cache EXPIRED: {$name}", 7); return false; } OX_Delivery_logMessage("Cache HIT: {$name}", 7); return $aCacheVar['cache_contents']; } OX_Delivery_logMessage("Cache MISS {$name}", 7); return false; } function OA_Delivery_Cache_store($name, $cache, $isHash = false, $expireAt = null) { if ($cache === OA_DELIVERY_CACHE_FUNCTION_ERROR) { return false; } $filename = OA_Delivery_Cache_buildFileName($name, $isHash); $aCacheVar = array(); $aCacheVar['cache_contents'] = $cache; $aCacheVar['cache_name'] = $name; $aCacheVar['cache_time'] = MAX_commonGetTimeNow(); $aCacheVar['cache_expire'] = $expireAt; return OX_Delivery_Common_hook( 'cacheStore', array($filename, $aCacheVar), $GLOBALS['_MAX']['CONF']['delivery']['cacheStorePlugin'] ); } function OA_Delivery_Cache_store_return($name, $cache, $isHash = false, $expireAt = null) { OX_Delivery_Common_hook( 'preCacheStore_'.OA_Delivery_Cache_getHookName($name), array($name, &$cache) ); if (OA_Delivery_Cache_store($name, $cache, $isHash, $expireAt)) { return $cache; } $currentCache = OA_Delivery_Cache_fetch($name, $isHash); if ($currentCache === false) { return $cache; } return $currentCache; } function OA_Delivery_Cache_getHookName($name) { $pos = strpos($name, '^'); return $pos ? substr($name, 0, $pos) : substr($name, 0, strpos($name, '@')); } function OA_Delivery_Cache_buildFileName($name, $isHash = false) { if(!$isHash) { $name = md5($name); } return $GLOBALS['OA_Delivery_Cache']['prefix'].$name.'.php'; } function OA_Delivery_Cache_getName($functionName) { $args = func_get_args(); $args[0] = strtolower(str_replace('MAX_cacheGet', '', $args[0])); return join('^', $args).'@'.$GLOBALS['OA_Delivery_Cache']['host']; } function MAX_cacheGetAd($ad_id, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $ad_id); if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aRows = OA_Dal_Delivery_getAd($ad_id); $aRows = OA_Delivery_Cache_store_return($sName, $aRows); } return $aRows; } function MAX_cacheGetAccountTZs($cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__); if (!$cached || ($aResult = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aResult = OA_Dal_Delivery_getAccountTZs(); $aResult = OA_Delivery_Cache_store_return($sName, $aResult); } return $aResult; } function MAX_cacheGetZoneLinkedAds($zoneId, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId); if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aRows = OA_Dal_Delivery_getZoneLinkedAds($zoneId); $aRows = OA_Delivery_Cache_store_return($sName, $aRows); } return $aRows; } function MAX_cacheGetZoneLinkedAdInfos($zoneId, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId); if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aRows = OA_Dal_Delivery_getZoneLinkedAdInfos($zoneId); $aRows = OA_Delivery_Cache_store_return($sName, $aRows); } return $aRows; } function MAX_cacheGetZoneInfo($zoneId, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $zoneId); if (!$cached || ($aRows = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aRows = OA_Dal_Delivery_getZoneInfo($zoneId); $aRows = OA_Delivery_Cache_store_return($sName, $aRows); } return $aRows; } function MAX_cacheGetLinkedAds($search, $campaignid, $laspart, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $search, $campaignid, $laspart); if (!$cached || ($aAds = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aAds = OA_Dal_Delivery_getLinkedAds($search, $campaignid, $laspart); $aAds = OA_Delivery_Cache_store_return($sName, $aAds); } return $aAds; } function MAX_cacheGetLinkedAdInfos($search, $campaignid, $laspart, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $search, $campaignid, $laspart); if (!$cached || ($aAds = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aAds = OA_Dal_Delivery_getLinkedAdInfos($search, $campaignid, $laspart); $aAds = OA_Delivery_Cache_store_return($sName, $aAds); } return $aAds; } function MAX_cacheGetCreative($filename, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $filename); if (!$cached || ($aCreative = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aCreative = OA_Dal_Delivery_getCreative($filename); $aCreative['contents'] = addslashes(serialize($aCreative['contents'])); $aCreative = OA_Delivery_Cache_store_return($sName, $aCreative); } $aCreative['contents'] = unserialize(stripslashes($aCreative['contents'])); return $aCreative; } function MAX_cacheGetTracker($trackerid, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid); if (!$cached || ($aTracker = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aTracker = OA_Dal_Delivery_getTracker($trackerid); $aTracker = OA_Delivery_Cache_store_return($sName, $aTracker); } return $aTracker; } function MAX_cacheGetTrackerLinkedCreatives($trackerid = null, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid); if (!$cached || ($aTracker = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aTracker = OA_Dal_Delivery_getTrackerLinkedCreatives($trackerid); $aTracker = OA_Delivery_Cache_store_return($sName, $aTracker); } return $aTracker; } function MAX_cacheGetTrackerVariables($trackerid, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $trackerid); if (!$cached || ($aVariables = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $aVariables = OA_Dal_Delivery_getTrackerVariables($trackerid); $aVariables = OA_Delivery_Cache_store_return($sName, $aVariables); } return $aVariables; } function MAX_cacheCheckIfMaintenanceShouldRun($cached = true) { $interval = $GLOBALS['_MAX']['CONF']['maintenance']['operationInterval'] * 60; $delay = intval(($GLOBALS['_MAX']['CONF']['maintenance']['operationInterval'] / 12) * 60); $now = MAX_commonGetTimeNow(); $today = strtotime(date('Y-m-d'), $now); $nextRunTime = $today + (floor(($now - $today) / $interval) + 1) * $interval + $delay; if ($nextRunTime - $now > $interval) { $nextRunTime -= $interval; } $cName = OA_Delivery_Cache_getName(__FUNCTION__); if (!$cached || ($lastRunTime = OA_Delivery_Cache_fetch($cName)) === false) { MAX_Dal_Delivery_Include(); $lastRunTime = OA_Dal_Delivery_getMaintenanceInfo(); if ($lastRunTime >= $nextRunTime - $delay) { $nextRunTime += $interval; } OA_Delivery_Cache_store($cName, $lastRunTime, false, $nextRunTime); } return $lastRunTime < $nextRunTime - $interval; } function MAX_cacheGetChannelLimitations($channelid, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $channelid); if (!$cached || ($limitations = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $limitations = OA_Dal_Delivery_getChannelLimitations($channelid); $limitations = OA_Delivery_Cache_store_return($sName, $limitations); } return $limitations; } function MAX_cacheGetGoogleJavaScript($cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__); if (!$cached || ($output = OA_Delivery_Cache_fetch($sName)) === false) { $file = '/lib/max/Delivery/google.php'; if(!isset($GLOBALS['_MAX']['FILES'][$file])) { include MAX_PATH . $file; } $output = MAX_googleGetJavaScript(); $output = OA_Delivery_Cache_store_return($sName, $output); } return $output; } function OA_cacheGetPublisherZones($affiliateid, $cached = true) { $sName = OA_Delivery_Cache_getName(__FUNCTION__, $affiliateid); if (!$cached || ($output = OA_Delivery_Cache_fetch($sName)) === false) { MAX_Dal_Delivery_Include(); $output = OA_Dal_Delivery_getPublisherZones($affiliateid); $output = OA_Delivery_Cache_store_return($sName, $output); } return $output; } OX_Delivery_logMessage('starting delivery script: ' . basename($_SERVER['REQUEST_URI']), 7); if (!empty($_REQUEST[$conf['var']['trace']])) { OX_Delivery_logMessage('trace enabled: ' . $_REQUEST[$conf['var']['trace']], 7); } MAX_remotehostSetInfo(); MAX_commonInitVariables(); MAX_cookieLoad(); MAX_cookieUnpackCapping(); if (empty($GLOBALS['_OA']['invocationType']) || $GLOBALS['_OA']['invocationType'] != 'xmlrpc') { OX_Delivery_Common_hook('postInit'); } function MAX_querystringConvertParams() { $conf = $GLOBALS['_MAX']['CONF']; $qs = $_SERVER['QUERY_STRING']; $dest = false; $destStr = $conf['var']['dest'] . '='; $pos = strpos($qs, $destStr); if ($pos === false) { $destStr = 'dest='; $pos = strpos($qs, $destStr); } if ($pos !== false) { $dest = urldecode(substr($qs, $pos + strlen($destStr))); $qs = substr($qs, 0, $pos); } $aGet = array(); $paramStr = $conf['var']['params'] . '='; $paramPos = strpos($qs, $paramStr); if (is_numeric($paramPos)) { $qs = urldecode(substr($qs, $paramPos + strlen($paramStr))); $delim = $qs{0}; if (is_numeric($delim)) { $delim = substr($qs, 1, $delim); } $qs = substr($qs, strlen($delim) + 1); MAX_querystringParseStr($qs, $aGet, $delim); $qPos = isset($aGet[$conf['var']['dest']]) ? strpos($aGet[$conf['var']['dest']], '?') : false; $aPos = isset($aGet[$conf['var']['dest']]) ? strpos($aGet[$conf['var']['dest']], '&') : false; if ($aPos && !$qPos) { $desturl = substr($aGet[$conf['var']['dest']], 0, $aPos); $destparams = substr($aGet[$conf['var']['dest']], $aPos+1); $aGet[$conf['var']['dest']] = $desturl . '?' . $destparams; } } else { parse_str($qs, $aGet); } if ($dest !== false) { $aGet[$conf['var']['dest']] = $dest; } $n = isset($_GET[$conf['var']['n']]) ? $_GET[$conf['var']['n']] : ''; if (empty($n)) { $n = isset($aGet[$conf['var']['n']]) ? $aGet[$conf['var']['n']] : ''; } if (!empty($n) && !empty($_COOKIE[$conf['var']['vars']][$n])) { $aVars = unserialize(stripslashes($_COOKIE[$conf['var']['vars']][$n])); foreach ($aVars as $name => $value) { if (!isset($_GET[$name])) { $aGet[$name] = $value; } } } $_GET = $aGet; $_REQUEST = $_GET + $_POST + $_COOKIE; } function MAX_querystringGetDestinationUrl($adId = null) { $conf = $GLOBALS['_MAX']['CONF']; $dest = isset($_REQUEST[$conf['var']['dest']]) ? $_REQUEST[$conf['var']['dest']] : ''; if (empty($dest) && !empty($adId)) { $aAd = MAX_cacheGetAd($adId); if (!empty($aAd)) { $dest = $aAd['url']; } } if (empty($dest)) { return; } $aVariables = array(); $aValidVariables = array_values($conf['var']); $componentParams = OX_Delivery_Common_hook('addUrlParams', array(array('bannerid' => $adId))); if (!empty($componentParams) && is_array($componentParams)) { foreach ($componentParams as $params) { if (!empty($params) && is_array($params)) { foreach ($params as $key => $value) { $aValidVariables[] = $key; } } } } $destParams = parse_url($dest); if (!empty($destParams['query'])) { $destQuery = explode('&', $destParams['query']); if (!empty($destQuery)) { foreach ($destQuery as $destPair) { list($destName, $destValue) = explode('=', $destPair); $aValidVariables[] = $destName; } } } foreach ($_GET as $name => $value) { if (!in_array($name, $aValidVariables)) { $aVariables[] = $name . '=' . $value; } } foreach ($_POST as $name => $value) { if (!in_array($name, $aValidVariables)) { $aVariables[] = $name . '=' . $value; } } if (!empty($aVariables)) { $dest .= ((strpos($dest, '?') > 0) ? '&' : '?') . implode('&', $aVariables); } return $dest; } function MAX_querystringParseStr($qs, &$aArr, $delim = '&') { $aArr = $_GET; $aElements = explode($delim, $qs); foreach($aElements as $element) { $len = strpos($element, '='); if ($len !== false) { $name = substr($element, 0, $len); $value = substr($element, $len+1); $aArr[$name] = urldecode($value); } } } MAX_commonSetNoCacheHeaders(); MAX_commonRemoveSpecialChars($_REQUEST); $viewerId = MAX_cookieGetUniqueViewerId(); MAX_cookieAdd($conf['var']['viewerId'], $viewerId, _getTimeYearFromNow()); $aAdIds = MAX_Delivery_log_getArrGetVariable('adId'); $aCampaignIds = MAX_Delivery_log_getArrGetVariable('campaignId'); $aCreativeIds = MAX_Delivery_log_getArrGetVariable('creativeId'); $aZoneIds = MAX_Delivery_log_getArrGetVariable('zoneId'); $aCapAd['block'] = MAX_Delivery_log_getArrGetVariable('blockAd'); $aCapAd['capping'] = MAX_Delivery_log_getArrGetVariable('capAd'); $aCapAd['session_capping'] = MAX_Delivery_log_getArrGetVariable('sessionCapAd'); $aCapCampaign['block'] = MAX_Delivery_log_getArrGetVariable('blockCampaign'); $aCapCampaign['capping'] = MAX_Delivery_log_getArrGetVariable('capCampaign'); $aCapCampaign['session_capping'] = MAX_Delivery_log_getArrGetVariable('sessionCapCampaign'); $aCapZone['block'] = MAX_Delivery_log_getArrGetVariable('blockZone'); $aCapZone['capping'] = MAX_Delivery_log_getArrGetVariable('capZone'); $aCapZone['session_capping'] = MAX_Delivery_log_getArrGetVariable('sessionCapZone'); $aSetLastSeen = MAX_Delivery_log_getArrGetVariable('lastView'); $countAdIds = count($aAdIds); for ($index = 0; $index < $countAdIds; $index++) { MAX_Delivery_log_ensureIntegerSet($aAdIds, $index); MAX_Delivery_log_ensureIntegerSet($aCampaignIds, $index); MAX_Delivery_log_ensureIntegerSet($aCreativeIds, $index); MAX_Delivery_log_ensureIntegerSet($aZoneIds, $index); if ($aAdIds[$index] >= -1) { $adId = $aAdIds[$index]; if ($GLOBALS['_MAX']['CONF']['logging']['adImpressions']) { MAX_Delivery_log_logAdImpression($adId, $aZoneIds[$index]); } if ($aAdIds[$index] == $adId) { MAX_Delivery_log_setAdLimitations($index, $aAdIds, $aCapAd); MAX_Delivery_log_setCampaignLimitations($index, $aCampaignIds, $aCapCampaign); MAX_Delivery_log_setLastAction($index, $aAdIds, $aZoneIds, $aSetLastSeen); if ($aZoneIds[$index] != 0) { MAX_Delivery_log_setZoneLimitations($index, $aZoneIds, $aCapZone); } } } } MAX_cookieFlush(); MAX_querystringConvertParams(); if (!empty($_REQUEST[$GLOBALS['_MAX']['CONF']['var']['dest']])) { MAX_redirect($_REQUEST[$GLOBALS['_MAX']['CONF']['var']['dest']]); } else { MAX_commonDisplay1x1(); } if (!empty($GLOBALS['_MAX']['CONF']['maintenance']['autoMaintenance']) && empty($GLOBALS['_MAX']['CONF']['lb']['enabled'])) { if (MAX_cacheCheckIfMaintenanceShouldRun()) { include MAX_PATH . '/lib/OA/Maintenance/Auto.php'; OA_Maintenance_Auto::run(); } } ?>
kriwil/OpenX
www/delivery/lg.php
PHP
gpl-2.0
107,769
/* smpppdunsettled.cpp Copyright (c) 2006 by Heiko Schaefer <heiko@rangun.de> Kopete (c) 2002-2006 by the Kopete developers <kopete-devel@kde.org> ************************************************************************* * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; version 2 of the License. * * * ************************************************************************* */ #include <cstdlib> #include <openssl/md5.h> #include <qregexp.h> #include <kdebug.h> #include <kstreamsocket.h> #include "smpppdready.h" #include "smpppdunsettled.h" using namespace SMPPPD; Unsettled * Unsettled::m_instance = NULL; Unsettled::Unsettled() {} Unsettled::~Unsettled() {} Unsettled * Unsettled::instance() { if(!m_instance) { m_instance = new Unsettled(); } return m_instance; } bool Unsettled::connect(Client * client, const QString& server, uint port) { if(!socket(client) || socket(client)->state() != KNetwork::KStreamSocket::Connected || socket(client)->state() != KNetwork::KStreamSocket::Connecting) { QString resolvedServer = server; changeState(client, Ready::instance()); disconnect(client); // since a lookup on a non-existant host can take a lot of time we // try to get the IP of server before and we do the lookup ourself KNetwork::KResolver resolver(server); resolver.start(); if(resolver.wait(500)) { KNetwork::KResolverResults results = resolver.results(); if(!results.empty()) { QString ip = results[0].address().asInet().ipAddress().toString(); kdDebug(14312) << k_funcinfo << "Found IP-Address for " << server << ": " << ip << endl; resolvedServer = ip; } else { kdWarning(14312) << k_funcinfo << "No IP-Address found for " << server << endl; return false; } } else { kdWarning(14312) << k_funcinfo << "Looking up hostname timed out, consider to use IP or correct host" << endl; return false; } setSocket(client, new KNetwork::KStreamSocket(resolvedServer, QString::number(port))); socket(client)->setBlocking(TRUE); if(!socket(client)->connect()) { kdDebug(14312) << k_funcinfo << "Socket Error: " << KNetwork::KStreamSocket::errorString(socket(client)->error()) << endl; } else { kdDebug(14312) << k_funcinfo << "Successfully connected to smpppd \"" << server << ":" << port << "\"" << endl; static QString verRex = "^SuSE Meta pppd \\(smpppd\\), Version (.*)$"; static QString clgRex = "^challenge = (.*)$"; QRegExp ver(verRex); QRegExp clg(clgRex); QString response = read(client)[0]; if(response != QString::null && ver.exactMatch(response)) { setServerID(client, response); setServerVersion(client, ver.cap(1)); changeState(client, Ready::instance()); return true; } else if(response != QString::null && clg.exactMatch(response)) { if(password(client) != QString::null) { // we are challenged, ok, respond write(client, QString("response = %1\n").arg(make_response(clg.cap(1).stripWhiteSpace(), password(client))).latin1()); response = read(client)[0]; if(ver.exactMatch(response)) { setServerID(client, response); setServerVersion(client, ver.cap(1)); return true; } else { kdWarning(14312) << k_funcinfo << "SMPPPD responded: " << response << endl; changeState(client, Ready::instance()); disconnect(client); } } else { kdWarning(14312) << k_funcinfo << "SMPPPD requested a challenge, but no password was supplied!" << endl; changeState(client, Ready::instance()); disconnect(client); } } } } return false; } QString Unsettled::make_response(const QString& chex, const QString& password) const { int size = chex.length (); if (size & 1) return "error"; size >>= 1; // convert challenge from hex to bin QString cbin; for (int i = 0; i < size; i++) { QString tmp = chex.mid (2 * i, 2); cbin.append ((char) strtol (tmp.ascii (), 0, 16)); } // calculate response unsigned char rbin[MD5_DIGEST_LENGTH]; MD5state_st md5; MD5_Init (&md5); MD5_Update (&md5, cbin.ascii (), size); MD5_Update (&md5, password.ascii(), password.length ()); MD5_Final (rbin, &md5); // convert response from bin to hex QString rhex; for (int i = 0; i < MD5_DIGEST_LENGTH; i++) { char buffer[3]; snprintf (buffer, 3, "%02x", rbin[i]); rhex.append (buffer); } return rhex; }
iegor/kdenetwork
kopete/plugins/smpppdcs/libsmpppdclient/smpppdunsettled.cpp
C++
gpl-2.0
5,200
/* Copyright_License { XCSoar Glide Computer - http://www.xcsoar.org/ Copyright (C) 2000-2011 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 "Navigation/GeoPoint.hpp" #include "Navigation/Geometry/GeoVector.hpp" #include "Math/Earth.hpp" GeoPoint GeoPoint::parametric(const GeoPoint &delta, const fixed t) const { return (*this) + delta * t; } GeoPoint GeoPoint::interpolate(const GeoPoint &end, const fixed t) const { return (*this) + (end - (*this)) * t; } fixed GeoPoint::distance(const GeoPoint &other) const { return ::Distance(*this, other); } Angle GeoPoint::bearing(const GeoPoint &other) const { return ::Bearing(*this, other); } GeoVector GeoPoint::distance_bearing(const GeoPoint &other) const { GeoVector gv; ::DistanceBearing(*this, other, &gv.Distance, &gv.Bearing); return gv; } fixed GeoPoint::projected_distance(const GeoPoint &from, const GeoPoint &to) const { return ::ProjectedDistance(from, to, *this); } bool GeoPoint::equals(const GeoPoint &other) const { return (Longitude == other.Longitude) && (Latitude == other.Latitude); } bool GeoPoint::sort(const GeoPoint &sp) const { if (Longitude < sp.Longitude) return false; else if (Longitude == sp.Longitude) return Latitude > sp.Latitude; else return true; } GeoPoint GeoPoint::intermediate_point(const GeoPoint &destination, const fixed distance) const { return ::IntermediatePoint(*this, destination, distance); }
joachimwieland/xcsoar-jwieland
src/Engine/Navigation/GeoPoint.cpp
C++
gpl-2.0
2,269
package net.minecraft.world.gen.structure; import java.util.Arrays; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Random; import java.util.Map.Entry; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.util.MathHelper; import net.minecraft.world.World; import net.minecraft.world.biome.BiomeGenBase; public class MapGenVillage extends MapGenStructure { /** A list of all the biomes villages can spawn in. */ public static final List villageSpawnBiomes = Arrays.asList(new BiomeGenBase[] {BiomeGenBase.plains, BiomeGenBase.desert, BiomeGenBase.field_150588_X}); /** World terrain type, 0 for normal, 1 for flat map */ private int terrainType; private int field_82665_g; private int field_82666_h; private static final String __OBFID = "CL_00000514"; public MapGenVillage() { this.field_82665_g = 32; this.field_82666_h = 8; } public MapGenVillage(Map p_i2093_1_) { this(); Iterator var2 = p_i2093_1_.entrySet().iterator(); while (var2.hasNext()) { Entry var3 = (Entry)var2.next(); if (((String)var3.getKey()).equals("size")) { this.terrainType = MathHelper.parseIntWithDefaultAndMax((String)var3.getValue(), this.terrainType, 0); } else if (((String)var3.getKey()).equals("distance")) { this.field_82665_g = MathHelper.parseIntWithDefaultAndMax((String)var3.getValue(), this.field_82665_g, this.field_82666_h + 1); } } } public String func_143025_a() { return "Village"; } protected boolean canSpawnStructureAtCoords(int p_75047_1_, int p_75047_2_) { int var3 = p_75047_1_; int var4 = p_75047_2_; if (p_75047_1_ < 0) { p_75047_1_ -= this.field_82665_g - 1; } if (p_75047_2_ < 0) { p_75047_2_ -= this.field_82665_g - 1; } int var5 = p_75047_1_ / this.field_82665_g; int var6 = p_75047_2_ / this.field_82665_g; Random var7 = this.worldObj.setRandomSeed(var5, var6, 10387312); var5 *= this.field_82665_g; var6 *= this.field_82665_g; var5 += var7.nextInt(this.field_82665_g - this.field_82666_h); var6 += var7.nextInt(this.field_82665_g - this.field_82666_h); if (var3 == var5 && var4 == var6) { boolean var8 = this.worldObj.getWorldChunkManager().areBiomesViable(var3 * 16 + 8, var4 * 16 + 8, 0, villageSpawnBiomes); if (var8) { return true; } } return false; } protected StructureStart getStructureStart(int p_75049_1_, int p_75049_2_) { return new MapGenVillage.Start(this.worldObj, this.rand, p_75049_1_, p_75049_2_, this.terrainType); } public static class Start extends StructureStart { private boolean hasMoreThanTwoComponents; private static final String __OBFID = "CL_00000515"; public Start() {} public Start(World p_i2092_1_, Random p_i2092_2_, int p_i2092_3_, int p_i2092_4_, int p_i2092_5_) { super(p_i2092_3_, p_i2092_4_); List var6 = StructureVillagePieces.getStructureVillageWeightedPieceList(p_i2092_2_, p_i2092_5_); StructureVillagePieces.Start var7 = new StructureVillagePieces.Start(p_i2092_1_.getWorldChunkManager(), 0, p_i2092_2_, (p_i2092_3_ << 4) + 2, (p_i2092_4_ << 4) + 2, var6, p_i2092_5_); this.components.add(var7); var7.buildComponent(var7, this.components, p_i2092_2_); List var8 = var7.field_74930_j; List var9 = var7.field_74932_i; int var10; while (!var8.isEmpty() || !var9.isEmpty()) { StructureComponent var11; if (var8.isEmpty()) { var10 = p_i2092_2_.nextInt(var9.size()); var11 = (StructureComponent)var9.remove(var10); var11.buildComponent(var7, this.components, p_i2092_2_); } else { var10 = p_i2092_2_.nextInt(var8.size()); var11 = (StructureComponent)var8.remove(var10); var11.buildComponent(var7, this.components, p_i2092_2_); } } this.updateBoundingBox(); var10 = 0; Iterator var13 = this.components.iterator(); while (var13.hasNext()) { StructureComponent var12 = (StructureComponent)var13.next(); if (!(var12 instanceof StructureVillagePieces.Road)) { ++var10; } } this.hasMoreThanTwoComponents = var10 > 2; } public boolean isSizeableStructure() { return this.hasMoreThanTwoComponents; } public void func_143022_a(NBTTagCompound p_143022_1_) { super.func_143022_a(p_143022_1_); p_143022_1_.setBoolean("Valid", this.hasMoreThanTwoComponents); } public void func_143017_b(NBTTagCompound p_143017_1_) { super.func_143017_b(p_143017_1_); this.hasMoreThanTwoComponents = p_143017_1_.getBoolean("Valid"); } } }
mviitanen/marsmod
mcp/src/minecraft_server/net/minecraft/world/gen/structure/MapGenVillage.java
Java
gpl-2.0
5,468
// Copyright 2008 Dolphin Emulator Project // SPDX-License-Identifier: GPL-2.0-or-later #include "VideoCommon/CommandProcessor.h" #include <atomic> #include <cstring> #include <fmt/format.h> #include "Common/Assert.h" #include "Common/ChunkFile.h" #include "Common/CommonTypes.h" #include "Common/Flag.h" #include "Common/Logging/Log.h" #include "Core/ConfigManager.h" #include "Core/CoreTiming.h" #include "Core/HW/GPFifo.h" #include "Core/HW/MMIO.h" #include "Core/HW/ProcessorInterface.h" #include "Core/System.h" #include "VideoCommon/Fifo.h" namespace CommandProcessor { static CoreTiming::EventType* et_UpdateInterrupts; // TODO(ector): Warn on bbox read/write // STATE_TO_SAVE SCPFifoStruct fifo; static UCPStatusReg m_CPStatusReg; static UCPCtrlReg m_CPCtrlReg; static UCPClearReg m_CPClearReg; static u16 m_bboxleft; static u16 m_bboxtop; static u16 m_bboxright; static u16 m_bboxbottom; static u16 m_tokenReg; static Common::Flag s_interrupt_set; static Common::Flag s_interrupt_waiting; static bool s_is_fifo_error_seen = false; static bool IsOnThread() { return Core::System::GetInstance().IsDualCoreMode(); } static void UpdateInterrupts_Wrapper(u64 userdata, s64 cyclesLate) { UpdateInterrupts(userdata); } void SCPFifoStruct::Init() { CPBase = 0; CPEnd = 0; CPHiWatermark = 0; CPLoWatermark = 0; CPReadWriteDistance = 0; CPWritePointer = 0; CPReadPointer = 0; CPBreakpoint = 0; SafeCPReadPointer = 0; bFF_GPLinkEnable = 0; bFF_GPReadEnable = 0; bFF_BPEnable = 0; bFF_BPInt = 0; bFF_Breakpoint.store(0, std::memory_order_relaxed); bFF_HiWatermark.store(0, std::memory_order_relaxed); bFF_HiWatermarkInt.store(0, std::memory_order_relaxed); bFF_LoWatermark.store(0, std::memory_order_relaxed); bFF_LoWatermarkInt.store(0, std::memory_order_relaxed); s_is_fifo_error_seen = false; } void SCPFifoStruct::DoState(PointerWrap& p) { p.Do(CPBase); p.Do(CPEnd); p.Do(CPHiWatermark); p.Do(CPLoWatermark); p.Do(CPReadWriteDistance); p.Do(CPWritePointer); p.Do(CPReadPointer); p.Do(CPBreakpoint); p.Do(SafeCPReadPointer); p.Do(bFF_GPLinkEnable); p.Do(bFF_GPReadEnable); p.Do(bFF_BPEnable); p.Do(bFF_BPInt); p.Do(bFF_Breakpoint); p.Do(bFF_LoWatermarkInt); p.Do(bFF_HiWatermarkInt); p.Do(bFF_LoWatermark); p.Do(bFF_HiWatermark); } void DoState(PointerWrap& p) { p.DoPOD(m_CPStatusReg); p.DoPOD(m_CPCtrlReg); p.DoPOD(m_CPClearReg); p.Do(m_bboxleft); p.Do(m_bboxtop); p.Do(m_bboxright); p.Do(m_bboxbottom); p.Do(m_tokenReg); fifo.DoState(p); p.Do(s_interrupt_set); p.Do(s_interrupt_waiting); } static inline void WriteLow(std::atomic<u32>& reg, u16 lowbits) { reg.store((reg.load(std::memory_order_relaxed) & 0xFFFF0000) | lowbits, std::memory_order_relaxed); } static inline void WriteHigh(std::atomic<u32>& reg, u16 highbits) { reg.store((reg.load(std::memory_order_relaxed) & 0x0000FFFF) | (static_cast<u32>(highbits) << 16), std::memory_order_relaxed); } void Init() { m_CPStatusReg.Hex = 0; m_CPStatusReg.CommandIdle = 1; m_CPStatusReg.ReadIdle = 1; m_CPCtrlReg.Hex = 0; m_CPClearReg.Hex = 0; m_bboxleft = 0; m_bboxtop = 0; m_bboxright = 640; m_bboxbottom = 480; m_tokenReg = 0; fifo.Init(); s_interrupt_set.Clear(); s_interrupt_waiting.Clear(); et_UpdateInterrupts = CoreTiming::RegisterEvent("CPInterrupt", UpdateInterrupts_Wrapper); } u32 GetPhysicalAddressMask() { // Physical addresses in CP seem to ignore some of the upper bits (depending on platform) // This can be observed in CP MMIO registers by setting to 0xffffffff and then reading back. return SConfig::GetInstance().bWii ? 0x1fffffff : 0x03ffffff; } void RegisterMMIO(MMIO::Mapping* mmio, u32 base) { constexpr u16 WMASK_NONE = 0x0000; constexpr u16 WMASK_ALL = 0xffff; constexpr u16 WMASK_LO_ALIGN_32BIT = 0xffe0; const u16 WMASK_HI_RESTRICT = GetPhysicalAddressMask() >> 16; struct { u32 addr; u16* ptr; bool readonly; // FIFO mmio regs in the range [cc000020-cc00003e] have certain bits that always read as 0 // For _LO registers in this range, only bits 0xffe0 can be set // For _HI registers in this range, only bits 0x03ff can be set on GCN and 0x1fff on Wii u16 wmask; } directly_mapped_vars[] = { {FIFO_TOKEN_REGISTER, &m_tokenReg, false, WMASK_ALL}, // Bounding box registers are read only. {FIFO_BOUNDING_BOX_LEFT, &m_bboxleft, true, WMASK_NONE}, {FIFO_BOUNDING_BOX_RIGHT, &m_bboxright, true, WMASK_NONE}, {FIFO_BOUNDING_BOX_TOP, &m_bboxtop, true, WMASK_NONE}, {FIFO_BOUNDING_BOX_BOTTOM, &m_bboxbottom, true, WMASK_NONE}, {FIFO_BASE_LO, MMIO::Utils::LowPart(&fifo.CPBase), false, WMASK_LO_ALIGN_32BIT}, {FIFO_BASE_HI, MMIO::Utils::HighPart(&fifo.CPBase), false, WMASK_HI_RESTRICT}, {FIFO_END_LO, MMIO::Utils::LowPart(&fifo.CPEnd), false, WMASK_LO_ALIGN_32BIT}, {FIFO_END_HI, MMIO::Utils::HighPart(&fifo.CPEnd), false, WMASK_HI_RESTRICT}, {FIFO_HI_WATERMARK_LO, MMIO::Utils::LowPart(&fifo.CPHiWatermark), false, WMASK_LO_ALIGN_32BIT}, {FIFO_HI_WATERMARK_HI, MMIO::Utils::HighPart(&fifo.CPHiWatermark), false, WMASK_HI_RESTRICT}, {FIFO_LO_WATERMARK_LO, MMIO::Utils::LowPart(&fifo.CPLoWatermark), false, WMASK_LO_ALIGN_32BIT}, {FIFO_LO_WATERMARK_HI, MMIO::Utils::HighPart(&fifo.CPLoWatermark), false, WMASK_HI_RESTRICT}, // FIFO_RW_DISTANCE has some complex read code different for // single/dual core. {FIFO_WRITE_POINTER_LO, MMIO::Utils::LowPart(&fifo.CPWritePointer), false, WMASK_LO_ALIGN_32BIT}, {FIFO_WRITE_POINTER_HI, MMIO::Utils::HighPart(&fifo.CPWritePointer), false, WMASK_HI_RESTRICT}, // FIFO_READ_POINTER has different code for single/dual core. }; for (auto& mapped_var : directly_mapped_vars) { mmio->Register(base | mapped_var.addr, MMIO::DirectRead<u16>(mapped_var.ptr), mapped_var.readonly ? MMIO::InvalidWrite<u16>() : MMIO::DirectWrite<u16>(mapped_var.ptr, mapped_var.wmask)); } mmio->Register(base | FIFO_BP_LO, MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.CPBreakpoint)), MMIO::ComplexWrite<u16>([](u32, u16 val) { WriteLow(fifo.CPBreakpoint, val & WMASK_LO_ALIGN_32BIT); })); mmio->Register(base | FIFO_BP_HI, MMIO::DirectRead<u16>(MMIO::Utils::HighPart(&fifo.CPBreakpoint)), MMIO::ComplexWrite<u16>([WMASK_HI_RESTRICT](u32, u16 val) { WriteHigh(fifo.CPBreakpoint, val & WMASK_HI_RESTRICT); })); // Timing and metrics MMIOs are stubbed with fixed values. struct { u32 addr; u16 value; } metrics_mmios[] = { {XF_RASBUSY_L, 0}, {XF_RASBUSY_H, 0}, {XF_CLKS_L, 0}, {XF_CLKS_H, 0}, {XF_WAIT_IN_L, 0}, {XF_WAIT_IN_H, 0}, {XF_WAIT_OUT_L, 0}, {XF_WAIT_OUT_H, 0}, {VCACHE_METRIC_CHECK_L, 0}, {VCACHE_METRIC_CHECK_H, 0}, {VCACHE_METRIC_MISS_L, 0}, {VCACHE_METRIC_MISS_H, 0}, {VCACHE_METRIC_STALL_L, 0}, {VCACHE_METRIC_STALL_H, 0}, {CLKS_PER_VTX_OUT, 4}, }; for (auto& metrics_mmio : metrics_mmios) { mmio->Register(base | metrics_mmio.addr, MMIO::Constant<u16>(metrics_mmio.value), MMIO::InvalidWrite<u16>()); } mmio->Register(base | STATUS_REGISTER, MMIO::ComplexRead<u16>([](u32) { Fifo::SyncGPUForRegisterAccess(); SetCpStatusRegister(); return m_CPStatusReg.Hex; }), MMIO::InvalidWrite<u16>()); mmio->Register(base | CTRL_REGISTER, MMIO::DirectRead<u16>(&m_CPCtrlReg.Hex), MMIO::ComplexWrite<u16>([](u32, u16 val) { UCPCtrlReg tmp(val); m_CPCtrlReg.Hex = tmp.Hex; SetCpControlRegister(); Fifo::RunGpu(); })); mmio->Register(base | CLEAR_REGISTER, MMIO::DirectRead<u16>(&m_CPClearReg.Hex), MMIO::ComplexWrite<u16>([](u32, u16 val) { UCPClearReg tmp(val); m_CPClearReg.Hex = tmp.Hex; SetCpClearRegister(); Fifo::RunGpu(); })); mmio->Register(base | PERF_SELECT, MMIO::InvalidRead<u16>(), MMIO::Nop<u16>()); // Some MMIOs have different handlers for single core vs. dual core mode. mmio->Register( base | FIFO_RW_DISTANCE_LO, IsOnThread() ? MMIO::ComplexRead<u16>([](u32) { if (fifo.CPWritePointer.load(std::memory_order_relaxed) >= fifo.SafeCPReadPointer.load(std::memory_order_relaxed)) { return static_cast<u16>(fifo.CPWritePointer.load(std::memory_order_relaxed) - fifo.SafeCPReadPointer.load(std::memory_order_relaxed)); } else { return static_cast<u16>(fifo.CPEnd.load(std::memory_order_relaxed) - fifo.SafeCPReadPointer.load(std::memory_order_relaxed) + fifo.CPWritePointer.load(std::memory_order_relaxed) - fifo.CPBase.load(std::memory_order_relaxed) + 32); } }) : MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.CPReadWriteDistance)), MMIO::DirectWrite<u16>(MMIO::Utils::LowPart(&fifo.CPReadWriteDistance), WMASK_LO_ALIGN_32BIT)); mmio->Register(base | FIFO_RW_DISTANCE_HI, IsOnThread() ? MMIO::ComplexRead<u16>([](u32) { Fifo::SyncGPUForRegisterAccess(); if (fifo.CPWritePointer.load(std::memory_order_relaxed) >= fifo.SafeCPReadPointer.load(std::memory_order_relaxed)) { return (fifo.CPWritePointer.load(std::memory_order_relaxed) - fifo.SafeCPReadPointer.load(std::memory_order_relaxed)) >> 16; } else { return (fifo.CPEnd.load(std::memory_order_relaxed) - fifo.SafeCPReadPointer.load(std::memory_order_relaxed) + fifo.CPWritePointer.load(std::memory_order_relaxed) - fifo.CPBase.load(std::memory_order_relaxed) + 32) >> 16; } }) : MMIO::ComplexRead<u16>([](u32) { Fifo::SyncGPUForRegisterAccess(); return fifo.CPReadWriteDistance.load(std::memory_order_relaxed) >> 16; }), MMIO::ComplexWrite<u16>([WMASK_HI_RESTRICT](u32, u16 val) { Fifo::SyncGPUForRegisterAccess(); WriteHigh(fifo.CPReadWriteDistance, val & WMASK_HI_RESTRICT); Fifo::RunGpu(); })); mmio->Register( base | FIFO_READ_POINTER_LO, IsOnThread() ? MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.SafeCPReadPointer)) : MMIO::DirectRead<u16>(MMIO::Utils::LowPart(&fifo.CPReadPointer)), MMIO::DirectWrite<u16>(MMIO::Utils::LowPart(&fifo.CPReadPointer), WMASK_LO_ALIGN_32BIT)); mmio->Register(base | FIFO_READ_POINTER_HI, IsOnThread() ? MMIO::ComplexRead<u16>([](u32) { Fifo::SyncGPUForRegisterAccess(); return fifo.SafeCPReadPointer.load(std::memory_order_relaxed) >> 16; }) : MMIO::ComplexRead<u16>([](u32) { Fifo::SyncGPUForRegisterAccess(); return fifo.CPReadPointer.load(std::memory_order_relaxed) >> 16; }), IsOnThread() ? MMIO::ComplexWrite<u16>([WMASK_HI_RESTRICT](u32, u16 val) { Fifo::SyncGPUForRegisterAccess(); WriteHigh(fifo.CPReadPointer, val & WMASK_HI_RESTRICT); fifo.SafeCPReadPointer.store(fifo.CPReadPointer.load(std::memory_order_relaxed), std::memory_order_relaxed); }) : MMIO::ComplexWrite<u16>([WMASK_HI_RESTRICT](u32, u16 val) { Fifo::SyncGPUForRegisterAccess(); WriteHigh(fifo.CPReadPointer, val & WMASK_HI_RESTRICT); })); } void GatherPipeBursted() { SetCPStatusFromCPU(); // if we aren't linked, we don't care about gather pipe data if (!m_CPCtrlReg.GPLinkEnable) { if (IsOnThread() && !Fifo::UseDeterministicGPUThread()) { // In multibuffer mode is not allowed write in the same FIFO attached to the GPU. // Fix Pokemon XD in DC mode. if ((ProcessorInterface::Fifo_CPUEnd == fifo.CPEnd.load(std::memory_order_relaxed)) && (ProcessorInterface::Fifo_CPUBase == fifo.CPBase.load(std::memory_order_relaxed)) && fifo.CPReadWriteDistance.load(std::memory_order_relaxed) > 0) { Fifo::FlushGpu(); } } Fifo::RunGpu(); return; } // update the fifo pointer if (fifo.CPWritePointer.load(std::memory_order_relaxed) == fifo.CPEnd.load(std::memory_order_relaxed)) { fifo.CPWritePointer.store(fifo.CPBase, std::memory_order_relaxed); } else { fifo.CPWritePointer.fetch_add(GATHER_PIPE_SIZE, std::memory_order_relaxed); } if (m_CPCtrlReg.GPReadEnable && m_CPCtrlReg.GPLinkEnable) { ProcessorInterface::Fifo_CPUWritePointer = fifo.CPWritePointer.load(std::memory_order_relaxed); ProcessorInterface::Fifo_CPUBase = fifo.CPBase.load(std::memory_order_relaxed); ProcessorInterface::Fifo_CPUEnd = fifo.CPEnd.load(std::memory_order_relaxed); } // If the game is running close to overflowing, make the exception checking more frequent. if (fifo.bFF_HiWatermark.load(std::memory_order_relaxed) != 0) CoreTiming::ForceExceptionCheck(0); fifo.CPReadWriteDistance.fetch_add(GATHER_PIPE_SIZE, std::memory_order_seq_cst); Fifo::RunGpu(); ASSERT_MSG(COMMANDPROCESSOR, fifo.CPReadWriteDistance.load(std::memory_order_relaxed) <= fifo.CPEnd.load(std::memory_order_relaxed) - fifo.CPBase.load(std::memory_order_relaxed), "FIFO is overflowed by GatherPipe !\nCPU thread is too fast!"); // check if we are in sync ASSERT_MSG(COMMANDPROCESSOR, fifo.CPWritePointer.load(std::memory_order_relaxed) == ProcessorInterface::Fifo_CPUWritePointer, "FIFOs linked but out of sync"); ASSERT_MSG(COMMANDPROCESSOR, fifo.CPBase.load(std::memory_order_relaxed) == ProcessorInterface::Fifo_CPUBase, "FIFOs linked but out of sync"); ASSERT_MSG(COMMANDPROCESSOR, fifo.CPEnd.load(std::memory_order_relaxed) == ProcessorInterface::Fifo_CPUEnd, "FIFOs linked but out of sync"); } void UpdateInterrupts(u64 userdata) { if (userdata) { s_interrupt_set.Set(); DEBUG_LOG_FMT(COMMANDPROCESSOR, "Interrupt set"); ProcessorInterface::SetInterrupt(INT_CAUSE_CP, true); } else { s_interrupt_set.Clear(); DEBUG_LOG_FMT(COMMANDPROCESSOR, "Interrupt cleared"); ProcessorInterface::SetInterrupt(INT_CAUSE_CP, false); } CoreTiming::ForceExceptionCheck(0); s_interrupt_waiting.Clear(); Fifo::RunGpu(); } void UpdateInterruptsFromVideoBackend(u64 userdata) { if (!Fifo::UseDeterministicGPUThread()) CoreTiming::ScheduleEvent(0, et_UpdateInterrupts, userdata, CoreTiming::FromThread::NON_CPU); } bool IsInterruptWaiting() { return s_interrupt_waiting.IsSet(); } void SetCPStatusFromGPU() { // breakpoint const bool breakpoint = fifo.bFF_Breakpoint.load(std::memory_order_relaxed); if (fifo.bFF_BPEnable.load(std::memory_order_relaxed) != 0) { if (fifo.CPBreakpoint.load(std::memory_order_relaxed) == fifo.CPReadPointer.load(std::memory_order_relaxed)) { if (!breakpoint) { DEBUG_LOG_FMT(COMMANDPROCESSOR, "Hit breakpoint at {}", fifo.CPReadPointer.load(std::memory_order_relaxed)); fifo.bFF_Breakpoint.store(1, std::memory_order_relaxed); } } else { if (breakpoint) { DEBUG_LOG_FMT(COMMANDPROCESSOR, "Cleared breakpoint at {}", fifo.CPReadPointer.load(std::memory_order_relaxed)); fifo.bFF_Breakpoint.store(0, std::memory_order_relaxed); } } } else { if (breakpoint) { DEBUG_LOG_FMT(COMMANDPROCESSOR, "Cleared breakpoint at {}", fifo.CPReadPointer.load(std::memory_order_relaxed)); fifo.bFF_Breakpoint = false; } } // overflow & underflow check fifo.bFF_HiWatermark.store( (fifo.CPReadWriteDistance.load(std::memory_order_relaxed) > fifo.CPHiWatermark), std::memory_order_relaxed); fifo.bFF_LoWatermark.store( (fifo.CPReadWriteDistance.load(std::memory_order_relaxed) < fifo.CPLoWatermark), std::memory_order_relaxed); bool bpInt = fifo.bFF_Breakpoint.load(std::memory_order_relaxed) && fifo.bFF_BPInt.load(std::memory_order_relaxed); bool ovfInt = fifo.bFF_HiWatermark.load(std::memory_order_relaxed) && fifo.bFF_HiWatermarkInt.load(std::memory_order_relaxed); bool undfInt = fifo.bFF_LoWatermark.load(std::memory_order_relaxed) && fifo.bFF_LoWatermarkInt.load(std::memory_order_relaxed); bool interrupt = (bpInt || ovfInt || undfInt) && m_CPCtrlReg.GPReadEnable; if (interrupt != s_interrupt_set.IsSet() && !s_interrupt_waiting.IsSet()) { u64 userdata = interrupt ? 1 : 0; if (IsOnThread()) { if (!interrupt || bpInt || undfInt || ovfInt) { // Schedule the interrupt asynchronously s_interrupt_waiting.Set(); CommandProcessor::UpdateInterruptsFromVideoBackend(userdata); } } else { CommandProcessor::UpdateInterrupts(userdata); } } } void SetCPStatusFromCPU() { // overflow & underflow check fifo.bFF_HiWatermark.store( (fifo.CPReadWriteDistance.load(std::memory_order_relaxed) > fifo.CPHiWatermark), std::memory_order_relaxed); fifo.bFF_LoWatermark.store( (fifo.CPReadWriteDistance.load(std::memory_order_relaxed) < fifo.CPLoWatermark), std::memory_order_relaxed); bool bpInt = fifo.bFF_Breakpoint.load(std::memory_order_relaxed) && fifo.bFF_BPInt.load(std::memory_order_relaxed); bool ovfInt = fifo.bFF_HiWatermark.load(std::memory_order_relaxed) && fifo.bFF_HiWatermarkInt.load(std::memory_order_relaxed); bool undfInt = fifo.bFF_LoWatermark.load(std::memory_order_relaxed) && fifo.bFF_LoWatermarkInt.load(std::memory_order_relaxed); bool interrupt = (bpInt || ovfInt || undfInt) && m_CPCtrlReg.GPReadEnable; if (interrupt != s_interrupt_set.IsSet() && !s_interrupt_waiting.IsSet()) { u64 userdata = interrupt ? 1 : 0; if (IsOnThread()) { if (!interrupt || bpInt || undfInt || ovfInt) { s_interrupt_set.Set(interrupt); DEBUG_LOG_FMT(COMMANDPROCESSOR, "Interrupt set"); ProcessorInterface::SetInterrupt(INT_CAUSE_CP, interrupt); } } else { CommandProcessor::UpdateInterrupts(userdata); } } } void SetCpStatusRegister() { // Here always there is one fifo attached to the GPU m_CPStatusReg.Breakpoint = fifo.bFF_Breakpoint.load(std::memory_order_relaxed); m_CPStatusReg.ReadIdle = !fifo.CPReadWriteDistance.load(std::memory_order_relaxed) || (fifo.CPReadPointer.load(std::memory_order_relaxed) == fifo.CPWritePointer.load(std::memory_order_relaxed)); m_CPStatusReg.CommandIdle = !fifo.CPReadWriteDistance.load(std::memory_order_relaxed) || Fifo::AtBreakpoint() || !fifo.bFF_GPReadEnable.load(std::memory_order_relaxed); m_CPStatusReg.UnderflowLoWatermark = fifo.bFF_LoWatermark.load(std::memory_order_relaxed); m_CPStatusReg.OverflowHiWatermark = fifo.bFF_HiWatermark.load(std::memory_order_relaxed); DEBUG_LOG_FMT(COMMANDPROCESSOR, "\t Read from STATUS_REGISTER : {:04x}", m_CPStatusReg.Hex); DEBUG_LOG_FMT( COMMANDPROCESSOR, "(r) status: iBP {} | fReadIdle {} | fCmdIdle {} | iOvF {} | iUndF {}", m_CPStatusReg.Breakpoint ? "ON" : "OFF", m_CPStatusReg.ReadIdle ? "ON" : "OFF", m_CPStatusReg.CommandIdle ? "ON" : "OFF", m_CPStatusReg.OverflowHiWatermark ? "ON" : "OFF", m_CPStatusReg.UnderflowLoWatermark ? "ON" : "OFF"); } void SetCpControlRegister() { fifo.bFF_BPInt.store(m_CPCtrlReg.BPInt, std::memory_order_relaxed); fifo.bFF_BPEnable.store(m_CPCtrlReg.BPEnable, std::memory_order_relaxed); fifo.bFF_HiWatermarkInt.store(m_CPCtrlReg.FifoOverflowIntEnable, std::memory_order_relaxed); fifo.bFF_LoWatermarkInt.store(m_CPCtrlReg.FifoUnderflowIntEnable, std::memory_order_relaxed); fifo.bFF_GPLinkEnable.store(m_CPCtrlReg.GPLinkEnable, std::memory_order_relaxed); if (fifo.bFF_GPReadEnable.load(std::memory_order_relaxed) && !m_CPCtrlReg.GPReadEnable) { fifo.bFF_GPReadEnable.store(m_CPCtrlReg.GPReadEnable, std::memory_order_relaxed); Fifo::FlushGpu(); } else { fifo.bFF_GPReadEnable = m_CPCtrlReg.GPReadEnable; } DEBUG_LOG_FMT(COMMANDPROCESSOR, "\t GPREAD {} | BP {} | Int {} | OvF {} | UndF {} | LINK {}", fifo.bFF_GPReadEnable.load(std::memory_order_relaxed) ? "ON" : "OFF", fifo.bFF_BPEnable.load(std::memory_order_relaxed) ? "ON" : "OFF", fifo.bFF_BPInt.load(std::memory_order_relaxed) ? "ON" : "OFF", m_CPCtrlReg.FifoOverflowIntEnable ? "ON" : "OFF", m_CPCtrlReg.FifoUnderflowIntEnable ? "ON" : "OFF", m_CPCtrlReg.GPLinkEnable ? "ON" : "OFF"); } // NOTE: We intentionally don't emulate this function at the moment. // We don't emulate proper GP timing anyway at the moment, so it would just slow down emulation. void SetCpClearRegister() { } void HandleUnknownOpcode(u8 cmd_byte, const u8* buffer, bool preprocess) { // Datel software uses 0x01 during startup, and Mario Party 5's Wiggler capsule // accidentally uses 0x01-0x03 due to sending 4 more vertices than intended. // Hardware testing indicates that 0x01-0x07 do nothing, so to avoid annoying the user with // spurious popups, we don't create a panic alert in those cases. Other unknown opcodes // (such as 0x18) seem to result in hangs. if (!s_is_fifo_error_seen && cmd_byte > 0x07) { s_is_fifo_error_seen = true; // TODO(Omega): Maybe dump FIFO to file on this error PanicAlertFmtT("GFX FIFO: Unknown Opcode ({0:#04x} @ {1}, preprocess={2}).\n" "This means one of the following:\n" "* The emulated GPU got desynced, disabling dual core can help\n" "* Command stream corrupted by some spurious memory bug\n" "* This really is an unknown opcode (unlikely)\n" "* Some other sort of bug\n\n" "Further errors will be sent to the Video Backend log and\n" "Dolphin will now likely crash or hang. Enjoy.", cmd_byte, fmt::ptr(buffer), preprocess); PanicAlertFmt("Illegal command {:02x}\n" "CPBase: {:#010x}\n" "CPEnd: {:#010x}\n" "CPHiWatermark: {:#010x}\n" "CPLoWatermark: {:#010x}\n" "CPReadWriteDistance: {:#010x}\n" "CPWritePointer: {:#010x}\n" "CPReadPointer: {:#010x}\n" "CPBreakpoint: {:#010x}\n" "bFF_GPReadEnable: {}\n" "bFF_BPEnable: {}\n" "bFF_BPInt: {}\n" "bFF_Breakpoint: {}\n" "bFF_GPLinkEnable: {}\n" "bFF_HiWatermarkInt: {}\n" "bFF_LoWatermarkInt: {}\n", cmd_byte, fifo.CPBase.load(std::memory_order_relaxed), fifo.CPEnd.load(std::memory_order_relaxed), fifo.CPHiWatermark, fifo.CPLoWatermark, fifo.CPReadWriteDistance.load(std::memory_order_relaxed), fifo.CPWritePointer.load(std::memory_order_relaxed), fifo.CPReadPointer.load(std::memory_order_relaxed), fifo.CPBreakpoint.load(std::memory_order_relaxed), fifo.bFF_GPReadEnable.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_BPEnable.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_BPInt.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_Breakpoint.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_GPLinkEnable.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_HiWatermarkInt.load(std::memory_order_relaxed) ? "true" : "false", fifo.bFF_LoWatermarkInt.load(std::memory_order_relaxed) ? "true" : "false"); } // We always generate this log message, though we only generate the panic alerts once. ERROR_LOG_FMT(VIDEO, "FIFO: Unknown Opcode ({:#04x} @ {}, preprocessing = {})", cmd_byte, fmt::ptr(buffer), preprocess ? "yes" : "no"); } } // namespace CommandProcessor
ZephyrSurfer/dolphin
Source/Core/VideoCommon/CommandProcessor.cpp
C++
gpl-2.0
25,741
/* * synergy -- mouse and keyboard sharing utility * Copyright (C) 2004 Chris Schoeneman * * This package is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * found in the file COPYING that should have accompanied this file. * * This package 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 "CXWindowsClipboardAnyBitmapConverter.h" // BMP info header structure struct CBMPInfoHeader { public: UInt32 biSize; SInt32 biWidth; SInt32 biHeight; UInt16 biPlanes; UInt16 biBitCount; UInt32 biCompression; UInt32 biSizeImage; SInt32 biXPelsPerMeter; SInt32 biYPelsPerMeter; UInt32 biClrUsed; UInt32 biClrImportant; }; // BMP is little-endian static void toLE(UInt8*& dst, UInt16 src) { dst[0] = static_cast<UInt8>(src & 0xffu); dst[1] = static_cast<UInt8>((src >> 8) & 0xffu); dst += 2; } static void toLE(UInt8*& dst, SInt32 src) { dst[0] = static_cast<UInt8>(src & 0xffu); dst[1] = static_cast<UInt8>((src >> 8) & 0xffu); dst[2] = static_cast<UInt8>((src >> 16) & 0xffu); dst[3] = static_cast<UInt8>((src >> 24) & 0xffu); dst += 4; } static void toLE(UInt8*& dst, UInt32 src) { dst[0] = static_cast<UInt8>(src & 0xffu); dst[1] = static_cast<UInt8>((src >> 8) & 0xffu); dst[2] = static_cast<UInt8>((src >> 16) & 0xffu); dst[3] = static_cast<UInt8>((src >> 24) & 0xffu); dst += 4; } static inline UInt16 fromLEU16(const UInt8* data) { return static_cast<UInt16>(data[0]) | (static_cast<UInt16>(data[1]) << 8); } static inline SInt32 fromLES32(const UInt8* data) { return static_cast<SInt32>(static_cast<UInt32>(data[0]) | (static_cast<UInt32>(data[1]) << 8) | (static_cast<UInt32>(data[2]) << 16) | (static_cast<UInt32>(data[3]) << 24)); } static inline UInt32 fromLEU32(const UInt8* data) { return static_cast<UInt32>(data[0]) | (static_cast<UInt32>(data[1]) << 8) | (static_cast<UInt32>(data[2]) << 16) | (static_cast<UInt32>(data[3]) << 24); } // // CXWindowsClipboardAnyBitmapConverter // CXWindowsClipboardAnyBitmapConverter::CXWindowsClipboardAnyBitmapConverter() { // do nothing } CXWindowsClipboardAnyBitmapConverter::~CXWindowsClipboardAnyBitmapConverter() { // do nothing } IClipboard::EFormat CXWindowsClipboardAnyBitmapConverter::getFormat() const { return IClipboard::kBitmap; } int CXWindowsClipboardAnyBitmapConverter::getDataSize() const { return 8; } CString CXWindowsClipboardAnyBitmapConverter::fromIClipboard(const CString& bmp) const { // fill BMP info header with native-endian data CBMPInfoHeader infoHeader; const UInt8* rawBMPInfoHeader = reinterpret_cast<const UInt8*>(bmp.data()); infoHeader.biSize = fromLEU32(rawBMPInfoHeader + 0); infoHeader.biWidth = fromLES32(rawBMPInfoHeader + 4); infoHeader.biHeight = fromLES32(rawBMPInfoHeader + 8); infoHeader.biPlanes = fromLEU16(rawBMPInfoHeader + 12); infoHeader.biBitCount = fromLEU16(rawBMPInfoHeader + 14); infoHeader.biCompression = fromLEU32(rawBMPInfoHeader + 16); infoHeader.biSizeImage = fromLEU32(rawBMPInfoHeader + 20); infoHeader.biXPelsPerMeter = fromLES32(rawBMPInfoHeader + 24); infoHeader.biYPelsPerMeter = fromLES32(rawBMPInfoHeader + 28); infoHeader.biClrUsed = fromLEU32(rawBMPInfoHeader + 32); infoHeader.biClrImportant = fromLEU32(rawBMPInfoHeader + 36); // check that format is acceptable if (infoHeader.biSize != 40 || infoHeader.biWidth == 0 || infoHeader.biHeight == 0 || infoHeader.biPlanes != 0 || infoHeader.biCompression != 0 || (infoHeader.biBitCount != 24 && infoHeader.biBitCount != 32)) { return CString(); } // convert to image format const UInt8* rawBMPPixels = rawBMPInfoHeader + 40; if (infoHeader.biBitCount == 24) { return doBGRFromIClipboard(rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight); } else { return doBGRAFromIClipboard(rawBMPPixels, infoHeader.biWidth, infoHeader.biHeight); } } CString CXWindowsClipboardAnyBitmapConverter::toIClipboard(const CString& image) const { // convert to raw BMP data UInt32 w, h, depth; CString rawBMP = doToIClipboard(image, w, h, depth); if (rawBMP.empty() || w == 0 || h == 0 || (depth != 24 && depth != 32)) { return CString(); } // fill BMP info header with little-endian data UInt8 infoHeader[40]; UInt8* dst = infoHeader; toLE(dst, static_cast<UInt32>(40)); toLE(dst, static_cast<SInt32>(w)); toLE(dst, static_cast<SInt32>(h)); toLE(dst, static_cast<UInt16>(1)); toLE(dst, static_cast<UInt16>(depth)); toLE(dst, static_cast<UInt32>(0)); // BI_RGB toLE(dst, static_cast<UInt32>(image.size())); toLE(dst, static_cast<SInt32>(2834)); // 72 dpi toLE(dst, static_cast<SInt32>(2834)); // 72 dpi toLE(dst, static_cast<UInt32>(0)); toLE(dst, static_cast<UInt32>(0)); // construct image return CString(reinterpret_cast<const char*>(infoHeader), sizeof(infoHeader)) + rawBMP; }
undecided/synergy
lib/platform/CXWindowsClipboardAnyBitmapConverter.cpp
C++
gpl-2.0
5,164
package org.openyu.mix.sasang.vo; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.openyu.mix.app.vo.Prize; import org.openyu.commons.bean.IdBean; import org.openyu.commons.bean.ProbabilityBean; import org.openyu.commons.enumz.IntEnum; import com.sun.xml.bind.AnyTypeAdapter; /** * 開出的結果 */ @XmlJavaTypeAdapter(AnyTypeAdapter.class) public interface Outcome extends IdBean, ProbabilityBean { String KEY = Outcome.class.getName(); /** * 結果類別 * */ public enum OutcomeType implements IntEnum { /** * 都不相同 */ STAND_ALONE(1), /** * 兩個相同 */ SAME_TWO(2), /** * 三個相同 */ SAME_THREE(3), // ; private final int value; private OutcomeType(int value) { this.value = value; } public int getValue() { return value; } } /** * 開出的獎 * * @return */ Prize getPrize(); void setPrize(Prize prize); /** * 結果類別 * * @return */ OutcomeType getOutcomeType(); void setOutcomeType(OutcomeType outcomeType); /** * 機率 * * @return */ double getProbability(); void setProbability(double probability); }
mixaceh/openyu-mix.j
openyu-mix-core/src/main/java/org/openyu/mix/sasang/vo/Outcome.java
Java
gpl-2.0
1,183
/* * thd_cdev_order_parser.cpp: Specify cdev order * * Copyright (C) 2012 Intel Corporation. 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 or later 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. * * * Author Name <Srinivas.Pandruvada@linux.intel.com> * */ #include "thd_cdev_order_parser.h" #include "thd_sys_fs.h" cthd_cdev_order_parse::cthd_cdev_order_parse() :doc(NULL), root_element(NULL) { std::string name = TDCONFDIR; filename=name+"/""thermal-cdev-order.xml"; } int cthd_cdev_order_parse::parser_init() { doc = xmlReadFile(filename.c_str(), NULL, 0); if (doc == NULL) { thd_log_warn("error: could not parse file %s\n", filename.c_str()); return THD_ERROR; } root_element = xmlDocGetRootElement(doc); if (root_element == NULL) { thd_log_warn("error: could not get root element \n"); return THD_ERROR; } return THD_SUCCESS; } int cthd_cdev_order_parse::start_parse() { parse(root_element, doc); return THD_SUCCESS; } void cthd_cdev_order_parse::parser_deinit() { xmlFreeDoc(doc); xmlCleanupParser(); } int cthd_cdev_order_parse::parse_new_cdev(xmlNode * a_node, xmlDoc *doc) { xmlNode *cur_node = NULL; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { thd_log_info("node type: Element, name: %s value: %s\n", cur_node->name, xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); cdev_order_list.push_back(xmlNodeListGetString(doc, cur_node->xmlChildrenNode, 1)); } } return THD_SUCCESS; } int cthd_cdev_order_parse::parse(xmlNode * a_node, xmlDoc *doc) { xmlNode *cur_node = NULL; for (cur_node = a_node; cur_node; cur_node = cur_node->next) { if (cur_node->type == XML_ELEMENT_NODE) { if (!strcmp((const char*)cur_node->name, "CoolingDeviceOrder")) { parse_new_cdev(cur_node->children, doc); } } } return THD_SUCCESS; } int cthd_cdev_order_parse::get_order_list(std::vector <std::string> &list) { list = cdev_order_list; return 0; }
RAOF/thermal_daemon
src/thd_cdev_order_parser.cpp
C++
gpl-2.0
2,571
<?php namespace Engelsystem\Test\Unit\Mail; use Engelsystem\Application; use Engelsystem\Config\Config; use Engelsystem\Mail\EngelsystemMailer; use Engelsystem\Mail\Mailer; use Engelsystem\Mail\MailerServiceProvider; use Engelsystem\Mail\Transport\LogTransport; use Engelsystem\Test\Unit\ServiceProviderTest; use InvalidArgumentException; use Psr\Log\LoggerInterface; use Symfony\Component\Mailer\Mailer as SymfonyMailer; use Symfony\Component\Mailer\Transport\SendmailTransport; use Symfony\Component\Mailer\Transport\Smtp\EsmtpTransport; use Symfony\Component\Mailer\Transport\TransportInterface; class MailerServiceProviderTest extends ServiceProviderTest { /** @var array */ protected $defaultConfig = [ 'app_name' => 'Engelsystem App', 'email' => [ 'driver' => 'mail', 'from' => [ 'name' => 'Engelsystem', 'address' => 'foo@bar.batz', ], 'sendmail' => '/opt/bin/sendmail -bs', ], ]; /** @var array */ protected $smtpConfig = [ 'email' => [ 'driver' => 'smtp', 'host' => 'mail.foo.bar', 'port' => 587, 'tls' => true, 'username' => 'foobar', 'password' => 'LoremIpsum123', ], ]; /** * @covers \Engelsystem\Mail\MailerServiceProvider::register */ public function testRegister() { $app = $this->getApplication(); $serviceProvider = new MailerServiceProvider($app); $serviceProvider->register(); $this->assertExistsInContainer(['mailer.transport', TransportInterface::class], $app); $this->assertExistsInContainer(['mailer.symfony', SymfonyMailer::class], $app); $this->assertExistsInContainer(['mailer', EngelsystemMailer::class, Mailer::class], $app); /** @var EngelsystemMailer $mailer */ $mailer = $app->get('mailer'); $this->assertEquals('Engelsystem App', $mailer->getSubjectPrefix()); $this->assertEquals('Engelsystem', $mailer->getFromName()); $this->assertEquals('foo@bar.batz', $mailer->getFromAddress()); /** @var SendmailTransport $transport */ $transport = $app->get('mailer.transport'); $this->assertInstanceOf(SendmailTransport::class, $transport); } /** * @return array */ public function provideTransports() { return [ [LogTransport::class, ['email' => ['driver' => 'log']]], [SendmailTransport::class, ['email' => ['driver' => 'mail']]], [SendmailTransport::class, ['email' => ['driver' => 'sendmail']]], [ EsmtpTransport::class, $this->smtpConfig, ], ]; } /** * @covers \Engelsystem\Mail\MailerServiceProvider::getTransport * @param string $class * @param array $emailConfig * @dataProvider provideTransports */ public function testGetTransport($class, $emailConfig = []) { $app = $this->getApplication($emailConfig); $serviceProvider = new MailerServiceProvider($app); $serviceProvider->register(); $transport = $app->get('mailer.transport'); $this->assertInstanceOf($class, $transport); } /** * @covers \Engelsystem\Mail\MailerServiceProvider::getTransport */ public function testGetTransportNotFound() { $app = $this->getApplication(['email' => ['driver' => 'foo-bar-batz']]); $this->expectException(InvalidArgumentException::class); $serviceProvider = new MailerServiceProvider($app); $serviceProvider->register(); } /** * @covers \Engelsystem\Mail\MailerServiceProvider::getSmtpTransport */ public function testGetSmtpTransport() { $app = $this->getApplication($this->smtpConfig); $serviceProvider = new MailerServiceProvider($app); $serviceProvider->register(); /** @var EsmtpTransport $transport */ $transport = $app->get('mailer.transport'); $this->assertEquals($this->smtpConfig['email']['username'], $transport->getUsername()); $this->assertEquals($this->smtpConfig['email']['password'], $transport->getPassword()); } /** * @param array $configuration * @return Application */ protected function getApplication($configuration = []): Application { $app = new Application(); $configuration = new Config(array_replace_recursive($this->defaultConfig, $configuration)); $app->instance('config', $configuration); $logger = $this->getMockForAbstractClass(LoggerInterface::class); $app->instance(LoggerInterface::class, $logger); return $app; } /** * @param string[] $abstracts * @param Application $container */ protected function assertExistsInContainer($abstracts, $container) { $first = array_shift($abstracts); $this->assertContainerHas($first, $container); foreach ($abstracts as $abstract) { $this->assertContainerHas($abstract, $container); $this->assertEquals($container->get($first), $container->get($abstract)); } } /** * @param string $abstract * @param Application $container */ protected function assertContainerHas($abstract, $container) { $this->assertTrue( $container->has($abstract) || $container->hasMethodBinding($abstract), sprintf('Container does not contain abstract %s', $abstract) ); } }
engelsystem/engelsystem
tests/Unit/Mail/MailerServiceProviderTest.php
PHP
gpl-2.0
5,660
<?php /* * (c) 2017 Siveo, http://www.siveo.net * * $Id$ * * This file is part of MMC, http://www.siveo.net * * MMC 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. * * MMC 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 MMC; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * * File xmppmaster/machine_xmpp_detail.php */ // recupere information machine //print_r($_GET); extract($_GET); ?> <?php //print_r($_GET); $cn = explode ( "/", $machine)[1]; $machinexmpp = xmlrpc_getMachinefromjid($machine); header('Location: main.php?module=base&submod=computers&action=glpitabs&cn='.urlencode($cn).'&objectUUID='.urlencode($machinexmpp['uuid_inventorymachine'])); exit(); /* echo "<pre>"; print_r($machinexmpp); echo "</pre>";*/ ?>
pulse-project/mmc-core
web/modules/xmppmaster/xmppmaster/machine_xmpp_detail.php
PHP
gpl-2.0
1,270
var expect = require('expect.js'); var Quantimodo = require('../../index'); var instance; beforeEach(function(){ instance = new Quantimodo.PostUserSettingsDataResponse(); }); describe('PostUserSettingsDataResponse', function(){ it('should create an instance of PostUserSettingsDataResponse', function(){ // uncomment below and update the code to test PostUserSettingsDataResponse //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be.a(Quantimodo.PostUserSettingsDataResponse); }); it('should have the property purchaseId (base name: "purchaseId")', function(){ // uncomment below and update the code to test the property purchaseId //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property description (base name: "description")', function(){ // uncomment below and update the code to test the property description //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property summary (base name: "summary")', function(){ // uncomment below and update the code to test the property summary //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property errors (base name: "errors")', function(){ // uncomment below and update the code to test the property errors //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property status (base name: "status")', function(){ // uncomment below and update the code to test the property status //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property success (base name: "success")', function(){ // uncomment below and update the code to test the property success //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property code (base name: "code")', function(){ // uncomment below and update the code to test the property code //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property link (base name: "link")', function(){ // uncomment below and update the code to test the property link //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); it('should have the property card (base name: "card")', function(){ // uncomment below and update the code to test the property card //var instance = new Quantimodo.PostUserSettingsDataResponse(); //expect(instance).to.be(); }); });
QuantiModo/quantimodo-android-chrome-ios-web-app
plain-javascript-client/test/generated/model/PostUserSettingsDataResponse.spec.js
JavaScript
gpl-2.0
2,975
/** \file * Base class for visual SVG elements */ /* * Authors: * Lauris Kaplinski <lauris@kaplinski.com> * bulia byak <buliabyak@users.sf.net> * Johan Engelen <j.b.c.engelen@ewi.utwente.nl> * Abhishek Sharma * Jon A. Cruz <jon@joncruz.org> * * Copyright (C) 2001-2006 authors * Copyright (C) 2001 Ximian, Inc. * * Released under GNU GPL, read the file 'COPYING' for more information */ /** \class SPItem * * SPItem is an abstract base class for all graphic (visible) SVG nodes. It * is a subclass of SPObject, with great deal of specific functionality. */ #ifdef HAVE_CONFIG_H # include "config.h" #endif #include "sp-item.h" #include "svg/svg.h" #include "print.h" #include "display/drawing-item.h" #include "attributes.h" #include "document.h" #include "uri.h" #include "inkscape.h" #include "desktop.h" #include "desktop-handles.h" #include "style.h" #include <glibmm/i18n.h> #include "sp-root.h" #include "sp-clippath.h" #include "sp-mask.h" #include "sp-rect.h" #include "sp-use.h" #include "sp-text.h" #include "sp-textpath.h" #include "sp-item-rm-unsatisfied-cns.h" #include "sp-pattern.h" #include "sp-paint-server.h" #include "sp-switch.h" #include "sp-guide-constraint.h" #include "gradient-chemistry.h" #include "preferences.h" #include "conn-avoid-ref.h" #include "conditions.h" #include "sp-filter-reference.h" #include "filter-chemistry.h" #include "sp-guide.h" #include "sp-title.h" #include "sp-desc.h" #include "util/find-last-if.h" #include "util/reverse-list.h" #include <2geom/rect.h> #include <2geom/affine.h> #include <2geom/transforms.h> #include "xml/repr.h" #include "extract-uri.h" #include "helper/geom.h" #include "live_effects/lpeobject.h" #include "live_effects/effect.h" #include "live_effects/lpeobject-reference.h" #include "util/units.h" #define noSP_ITEM_DEBUG_IDLE static SPItemView* sp_item_view_list_remove(SPItemView *list, SPItemView *view); SPItem::SPItem() : SPObject() { this->sensitive = 0; this->clip_ref = NULL; this->avoidRef = NULL; this->_is_evaluated = false; this->stop_paint = 0; this->_evaluated_status = StatusUnknown; this->bbox_valid = 0; this->freeze_stroke_width = false; this->transform_center_x = 0; this->transform_center_y = 0; this->display = NULL; this->mask_ref = NULL; sensitive = TRUE; bbox_valid = FALSE; transform_center_x = 0; transform_center_y = 0; _is_evaluated = true; _evaluated_status = StatusUnknown; transform = Geom::identity(); doc_bbox = Geom::OptRect(); freeze_stroke_width = false; display = NULL; clip_ref = new SPClipPathReference(this); clip_ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(clip_ref_changed), this)); mask_ref = new SPMaskReference(this); mask_ref->changedSignal().connect(sigc::bind(sigc::ptr_fun(mask_ref_changed), this)); style->signal_fill_ps_changed.connect(sigc::bind(sigc::ptr_fun(fill_ps_ref_changed), this)); style->signal_stroke_ps_changed.connect(sigc::bind(sigc::ptr_fun(stroke_ps_ref_changed), this)); avoidRef = new SPAvoidRef(this); } SPItem::~SPItem() { } bool SPItem::isVisibleAndUnlocked() const { return (!isHidden() && !isLocked()); } bool SPItem::isVisibleAndUnlocked(unsigned display_key) const { return (!isHidden(display_key) && !isLocked()); } bool SPItem::isLocked() const { for (SPObject const *o = this; o != NULL; o = o->parent) { if (SP_IS_ITEM(o) && !(SP_ITEM(o)->sensitive)) { return true; } } return false; } void SPItem::setLocked(bool locked) { setAttribute("sodipodi:insensitive", ( locked ? "1" : NULL )); updateRepr(); } bool SPItem::isHidden() const { if (!isEvaluated()) return true; return style->display.computed == SP_CSS_DISPLAY_NONE; } void SPItem::setHidden(bool hide) { style->display.set = TRUE; style->display.value = ( hide ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE ); style->display.computed = style->display.value; style->display.inherit = FALSE; updateRepr(); } bool SPItem::isHidden(unsigned display_key) const { if (!isEvaluated()) return true; for ( SPItemView *view(display) ; view ; view = view->next ) { if ( view->key == display_key ) { g_assert(view->arenaitem != NULL); for ( Inkscape::DrawingItem *arenaitem = view->arenaitem ; arenaitem ; arenaitem = arenaitem->parent() ) { if (!arenaitem->visible()) { return true; } } return false; } } return true; } void SPItem::setEvaluated(bool evaluated) { _is_evaluated = evaluated; _evaluated_status = StatusSet; } void SPItem::resetEvaluated() { if ( StatusCalculated == _evaluated_status ) { _evaluated_status = StatusUnknown; bool oldValue = _is_evaluated; if ( oldValue != isEvaluated() ) { requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); } } if ( StatusSet == _evaluated_status ) { if (SP_IS_SWITCH(parent)) { SP_SWITCH(parent)->resetChildEvaluated(); } } } bool SPItem::isEvaluated() const { if ( StatusUnknown == _evaluated_status ) { _is_evaluated = sp_item_evaluate(this); _evaluated_status = StatusCalculated; } return _is_evaluated; } /** * Returns something suitable for the `Hide' checkbox in the Object Properties dialog box. * Corresponds to setExplicitlyHidden. */ bool SPItem::isExplicitlyHidden() const { return (style->display.set && style->display.value == SP_CSS_DISPLAY_NONE); } /** * Sets the display CSS property to `hidden' if \a val is true, * otherwise makes it unset */ void SPItem::setExplicitlyHidden(bool val) { style->display.set = val; style->display.value = ( val ? SP_CSS_DISPLAY_NONE : SP_CSS_DISPLAY_INLINE ); style->display.computed = style->display.value; updateRepr(); } /** * Sets the transform_center_x and transform_center_y properties to retain the rotation center */ void SPItem::setCenter(Geom::Point const &object_centre) { document->ensureUpToDate(); // Copied from DocumentProperties::onDocUnitChange() gdouble viewscale = 1.0; Geom::Rect vb = this->document->getRoot()->viewBox; if ( !vb.hasZeroArea() ) { gdouble viewscale_w = this->document->getWidth().value("px") / vb.width(); gdouble viewscale_h = this->document->getHeight().value("px")/ vb.height(); viewscale = std::min(viewscale_h, viewscale_w); } // FIXME this is seriously wrong Geom::OptRect bbox = desktopGeometricBounds(); if (bbox) { // object centre is document coordinates (i.e. in pixels), so we need to consider the viewbox // to translate to user units; transform_center_x/y is in user units transform_center_x = (object_centre[Geom::X] - bbox->midpoint()[Geom::X])/viewscale; if (Geom::are_near(transform_center_x, 0)) // rounding error transform_center_x = 0; transform_center_y = (object_centre[Geom::Y] - bbox->midpoint()[Geom::Y])/viewscale; if (Geom::are_near(transform_center_y, 0)) // rounding error transform_center_y = 0; } } void SPItem::unsetCenter() { transform_center_x = 0; transform_center_y = 0; } bool SPItem::isCenterSet() const { return (transform_center_x != 0 || transform_center_y != 0); } // Get the item's transformation center in document coordinates (i.e. in pixels) Geom::Point SPItem::getCenter() const { document->ensureUpToDate(); // Copied from DocumentProperties::onDocUnitChange() gdouble viewscale = 1.0; Geom::Rect vb = this->document->getRoot()->viewBox; if ( !vb.hasZeroArea() ) { gdouble viewscale_w = this->document->getWidth().value("px") / vb.width(); gdouble viewscale_h = this->document->getHeight().value("px")/ vb.height(); viewscale = std::min(viewscale_h, viewscale_w); } // FIXME this is seriously wrong Geom::OptRect bbox = desktopGeometricBounds(); if (bbox) { // transform_center_x/y are stored in user units, so we have to take the viewbox into account to translate to document coordinates return bbox->midpoint() + Geom::Point (transform_center_x*viewscale, transform_center_y*viewscale); } else { return Geom::Point(0, 0); // something's wrong! } } void SPItem::scaleCenter(Geom::Scale const &sc) { transform_center_x *= sc[Geom::X]; transform_center_y *= sc[Geom::Y]; } namespace { bool is_item(SPObject const &object) { return SP_IS_ITEM(&object); } } void SPItem::raiseToTop() { using Inkscape::Algorithms::find_last_if; SPObject *topmost=find_last_if<SPObject::SiblingIterator>( next, NULL, &is_item ); if (topmost) { getRepr()->parent()->changeOrder( getRepr(), topmost->getRepr() ); } } void SPItem::raiseOne() { SPObject *next_higher=std::find_if<SPObject::SiblingIterator>( next, NULL, &is_item ); if (next_higher) { Inkscape::XML::Node *ref = next_higher->getRepr(); getRepr()->parent()->changeOrder(getRepr(), ref); } } void SPItem::lowerOne() { using Inkscape::Util::MutableList; using Inkscape::Util::reverse_list; MutableList<SPObject &> next_lower=std::find_if( reverse_list<SPObject::SiblingIterator>( parent->firstChild(), this ), MutableList<SPObject &>(), &is_item ); if (next_lower) { ++next_lower; Inkscape::XML::Node *ref = ( next_lower ? next_lower->getRepr() : NULL ); getRepr()->parent()->changeOrder(getRepr(), ref); } } void SPItem::lowerToBottom() { using Inkscape::Algorithms::find_last_if; using Inkscape::Util::MutableList; using Inkscape::Util::reverse_list; MutableList<SPObject &> bottom=find_last_if( reverse_list<SPObject::SiblingIterator>( parent->firstChild(), this ), MutableList<SPObject &>(), &is_item ); if (bottom) { ++bottom; Inkscape::XML::Node *ref = ( bottom ? bottom->getRepr() : NULL ); getRepr()->parent()->changeOrder(getRepr(), ref); } } /* * Move this SPItem into or after another SPItem in the doc * \param target - the SPItem to move into or after * \param intoafter - move to after the target (false), move inside (sublayer) of the target (true) */ void SPItem::moveTo(SPItem *target, gboolean intoafter) { Inkscape::XML::Node *target_ref = ( target ? target->getRepr() : NULL ); Inkscape::XML::Node *our_ref = getRepr(); gboolean first = FALSE; if (target_ref == our_ref) { // Move to ourself ignore return; } if (!target_ref) { // Assume move to the "first" in the top node, find the top node target_ref = our_ref; while (target_ref->parent() != target_ref->root()) { target_ref = target_ref->parent(); } first = TRUE; } if (intoafter) { // Move this inside of the target at the end our_ref->parent()->removeChild(our_ref); target_ref->addChild(our_ref, NULL); } else if (target_ref->parent() != our_ref->parent()) { // Change in parent, need to remove and add our_ref->parent()->removeChild(our_ref); target_ref->parent()->addChild(our_ref, target_ref); } else if (!first) { // Same parent, just move our_ref->parent()->changeOrder(our_ref, target_ref); } if (first && parent) { // If "first" ensure it appears after the defs etc lowerToBottom(); return; } } void SPItem::build(SPDocument *document, Inkscape::XML::Node *repr) { SPItem* object = this; object->readAttr( "style" ); object->readAttr( "transform" ); object->readAttr( "clip-path" ); object->readAttr( "mask" ); object->readAttr( "sodipodi:insensitive" ); object->readAttr( "sodipodi:nonprintable" ); object->readAttr( "inkscape:transform-center-x" ); object->readAttr( "inkscape:transform-center-y" ); object->readAttr( "inkscape:connector-avoid" ); object->readAttr( "inkscape:connection-points" ); SPObject::build(document, repr); } void SPItem::release() { SPItem* item = this; // Note: do this here before the clip_ref is deleted, since calling // ensureUpToDate() for triggered routing may reference // the deleted clip_ref. delete item->avoidRef; // we do NOT disconnect from the changed signal of those before deletion. // The destructor will call *_ref_changed with NULL as the new value, // which will cause the hide() function to be called. delete item->clip_ref; delete item->mask_ref; SPObject::release(); SPPaintServer *fill_ps = style->getFillPaintServer(); SPPaintServer *stroke_ps = style->getStrokePaintServer(); while (item->display) { if (fill_ps) { fill_ps->hide(item->display->arenaitem->key()); } if (stroke_ps) { stroke_ps->hide(item->display->arenaitem->key()); } item->display = sp_item_view_list_remove(item->display, item->display); } //item->_transformed_signal.~signal(); } void SPItem::set(unsigned int key, gchar const* value) { SPItem *item = this; SPItem* object = item; switch (key) { case SP_ATTR_TRANSFORM: { Geom::Affine t; if (value && sp_svg_transform_read(value, &t)) { item->set_item_transform(t); } else { item->set_item_transform(Geom::identity()); } break; } case SP_PROP_CLIP_PATH: { gchar *uri = extract_uri(value); if (uri) { try { item->clip_ref->attach(Inkscape::URI(uri)); } catch (Inkscape::BadURIException &e) { g_warning("%s", e.what()); item->clip_ref->detach(); } g_free(uri); } else { item->clip_ref->detach(); } break; } case SP_PROP_MASK: { gchar *uri = extract_uri(value); if (uri) { try { item->mask_ref->attach(Inkscape::URI(uri)); } catch (Inkscape::BadURIException &e) { g_warning("%s", e.what()); item->mask_ref->detach(); } g_free(uri); } else { item->mask_ref->detach(); } break; } case SP_ATTR_SODIPODI_INSENSITIVE: item->sensitive = !value; for (SPItemView *v = item->display; v != NULL; v = v->next) { v->arenaitem->setSensitive(item->sensitive); } break; case SP_ATTR_CONNECTOR_AVOID: item->avoidRef->setAvoid(value); break; case SP_ATTR_TRANSFORM_CENTER_X: if (value) { item->transform_center_x = g_strtod(value, NULL); } else { item->transform_center_x = 0; } object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; case SP_ATTR_TRANSFORM_CENTER_Y: if (value) { item->transform_center_y = g_strtod(value, NULL); } else { item->transform_center_y = 0; } object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); break; case SP_PROP_SYSTEM_LANGUAGE: case SP_PROP_REQUIRED_FEATURES: case SP_PROP_REQUIRED_EXTENSIONS: { item->resetEvaluated(); // pass to default handler } default: if (SP_ATTRIBUTE_IS_CSS(key)) { sp_style_read_from_object(object->style, object); object->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG); } else { SPObject::set(key, value); } break; } } void SPItem::clip_ref_changed(SPObject *old_clip, SPObject *clip, SPItem *item) { item->bbox_valid = FALSE; // force a re-evaluation if (old_clip) { SPItemView *v; /* Hide clippath */ for (v = item->display; v != NULL; v = v->next) { SP_CLIPPATH(old_clip)->hide(v->arenaitem->key()); } } if (SP_IS_CLIPPATH(clip)) { Geom::OptRect bbox = item->geometricBounds(); for (SPItemView *v = item->display; v != NULL; v = v->next) { if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } Inkscape::DrawingItem *ai = SP_CLIPPATH(clip)->show( v->arenaitem->drawing(), v->arenaitem->key()); v->arenaitem->setClip(ai); SP_CLIPPATH(clip)->setBBox(v->arenaitem->key(), bbox); clip->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } } void SPItem::mask_ref_changed(SPObject *old_mask, SPObject *mask, SPItem *item) { if (old_mask) { /* Hide mask */ for (SPItemView *v = item->display; v != NULL; v = v->next) { SP_MASK(old_mask)->sp_mask_hide(v->arenaitem->key()); } } if (SP_IS_MASK(mask)) { Geom::OptRect bbox = item->geometricBounds(); for (SPItemView *v = item->display; v != NULL; v = v->next) { if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } Inkscape::DrawingItem *ai = SP_MASK(mask)->sp_mask_show( v->arenaitem->drawing(), v->arenaitem->key()); v->arenaitem->setMask(ai); SP_MASK(mask)->sp_mask_set_bbox(v->arenaitem->key(), bbox); mask->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } } void SPItem::fill_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) { SPPaintServer *old_fill_ps = SP_PAINT_SERVER(old_ps); if (old_fill_ps) { for (SPItemView *v =item->display; v != NULL; v = v->next) { old_fill_ps->hide(v->arenaitem->key()); } } SPPaintServer *new_fill_ps = SP_PAINT_SERVER(ps); if (new_fill_ps) { Geom::OptRect bbox = item->geometricBounds(); for (SPItemView *v = item->display; v != NULL; v = v->next) { if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } Inkscape::DrawingPattern *pi = new_fill_ps->show( v->arenaitem->drawing(), v->arenaitem->key(), bbox); v->arenaitem->setFillPattern(pi); if (pi) { new_fill_ps->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } } } void SPItem::stroke_ps_ref_changed(SPObject *old_ps, SPObject *ps, SPItem *item) { SPPaintServer *old_stroke_ps = SP_PAINT_SERVER(old_ps); if (old_stroke_ps) { for (SPItemView *v =item->display; v != NULL; v = v->next) { old_stroke_ps->hide(v->arenaitem->key()); } } SPPaintServer *new_stroke_ps = SP_PAINT_SERVER(ps); if (new_stroke_ps) { Geom::OptRect bbox = item->geometricBounds(); for (SPItemView *v = item->display; v != NULL; v = v->next) { if (!v->arenaitem->key()) { v->arenaitem->setKey(SPItem::display_key_new(3)); } Inkscape::DrawingPattern *pi = new_stroke_ps->show( v->arenaitem->drawing(), v->arenaitem->key(), bbox); v->arenaitem->setStrokePattern(pi); if (pi) { new_stroke_ps->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } } } void SPItem::update(SPCtx* /*ctx*/, guint flags) { SPItem *item = this; SPItem* object = item; // SPObject::onUpdate(ctx, flags); // any of the modifications defined in sp-object.h might change bbox, // so we invalidate it unconditionally item->bbox_valid = FALSE; if (flags & (SP_OBJECT_CHILD_MODIFIED_FLAG | SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_STYLE_MODIFIED_FLAG)) { if (flags & SP_OBJECT_MODIFIED_FLAG) { for (SPItemView *v = item->display; v != NULL; v = v->next) { v->arenaitem->setTransform(item->transform); } } SPClipPath *clip_path = item->clip_ref ? item->clip_ref->getObject() : NULL; SPMask *mask = item->mask_ref ? item->mask_ref->getObject() : NULL; if ( clip_path || mask ) { Geom::OptRect bbox = item->geometricBounds(); if (clip_path) { for (SPItemView *v = item->display; v != NULL; v = v->next) { clip_path->setBBox(v->arenaitem->key(), bbox); } } if (mask) { for (SPItemView *v = item->display; v != NULL; v = v->next) { mask->sp_mask_set_bbox(v->arenaitem->key(), bbox); } } } if (flags & SP_OBJECT_STYLE_MODIFIED_FLAG) { for (SPItemView *v = item->display; v != NULL; v = v->next) { v->arenaitem->setOpacity(SP_SCALE24_TO_FLOAT(object->style->opacity.value)); v->arenaitem->setAntialiasing(object->style->shape_rendering.computed != SP_CSS_SHAPE_RENDERING_CRISPEDGES); v->arenaitem->setIsolation( object->style->isolation.value ); v->arenaitem->setBlendMode( object->style->mix_blend_mode.value ); v->arenaitem->setVisible(!item->isHidden()); } } } /* Update bounding box in user space, used for filter and objectBoundingBox units */ if (item->style->filter.set && item->display) { Geom::OptRect item_bbox = item->geometricBounds(); SPItemView *itemview = item->display; do { if (itemview->arenaitem) itemview->arenaitem->setItemBounds(item_bbox); } while ( (itemview = itemview->next) ); } // Update libavoid with item geometry (for connector routing). if (item->avoidRef) item->avoidRef->handleSettingChange(); } void SPItem::modified(unsigned int /*flags*/) { } Inkscape::XML::Node* SPItem::write(Inkscape::XML::Document *xml_doc, Inkscape::XML::Node *repr, guint flags) { SPItem *item = this; SPItem* object = item; // in the case of SP_OBJECT_WRITE_BUILD, the item should always be newly created, // so we need to add any children from the underlying object to the new repr if (flags & SP_OBJECT_WRITE_BUILD) { GSList *l = NULL; for (SPObject *child = object->firstChild(); child != NULL; child = child->next ) { if (SP_IS_TITLE(child) || SP_IS_DESC(child)) { Inkscape::XML::Node *crepr = child->updateRepr(xml_doc, NULL, flags); if (crepr) { l = g_slist_prepend (l, crepr); } } } while (l) { repr->addChild((Inkscape::XML::Node *) l->data, NULL); Inkscape::GC::release((Inkscape::XML::Node *) l->data); l = g_slist_remove (l, l->data); } } else { for (SPObject *child = object->firstChild() ; child != NULL; child = child->next ) { if (SP_IS_TITLE(child) || SP_IS_DESC(child)) { child->updateRepr(flags); } } } gchar *c = sp_svg_transform_write(item->transform); repr->setAttribute("transform", c); g_free(c); if (flags & SP_OBJECT_WRITE_EXT) { repr->setAttribute("sodipodi:insensitive", ( item->sensitive ? NULL : "true" )); if (item->transform_center_x != 0) sp_repr_set_svg_double (repr, "inkscape:transform-center-x", item->transform_center_x); else repr->setAttribute ("inkscape:transform-center-x", NULL); if (item->transform_center_y != 0) sp_repr_set_svg_double (repr, "inkscape:transform-center-y", item->transform_center_y); else repr->setAttribute ("inkscape:transform-center-y", NULL); } if (item->clip_ref){ if (item->clip_ref->getObject()) { gchar *uri = item->clip_ref->getURI()->toString(); const gchar *value = g_strdup_printf ("url(%s)", uri); repr->setAttribute ("clip-path", value); g_free ((void *) value); g_free ((void *) uri); } } if (item->mask_ref){ if (item->mask_ref->getObject()) { gchar *uri = item->mask_ref->getURI()->toString(); const gchar *value = g_strdup_printf ("url(%s)", uri); repr->setAttribute ("mask", value); g_free ((void *) value); g_free ((void *) uri); } } SPObject::write(xml_doc, repr, flags); return repr; } // CPPIFY: make pure virtual Geom::OptRect SPItem::bbox(Geom::Affine const & /*transform*/, SPItem::BBoxType /*type*/) const { //throw; return Geom::OptRect(); } /** * Get item's geometric bounding box in this item's coordinate system. * * The geometric bounding box includes only the path, disregarding all style attributes. */ Geom::OptRect SPItem::geometricBounds(Geom::Affine const &transform) const { Geom::OptRect bbox; // call the subclass method // CPPIFY //bbox = this->bbox(transform, SPItem::GEOMETRIC_BBOX); bbox = const_cast<SPItem*>(this)->bbox(transform, SPItem::GEOMETRIC_BBOX); return bbox; } /** * Get item's visual bounding box in this item's coordinate system. * * The visual bounding box includes the stroke and the filter region. */ Geom::OptRect SPItem::visualBounds(Geom::Affine const &transform) const { using Geom::X; using Geom::Y; Geom::OptRect bbox; if ( style && style->filter.href && style->getFilter() && SP_IS_FILTER(style->getFilter())) { // call the subclass method // CPPIFY //bbox = this->bbox(Geom::identity(), SPItem::VISUAL_BBOX); bbox = const_cast<SPItem*>(this)->bbox(Geom::identity(), SPItem::GEOMETRIC_BBOX); // see LP Bug 1229971 SPFilter *filter = SP_FILTER(style->getFilter()); // default filer area per the SVG spec: SVGLength x, y, w, h; Geom::Point minp, maxp; x.set(SVGLength::PERCENT, -0.10, 0); y.set(SVGLength::PERCENT, -0.10, 0); w.set(SVGLength::PERCENT, 1.20, 0); h.set(SVGLength::PERCENT, 1.20, 0); // if area is explicitly set, override: if (filter->x._set) x = filter->x; if (filter->y._set) y = filter->y; if (filter->width._set) w = filter->width; if (filter->height._set) h = filter->height; double len_x = bbox ? bbox->width() : 0; double len_y = bbox ? bbox->height() : 0; x.update(12, 6, len_x); y.update(12, 6, len_y); w.update(12, 6, len_x); h.update(12, 6, len_y); if (filter->filterUnits == SP_FILTER_UNITS_OBJECTBOUNDINGBOX && bbox) { minp[X] = bbox->left() + x.computed * (x.unit == SVGLength::PERCENT ? 1.0 : len_x); maxp[X] = minp[X] + w.computed * (w.unit == SVGLength::PERCENT ? 1.0 : len_x); minp[Y] = bbox->top() + y.computed * (y.unit == SVGLength::PERCENT ? 1.0 : len_y); maxp[Y] = minp[Y] + h.computed * (h.unit == SVGLength::PERCENT ? 1.0 : len_y); } else if (filter->filterUnits == SP_FILTER_UNITS_USERSPACEONUSE) { minp[X] = x.computed; maxp[X] = minp[X] + w.computed; minp[Y] = y.computed; maxp[Y] = minp[Y] + h.computed; } bbox = Geom::OptRect(minp, maxp); *bbox *= transform; } else { // call the subclass method // CPPIFY //bbox = this->bbox(transform, SPItem::VISUAL_BBOX); bbox = const_cast<SPItem*>(this)->bbox(transform, SPItem::VISUAL_BBOX); } if (clip_ref->getObject()) { SP_ITEM(clip_ref->getOwner())->bbox_valid = FALSE; // LP Bug 1349018 bbox.intersectWith(SP_CLIPPATH(clip_ref->getObject())->geometricBounds(transform)); } return bbox; } Geom::OptRect SPItem::bounds(BBoxType type, Geom::Affine const &transform) const { if (type == GEOMETRIC_BBOX) { return geometricBounds(transform); } else { return visualBounds(transform); } } /** Get item's geometric bbox in document coordinate system. * Document coordinates are the default coordinates of the root element: * the origin is at the top left, X grows to the right and Y grows downwards. */ Geom::OptRect SPItem::documentGeometricBounds() const { return geometricBounds(i2doc_affine()); } /// Get item's visual bbox in document coordinate system. Geom::OptRect SPItem::documentVisualBounds() const { if (!bbox_valid) { doc_bbox = visualBounds(i2doc_affine()); bbox_valid = true; } return doc_bbox; } Geom::OptRect SPItem::documentBounds(BBoxType type) const { if (type == GEOMETRIC_BBOX) { return documentGeometricBounds(); } else { return documentVisualBounds(); } } /** Get item's geometric bbox in desktop coordinate system. * Desktop coordinates should be user defined. Currently they are hardcoded: * origin is at bottom left, X grows to the right and Y grows upwards. */ Geom::OptRect SPItem::desktopGeometricBounds() const { return geometricBounds(i2dt_affine()); } /// Get item's visual bbox in desktop coordinate system. Geom::OptRect SPItem::desktopVisualBounds() const { /// @fixme hardcoded desktop transform Geom::Affine m = Geom::Scale(1, -1) * Geom::Translate(0, document->getHeight().value("px")); Geom::OptRect ret = documentVisualBounds(); if (ret) *ret *= m; return ret; } Geom::OptRect SPItem::desktopPreferredBounds() const { if (Inkscape::Preferences::get()->getInt("/tools/bounding_box") == 0) { return desktopBounds(SPItem::VISUAL_BBOX); } else { return desktopBounds(SPItem::GEOMETRIC_BBOX); } } Geom::OptRect SPItem::desktopBounds(BBoxType type) const { if (type == GEOMETRIC_BBOX) { return desktopGeometricBounds(); } else { return desktopVisualBounds(); } } unsigned int SPItem::pos_in_parent() const { g_assert(parent != NULL); g_assert(SP_IS_OBJECT(parent)); unsigned int pos = 0; for ( SPObject *iter = parent->firstChild() ; iter ; iter = iter->next) { if (iter == this) { return pos; } if (SP_IS_ITEM(iter)) { pos++; } } g_assert_not_reached(); return 0; } // CPPIFY: make pure virtual, see below! void SPItem::snappoints(std::vector<Inkscape::SnapCandidatePoint> & /*p*/, Inkscape::SnapPreferences const */*snapprefs*/) const { //throw; } /* This will only be called if the derived class doesn't override this. * see for example sp_genericellipse_snappoints in sp-ellipse.cpp * We don't know what shape we could be dealing with here, so we'll just * do nothing */ void SPItem::getSnappoints(std::vector<Inkscape::SnapCandidatePoint> &p, Inkscape::SnapPreferences const *snapprefs) const { // Get the snappoints of the item // CPPIFY //this->snappoints(p, snapprefs); const_cast<SPItem*>(this)->snappoints(p, snapprefs); // Get the snappoints at the item's center if (snapprefs != NULL && snapprefs->isTargetSnappable(Inkscape::SNAPTARGET_ROTATION_CENTER)) { p.push_back(Inkscape::SnapCandidatePoint(getCenter(), Inkscape::SNAPSOURCE_ROTATION_CENTER, Inkscape::SNAPTARGET_ROTATION_CENTER)); } // Get the snappoints of clipping paths and mask, if any std::list<SPObject const *> clips_and_masks; clips_and_masks.push_back(clip_ref->getObject()); clips_and_masks.push_back(mask_ref->getObject()); SPDesktop *desktop = inkscape_active_desktop(); for (std::list<SPObject const *>::const_iterator o = clips_and_masks.begin(); o != clips_and_masks.end(); ++o) { if (*o) { // obj is a group object, the children are the actual clippers for (SPObject *child = (*o)->children ; child ; child = child->next) { if (SP_IS_ITEM(child)) { std::vector<Inkscape::SnapCandidatePoint> p_clip_or_mask; // Please note the recursive call here! SP_ITEM(child)->getSnappoints(p_clip_or_mask, snapprefs); // Take into account the transformation of the item being clipped or masked for (std::vector<Inkscape::SnapCandidatePoint>::const_iterator p_orig = p_clip_or_mask.begin(); p_orig != p_clip_or_mask.end(); ++p_orig) { // All snappoints are in desktop coordinates, but the item's transformation is // in document coordinates. Hence the awkward construction below Geom::Point pt = desktop->dt2doc((*p_orig).getPoint()) * i2dt_affine(); p.push_back(Inkscape::SnapCandidatePoint(pt, (*p_orig).getSourceType(), (*p_orig).getTargetType())); } } } } } } // CPPIFY: make pure virtual void SPItem::print(SPPrintContext* /*ctx*/) { //throw; } void SPItem::invoke_print(SPPrintContext *ctx) { if ( !isHidden() ) { if (!transform.isIdentity() || style->opacity.value != SP_SCALE24_MAX) { sp_print_bind(ctx, transform, SP_SCALE24_TO_FLOAT(style->opacity.value)); this->print(ctx); sp_print_release(ctx); } else { this->print(ctx); } } } const char* SPItem::displayName() const { return _("Object"); } gchar* SPItem::description() const { return g_strdup(""); } /** * Returns a string suitable for status bar, formatted in pango markup language. * * Must be freed by caller. */ gchar *SPItem::detailedDescription() const { gchar* s = g_strdup_printf("<b>%s</b> %s", this->displayName(), this->description()); if (s && clip_ref->getObject()) { gchar *snew = g_strdup_printf (_("%s; <i>clipped</i>"), s); g_free (s); s = snew; } if (s && mask_ref->getObject()) { gchar *snew = g_strdup_printf (_("%s; <i>masked</i>"), s); g_free (s); s = snew; } if ( style && style->filter.href && style->filter.href->getObject() ) { const gchar *label = style->filter.href->getObject()->label(); gchar *snew = 0; if (label) { snew = g_strdup_printf (_("%s; <i>filtered (%s)</i>"), s, _(label)); } else { snew = g_strdup_printf (_("%s; <i>filtered</i>"), s); } g_free (s); s = snew; } return s; } /** * Returns true if the item is filtered, false otherwise. Used with groups/lists to determine how many, or if any, are filtered * */ bool SPItem::isFiltered() const { return (style && style->filter.href && style->filter.href->getObject()); } /** * Allocates unique integer keys. * \param numkeys Number of keys required. * \return First allocated key; hence if the returned key is n * you can use n, n + 1, ..., n + (numkeys - 1) */ unsigned SPItem::display_key_new(unsigned numkeys) { static unsigned dkey = 0; dkey += numkeys; return dkey - numkeys; } // CPPIFY: make pure virtual Inkscape::DrawingItem* SPItem::show(Inkscape::Drawing& /*drawing*/, unsigned int /*key*/, unsigned int /*flags*/) { //throw; return 0; } Inkscape::DrawingItem *SPItem::invoke_show(Inkscape::Drawing &drawing, unsigned key, unsigned flags) { Inkscape::DrawingItem *ai = NULL; ai = this->show(drawing, key, flags); if (ai != NULL) { Geom::OptRect item_bbox = geometricBounds(); display = sp_item_view_new_prepend(display, this, flags, key, ai); ai->setTransform(transform); ai->setOpacity(SP_SCALE24_TO_FLOAT(style->opacity.value)); ai->setIsolation( style->isolation.value ); ai->setBlendMode( style->mix_blend_mode.value ); //ai->setCompositeOperator( style->composite_op.value ); ai->setVisible(!isHidden()); ai->setSensitive(sensitive); if (clip_ref->getObject()) { SPClipPath *cp = clip_ref->getObject(); if (!display->arenaitem->key()) { display->arenaitem->setKey(display_key_new(3)); } int clip_key = display->arenaitem->key(); // Show and set clip Inkscape::DrawingItem *ac = cp->show(drawing, clip_key); ai->setClip(ac); // Update bbox, in case the clip uses bbox units SP_CLIPPATH(cp)->setBBox(clip_key, item_bbox); cp->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } if (mask_ref->getObject()) { SPMask *mask = mask_ref->getObject(); if (!display->arenaitem->key()) { display->arenaitem->setKey(display_key_new(3)); } int mask_key = display->arenaitem->key(); // Show and set mask Inkscape::DrawingItem *ac = mask->sp_mask_show(drawing, mask_key); ai->setMask(ac); // Update bbox, in case the mask uses bbox units SP_MASK(mask)->sp_mask_set_bbox(mask_key, item_bbox); mask->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } SPPaintServer *fill_ps = style->getFillPaintServer(); if (fill_ps) { if (!display->arenaitem->key()) { display->arenaitem->setKey(display_key_new(3)); } int fill_key = display->arenaitem->key(); Inkscape::DrawingPattern *ap = fill_ps->show(drawing, fill_key, item_bbox); ai->setFillPattern(ap); if (ap) { fill_ps->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } SPPaintServer *stroke_ps = style->getStrokePaintServer(); if (stroke_ps) { if (!display->arenaitem->key()) { display->arenaitem->setKey(display_key_new(3)); } int stroke_key = display->arenaitem->key(); Inkscape::DrawingPattern *ap = stroke_ps->show(drawing, stroke_key, item_bbox); ai->setStrokePattern(ap); if (ap) { stroke_ps->requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG); } } ai->setData(this); ai->setItemBounds(geometricBounds()); } return ai; } // CPPIFY: make pure virtual void SPItem::hide(unsigned int /*key*/) { //throw; } void SPItem::invoke_hide(unsigned key) { this->hide(key); SPItemView *ref = NULL; SPItemView *v = display; while (v != NULL) { SPItemView *next = v->next; if (v->key == key) { if (clip_ref->getObject()) { (clip_ref->getObject())->hide(v->arenaitem->key()); v->arenaitem->setClip(NULL); } if (mask_ref->getObject()) { mask_ref->getObject()->sp_mask_hide(v->arenaitem->key()); v->arenaitem->setMask(NULL); } SPPaintServer *fill_ps = style->getFillPaintServer(); if (fill_ps) { fill_ps->hide(v->arenaitem->key()); } SPPaintServer *stroke_ps = style->getStrokePaintServer(); if (stroke_ps) { stroke_ps->hide(v->arenaitem->key()); } if (!ref) { display = v->next; } else { ref->next = v->next; } delete v->arenaitem; g_free(v); } else { ref = v; } v = next; } } // Adjusters void SPItem::adjust_pattern(Geom::Affine const &postmul, bool set, PatternTransform pt) { bool fill = (pt == TRANSFORM_FILL || pt == TRANSFORM_BOTH); if (fill && style && (style->fill.isPaintserver())) { SPObject *server = style->getFillPaintServer(); if ( SP_IS_PATTERN(server) ) { SPPattern *pattern = sp_pattern_clone_if_necessary(this, SP_PATTERN(server), "fill"); sp_pattern_transform_multiply(pattern, postmul, set); } } bool stroke = (pt == TRANSFORM_STROKE || pt == TRANSFORM_BOTH); if (stroke && style && (style->stroke.isPaintserver())) { SPObject *server = style->getStrokePaintServer(); if ( SP_IS_PATTERN(server) ) { SPPattern *pattern = sp_pattern_clone_if_necessary(this, SP_PATTERN(server), "stroke"); sp_pattern_transform_multiply(pattern, postmul, set); } } } void SPItem::adjust_gradient( Geom::Affine const &postmul, bool set ) { if ( style && style->fill.isPaintserver() ) { SPPaintServer *server = style->getFillPaintServer(); if ( SP_IS_GRADIENT(server) ) { /** * \note Bbox units for a gradient are generally a bad idea because * with them, you cannot preserve the relative position of the * object and its gradient after rotation or skew. So now we * convert them to userspace units which are easy to keep in sync * just by adding the object's transform to gradientTransform. * \todo FIXME: convert back to bbox units after transforming with * the item, so as to preserve the original units. */ SPGradient *gradient = sp_gradient_convert_to_userspace( SP_GRADIENT(server), this, "fill" ); sp_gradient_transform_multiply( gradient, postmul, set ); } } if ( style && style->stroke.isPaintserver() ) { SPPaintServer *server = style->getStrokePaintServer(); if ( SP_IS_GRADIENT(server) ) { SPGradient *gradient = sp_gradient_convert_to_userspace( SP_GRADIENT(server), this, "stroke"); sp_gradient_transform_multiply( gradient, postmul, set ); } } } void SPItem::adjust_stroke( gdouble ex ) { if (freeze_stroke_width) { return; } SPStyle *style = this->style; if (style && !style->stroke.isNone() && !Geom::are_near(ex, 1.0, Geom::EPSILON)) { style->stroke_width.computed *= ex; style->stroke_width.set = TRUE; if ( !style->stroke_dasharray.values.empty() ) { for (unsigned i = 0; i < style->stroke_dasharray.values.size(); i++) { style->stroke_dasharray.values[i] *= ex; } style->stroke_dashoffset.value *= ex; } updateRepr(); } } /** * Find out the inverse of previous transform of an item (from its repr) */ static Geom::Affine sp_item_transform_repr (SPItem *item) { Geom::Affine t_old(Geom::identity()); gchar const *t_attr = item->getRepr()->attribute("transform"); if (t_attr) { Geom::Affine t; if (sp_svg_transform_read(t_attr, &t)) { t_old = t; } } return t_old; } /** * Recursively scale stroke width in \a item and its children by \a expansion. */ void SPItem::adjust_stroke_width_recursive(double expansion) { adjust_stroke (expansion); // A clone's child is the ghost of its original - we must not touch it, skip recursion if ( !SP_IS_USE(this) ) { for ( SPObject *o = children; o; o = o->getNext() ) { if (SP_IS_ITEM(o)) { SP_ITEM(o)->adjust_stroke_width_recursive(expansion); } } } } void SPItem::freeze_stroke_width_recursive(bool freeze) { freeze_stroke_width = freeze; // A clone's child is the ghost of its original - we must not touch it, skip recursion if ( !SP_IS_USE(this) ) { for ( SPObject *o = children; o; o = o->getNext() ) { if (SP_IS_ITEM(o)) { SP_ITEM(o)->freeze_stroke_width_recursive(freeze); } } } } /** * Recursively adjust rx and ry of rects. */ static void sp_item_adjust_rects_recursive(SPItem *item, Geom::Affine advertized_transform) { if (SP_IS_RECT (item)) { SP_RECT(item)->compensateRxRy(advertized_transform); } for (SPObject *o = item->children; o != NULL; o = o->next) { if (SP_IS_ITEM(o)) sp_item_adjust_rects_recursive(SP_ITEM(o), advertized_transform); } } /** * Recursively compensate pattern or gradient transform. */ void SPItem::adjust_paint_recursive (Geom::Affine advertized_transform, Geom::Affine t_ancestors, bool is_pattern) { // _Before_ full pattern/gradient transform: t_paint * t_item * t_ancestors // _After_ full pattern/gradient transform: t_paint_new * t_item * t_ancestors * advertised_transform // By equating these two expressions we get t_paint_new = t_paint * paint_delta, where: Geom::Affine t_item = sp_item_transform_repr (this); Geom::Affine paint_delta = t_item * t_ancestors * advertized_transform * t_ancestors.inverse() * t_item.inverse(); // Within text, we do not fork gradients, and so must not recurse to avoid double compensation; // also we do not recurse into clones, because a clone's child is the ghost of its original - // we must not touch it if (!(this && (SP_IS_TEXT(this) || SP_IS_USE(this)))) { for (SPObject *o = children; o != NULL; o = o->next) { if (SP_IS_ITEM(o)) { // At the level of the transformed item, t_ancestors is identity; // below it, it is the accmmulated chain of transforms from this level to the top level SP_ITEM(o)->adjust_paint_recursive (advertized_transform, t_item * t_ancestors, is_pattern); } } } // We recursed into children first, and are now adjusting this object second; // this is so that adjustments in a tree are done from leaves up to the root, // and paintservers on leaves inheriting their values from ancestors could adjust themselves properly // before ancestors themselves are adjusted, probably differently (bug 1286535) if (is_pattern) { adjust_pattern(paint_delta); } else { adjust_gradient(paint_delta); } } void SPItem::adjust_livepatheffect (Geom::Affine const &postmul, bool set) { if ( SP_IS_LPE_ITEM(this) ) { SPLPEItem *lpeitem = SP_LPE_ITEM (this); if ( lpeitem->hasPathEffect() ) { lpeitem->forkPathEffectsIfNecessary(); // now that all LPEs are forked_if_necessary, we can apply the transform PathEffectList effect_list = lpeitem->getEffectList(); for (PathEffectList::iterator it = effect_list.begin(); it != effect_list.end(); ++it) { LivePathEffectObject *lpeobj = (*it)->lpeobject; if (lpeobj && lpeobj->get_lpe()) { Inkscape::LivePathEffect::Effect * effect = lpeobj->get_lpe(); effect->transform_multiply(postmul, set); } } } } } // CPPIFY:: make pure virtual? // Not all SPItems must necessarily have a set transform method! Geom::Affine SPItem::set_transform(Geom::Affine const &transform) { // throw; return transform; } /** * Set a new transform on an object. * * Compensate for stroke scaling and gradient/pattern fill transform, if * necessary. Call the object's set_transform method if transforms are * stored optimized. Send _transformed_signal. Invoke _write method so that * the repr is updated with the new transform. */ void SPItem::doWriteTransform(Inkscape::XML::Node *repr, Geom::Affine const &transform, Geom::Affine const *adv, bool compensate) { g_return_if_fail(repr != NULL); // calculate the relative transform, if not given by the adv attribute Geom::Affine advertized_transform; if (adv != NULL) { advertized_transform = *adv; } else { advertized_transform = sp_item_transform_repr (this).inverse() * transform; } Inkscape::Preferences *prefs = Inkscape::Preferences::get(); if (compensate) { // recursively compensating for stroke scaling will not always work, because it can be scaled to zero or infinite // from which we cannot ever recover by applying an inverse scale; therefore we temporarily block any changes // to the strokewidth in such a case instead, and unblock these after the transformation // (as reported in https://bugs.launchpad.net/inkscape/+bug/825840/comments/4) if (!prefs->getBool("/options/transform/stroke", true)) { double const expansion = 1. / advertized_transform.descrim(); if (expansion < 1e-9 || expansion > 1e9) { freeze_stroke_width_recursive(true); // This will only work if the item has a set_transform method (in this method adjust_stroke() will be called) // We will still have to apply the inverse scaling to other items, not having a set_transform method // such as ellipses and stars // PS: We cannot use this freeze_stroke_width_recursive() trick in all circumstances. For example, it will // break pasting objects within their group (because in such a case the transformation of the group will affect // the strokewidth, and has to be compensated for. See https://bugs.launchpad.net/inkscape/+bug/959223/comments/10) } else { adjust_stroke_width_recursive(expansion); } } // recursively compensate rx/ry of a rect if requested if (!prefs->getBool("/options/transform/rectcorners", true)) { sp_item_adjust_rects_recursive(this, advertized_transform); } // recursively compensate pattern fill if it's not to be transformed if (!prefs->getBool("/options/transform/pattern", true)) { adjust_paint_recursive (advertized_transform.inverse(), Geom::identity(), true); } /// \todo FIXME: add the same else branch as for gradients below, to convert patterns to userSpaceOnUse as well /// recursively compensate gradient fill if it's not to be transformed if (!prefs->getBool("/options/transform/gradient", true)) { adjust_paint_recursive (advertized_transform.inverse(), Geom::identity(), false); } else { // this converts the gradient/pattern fill/stroke, if any, to userSpaceOnUse; we need to do // it here _before_ the new transform is set, so as to use the pre-transform bbox adjust_paint_recursive (Geom::identity(), Geom::identity(), false); } } // endif(compensate) gint preserve = prefs->getBool("/options/preservetransform/value", 0); Geom::Affine transform_attr (transform); // CPPIFY: check this code. // If onSetTransform is not overridden, CItem::onSetTransform will return the transform it was given as a parameter. // onSetTransform cannot be pure due to the fact that not all visible Items are transformable. if ( // run the object's set_transform (i.e. embed transform) only if: SP_IS_TEXT_TEXTPATH(this) || (!preserve && // user did not chose to preserve all transforms (!clip_ref || !clip_ref->getObject()) && // the object does not have a clippath (!mask_ref || !mask_ref->getObject()) && // the object does not have a mask !(!transform.isTranslation() && style && style->getFilter())) // the object does not have a filter, or the transform is translation (which is supposed to not affect filters) ) { transform_attr = this->set_transform(transform); if (freeze_stroke_width) { freeze_stroke_width_recursive(false); } } else { if (freeze_stroke_width) { freeze_stroke_width_recursive(false); if (compensate) { if (!prefs->getBool("/options/transform/stroke", true)) { // Recursively compensate for stroke scaling, depending on user preference // (As to why we need to do this, see the comment a few lines above near the freeze_stroke_width_recursive(true) call) double const expansion = 1. / advertized_transform.descrim(); adjust_stroke_width_recursive(expansion); } } } } set_item_transform(transform_attr); // Note: updateRepr comes before emitting the transformed signal since // it causes clone SPUse's copy of the original object to brought up to // date with the original. Otherwise, sp_use_bbox returns incorrect // values if called in code handling the transformed signal. updateRepr(); // send the relative transform with a _transformed_signal _transformed_signal.emit(&advertized_transform, this); } // CPPIFY: see below, do not make pure? gint SPItem::event(SPEvent* /*event*/) { return FALSE; } gint SPItem::emitEvent(SPEvent &event) { return this->event(&event); } /** * Sets item private transform (not propagated to repr), without compensating stroke widths, * gradients, patterns as sp_item_write_transform does. */ void SPItem::set_item_transform(Geom::Affine const &transform_matrix) { if (!Geom::are_near(transform_matrix, transform, 1e-18)) { transform = transform_matrix; /* The SP_OBJECT_USER_MODIFIED_FLAG_B is used to mark the fact that it's only a transformation. It's apparently not used anywhere else. */ requestDisplayUpdate(SP_OBJECT_MODIFIED_FLAG | SP_OBJECT_USER_MODIFIED_FLAG_B); sp_item_rm_unsatisfied_cns(*this); } } //void SPItem::convert_to_guides() const { // // CPPIFY: If not overridden, call SPItem::convert_to_guides() const, see below! // this->convert_to_guides(); //} /** * \pre \a ancestor really is an ancestor (\>=) of \a object, or NULL. * ("Ancestor (\>=)" here includes as far as \a object itself.) */ Geom::Affine i2anc_affine(SPObject const *object, SPObject const *const ancestor) { Geom::Affine ret(Geom::identity()); g_return_val_if_fail(object != NULL, ret); /* stop at first non-renderable ancestor */ while ( object != ancestor && SP_IS_ITEM(object) ) { if (SP_IS_ROOT(object)) { ret *= SP_ROOT(object)->c2p; } else { ret *= SP_ITEM(object)->transform; } object = object->parent; } return ret; } Geom::Affine i2i_affine(SPObject const *src, SPObject const *dest) { g_return_val_if_fail(src != NULL && dest != NULL, Geom::identity()); SPObject const *ancestor = src->nearestCommonAncestor(dest); return i2anc_affine(src, ancestor) * i2anc_affine(dest, ancestor).inverse(); } Geom::Affine SPItem::getRelativeTransform(SPObject const *dest) const { return i2i_affine(this, dest); } /** * Returns the accumulated transformation of the item and all its ancestors, including root's viewport. * \pre (item != NULL) and SP_IS_ITEM(item). */ Geom::Affine SPItem::i2doc_affine() const { return i2anc_affine(this, NULL); } /** * Returns the transformation from item to desktop coords */ Geom::Affine SPItem::i2dt_affine() const { Geom::Affine ret; SPDesktop const *desktop = inkscape_active_desktop(); if ( desktop ) { ret = i2doc_affine() * desktop->doc2dt(); } else { // TODO temp code to prevent crashing on command-line launch: ret = i2doc_affine() * Geom::Scale(1, -1) * Geom::Translate(0, document->getHeight().value("px")); } return ret; } void SPItem::set_i2d_affine(Geom::Affine const &i2dt) { Geom::Affine dt2p; /* desktop to item parent transform */ if (parent) { dt2p = static_cast<SPItem *>(parent)->i2dt_affine().inverse(); } else { SPDesktop *dt = inkscape_active_desktop(); dt2p = dt->dt2doc(); } Geom::Affine const i2p( i2dt * dt2p ); set_item_transform(i2p); } /** * should rather be named "sp_item_d2i_affine" to match "sp_item_i2d_affine" (or vice versa) */ Geom::Affine SPItem::dt2i_affine() const { /* fixme: Implement the right way (Lauris) */ return i2dt_affine().inverse(); } /* Item views */ SPItemView *SPItem::sp_item_view_new_prepend(SPItemView *list, SPItem *item, unsigned flags, unsigned key, Inkscape::DrawingItem *drawing_item) { g_assert(item != NULL); g_assert(SP_IS_ITEM(item)); g_assert(drawing_item != NULL); SPItemView *new_view = g_new(SPItemView, 1); new_view->next = list; new_view->flags = flags; new_view->key = key; new_view->arenaitem = drawing_item; return new_view; } static SPItemView* sp_item_view_list_remove(SPItemView *list, SPItemView *view) { SPItemView *ret = list; if (view == list) { ret = list->next; } else { SPItemView *prev; prev = list; while (prev->next != view) prev = prev->next; prev->next = view->next; } delete view->arenaitem; g_free(view); return ret; } /** * Return the arenaitem corresponding to the given item in the display * with the given key */ Inkscape::DrawingItem *SPItem::get_arenaitem(unsigned key) { for ( SPItemView *iv = display ; iv ; iv = iv->next ) { if ( iv->key == key ) { return iv->arenaitem; } } return NULL; } int sp_item_repr_compare_position(SPItem const *first, SPItem const *second) { return sp_repr_compare_position(first->getRepr(), second->getRepr()); } SPItem const *sp_item_first_item_child(SPObject const *obj) { return sp_item_first_item_child( const_cast<SPObject *>(obj) ); } SPItem *sp_item_first_item_child(SPObject *obj) { SPItem *child = 0; for ( SPObject *iter = obj->firstChild() ; iter ; iter = iter->next ) { if ( SP_IS_ITEM(iter) ) { child = SP_ITEM(iter); break; } } return child; } void SPItem::convert_to_guides() const { Inkscape::Preferences *prefs = Inkscape::Preferences::get(); int prefs_bbox = prefs->getInt("/tools/bounding_box", 0); Geom::OptRect bbox = (prefs_bbox == 0) ? desktopVisualBounds() : desktopGeometricBounds(); if (!bbox) { g_warning ("Cannot determine item's bounding box during conversion to guides.\n"); return; } std::list<std::pair<Geom::Point, Geom::Point> > pts; Geom::Point A((*bbox).min()); Geom::Point C((*bbox).max()); Geom::Point B(A[Geom::X], C[Geom::Y]); Geom::Point D(C[Geom::X], A[Geom::Y]); pts.push_back(std::make_pair(A, B)); pts.push_back(std::make_pair(B, C)); pts.push_back(std::make_pair(C, D)); pts.push_back(std::make_pair(D, A)); sp_guide_pt_pairs_to_guides(document, pts); } /* Local Variables: mode:c++ c-file-style:"stroustrup" c-file-offsets:((innamespace . 0)(inline-open . 0)(case-label . +)) indent-tabs-mode:nil fill-column:99 End: */ // vim: filetype=cpp:expandtab:shiftwidth=4:tabstop=8:softtabstop=4 :
yaii/yai
src/sp-item.cpp
C++
gpl-2.0
59,315
class CreateFeedbacks < ActiveRecord::Migration[4.2] def change create_table :feedbacks do |t| t.references :feedback_receiving, index: {name: :feedbacks_polymorphic_index}, polymorphic: true, null: false t.string :author_email t.integer :rating, null: false t.text :comment, null: false t.string :ip_address t.string :session_id, index: true t.timestamps null: false end end end
ignisf/clarion
db/migrate/20171022182011_create_feedbacks.rb
Ruby
gpl-2.0
435
/* $Id$ */ /* * This file is part of OpenTTD. * OpenTTD is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, version 2. * OpenTTD 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 OpenTTD. If not, see <http://www.gnu.org/licenses/>. */ /** @file yapf_common.hpp Commonly used classes for YAPF. */ #ifndef YAPF_COMMON_HPP #define YAPF_COMMON_HPP /** YAPF origin provider base class - used when origin is one tile / multiple trackdirs */ template <class Types> class CYapfOriginTileT { public: typedef typename Types::Tpf Tpf; ///< the pathfinder class (derived from THIS class) typedef typename Types::NodeList::Titem Node; ///< this will be our node type typedef typename Node::Key Key; ///< key to hash tables protected: TileIndex m_orgTile; ///< origin tile TrackdirBits m_orgTrackdirs; ///< origin trackdir mask /** to access inherited path finder */ FORCEINLINE Tpf& Yapf() { return *static_cast<Tpf*>(this); } public: /** Set origin tile / trackdir mask */ void SetOrigin(TileIndex tile, TrackdirBits trackdirs) { m_orgTile = tile; m_orgTrackdirs = trackdirs; } /** Called when YAPF needs to place origin nodes into open list */ void PfSetStartupNodes() { bool is_choice = (KillFirstBit(m_orgTrackdirs) != TRACKDIR_BIT_NONE); for (TrackdirBits tdb = m_orgTrackdirs; tdb != TRACKDIR_BIT_NONE; tdb = KillFirstBit(tdb)) { Trackdir td = (Trackdir)FindFirstBit2x64(tdb); Node& n1 = Yapf().CreateNewNode(); n1.Set(NULL, m_orgTile, td, is_choice); Yapf().AddStartupNode(n1); } } }; /** YAPF origin provider base class - used when there are two tile/trackdir origins */ template <class Types> class CYapfOriginTileTwoWayT { public: typedef typename Types::Tpf Tpf; ///< the pathfinder class (derived from THIS class) typedef typename Types::NodeList::Titem Node; ///< this will be our node type typedef typename Node::Key Key; ///< key to hash tables protected: TileIndex m_orgTile; ///< first origin tile Trackdir m_orgTd; ///< first origin trackdir TileIndex m_revTile; ///< second (reversed) origin tile Trackdir m_revTd; ///< second (reversed) origin trackdir int m_reverse_penalty; ///< penalty to be added for using the reversed origin bool m_treat_first_red_two_way_signal_as_eol; ///< in some cases (leaving station) we need to handle first two-way signal differently /** to access inherited path finder */ FORCEINLINE Tpf& Yapf() { return *static_cast<Tpf*>(this); } public: /** set origin (tiles, trackdirs, etc.) */ void SetOrigin(TileIndex tile, Trackdir td, TileIndex tiler = INVALID_TILE, Trackdir tdr = INVALID_TRACKDIR, int reverse_penalty = 0, bool treat_first_red_two_way_signal_as_eol = true) { m_orgTile = tile; m_orgTd = td; m_revTile = tiler; m_revTd = tdr; m_reverse_penalty = reverse_penalty; m_treat_first_red_two_way_signal_as_eol = treat_first_red_two_way_signal_as_eol; } /** Called when YAPF needs to place origin nodes into open list */ void PfSetStartupNodes() { if (m_orgTile != INVALID_TILE && m_orgTd != INVALID_TRACKDIR) { Node& n1 = Yapf().CreateNewNode(); n1.Set(NULL, m_orgTile, m_orgTd, false); Yapf().AddStartupNode(n1); } if (m_revTile != INVALID_TILE && m_revTd != INVALID_TRACKDIR) { Node& n2 = Yapf().CreateNewNode(); n2.Set(NULL, m_revTile, m_revTd, false); n2.m_cost = m_reverse_penalty; Yapf().AddStartupNode(n2); } } /** return true if first two-way signal should be treated as dead end */ FORCEINLINE bool TreatFirstRedTwoWaySignalAsEOL() { return Yapf().PfGetSettings().rail_firstred_twoway_eol && m_treat_first_red_two_way_signal_as_eol; } }; /** YAPF destination provider base class - used when destination is single tile / multiple trackdirs */ template <class Types> class CYapfDestinationTileT { public: typedef typename Types::Tpf Tpf; ///< the pathfinder class (derived from THIS class) typedef typename Types::NodeList::Titem Node; ///< this will be our node type typedef typename Node::Key Key; ///< key to hash tables protected: TileIndex m_destTile; ///< destination tile TrackdirBits m_destTrackdirs; ///< destination trackdir mask public: /** set the destination tile / more trackdirs */ void SetDestination(TileIndex tile, TrackdirBits trackdirs) { m_destTile = tile; m_destTrackdirs = trackdirs; } protected: /** to access inherited path finder */ Tpf& Yapf() { return *static_cast<Tpf*>(this); } public: /** Called by YAPF to detect if node ends in the desired destination */ FORCEINLINE bool PfDetectDestination(Node& n) { bool bDest = (n.m_key.m_tile == m_destTile) && ((m_destTrackdirs & TrackdirToTrackdirBits(n.GetTrackdir())) != TRACKDIR_BIT_NONE); return bDest; } /** Called by YAPF to calculate cost estimate. Calculates distance to the destination * adds it to the actual cost from origin and stores the sum to the Node::m_estimate */ inline bool PfCalcEstimate(Node& n) { static const int dg_dir_to_x_offs[] = {-1, 0, 1, 0}; static const int dg_dir_to_y_offs[] = {0, 1, 0, -1}; if (PfDetectDestination(n)) { n.m_estimate = n.m_cost; return true; } TileIndex tile = n.GetTile(); DiagDirection exitdir = TrackdirToExitdir(n.GetTrackdir()); int x1 = 2 * TileX(tile) + dg_dir_to_x_offs[(int)exitdir]; int y1 = 2 * TileY(tile) + dg_dir_to_y_offs[(int)exitdir]; int x2 = 2 * TileX(m_destTile); int y2 = 2 * TileY(m_destTile); int dx = abs(x1 - x2); int dy = abs(y1 - y2); int dmin = min(dx, dy); int dxy = abs(dx - dy); int d = dmin * YAPF_TILE_CORNER_LENGTH + (dxy - 1) * (YAPF_TILE_LENGTH / 2); n.m_estimate = n.m_cost + d; assert(n.m_estimate >= n.m_parent->m_estimate); return true; } }; /** YAPF template that uses Ttypes template argument to determine all YAPF * components (base classes) from which the actual YAPF is composed. * For example classes consult: CYapfRail_TypesT template and its instantiations: * CYapfRail1, CYapfRail2, CYapfRail3, CYapfAnyDepotRail1, CYapfAnyDepotRail2, CYapfAnyDepotRail3 */ template <class Ttypes> class CYapfT : public Ttypes::PfBase ///< Instance of CYapfBaseT - main YAPF loop and support base class , public Ttypes::PfCost ///< Cost calculation provider base class , public Ttypes::PfCache ///< Segment cost cache provider , public Ttypes::PfOrigin ///< Origin (tile or two-tile origin) , public Ttypes::PfDestination ///< Destination detector and distance (estimate) calculation provider , public Ttypes::PfFollow ///< Node follower (stepping provider) { }; #endif /* YAPF_COMMON_HPP */
oshepherd/openttd-progsigs
src/pathfinder/yapf/yapf_common.hpp
C++
gpl-2.0
7,218
function updateLabel() { var form = $('contentForm'); var preset_ddm = form.elements['preset']; var presetIndex = preset_ddm[preset_ddm.selectedIndex].value; if ( labels[presetIndex] ) { form.newLabel.value = labels[presetIndex]; } else { form.newLabel.value = ''; } } window.addEvent('domready', updateLabel);
pliablepixels/ZoneMinder
web/skins/classic/views/js/controlpreset.js
JavaScript
gpl-2.0
332
import fill import array a = array.array('I') a.append(1) a.append(1) a.append(3) a.append(2) a.append(2) a.append(2) a.append(2) a.append(2) a.append(2) a.append(2) a.append(2) a.append(2) print "before", a b = fill.fill(a, 2, 2, 3, 3, 4278190080) print "after", b print "after 2", array.array('I', b)
samdroid-apps/paint-activity
test_fill.py
Python
gpl-2.0
304
/* Copyright_License { Top Hat Soaring Glide Computer - http://www.tophatsoaring.org/ Copyright (C) 2000-2016 The Top Hat Soaring 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. } */ #ifndef XCSOAR_DEVICE_DECLARATION_HPP #define XCSOAR_DEVICE_DECLARATION_HPP #include "Geo/GeoPoint.hpp" #include "Engine/Waypoint/Waypoint.hpp" #include "Util/StaticString.hxx" #include "Compiler.h" #include <vector> #include <tchar.h> struct LoggerSettings; struct Plane; class OrderedTask; class OrderedTaskPoint; struct Declaration { struct TurnPoint { enum Shape { CYLINDER, SECTOR, LINE, DAEC_KEYHOLE }; Waypoint waypoint; Shape shape; unsigned radius; TurnPoint(const Waypoint &_waypoint) :waypoint(_waypoint), shape(CYLINDER), radius(1500) {} TurnPoint(const OrderedTaskPoint &tp); }; StaticString<64> pilot_name; StaticString<32> aircraft_type; StaticString<32> aircraft_registration; StaticString<8> competition_id; std::vector<TurnPoint> turnpoints; Declaration(const LoggerSettings &logger_settings, const Plane &plane, const OrderedTask* task); void Append(const Waypoint &waypoint) { turnpoints.push_back(waypoint); } const Waypoint &GetWaypoint(unsigned i) const { return turnpoints[i].waypoint; } const Waypoint &GetFirstWaypoint() const { return turnpoints.front().waypoint; } const Waypoint &GetLastWaypoint() const { return turnpoints.back().waypoint; } gcc_pure const TCHAR *GetName(const unsigned i) const { return turnpoints[i].waypoint.name.c_str(); } const GeoPoint &GetLocation(const unsigned i) const { return turnpoints[i].waypoint.location; } gcc_pure unsigned Size() const { return turnpoints.size(); } }; #endif
rdunning0823/tophat
src/Device/Declaration.hpp
C++
gpl-2.0
2,530
jQuery(function($) { //Get Level 2 Category $('#level1').on("change", ":checkbox", function () { $("#imageloader").show(); if (this.checked) { var parentCat=this.value; // call ajax add_action declared in functions.php $.ajax({ url: "/wp-admin/admin-ajax.php", type:'POST', data:'action=home_category_select_action&parent_cat_ID=' + parentCat, success:function(results) { $("#level2help").hide(); $("#imageloader").hide(); $(".lev1.cat-col").removeClass('dsbl'); //Append all child element in level 2 $("#level2").append(results); } }); } else { //Remove all level 2 element if unchecked $("#imageloader").hide(); $("#getallcat"+this.value).remove(); } }); //Get Level 3 Category $('#level2').on("change", ":checkbox", function () { $("#imageloader2").show(); if (this.checked) { var parentCat=this.value; var parentvalue = $('#parent_id'+parentCat).val(); // call ajax $.ajax({ url: "/wp-admin/admin-ajax.php", type:'POST', data:'action=home_category_select_action&parent_cat_ID=' + parentCat, success:function(results) { $("#level3help").hide(); $(".lev2.cat-col").removeClass('dsbl'); $("#imageloader2").hide(); //Append all child element in level 3 $("#level3").append(results); //Disable parent category $("#level1 input[value='"+parentvalue+"']").prop("disabled", true); // removeChild.push(parentCat); } }); } else { $("#imageloader2").hide(); var parentvalue = $('#parent_id'+this.value).val(); var checkcheckbox=$('#getallcat'+parentvalue+' #parent_cat2').is(':checked'); //check if any child category is checked if(checkcheckbox==false) { //Enable the parent checkbox if unchecked all child element $("#level1 input[value='"+parentvalue+"']").prop("disabled", false); } //Remove all level 3 element if unchecked $("#getallcat"+this.value).remove(); } }); //Load Profile based on tags var list = new Array(); var $container = $('#getTagProfiles'); var $checkboxes = $('#levelContainer input.cb'); $('#levelContainer').on("change", ":checkbox", function () { if (this.checked) { var filterclass=".isoShow"; list.push(this.value); $("#getAllCatId").val(list); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $.post("/wp-admin/admin-ajax.php", 'action=home_tag_select_action&All_cat_ID=' + list+'&listlength='+list.length, function(response) { $(".firstsearch").remove(); $("#contentSection").remove(); $container.html(response); if(!$container.hasClass('isotope')){ $container.isotope({ filter: filterclass }); } else { $container.isotope('reloadItems'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $container.isotope({ filter: filterclass }); } }); } else //If unchecked { var filterclass=".isoShow"; list.splice( $.inArray(this.value,list) ,1 ); $("#getAllCatId").val(list); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $.post("/wp-admin/admin-ajax.php", 'action=home_tag_select_action&All_cat_ID=' + list+'&listlength='+list.length, function(response) { $(".firstsearch").remove(); $("#contentSection").remove(); $container.html(response); if(!$container.hasClass('isotope')){ $container.isotope({ filter: filterclass }); } else { $container.isotope('reloadItems'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $container.isotope({ filter: filterclass }); } }); } }); //Load more $('.more_button').live("click",function() { //var $container2 = $('#getTagProfiles .profile-sec'); var getId = $(this).attr("id"); var getCat= $("#getAllCatId").val(); var filterclass=".isoShow"; if(getId) { $("#load_more_"+getId).html('<img src="/wp-content/themes/marsaec/img/load_img.gif" style="padding:10px 0 0 100px;"/>'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $.post("/wp-admin/admin-ajax.php", 'action=get_loadmore_profile&getLastContentId='+getId+'&getParentId='+getCat+'&listlength='+getCat.length, function(response) { $container.append(response); if(!$container.hasClass('isotope')){ $("#load_more_"+getId).remove(); $container.isotope({ filter: filterclass }); } else { $("#load_more_"+getId).remove(); $container.isotope('reloadItems'); $container.isotope({ itemSelector: '.items', masonry: { columnWidth: 40, rowHeight: 107, isFitWidth: true } }); $container.isotope({ filter: filterclass }); } }); // $.ajax({ // type: "POST", // url: "/wp-admin/admin-ajax.php", // data:'action=get_loadmore_profile&getLastContentId='+getId+'&getParentId='+getCat+'&listlength='+getCat.length, // success: function(html){ // $container2.append(html); // $("#load_more_"+getId).remove(); // } // }); } return false; }); });
moveable-dev1/rep1
wp-content/themes/marsaec/js/toggle.js
JavaScript
gpl-2.0
7,013
//===-- tsan_platform_mac.cpp ---------------------------------------------===// // // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. // See https://llvm.org/LICENSE.txt for license information. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception // //===----------------------------------------------------------------------===// // // This file is a part of ThreadSanitizer (TSan), a race detector. // // Mac-specific code. //===----------------------------------------------------------------------===// #include "sanitizer_common/sanitizer_platform.h" #if SANITIZER_MAC #include "sanitizer_common/sanitizer_atomic.h" #include "sanitizer_common/sanitizer_common.h" #include "sanitizer_common/sanitizer_libc.h" #include "sanitizer_common/sanitizer_posix.h" #include "sanitizer_common/sanitizer_procmaps.h" #include "sanitizer_common/sanitizer_ptrauth.h" #include "sanitizer_common/sanitizer_stackdepot.h" #include "tsan_platform.h" #include "tsan_rtl.h" #include "tsan_flags.h" #include <mach/mach.h> #include <pthread.h> #include <signal.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <stdarg.h> #include <sys/mman.h> #include <sys/syscall.h> #include <sys/time.h> #include <sys/types.h> #include <sys/resource.h> #include <sys/stat.h> #include <unistd.h> #include <errno.h> #include <sched.h> namespace __tsan { #if !SANITIZER_GO static void *SignalSafeGetOrAllocate(uptr *dst, uptr size) { atomic_uintptr_t *a = (atomic_uintptr_t *)dst; void *val = (void *)atomic_load_relaxed(a); atomic_signal_fence(memory_order_acquire); // Turns the previous load into // acquire wrt signals. if (UNLIKELY(val == nullptr)) { val = (void *)internal_mmap(nullptr, size, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0); CHECK(val); void *cmp = nullptr; if (!atomic_compare_exchange_strong(a, (uintptr_t *)&cmp, (uintptr_t)val, memory_order_acq_rel)) { internal_munmap(val, size); val = cmp; } } return val; } // On OS X, accessing TLVs via __thread or manually by using pthread_key_* is // problematic, because there are several places where interceptors are called // when TLVs are not accessible (early process startup, thread cleanup, ...). // The following provides a "poor man's TLV" implementation, where we use the // shadow memory of the pointer returned by pthread_self() to store a pointer to // the ThreadState object. The main thread's ThreadState is stored separately // in a static variable, because we need to access it even before the // shadow memory is set up. static uptr main_thread_identity = 0; ALIGNED(64) static char main_thread_state[sizeof(ThreadState)]; static ThreadState *main_thread_state_loc = (ThreadState *)main_thread_state; // We cannot use pthread_self() before libpthread has been initialized. Our // current heuristic for guarding this is checking `main_thread_identity` which // is only assigned in `__tsan::InitializePlatform`. static ThreadState **cur_thread_location() { if (main_thread_identity == 0) return &main_thread_state_loc; uptr thread_identity = (uptr)pthread_self(); if (thread_identity == main_thread_identity) return &main_thread_state_loc; return (ThreadState **)MemToShadow(thread_identity); } ThreadState *cur_thread() { return (ThreadState *)SignalSafeGetOrAllocate( (uptr *)cur_thread_location(), sizeof(ThreadState)); } void set_cur_thread(ThreadState *thr) { *cur_thread_location() = thr; } // TODO(kuba.brecka): This is not async-signal-safe. In particular, we call // munmap first and then clear `fake_tls`; if we receive a signal in between, // handler will try to access the unmapped ThreadState. void cur_thread_finalize() { ThreadState **thr_state_loc = cur_thread_location(); if (thr_state_loc == &main_thread_state_loc) { // Calling dispatch_main() or xpc_main() actually invokes pthread_exit to // exit the main thread. Let's keep the main thread's ThreadState. return; } internal_munmap(*thr_state_loc, sizeof(ThreadState)); *thr_state_loc = nullptr; } #endif void FlushShadowMemory() { } static void RegionMemUsage(uptr start, uptr end, uptr *res, uptr *dirty) { vm_address_t address = start; vm_address_t end_address = end; uptr resident_pages = 0; uptr dirty_pages = 0; while (address < end_address) { vm_size_t vm_region_size; mach_msg_type_number_t count = VM_REGION_EXTENDED_INFO_COUNT; vm_region_extended_info_data_t vm_region_info; mach_port_t object_name; kern_return_t ret = vm_region_64( mach_task_self(), &address, &vm_region_size, VM_REGION_EXTENDED_INFO, (vm_region_info_t)&vm_region_info, &count, &object_name); if (ret != KERN_SUCCESS) break; resident_pages += vm_region_info.pages_resident; dirty_pages += vm_region_info.pages_dirtied; address += vm_region_size; } *res = resident_pages * GetPageSizeCached(); *dirty = dirty_pages * GetPageSizeCached(); } void WriteMemoryProfile(char *buf, uptr buf_size, uptr nthread, uptr nlive) { uptr shadow_res, shadow_dirty; uptr meta_res, meta_dirty; uptr trace_res, trace_dirty; RegionMemUsage(ShadowBeg(), ShadowEnd(), &shadow_res, &shadow_dirty); RegionMemUsage(MetaShadowBeg(), MetaShadowEnd(), &meta_res, &meta_dirty); RegionMemUsage(TraceMemBeg(), TraceMemEnd(), &trace_res, &trace_dirty); #if !SANITIZER_GO uptr low_res, low_dirty; uptr high_res, high_dirty; uptr heap_res, heap_dirty; RegionMemUsage(LoAppMemBeg(), LoAppMemEnd(), &low_res, &low_dirty); RegionMemUsage(HiAppMemBeg(), HiAppMemEnd(), &high_res, &high_dirty); RegionMemUsage(HeapMemBeg(), HeapMemEnd(), &heap_res, &heap_dirty); #else // !SANITIZER_GO uptr app_res, app_dirty; RegionMemUsage(AppMemBeg(), AppMemEnd(), &app_res, &app_dirty); #endif StackDepotStats *stacks = StackDepotGetStats(); internal_snprintf(buf, buf_size, "shadow (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" "meta (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" "traces (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" #if !SANITIZER_GO "low app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" "high app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" "heap (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" #else // !SANITIZER_GO "app (0x%016zx-0x%016zx): resident %zd kB, dirty %zd kB\n" #endif "stacks: %zd unique IDs, %zd kB allocated\n" "threads: %zd total, %zd live\n" "------------------------------\n", ShadowBeg(), ShadowEnd(), shadow_res / 1024, shadow_dirty / 1024, MetaShadowBeg(), MetaShadowEnd(), meta_res / 1024, meta_dirty / 1024, TraceMemBeg(), TraceMemEnd(), trace_res / 1024, trace_dirty / 1024, #if !SANITIZER_GO LoAppMemBeg(), LoAppMemEnd(), low_res / 1024, low_dirty / 1024, HiAppMemBeg(), HiAppMemEnd(), high_res / 1024, high_dirty / 1024, HeapMemBeg(), HeapMemEnd(), heap_res / 1024, heap_dirty / 1024, #else // !SANITIZER_GO AppMemBeg(), AppMemEnd(), app_res / 1024, app_dirty / 1024, #endif stacks->n_uniq_ids, stacks->allocated / 1024, nthread, nlive); } #if !SANITIZER_GO void InitializeShadowMemoryPlatform() { } // On OS X, GCD worker threads are created without a call to pthread_create. We // need to properly register these threads with ThreadCreate and ThreadStart. // These threads don't have a parent thread, as they are created "spuriously". // We're using a libpthread API that notifies us about a newly created thread. // The `thread == pthread_self()` check indicates this is actually a worker // thread. If it's just a regular thread, this hook is called on the parent // thread. typedef void (*pthread_introspection_hook_t)(unsigned int event, pthread_t thread, void *addr, size_t size); extern "C" pthread_introspection_hook_t pthread_introspection_hook_install( pthread_introspection_hook_t hook); static const uptr PTHREAD_INTROSPECTION_THREAD_CREATE = 1; static const uptr PTHREAD_INTROSPECTION_THREAD_TERMINATE = 3; static pthread_introspection_hook_t prev_pthread_introspection_hook; static void my_pthread_introspection_hook(unsigned int event, pthread_t thread, void *addr, size_t size) { if (event == PTHREAD_INTROSPECTION_THREAD_CREATE) { if (thread == pthread_self()) { // The current thread is a newly created GCD worker thread. ThreadState *thr = cur_thread(); Processor *proc = ProcCreate(); ProcWire(proc, thr); ThreadState *parent_thread_state = nullptr; // No parent. int tid = ThreadCreate(parent_thread_state, 0, (uptr)thread, true); CHECK_NE(tid, 0); ThreadStart(thr, tid, GetTid(), ThreadType::Worker); } } else if (event == PTHREAD_INTROSPECTION_THREAD_TERMINATE) { if (thread == pthread_self()) { ThreadState *thr = cur_thread(); if (thr->tctx) { DestroyThreadState(); } } } if (prev_pthread_introspection_hook != nullptr) prev_pthread_introspection_hook(event, thread, addr, size); } #endif void InitializePlatformEarly() { #if !SANITIZER_GO && defined(__aarch64__) uptr max_vm = GetMaxUserVirtualAddress() + 1; if (max_vm != Mapping::kHiAppMemEnd) { Printf("ThreadSanitizer: unsupported vm address limit %p, expected %p.\n", max_vm, Mapping::kHiAppMemEnd); Die(); } #endif } static uptr longjmp_xor_key = 0; void InitializePlatform() { DisableCoreDumperIfNecessary(); #if !SANITIZER_GO CheckAndProtect(); CHECK_EQ(main_thread_identity, 0); main_thread_identity = (uptr)pthread_self(); prev_pthread_introspection_hook = pthread_introspection_hook_install(&my_pthread_introspection_hook); #endif if (GetMacosAlignedVersion() >= MacosVersion(10, 14)) { // Libsystem currently uses a process-global key; this might change. const unsigned kTLSLongjmpXorKeySlot = 0x7; longjmp_xor_key = (uptr)pthread_getspecific(kTLSLongjmpXorKeySlot); } } #ifdef __aarch64__ # define LONG_JMP_SP_ENV_SLOT \ ((GetMacosAlignedVersion() >= MacosVersion(10, 14)) ? 12 : 13) #else # define LONG_JMP_SP_ENV_SLOT 2 #endif uptr ExtractLongJmpSp(uptr *env) { uptr mangled_sp = env[LONG_JMP_SP_ENV_SLOT]; uptr sp = mangled_sp ^ longjmp_xor_key; sp = (uptr)ptrauth_auth_data((void *)sp, ptrauth_key_asdb, ptrauth_string_discriminator("sp")); return sp; } #if !SANITIZER_GO void ImitateTlsWrite(ThreadState *thr, uptr tls_addr, uptr tls_size) { // The pointer to the ThreadState object is stored in the shadow memory // of the tls. uptr tls_end = tls_addr + tls_size; uptr thread_identity = (uptr)pthread_self(); if (thread_identity == main_thread_identity) { MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr, tls_size); } else { uptr thr_state_start = thread_identity; uptr thr_state_end = thr_state_start + sizeof(uptr); CHECK_GE(thr_state_start, tls_addr); CHECK_LE(thr_state_start, tls_addr + tls_size); CHECK_GE(thr_state_end, tls_addr); CHECK_LE(thr_state_end, tls_addr + tls_size); MemoryRangeImitateWrite(thr, /*pc=*/2, tls_addr, thr_state_start - tls_addr); MemoryRangeImitateWrite(thr, /*pc=*/2, thr_state_end, tls_end - thr_state_end); } } #endif #if !SANITIZER_GO // Note: this function runs with async signals enabled, // so it must not touch any tsan state. int call_pthread_cancel_with_cleanup(int(*fn)(void *c, void *m, void *abstime), void *c, void *m, void *abstime, void(*cleanup)(void *arg), void *arg) { // pthread_cleanup_push/pop are hardcore macros mess. // We can't intercept nor call them w/o including pthread.h. int res; pthread_cleanup_push(cleanup, arg); res = fn(c, m, abstime); pthread_cleanup_pop(0); return res; } #endif } // namespace __tsan #endif // SANITIZER_MAC
Gurgel100/gcc
libsanitizer/tsan/tsan_platform_mac.cpp
C++
gpl-2.0
12,112
(function ($) { 'use strict'; function Ninja() { this.keys = { arrowDown: 40, arrowLeft: 37, arrowRight: 39, arrowUp: 38, enter: 13, escape: 27, tab: 9 }; this.version = '0.0.0development'; } Ninja.prototype.log = function (message) { if (console && 'log' in console) { console.log('Ninja: ' + message); } }; Ninja.prototype.warn = function (message) { if (console && 'warn' in console) { console.warn('Ninja: ' + message); } }; Ninja.prototype.error = function (message) { var fullMessage = 'Ninja: ' + message; if (console && 'error' in console) { console.error(fullMessage); } throw fullMessage; }; Ninja.prototype.key = function (code, names) { var keys = this.keys, codes = $.map(names, function (name) { return keys[name]; }); return $.inArray(code, codes) > -1; }; $.Ninja = function (element, options) { if ($.isPlainObject(element)) { this.$element = $('<span>'); this.options = element; } else { this.$element = $(element); this.options = options || {}; } }; $.Ninja.prototype.deselect = function () { if (this.$element.hasClass('nui-slc') && !this.$element.hasClass('nui-dsb')) { this.$element.trigger('deselect.ninja'); } }; $.Ninja.prototype.disable = function () { this.$element.addClass('nui-dsb').trigger('disable.ninja'); }; $.Ninja.prototype.enable = function () { this.$element.removeClass('nui-dsb').trigger('enable.ninja'); }; $.Ninja.prototype.select = function () { if (!this.$element.hasClass('nui-dsb')) { this.$element.trigger('select.ninja'); } }; $.ninja = new Ninja(); $.fn.ninja = function (component, options) { return this.each(function () { if (!$.data(this, 'ninja.' + component)) { $.data(this, 'ninja.' + component); $.ninja[component](this, options); } }); }; }(jQuery));
Bremaweb/streber
js/ninja.js
JavaScript
gpl-2.0
2,022
define([ 'container/BasicContainer', 'text!./CascadeContainer.html', 'core/functions/ComponentFactory', 'jquery', 'underscore' ], function (BasicContainer, template, ComponentFactory, $, _) { var CascadeContainer = BasicContainer.extend({ events: { "click .btn-prev": "clickPrev", "click .btn-next": "clickNext" }, clickPrev: function () { if (this._currentindex > 0) { this._currentindex--; var root = this._containerRoot; var li = root.find('.form-bootstrapWizard>li'); li.removeClass('active'); li.eq(this._currentindex).addClass('active'); root.find('.form-pane'); var pane = root.find('.form-pane'); pane.hide(); pane.eq(this._currentindex).show(); } }, clickNext: function (state) { if (this._currentindex <= this._renderindex - 1) { this._currentindex++; var root = this._containerRoot; var li = root.find('.form-bootstrapWizard>li'); li.removeClass('active'); li.eq(this._currentindex - 1).addClass(state || 'success'); li.eq(this._currentindex).addClass('active'); var pane = root.find('.form-pane'); pane.hide(); pane.eq(this._currentindex).show(); } }, addComponent: function (options) { this._components.push({ name: options.name, description: options.description, constructor: options.constructor, factory: options.factory || ComponentFactory, options: options.options, extend: options.extend }); }, getContainer: function (index, options) { var node = '<div id="' + index + '" class="form-pane" ' + (this._renderindex == 0 ? '' : 'style="display:none"') + ' data-value="step' + (this._renderindex + 1) + '" ></div>'; return $(node); }, addStep: function (name, index, text) { var root = this._containerRoot; root.find('.form-bootstrapWizard').append('<li ' + (index == 1 ? 'class="active"' : '') + ' data-target="step1">' + '<span class="step">' + index + '</span>' + '<span class="title">' + name + '</span>' + (text ? '<span class="text">' + text + '</span>' : '') + '</li>'); }, renderComponents: function (options) { this._currentindex = 0; this._renderindex = 0; var self = this; var containerRoot; if (this.options.root) { var tmp = this._containerRoot.find(this.options.root); containerRoot = tmp.length ? tmp : $(this._containerRoot.get(0)); } else { containerRoot = $(this._containerRoot.get(0)); } _.forEach(this._components, function (item) { var name = item.name; if (typeof self._componentStack[name] == 'undefined') { self._componentStack[name] = self.createComponent(item, options || {}); } var component = self._componentStack[name]; var el = self.getContainer(name, options || {}).appendTo(containerRoot).get(0); component.setElement(el); component.beforeShow(); component.render(options || {}); self.addStep(name, self._renderindex + 1, item.description); self._renderindex++; }); this.addStep('Complete', this._renderindex + 1); containerRoot.append('' + '<div id="Complete" class="form-pane" style="display:none" data-value="step' + (this._renderindex + 1) + '"><br/>' + '<h1 class="text-center text-success"><strong><i class="fa fa-check fa-lg"></i> Complete</strong></h1>' + '<h4 class="text-center">Click next to finish</h4>' + '<br/><br/></div>'); } }); CascadeContainer.create = function (options) { var ret = new CascadeContainer(); options.template = template; options.root = '.form-content'; if (ret.initialize(options) == false) { return false; } return ret; }; return CascadeContainer; });
MaxLeap/MyBaaS
webroot/javascript/core/container/CascadeContainer.js
JavaScript
gpl-2.0
4,532
<?php /*------------------------------------------------------------------------ # JSN PowerAdmin # ------------------------------------------------------------------------ # author JoomlaShine.com Team # copyright Copyright (C) 2012 JoomlaShine.com. All Rights Reserved. # Websites: http://www.joomlashine.com # Technical Support: Feedback - http://www.joomlashine.com/joomlashine/contact-us.html # @license - http://www.gnu.org/licenses/gpl-2.0.html GNU/GPL # @version $Id: controller.php 12506 2012-05-09 03:55:24Z hiennh $ -------------------------------------------------------------------------*/ defined( '_JEXEC' ) or die( 'Restricted access' ); jimport('joomla.application.component.controller'); /** * Poweradmin Controller * * @package Joomla * @subpackage Poweradmin * @since 1.6 */ class PoweradminController extends JController { /** * Joomla display */ public function display( $tpl = '' ) { parent::display($tpl); } /** * * Ajax sef URL */ public function getRouterLink() { $config = JFactory::getConfig(); if ($config->get('sef') == 1){ $url = base64_decode(JRequest::getVar('link', '')); if ($url){ $uri = new JURI($url); $query = $uri->getQuery(); if ($query){ $routeLink = JRoute::_('index.php?'.$query); echo base64_encode($routeLink); }else{ echo base64_encode(JURI::root()); } } }else{ echo 'error'; } jexit(); } }
ducdongmg/joomla_tut25
components/com_poweradmin/controller.php
PHP
gpl-2.0
1,429
/* -*- OpenSAF -*- * * (C) Copyright 2008 The OpenSAF 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. This file and program are licensed * under the GNU Lesser General Public License Version 2.1, February 1999. * The complete license can be accessed from the following location: * http://opensource.org/licenses/lgpl-license.php * See the Copying file included with the OpenSAF distribution for full * licensing terms. * * Author(s): Ericsson AB * */ /** * This object handles information about NTF clients. * */ #include "NtfClient.hh" #include "logtrace.h" #include "NtfAdmin.hh" /** * This is the constructor. * * Client object is created, initial variables are set. * * @param clientId Node-wide unique id of this client. * @param mds_dest MDS communication pointer to this client. * * @param locatedOnThisNode * Flag that is set if the client is located on this node. */ NtfClient::NtfClient(unsigned int clientId, MDS_DEST mds_dest):readerId_(0),mdsDest_(mds_dest) { clientId_ = clientId; mdsDest_ = mds_dest; TRACE_3("NtfClient::NtfClient NtfClient %u created mdest: %" PRIu64, clientId_, mdsDest_); } /** * This is the destructor. * * It is called when a client is removed, i.e. a client finalized its * connection. * * Subscription objects belonging to this client are deleted. */ NtfClient::~NtfClient() { // delete all subscriptions SubscriptionMap::iterator pos; for (pos = subscriptionMap.begin(); pos != subscriptionMap.end(); pos++) { NtfSubscription* subscription = pos->second; delete subscription; } // delete all readers ReaderMapT::iterator rpos; for (rpos = readerMap.begin(); rpos != readerMap.end(); rpos++) { unsigned int readerId = 0; NtfReader* reader = rpos->second; if (reader != NULL) { readerId = reader->getId(); TRACE_3("~Client delete reader Id %u ", readerId); delete reader; } } TRACE_3("NtfClient::~NtfClient NtfClient %u destroyed, mdest %" PRIu64, clientId_, mdsDest_); } /** * This method is called to get the id of this client. * * @return Node-wide unique id of this client. */ unsigned int NtfClient::getClientId() const { return clientId_; } MDS_DEST NtfClient::getMdsDest() const { return mdsDest_; } /** * This method is called when the client made a new subscription. * * The pointer to the subscription object is stored if it did not * exist. If the client is located on this node, a confirmation * for the subscription is sent. * * @param subscription * Pointer to the subscription object. */ void NtfClient::subscriptionAdded(NtfSubscription* subscription, MDS_SYNC_SND_CTXT *mdsCtxt) { // check if subscription already exists SubscriptionMap::iterator pos; pos = subscriptionMap.find(subscription->getSubscriptionId()); if (pos != subscriptionMap.end()) { // subscription found TRACE_3("NtfClient::subscriptionAdded subscription %u already exists" ", client %u", subscription->getSubscriptionId(), clientId_); delete subscription; } else { // store new subscription in subscriptionMap subscriptionMap[subscription->getSubscriptionId()] = subscription; TRACE_3("NtfClient::subscriptionAdded subscription %u added," " client %u, subscriptionMap size is %u", subscription->getSubscriptionId(), clientId_, (unsigned int)subscriptionMap.size()); if (activeController()) { sendSubscriptionUpdate(subscription->getSubscriptionInfo()); confirmNtfSubscribe(subscription->getSubscriptionId(), mdsCtxt); } } } /** * This method is called when the client received a notification. * * If the notification is send from this client, a confirmation * for the notification is sent. * * The client scans through its subscriptions and if it finds a * matching one, it stores the id of the matching subscription in * the notification object. * * @param clientId Node-wide unique id of the client who sent the notification. * @param notification * Pointer to the notification object. */ void NtfClient::notificationReceived(unsigned int clientId, NtfSmartPtr& notification, MDS_SYNC_SND_CTXT *mdsCtxt) { TRACE_ENTER2("%u %u", clientId_, clientId); // send acknowledgement if (clientId_ == clientId) { // this is the client who sent the notification if (activeController()) { confirmNtfNotification(notification->getNotificationId(), mdsCtxt, mdsDest_); if (notification->loggedOk()) { sendLoggedConfirmUpdate(notification->getNotificationId()); } else { notification->loggFromCallback_= true; } } } // scan through all subscriptions SubscriptionMap::iterator pos; for (pos = subscriptionMap.begin(); pos != subscriptionMap.end(); pos++) { NtfSubscription* subscription = pos->second; if (subscription->checkSubscription(notification)) { // notification matches the subscription TRACE_2("NtfClient::notificationReceived notification %llu matches" " subscription %d, client %u", notification->getNotificationId(), subscription->getSubscriptionId(), clientId_); // first store subscription data in notifiaction object for // tracking purposes notification->storeMatchingSubscription(clientId_, subscription->getSubscriptionId()); // if active, send out the notification if (activeController()) { subscription->sendNotification(notification, this); } } else { TRACE_2("NtfClient::notificationReceived notification %llu does not" " match subscription %u, client %u", notification->getNotificationId(), subscription->getSubscriptionId(), clientId_); } } TRACE_LEAVE(); } /** * This method is called if the client made an unsubscribe. * * The subscription object is deleted. If the client is located on * this node, a confirmation is sent. * * @param subscriptionId * Client-wide unique id of the subscription that was removed. */ void NtfClient::subscriptionRemoved(SaNtfSubscriptionIdT subscriptionId, MDS_SYNC_SND_CTXT *mdsCtxt) { // find subscription SubscriptionMap::iterator pos; pos = subscriptionMap.find(subscriptionId); if (pos != subscriptionMap.end()) { // subscription found NtfSubscription* subscription = pos->second; delete subscription; // remove subscription from subscription map subscriptionMap.erase(pos); } else { LOG_ER( "NtfClient::subscriptionRemoved subscription" " %u not found", subscriptionId); } if (activeController()) { // client is located on this node sendUnsubscribeUpdate(clientId_, subscriptionId); confirmNtfUnsubscribe(subscriptionId, mdsCtxt); } } void NtfClient::discardedAdd(SaNtfSubscriptionIdT subscriptionId, SaNtfIdentifierT notificationId) { SubscriptionMap::iterator pos; pos = subscriptionMap.find(subscriptionId); if (pos != subscriptionMap.end()) { pos->second->discardedAdd(notificationId); } else { LOG_ER( "discardedAdd subscription %u not found", subscriptionId); } } void NtfClient::discardedClear(SaNtfSubscriptionIdT subscriptionId) { SubscriptionMap::iterator pos; pos = subscriptionMap.find(subscriptionId); if (pos != subscriptionMap.end()) { pos->second->discardedClear(); } else { LOG_ER( "discardedClear subscription %u not found", subscriptionId); } } /** * This method is called when information about this client is * requested by another node. * * The client scans through its subscriptions and sends them out one by one. */ void NtfClient::syncRequest(NCS_UBAID *uba) { // scan through all subscriptions sendNoOfSubscriptions(subscriptionMap.size(), uba); SubscriptionMap::iterator pos; for (pos = subscriptionMap.begin(); pos != subscriptionMap.end(); pos++) { NtfSubscription* subscription = pos->second; TRACE_3("NtfClient::syncRequest sending info about subscription %u for " "client %u", subscription->getSubscriptionId(), clientId_); subscription->syncRequest(uba); } } void NtfClient::sendNotConfirmedNotification(NtfSmartPtr notification, SaNtfSubscriptionIdT subscriptionId) { TRACE_ENTER(); // if active, send out the notification if (activeController()) { SubscriptionMap::iterator pos; pos = subscriptionMap.find(subscriptionId); if (pos != subscriptionMap.end()) { pos->second->sendNotification(notification, this); } else { TRACE_3("subscription: %u client: %u not found", subscriptionId, getClientId()); } } TRACE_LEAVE(); } /** * This method is called when a confirmation for the subscription * should be sent to a client. * * @param subscriptionId Client-wide unique id of the subscription that should * be confirmed. */ void NtfClient::confirmNtfSubscribe(SaNtfSubscriptionIdT subscriptionId, MDS_SYNC_SND_CTXT *mds_ctxt) { TRACE_2("NtfClient::confirmNtfSubscribe subscribe_res_lib called, " "client %u, subscription %u", clientId_, subscriptionId); subscribe_res_lib( SA_AIS_OK, subscriptionId, mdsDest_, mds_ctxt); } /** * This method is called when a confirmation for the unsubscription * should be sent to a client. * * @param subscriptionId Client-wide unique id of the subscription that shoul be * confirmed. */ void NtfClient::confirmNtfUnsubscribe(SaNtfSubscriptionIdT subscriptionId, MDS_SYNC_SND_CTXT *mdsCtxt) { TRACE_2("NtfClient::confirmNtfUnsubscribe unsubscribe_res_lib called," " client %u, subscription %u", clientId_, subscriptionId); unsubscribe_res_lib(SA_AIS_OK, subscriptionId, mdsDest_, mdsCtxt); } /** * This method is called when a confirmation for the notification * should be sent to a client. * * @param notificationId * Cluster-wide unique id of the notification that should be confirmed. */ void NtfClient::confirmNtfNotification(SaNtfIdentifierT notificationId, MDS_SYNC_SND_CTXT *mdsCtxt, MDS_DEST mdsDest) { notfication_result_lib( SA_AIS_OK, notificationId, mdsCtxt, mdsDest); } void NtfClient::newReaderResponse(SaAisErrorT* error, unsigned int readerId, MDS_SYNC_SND_CTXT *mdsCtxt) { new_reader_res_lib( *error, readerId, mdsDest_, mdsCtxt); } void NtfClient::readNextResponse(SaAisErrorT* error, NtfSmartPtr& notification, MDS_SYNC_SND_CTXT *mdsCtxt) { TRACE_ENTER(); if (*error == SA_AIS_OK) { read_next_res_lib(*error, notification->sendNotInfo_, mdsDest_, mdsCtxt); } else { read_next_res_lib(*error, NULL, mdsDest_, mdsCtxt); } TRACE_ENTER(); } void NtfClient::deleteReaderResponse(SaAisErrorT* error, MDS_SYNC_SND_CTXT *mdsCtxt) { delete_reader_res_lib( *error, mdsDest_, mdsCtxt); } void NtfClient::newReader(SaNtfSearchCriteriaT searchCriteria, ntfsv_filter_ptrs_t *f_rec, MDS_SYNC_SND_CTXT *mdsCtxt) { SaAisErrorT error = SA_AIS_OK; readerId_++; NtfReader* reader; if (f_rec) { reader = new NtfReader(NtfAdmin::theNtfAdmin->logger, readerId_, searchCriteria, f_rec); } else { /*old API no filtering */ reader = new NtfReader(NtfAdmin::theNtfAdmin->logger, readerId_); } readerMap[readerId_] = reader; newReaderResponse(&error,readerId_, mdsCtxt); } void NtfClient::readNext(unsigned int readerId, SaNtfSearchDirectionT searchDirection, MDS_SYNC_SND_CTXT *mdsCtxt) { TRACE_ENTER(); TRACE_6("readerId %u", readerId); // check if reader already exists SaAisErrorT error = SA_AIS_ERR_NOT_EXIST; ReaderMapT::iterator pos; pos = readerMap.find(readerId); if (pos != readerMap.end()) { // reader found TRACE_3("NtfClient::readNext readerId %u FOUND!", readerId); NtfReader* reader = pos->second; NtfSmartPtr notif(reader->next(searchDirection, &error)); readNextResponse(&error, notif, mdsCtxt); TRACE_LEAVE(); return; } else { NtfSmartPtr notif; // reader not found TRACE_3("NtfClient::readNext readerId %u not found", readerId); error = SA_AIS_ERR_BAD_HANDLE; readNextResponse(&error, notif, mdsCtxt); TRACE_LEAVE(); } } void NtfClient::deleteReader(unsigned int readerId, MDS_SYNC_SND_CTXT *mdsCtxt) { SaAisErrorT error = SA_AIS_ERR_NOT_EXIST; ReaderMapT::iterator pos; pos = readerMap.find(readerId); if (pos != readerMap.end()) { // reader found TRACE_3("NtfClient::deleteReader readerId %u ", readerId); NtfReader* reader = pos->second; error = SA_AIS_OK; delete reader; readerMap.erase(pos); } else { // reader not found TRACE_3("NtfClient::readNext readerId %u not found", readerId); } deleteReaderResponse(&error, mdsCtxt); } void NtfClient::printInfo() { TRACE("Client information"); TRACE(" clientId: %u", clientId_); TRACE(" mdsDest %" PRIu64, mdsDest_); SubscriptionMap::iterator pos; for (pos = subscriptionMap.begin(); pos != subscriptionMap.end(); pos++) { NtfSubscription* subscription = pos->second; subscription->printInfo(); } TRACE(" readerId counter: %u", readerId_); ReaderMapT::iterator rpos; for (rpos = readerMap.begin(); rpos != readerMap.end(); rpos++) { unsigned int readerId = 0; NtfReader* reader = rpos->second; if (reader != NULL) { readerId = reader->getId(); TRACE(" Reader Id %u ", readerId); } } }
indonexia2004/opensaf-indo
osaf/services/saf/ntfsv/ntfs/NtfClient.cc
C++
gpl-2.0
15,097
package lk.score.androphsy.exceptions; /** * This exception is thrown when a property cannot be read from the property * file */ public class PropertyNotDefinedException extends Exception { private static final String MESSAGE_PREFIX = "Property not defined!! : "; public PropertyNotDefinedException(String message) { super(MESSAGE_PREFIX + message); } public PropertyNotDefinedException() { } }
swsachith/ANDROPHSY
src/main/java/lk/score/androphsy/exceptions/PropertyNotDefinedException.java
Java
gpl-2.0
409